All files / src postgres.listener.ts

100% Statements 63/63
100% Branches 29/29
100% Functions 17/17
100% Lines 58/58

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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138    3x 3x                     3x 3x   3x   23x 23x       8x       34x 22x 22x                     22x 22x     22x 22x 22x 22x   22x 21x 1x       4x       29x   28x 3x 3x 1x   2x       28x 5x 5x     28x 2x 1x 1x     28x 22x   22x 22x         22x       13x   12x             12x 12x 11x   1x     12x 12x   12x 12x 7x 1x 6x         22x 22x         22x 22x 21x   3x        
'use strict';
 
import {Client} from 'pg';
import {ReplaySubject, Subject} from 'rxjs';
 
import type {LifecycleEvent} from '@owservable/core';
 
export type PostgresNotificationType = {
	table: string;
	op: 'insert' | 'update' | 'delete' | string;
	id: string;
	changed?: string[];
};
 
const RECONNECT_INITIAL_DELAY: number = 1000;
const RECONNECT_MAX_DELAY: number = 30000;
 
export default class PostgresListener {
	public static init(config: any, channel: string = 'owservable'): PostgresListener {
		if (!PostgresListener._instance) PostgresListener._instance = new PostgresListener(config, channel);
		return PostgresListener._instance;
	}
 
	public static get instance(): PostgresListener {
		return PostgresListener._instance;
	}
 
	public static async stop(): Promise<void> {
		if (!PostgresListener._instance) return;
		await PostgresListener._instance._stop();
		PostgresListener._instance = null;
	}
 
	public readonly notifications: Subject<PostgresNotificationType>;
	public readonly lifecycle: ReplaySubject<LifecycleEvent>;
 
	private static _instance: PostgresListener;
 
	private readonly _config: any;
	private readonly _channel: string;
	private _client: Client;
	private _stopped: boolean = false;
	private _reconnectDelay: number = RECONNECT_INITIAL_DELAY;
 
	private constructor(config: any, channel: string) {
		this._config = config;
		this._channel = channel;
		this.notifications = new Subject<PostgresNotificationType>();
		this.lifecycle = new ReplaySubject<LifecycleEvent>(1);
 
		this._connect() //
			.then((): null => null)
			.catch((error: any): void => this._handleFailure(error));
	}
 
	public get channel(): string {
		return this._channel;
	}
 
	private async _connect(): Promise<void> {
		this._client = new Client(this._config);
 
		this._client.on('notification', (message: any): void => {
			try {
				const notification: PostgresNotificationType = JSON.parse(message.payload);
				this.notifications.next(notification);
			} catch (error) {
				console.error(`[@owservable/postgres] -> PostgresListener[${this._channel}] Error parsing notification payload:`, message?.payload, error);
			}
		});
 
		this._client.on('error', (error: any): void => {
			console.error(`[@owservable/postgres] -> PostgresListener[${this._channel}] connection error:`, error, ', attempting reconnection...');
			this._handleFailure(error);
		});
 
		this._client.on('end', (): void => {
			if (this._stopped) return;
			console.warn(`[@owservable/postgres] -> PostgresListener[${this._channel}] connection ended, attempting reconnection...`);
			this._handleFailure();
		});
 
		await this._client.connect();
		await this._client.query(`LISTEN "${this._channel}"`);
 
		this._reconnectDelay = RECONNECT_INITIAL_DELAY;
		this.lifecycle.next({
			type: 'live',
			collection: this._channel,
			timestamp: new Date()
		});
		console.log(`[@owservable/postgres] -> PostgresListener listening on channel "${this._channel}"`);
	}
 
	private _handleFailure(error?: any): void {
		if (this._stopped) return;
 
		this.lifecycle.next({
			type: 'error',
			collection: this._channel,
			timestamp: new Date(),
			error
		});
 
		try {
			this._client?.removeAllListeners();
			this._client?.end().catch((): null => null);
		} catch (cleanupError) {
			console.error(`[@owservable/postgres] -> PostgresListener[${this._channel}] Error cleaning up old client:`, cleanupError);
		}
 
		const delay: number = this._reconnectDelay;
		this._reconnectDelay = Math.min(this._reconnectDelay * 2, RECONNECT_MAX_DELAY);
 
		console.info(`[@owservable/postgres] -> PostgresListener[${this._channel}] Reconnecting in ${delay}ms...`);
		setTimeout((): void => {
			this._connect() //
				.then((): null => null)
				.catch((reconnectError: any): void => this._handleFailure(reconnectError));
		}, delay);
	}
 
	private async _stop(): Promise<void> {
		this._stopped = true;
		this.lifecycle.next({
			type: 'close',
			collection: this._channel,
			timestamp: new Date()
		});
		try {
			this._client?.removeAllListeners();
			await this._client?.end();
		} catch (error) {
			console.error(`[@owservable/postgres] -> PostgresListener[${this._channel}] Error stopping:`, error);
		}
	}
}