All files / src/connection notifications.ts

98.14% Statements 53/54
93.75% Branches 15/16
95.45% Functions 21/22
100% Lines 47/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114            132x               15x   15x           15x                     49x 49x 45x 45x 43x   4x 4x   47x 37x 37x 37x 34x 34x 34x                     14x 14x 14x 14x 14x       40x 43x 43x 2x         54x 35x   19x 19x 19x 5x 5x     19x       40x 14x 14x 8x 8x 4x     14x   15x     14x       7x 5x 3x          
import type { Client as PgClient } from 'pg';
import { SqlCompiler } from '../sql/compile.ts';
 
/** Handler of `LISTEN` notifications. */
export type NotificationHandler = (payload: string | undefined, channel: string) => unknown;
 
const RECONNECT_DELAY_MS = 1000;
 
/**
 * Dedicated LISTEN connection shared by all subscriptions of a Sequelize instance: opened lazily and
 * re-subscribed after connection loss.
 */
export class NotificationListener {
  readonly #connect: () => Promise<PgClient>;
  readonly #handlers = new Map<string, Set<NotificationHandler>>();
  #client: Promise<PgClient> | undefined;
  #closed = false;
 
  /**
   * @param connect - Opens a dedicated client.
   */
  constructor(connect: () => Promise<PgClient>) {
    this.#connect = connect;
  }
 
  /**
   * Subscribes `handler` to a channel.
   *
   * @param channel - Channel name.
   * @param handler - Called with the payload and the channel.
   * @returns Function that unsubscribes the handler.
   */
  async listen(channel: string, handler: NotificationHandler): Promise<() => Promise<void>> {
    const existing = this.#handlers.get(channel);
    if (existing === undefined) {
      this.#handlers.set(channel, new Set([handler]));
      const client = await this.#open();
      await client.query(`LISTEN ${SqlCompiler.quoteIdent(channel)}`);
    } else {
      existing.add(handler);
      await this.#open();
    }
    return async () => {
      const handlers = this.#handlers.get(channel);
      handlers?.delete(handler);
      if (handlers !== undefined && handlers.size === 0) {
        this.#handlers.delete(channel);
        const client = await this.#client;
        await client?.query(`UNLISTEN ${SqlCompiler.quoteIdent(channel)}`);
      }
    };
  }
 
  /**
   * Removes all subscriptions and closes the connection.
   *
   * @returns Resolves when closed.
   */
  async close(): Promise<void> {
    this.#closed = true;
    this.#handlers.clear();
    const client = await this.#client?.catch(() => undefined);
    this.#client = undefined;
    await client?.end();
  }
 
  #dispatch(message: Readonly<{ channel: string; payload?: string }>): void {
    this.#handlers.get(message.channel)?.forEach((handler) => {
      void Promise.resolve()
        .then(() => handler(message.payload, message.channel))
        .catch(() => undefined);
    });
  }
 
  #open(): Promise<PgClient> {
    if (this.#client !== undefined) {
      return this.#client;
    }
    const opening = this.#connect().then((client) => this.#attach(client));
    this.#client = opening;
    opening.catch(() => {
      Eif (this.#client === opening) {
        this.#client = undefined;
      }
    });
    return opening;
  }
 
  async #attach(client: PgClient): Promise<PgClient> {
    client.on('notification', (message) => this.#dispatch(message));
    client.on('error', () => undefined);
    client.on('end', () => {
      this.#client = undefined;
      if (!this.#closed && this.#handlers.size > 0) {
        setTimeout(() => void this.#resubscribe(), RECONNECT_DELAY_MS);
      }
    });
    await [...this.#handlers.keys()].reduce<Promise<unknown>>(
      (previous, channel) =>
        previous.then(() => client.query(`LISTEN ${SqlCompiler.quoteIdent(channel)}`)),
      Promise.resolve(),
    );
    return client;
  }
 
  async #resubscribe(): Promise<void> {
    if (!this.#closed) {
      await this.#open().catch(() => {
        setTimeout(() => void this.#resubscribe(), RECONNECT_DELAY_MS);
      });
    }
  }
}