import { Request } from 'express'; import { ciqPdTrigger } from '../pagerduty/index'; import { ciqOppexTrigger } from '../oppex/index'; import { setPdConfig } from '../pagerduty/pd-config-builder'; import { setOppexConfig } from '../oppex/oppex-config-builder'; /** * Thin facade over the individual alerting providers (PagerDuty, Oppex, ...). It does * NOT introduce a new config system -- each provider is still configured independently * via its own setPdConfig/setOppexConfig. This facade only decides, at call time, which * already-configured provider(s) to fan a single alert out to. * @sync * @stable */ type AlertTrigger = (err: any, req: Request, status: any) => void; const PROVIDERS: Record = { pagerduty: ciqPdTrigger.triggerPd, oppex: ciqOppexTrigger.triggerOppex }; /** * Reads CIQ_ALERTING_PROVIDER (comma-separated, e.g. "pagerduty" or "oppex,pagerduty") * at call time and fans the alert out to each configured provider. Each provider call * is isolated in its own try/catch so one provider throwing never blocks another. * @notes We are not going to wait for any provider to trigger, hence you can't await on it. * @sync * @stable * @param err * @param req * @param status */ export const triggerAlert = (err: any, req: Request, status: any) => { const raw = process.env.CIQ_ALERTING_PROVIDER || ''; const providerNames = raw .split(',') .map((name) => name.trim().toLowerCase()) .filter((name) => name.length > 0); if (providerNames.length === 0) { console.error('[ciqAlerting] CIQ_ALERTING_PROVIDER is empty/unset -- no alerting provider configured, dropping alert'); return; } providerNames.forEach((name) => { const trigger = PROVIDERS[name]; if (!trigger) { console.error(`[ciqAlerting] Unknown alerting provider "${name}" in CIQ_ALERTING_PROVIDER -- skipping`); return; } try { trigger(err, req, status); } catch (triggerErr) { console.error(`[ciqAlerting] Provider "${name}" threw while triggering an alert`, triggerErr); } }); }; /** * Convenience passthrough so callers can configure both providers via a single import * (`ciqAlerting`) if they want to. Each provider still owns its own config key -- this * does not merge or share config between providers. * @sync * @stable */ const trimKey = (value: any): string => typeof value === 'string' ? value.trim() : ''; export const setAlertingConfig = (options: { pdServiceKey?: string; oppexApiKey?: string; oppexServiceKey?: string }) => { const pdServiceKey = trimKey(options.pdServiceKey); const oppexApiKey = trimKey(options.oppexApiKey); if (pdServiceKey) { setPdConfig(pdServiceKey); } if (oppexApiKey) { setOppexConfig(oppexApiKey, trimKey(options.oppexServiceKey) || undefined); } };