import {PgPool} from '@arborknot/db' import { loggerManager } from "@logger"; import { LOGGER_FILTER, LOGGER_LEVEL } from "@types"; import EventEmitter from "events"; export class RuntimeConfig extends EventEmitter { private _LOGGER_LEVEL: string = "info"; private _LOGGER_FILTER: string = ""; constructor(private readonly db: PgPool) { super(); } get LOGGER_LEVEL(): string { return this._LOGGER_LEVEL; } private setLOGGER_LEVEL(value: string = "info"): void { this._LOGGER_LEVEL = value; this.emit(LOGGER_LEVEL, value); } get LOGGER_FILTER(): string { return this._LOGGER_FILTER; } private setLOGGER_FILTER(value: string = ""): void { this._LOGGER_FILTER = value; this.emit(LOGGER_FILTER, value); } on(eventName: typeof LOGGER_LEVEL, listener: (value: string) => void): this; on(eventName: typeof LOGGER_FILTER, listener: (value: string) => void): this; on(eventName: string | symbol, listener: (...args: any[]) => void): this { return super.on(eventName, listener); } async setServiceEnvironmentVariablesFromDB() { const queryResponse = await this.db.query<{ environment_variables: Record }>(` SELECT environment_variables FROM service_config WHERE name = 'webhook-listener' `); if (!queryResponse?.rows.length) { loggerManager.error("Couldn't find environment variable for webhook handler"); return; } this.updateServiceEnvironmentVariables(queryResponse.rows[0].environment_variables); } async listenToServiceEnvironmentVariableChangeOnDB() { //this.db.listenTo("webhook-listener", this.handleDBNotification.bind(this)); } private handleDBNotification(payload: string) { if (!payload) { loggerManager.warn( "Failed to update the environment variable because the payload is undefined", ); return; } try { const parsedPayload = typeof payload == "object" ? payload : JSON.parse(payload); this.updateServiceEnvironmentVariables(parsedPayload); } catch (e) { loggerManager.error( `Failed to update the environment variables because: ${(e as Error).message}`, ); return; } } private updateServiceEnvironmentVariables(object: Record) { this.setLOGGER_LEVEL(object[LOGGER_LEVEL]); this.setLOGGER_FILTER(object[LOGGER_FILTER]); } }