@sdflc/backend-helpers 1.0.139 → 1.0.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +176 -20
  2. package/build/EmergencyAlerter.d.ts +140 -0
  3. package/build/EmergencyAlerter.js +465 -0
  4. package/build/esm/EmergencyAlerter.d.ts +140 -0
  5. package/build/esm/EmergencyAlerter.js +454 -0
  6. package/build/esm/gateways/BaseExternalApiGateway.d.ts +94 -0
  7. package/build/esm/gateways/BaseExternalApiGateway.js +319 -0
  8. package/build/esm/gateways/DiscordWebhookGw.d.ts +50 -0
  9. package/build/esm/gateways/DiscordWebhookGw.js +70 -0
  10. package/build/esm/gateways/HttpWebhookGw.d.ts +43 -0
  11. package/build/esm/gateways/HttpWebhookGw.js +131 -0
  12. package/build/esm/gateways/SendGridGw.d.ts +41 -0
  13. package/build/esm/gateways/SendGridGw.js +116 -0
  14. package/build/esm/gateways/SlackWebhookGw.d.ts +23 -0
  15. package/build/esm/gateways/SlackWebhookGw.js +59 -0
  16. package/build/esm/gateways/TelegramGw.d.ts +45 -0
  17. package/build/esm/gateways/TelegramGw.js +110 -0
  18. package/build/esm/gateways/TwilioGw.d.ts +33 -0
  19. package/build/esm/gateways/TwilioGw.js +107 -0
  20. package/build/esm/gateways/externalUrl.d.ts +16 -0
  21. package/build/esm/gateways/externalUrl.js +116 -0
  22. package/build/esm/gateways/guardedFetch.d.ts +15 -0
  23. package/build/esm/gateways/guardedFetch.js +133 -0
  24. package/build/esm/gateways/index.d.ts +9 -0
  25. package/build/esm/gateways/index.js +9 -0
  26. package/build/esm/index.d.ts +2 -1
  27. package/build/esm/index.js +2 -1
  28. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  29. package/build/gateways/BaseExternalApiGateway.d.ts +94 -0
  30. package/build/gateways/BaseExternalApiGateway.js +326 -0
  31. package/build/gateways/DiscordWebhookGw.d.ts +50 -0
  32. package/build/gateways/DiscordWebhookGw.js +73 -0
  33. package/build/gateways/HttpWebhookGw.d.ts +43 -0
  34. package/build/gateways/HttpWebhookGw.js +135 -0
  35. package/build/gateways/SendGridGw.d.ts +41 -0
  36. package/build/gateways/SendGridGw.js +119 -0
  37. package/build/gateways/SlackWebhookGw.d.ts +23 -0
  38. package/build/gateways/SlackWebhookGw.js +62 -0
  39. package/build/gateways/TelegramGw.d.ts +45 -0
  40. package/build/gateways/TelegramGw.js +115 -0
  41. package/build/gateways/TwilioGw.d.ts +33 -0
  42. package/build/gateways/TwilioGw.js +110 -0
  43. package/build/gateways/externalUrl.d.ts +16 -0
  44. package/build/gateways/externalUrl.js +121 -0
  45. package/build/gateways/guardedFetch.d.ts +15 -0
  46. package/build/gateways/guardedFetch.js +141 -0
  47. package/build/gateways/index.d.ts +9 -0
  48. package/build/gateways/index.js +25 -0
  49. package/build/index.d.ts +2 -1
  50. package/build/index.js +2 -1
  51. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  52. package/package.json +2 -1
  53. package/build/BaseExternalApiGateway.d.ts +0 -16
  54. package/build/BaseExternalApiGateway.js +0 -54
  55. package/build/esm/BaseExternalApiGateway.d.ts +0 -16
  56. package/build/esm/BaseExternalApiGateway.js +0 -48
@@ -0,0 +1,454 @@
1
+ // ./src/EmergencyAlerter.ts
2
+ //
3
+ // An EMERGENCY alert a service sends BY ITSELF — for what nobody would otherwise notice until somebody trips over it: a
4
+ // missing configuration value, a crash. It sends through the library's gateways (./gateways — SendGridGw for email,
5
+ // TelegramGw for Telegram); this class decides WHAT is said, to WHOM, and HOW OFTEN — never how it travels.
6
+ //
7
+ // const alerter = EmergencyAlerter.fromConfig(config, 'ms_storage', { log: (m) => logger.error(m) });
8
+ // alerter.installCrashHandlers(process);
9
+ // … after the server listens: await alerter.checkConfig(config, CRITICAL_CONFIG);
10
+ //
11
+ // Every alert names its app, service and environment — `[partylabz · ms_storage · production]` — because several apps
12
+ // run the same services side by side on one machine, and "ms_storage crashed" alone does not say whose.
13
+ //
14
+ // ⚠ It goes STRAIGHT to the providers, never through another service of ours: it has to work when the rest does not.
15
+ // ⚠ It never throws, and every operation answers an OpResult.
16
+ // ⚠ One alert per KEY per interval (default an hour) across ALL channels, remembered in a file under the OS temp folder
17
+ // named after the app and service — so a crash loop, where every restart is a fresh process, sends one message, not one
18
+ // per restart. Sends of the same key AT ONCE go out once (claimed before the network call). It counts as sent when ANY
19
+ // channel delivered it; a send that failed everywhere is not remembered, so the next one tries again.
20
+ // ⚠ Never put a secret, a token or a database row into an alert: it leaves our infrastructure.
21
+ //
22
+ // The settings `fromConfig` reads (env names as in .env; all optional — each channel needs all of its own):
23
+ // APP_NAME — the app this service belongs to (alerts say 'unknown-app' without it)
24
+ // EMERGENCY_SENDGRID_API_KEY — email: a SendGrid key allowed to send mail
25
+ // EMERGENCY_EMAIL_FROM — email: an address on a domain authenticated in that SendGrid account
26
+ // EMERGENCY_EMAIL_TO — email: where alerts go; several addresses separated by commas
27
+ // TELEGRAM_BOT_ID — Telegram: the bot's token (`<id>:<secret>`, from @BotFather)
28
+ // TELEGRAM_CHAT_ID — Telegram: the chat the bot writes to (the bot must be in it)
29
+ // EMERGENCY_EMAIL_MIN_INTERVAL_MINUTES — the same alert at most once per this many minutes, every channel (default 60)
30
+ import { createHash } from 'crypto';
31
+ import fs from 'fs';
32
+ import os from 'os';
33
+ import path from 'path';
34
+ import { setTimeout as sleep } from 'timers/promises';
35
+ import { camelCase } from 'lodash';
36
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
37
+ import { SendGridGw } from './gateways/SendGridGw';
38
+ import { TelegramGw, TELEGRAM_MAX_MESSAGE_LENGTH, isTelegramChatId } from './gateways/TelegramGw';
39
+ /** What an alert says when APP_NAME is not set. */
40
+ export const UNKNOWN_APP_NAME = 'unknown-app';
41
+ /** Checked in every service: without it no alert can say which app it comes from. */
42
+ export const APP_NAME_CONFIG = {
43
+ env: 'APP_NAME',
44
+ effect: `Emergency alerts cannot say which app they come from (they say '${UNKNOWN_APP_NAME}').`,
45
+ };
46
+ const textOf = (value) => (value === undefined || value === null ? '' : String(value)).trim();
47
+ /**
48
+ * One line of at most `max` characters: line breaks, tabs and other control characters become spaces, runs of spaces one.
49
+ * ⚠ For every SUBJECT and label part — a crash's subject is the error's message, which often spans lines, and a line
50
+ * break in a mail subject or the Telegram heading breaks it. Pure.
51
+ */
52
+ export const emergencyOneLine = (value, max) => Array.from(textOf(value))
53
+ .map((char) => (char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127 ? ' ' : char))
54
+ .join('')
55
+ .replace(/\s+/g, ' ')
56
+ .trim()
57
+ .slice(0, max);
58
+ /** `15 minutes`, `30 seconds` — how long the same alert stays quiet. Pure. */
59
+ export const emergencyIntervalText = (ms) => ms < 60_000 ? `${Math.round(ms / 1000)} seconds` : `${Math.round(ms / 60_000)} minutes`;
60
+ /** The critical values that are missing (unset or blank) — APP_NAME always among those checked. Pure. */
61
+ export const missingCriticalConfig = (config, items = []) => [...items, APP_NAME_CONFIG]
62
+ .map((item) => ({ ...item, key: item.key || camelCase(item.env) }))
63
+ .filter((item, index, all) => all.findIndex((other) => other.key === item.key) === index)
64
+ // ⚠ buildConfig turns 'false'/'0' into false: a value of false is SET (textOf gives 'false'); only absent or blank is
65
+ // missing — a falsy test would report it.
66
+ .filter((item) => textOf(config?.[item.key]) === '')
67
+ .map(({ env, effect }) => ({ env, effect }));
68
+ /** The alert for missing configuration, or null when nothing is missing. Pure. */
69
+ export const missingConfigAlert = (config, items = []) => {
70
+ const missing = missingCriticalConfig(config, items);
71
+ if (missing.length === 0) {
72
+ return null;
73
+ }
74
+ return {
75
+ key: `config:${missing.map((one) => one.env).join(',')}`,
76
+ subject: `Started with missing configuration: ${missing.map((one) => one.env).join(', ')}`,
77
+ lines: [
78
+ 'The service started and is answering, but these values are not set:',
79
+ ...missing.map((one) => `• ${one.env} — ${one.effect}`),
80
+ 'Set them in the service environment and restart it.',
81
+ ],
82
+ };
83
+ };
84
+ const escapeHtml = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
85
+ /** Kept under Telegram's 4096 with room to spare (it counts after parsing; we count before). */
86
+ const TELEGRAM_TEXT_MAX = Math.min(4000, TELEGRAM_MAX_MESSAGE_LENGTH);
87
+ const CUT_MARK = '\n… (cut)';
88
+ /** The longest start of `text` whose ESCAPED form fits `budget` — never splitting a surrogate pair. Pure. */
89
+ const escapedPrefix = (text, budget) => {
90
+ let low = 0;
91
+ let high = text.length;
92
+ // Escaping only lengthens, so the escaped length grows with the prefix: a binary search finds the longest that fits.
93
+ while (low < high) {
94
+ const middle = Math.ceil((low + high) / 2);
95
+ if (escapeHtml(text.slice(0, middle)).length <= budget) {
96
+ low = middle;
97
+ }
98
+ else {
99
+ high = middle - 1;
100
+ }
101
+ }
102
+ const code = text.charCodeAt(low - 1);
103
+ const keep = low > 0 && code >= 0xd800 && code <= 0xdbff ? low - 1 : low;
104
+ return escapeHtml(text.slice(0, keep));
105
+ };
106
+ /** The memory in a file under the OS temp folder, one per app AND service (several may share a temp folder). */
107
+ export const emergencyFileMemory = (appName, serviceName, dir = os.tmpdir()) => {
108
+ const safe = (name) => name.replace(/[^A-Za-z0-9_.-]/g, '_');
109
+ const file = path.join(dir, `${safe(appName)}-${safe(serviceName)}-emergency-alerts.json`);
110
+ return {
111
+ read: () => {
112
+ try {
113
+ return JSON.parse(fs.readFileSync(file, 'utf8')) || {};
114
+ }
115
+ catch {
116
+ return {};
117
+ }
118
+ },
119
+ write: (sent) => {
120
+ try {
121
+ fs.writeFileSync(file, JSON.stringify(sent));
122
+ }
123
+ catch {
124
+ // A read-only temp folder costs the interval, not the alert.
125
+ }
126
+ },
127
+ };
128
+ };
129
+ /** One provider call's budget in `fromConfig` — both channels together fit the crash wait (10 s). */
130
+ const PROVIDER_TIMEOUT_MS = 4000;
131
+ class EmergencyAlerter {
132
+ settings = { serviceName: 'unknown-service' };
133
+ email;
134
+ telegram;
135
+ log;
136
+ redact;
137
+ memoryOverride;
138
+ now;
139
+ hostname;
140
+ /** Keys being sent right now → when they were claimed. */
141
+ claims = new Map();
142
+ constructor(props = {}) {
143
+ this.email = props.email ?? null;
144
+ this.telegram = props.telegram ?? null;
145
+ const log = props.log ?? ((message) => console.error(message));
146
+ // ⚠ A log that throws must not make `send` throw: the alerter is what runs when everything else is broken.
147
+ this.log = (message) => {
148
+ try {
149
+ log(message);
150
+ }
151
+ catch {
152
+ // Nowhere left to say it.
153
+ }
154
+ };
155
+ const redact = props.redact ?? ((text) => text);
156
+ this.redact = (text) => {
157
+ try {
158
+ return String(redact(String(text ?? '')));
159
+ }
160
+ catch {
161
+ return '[redacted: the redact hook failed]';
162
+ }
163
+ };
164
+ this.memoryOverride = props.memory ?? null;
165
+ this.now = props.now ?? (() => Date.now());
166
+ this.hostname = props.hostname ?? (() => os.hostname());
167
+ if (props.settings) {
168
+ this.configure(props.settings);
169
+ }
170
+ }
171
+ /**
172
+ * One service's alerter from its built config (buildConfig) — the gateways created and configured from the env names in
173
+ * the file header, with a short timeout so a crash's alert fits its wait. Says once, through `log`, when a channel was
174
+ * set up but cannot be used.
175
+ */
176
+ static fromConfig(config, serviceName, props = {}) {
177
+ const gatewayProps = { timeoutMs: PROVIDER_TIMEOUT_MS, retries: 1, retryDelaysMs: [500] };
178
+ const raw = config?.emergencyEmailMinIntervalMinutes;
179
+ // ⚠ buildConfig turns '0' into false and '1' into true — Number() reads them back as 0 and 1.
180
+ const minutes = textOf(raw) === '' ? NaN : Number(raw);
181
+ // Every config value whose NAME looks secret, longest first — removed from whatever an alert says.
182
+ const secrets = Object.entries(config ?? {})
183
+ .filter(([key, value]) => /secret|password|passwd|token|apikey|api_key|botid|credential|connectionstring|dsn|key$/i.test(key) &&
184
+ typeof value === 'string' &&
185
+ value.trim().length >= 8)
186
+ .map(([, value]) => String(value))
187
+ .sort((a, b) => b.length - a.length);
188
+ const scrubSecrets = (text) => secrets.reduce((out, secret) => out.split(secret).join('***'), text);
189
+ const alerter = new EmergencyAlerter({
190
+ ...props,
191
+ redact: props.redact ? (text) => props.redact(scrubSecrets(text)) : scrubSecrets,
192
+ email: textOf(config?.emergencySendgridApiKey)
193
+ ? new SendGridGw(gatewayProps).configure({ apiKey: textOf(config.emergencySendgridApiKey) })
194
+ : null,
195
+ telegram: textOf(config?.telegramBotId)
196
+ ? new TelegramGw(gatewayProps).configure({ botToken: textOf(config.telegramBotId) })
197
+ : null,
198
+ settings: {
199
+ appName: textOf(config?.appName),
200
+ serviceName,
201
+ environment: textOf(config?.nodeEnv),
202
+ minIntervalMinutes: Number.isFinite(minutes) && minutes >= 0 ? minutes : undefined,
203
+ emailTo: textOf(config?.emergencyEmailTo)
204
+ .split(',')
205
+ .map((one) => one.trim())
206
+ .filter(Boolean),
207
+ emailFrom: textOf(config?.emergencyEmailFrom),
208
+ telegramChatId: textOf(config?.telegramChatId),
209
+ },
210
+ });
211
+ const emailTouched = ['emergencySendgridApiKey', 'emergencyEmailTo', 'emergencyEmailFrom'].some((key) => textOf(config?.[key]));
212
+ const telegramTouched = ['telegramBotId', 'telegramChatId'].some((key) => textOf(config?.[key]));
213
+ for (const problem of alerter.getChannelProblems()) {
214
+ if ((problem.startsWith('Email') && emailTouched) || (problem.startsWith('Telegram') && telegramTouched)) {
215
+ alerter.log(`[EMERGENCY] ${problem}`);
216
+ }
217
+ }
218
+ return alerter;
219
+ }
220
+ /** Sets the alerter up. REPLACES what was set before. Never throws. */
221
+ configure(settings) {
222
+ this.settings = { ...settings };
223
+ this.claims.clear();
224
+ return this;
225
+ }
226
+ /** Sends email through this gateway (configured with its API key), or not at all (null). */
227
+ useEmail(gateway) {
228
+ this.email = gateway;
229
+ return this;
230
+ }
231
+ /** Sends to Telegram through this gateway (configured with its bot token), or not at all (null). */
232
+ useTelegram(gateway) {
233
+ this.telegram = gateway;
234
+ return this;
235
+ }
236
+ getAppName() {
237
+ return emergencyOneLine(this.settings.appName, 64) || UNKNOWN_APP_NAME;
238
+ }
239
+ /** `eventsmagic · ms_auth · production` — who is raising the alerts. */
240
+ getLabel() {
241
+ const service = emergencyOneLine(this.settings.serviceName, 64) || 'unknown-service';
242
+ const environment = emergencyOneLine(this.settings.environment, 32) || 'unknown';
243
+ return `${this.getAppName()} · ${service} · ${environment}`;
244
+ }
245
+ getMinIntervalMs() {
246
+ const minutes = Number(this.settings.minIntervalMinutes);
247
+ return (Number.isFinite(minutes) && minutes >= 0 ? minutes : 60) * 60_000;
248
+ }
249
+ /** Why each channel cannot be used, in words (never a value). Empty when both can. */
250
+ getChannelProblems() {
251
+ const problems = [];
252
+ const emailTo = (this.settings.emailTo ?? []).filter((one) => String(one).includes('@'));
253
+ if (!this.email) {
254
+ problems.push('Email is not used: no SendGrid API key (EMERGENCY_SENDGRID_API_KEY).');
255
+ }
256
+ else if (!this.email.isConfigured()) {
257
+ problems.push(`Email is not used: ${this.email.getConfigProblems().join('; ')}.`);
258
+ }
259
+ else if (emailTo.length === 0) {
260
+ problems.push('Email is not used: no recipient (EMERGENCY_EMAIL_TO).');
261
+ }
262
+ else if (!textOf(this.settings.emailFrom).includes('@')) {
263
+ problems.push('Email is not used: no sender (EMERGENCY_EMAIL_FROM — a guessed one is refused by SendGrid).');
264
+ }
265
+ if (!this.telegram) {
266
+ problems.push('Telegram is not used: no bot token (TELEGRAM_BOT_ID).');
267
+ }
268
+ else if (!this.telegram.isConfigured()) {
269
+ problems.push(`Telegram is not used: ${this.telegram.getConfigProblems().join('; ')}.`);
270
+ }
271
+ else if (!isTelegramChatId(this.settings.telegramChatId)) {
272
+ problems.push('Telegram is not used: no chat, or a malformed one (TELEGRAM_CHAT_ID).');
273
+ }
274
+ return problems;
275
+ }
276
+ /** The email for one alert. */
277
+ emailOf(alert, host, at) {
278
+ return {
279
+ to: (this.settings.emailTo ?? []).filter((one) => String(one).includes('@')),
280
+ from: {
281
+ email: textOf(this.settings.emailFrom),
282
+ name: `${this.getAppName()} ${emergencyOneLine(this.settings.serviceName, 64)} alerts`,
283
+ },
284
+ subject: `[${this.getLabel()}] ${emergencyOneLine(alert.subject, 200)}`,
285
+ text: [
286
+ alert.subject,
287
+ '',
288
+ ...alert.lines,
289
+ '',
290
+ `${this.getLabel()} · host: ${host}`,
291
+ `When: ${at.toISOString()}`,
292
+ `The same alert is not sent again for ${emergencyIntervalText(this.getMinIntervalMs())}.`,
293
+ ].join('\n'),
294
+ };
295
+ }
296
+ /**
297
+ * The Telegram message for one alert (HTML), always under Telegram's limit. ⚠ The text is cut BEFORE it is escaped and
298
+ * wrapped, to what the heading and footer leave: cutting finished HTML can split an entity, and Telegram then refuses
299
+ * the whole message — a long stack trace would silence exactly the crash it reports.
300
+ */
301
+ telegramTextOf(alert, host, at) {
302
+ const heading = `🔴 <b>[${escapeHtml(this.getLabel())}] ${escapeHtml(emergencyOneLine(alert.subject, 200))}</b>`;
303
+ const footer = [
304
+ `🖥 ${escapeHtml(emergencyOneLine(host, 100))} · ${at.toISOString()}`,
305
+ `<i>The same alert is not sent again for ${emergencyIntervalText(this.getMinIntervalMs())}.</i>`,
306
+ ].join('\n');
307
+ const wrap = (block) => [heading, '', `<pre>${block}</pre>`, '', footer].join('\n');
308
+ const body = alert.lines.join('\n');
309
+ const whole = escapeHtml(body);
310
+ if (wrap(whole).length <= TELEGRAM_TEXT_MAX) {
311
+ return wrap(whole);
312
+ }
313
+ const budget = Math.max(0, TELEGRAM_TEXT_MAX - wrap('').length - CUT_MARK.length);
314
+ return wrap(`${escapedPrefix(body, budget)}${CUT_MARK}`);
315
+ }
316
+ memory() {
317
+ return (this.memoryOverride ??
318
+ emergencyFileMemory(this.getAppName(), emergencyOneLine(this.settings.serviceName, 64) || 'unknown-service'));
319
+ }
320
+ /**
321
+ * Sends one alert. ALWAYS logs it; sends it to every usable channel unless the same key went out within the interval.
322
+ * OK with `{ status: 'sent', channels }` or `{ status: 'recently-sent' }`; VALIDATION_FAILED when no channel can be
323
+ * used; FAILED (every channel's error merged in) when none delivered it. Never throws.
324
+ */
325
+ async send(given) {
326
+ try {
327
+ const alert = {
328
+ key: String(given?.key ?? 'alert'),
329
+ subject: this.redact(given?.subject ?? ''),
330
+ lines: (Array.isArray(given?.lines) ? given.lines : []).map((line) => this.redact(line)),
331
+ };
332
+ this.log(`[EMERGENCY] [${this.getLabel()}] ${emergencyOneLine(alert.subject, 200)} — ${alert.lines.join(' | ')}`);
333
+ const problems = this.getChannelProblems();
334
+ const emailOn = !problems.some((one) => one.startsWith('Email'));
335
+ const telegramOn = !problems.some((one) => one.startsWith('Telegram'));
336
+ if (!emailOn && !telegramOn) {
337
+ this.log(`[EMERGENCY] not sent: ${problems.join(' ')}`);
338
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, [{ status: 'unconfigured' }], 'No emergency channel can be used');
339
+ }
340
+ const memory = this.memory();
341
+ const now = this.now();
342
+ // ⚠ A time AFTER now (a clock moved back, a hand-edited file) is stale — it must not silence alerts until then.
343
+ const remembered = Number(memory.read()[alert.key]) || 0;
344
+ const last = Math.max(remembered <= now ? remembered : 0, this.claims.get(alert.key) ?? 0);
345
+ if (last > 0 && now - last < this.getMinIntervalMs()) {
346
+ return OpResult.ok([{ status: 'recently-sent' }]);
347
+ }
348
+ // Claimed BEFORE the first await, so a second send of the same key meanwhile finds it.
349
+ this.claims.set(alert.key, now);
350
+ const host = this.hostname();
351
+ const at = new Date(now);
352
+ // Both at once: a crash waits for the alert only a few seconds before the process exits.
353
+ const [email, telegram] = await Promise.all([
354
+ emailOn ? this.email.sendEmail(this.emailOf(alert, host, at)).catch((e) => OpResult.fromException(e)) : null,
355
+ telegramOn
356
+ ? this.telegram.sendMessage({
357
+ chatId: textOf(this.settings.telegramChatId),
358
+ text: this.telegramTextOf(alert, host, at),
359
+ parseMode: 'HTML',
360
+ }).catch((e) => OpResult.fromException(e))
361
+ : null,
362
+ ]);
363
+ const channels = {
364
+ email: email ? (email.didSucceed() ? 'sent' : 'failed') : 'off',
365
+ telegram: telegram ? (telegram.didSucceed() ? 'sent' : 'failed') : 'off',
366
+ };
367
+ for (const [name, result] of [
368
+ ['SendGrid', email],
369
+ ['Telegram', telegram],
370
+ ]) {
371
+ if (result && result.didFail()) {
372
+ this.log(`[EMERGENCY] ${name} refused the alert: ${result.getErrorSummary('') || result.getErrorSummary()}`);
373
+ }
374
+ }
375
+ if (channels.email !== 'sent' && channels.telegram !== 'sent') {
376
+ // Not delivered: the next one tries again.
377
+ if (this.claims.get(alert.key) === now) {
378
+ this.claims.delete(alert.key);
379
+ }
380
+ const failed = OpResult.fail(OP_RESULT_CODES.FAILED, [{ status: 'failed', channels }], 'The alert was not delivered by any channel');
381
+ for (const result of [email, telegram]) {
382
+ if (result) {
383
+ failed.mergeErrorsIn(result);
384
+ }
385
+ }
386
+ return failed;
387
+ }
388
+ // Read again just before writing: another key may have been written while this one was in flight.
389
+ memory.write({ ...memory.read(), [alert.key]: now });
390
+ return OpResult.ok([{ status: 'sent', channels }]);
391
+ }
392
+ catch (e) {
393
+ this.log(`[EMERGENCY] the alert could not be sent: ${e?.message ?? e}`);
394
+ return OpResult.fromException(e);
395
+ }
396
+ }
397
+ /**
398
+ * Sends the missing-configuration alert when something critical is missing (APP_NAME is always checked). OK with `[]`
399
+ * when nothing is missing; otherwise what `send` answered. Never throws.
400
+ */
401
+ async checkConfig(config, items = []) {
402
+ const alert = missingConfigAlert(config, items);
403
+ return alert ? this.send(alert) : OpResult.ok([]);
404
+ }
405
+ /**
406
+ * Alerts on an uncaught exception or an unhandled rejection, then exits 1 — the process is in an unknown state after an
407
+ * uncaught error, and a restart is the recovery (what Node would have done without the handler). The exit waits for the
408
+ * alert at most `waitMs`. ⚠ The exit is GUARANTEED, whatever was thrown: a handler that failed after marking itself as
409
+ * exiting would ignore its own error and leave a broken process running for ever.
410
+ */
411
+ installCrashHandlers(proc, waitMs = 10_000) {
412
+ let exiting = false;
413
+ const crash = (kind) => (error) => {
414
+ if (exiting) {
415
+ return;
416
+ }
417
+ exiting = true;
418
+ try {
419
+ const { message, stack } = describeError(error);
420
+ // ⚠ The key names WHICH crash (its message and top frame): one crash must not silence a different one for an hour.
421
+ const fingerprint = createHash('sha256')
422
+ .update(`${message}\n${stack[1] ?? ''}`)
423
+ .digest('hex')
424
+ .slice(0, 12);
425
+ const alert = {
426
+ key: `crash:${kind}:${fingerprint}`,
427
+ subject: `Crashed (${kind}): ${emergencyOneLine(message, 120)}`,
428
+ lines: [message, '', ...stack],
429
+ };
430
+ void Promise.race([this.send(alert), sleep(waitMs)])
431
+ .catch(() => null)
432
+ .finally(() => proc.exit(1));
433
+ }
434
+ catch {
435
+ proc.exit(1);
436
+ }
437
+ };
438
+ proc.on('uncaughtException', crash('uncaughtException'));
439
+ proc.on('unhandledRejection', crash('unhandledRejection'));
440
+ return this;
441
+ }
442
+ }
443
+ /** What an error says, whatever was thrown — `String()` itself throws for some values (`Object.create(null)`). Pure. */
444
+ const describeError = (error) => {
445
+ try {
446
+ const message = error instanceof Error ? String(error.message) : String(error);
447
+ const stack = error instanceof Error && error.stack ? String(error.stack).split('\n').slice(0, 12) : [];
448
+ return { message, stack };
449
+ }
450
+ catch {
451
+ return { message: 'an error that cannot be printed', stack: [] };
452
+ }
453
+ };
454
+ export { EmergencyAlerter };
@@ -0,0 +1,94 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { Logger } from '@sdflc/utils';
3
+ import { BaseExternalApiGatewayPropsInterface, ExternalApiFetch } from '../interfaces';
4
+ /** One outbound HTTP request. */
5
+ export interface ExternalApiRequest {
6
+ url: string;
7
+ method?: string;
8
+ headers?: Record<string, string>;
9
+ /** Sent as JSON (with the JSON content type) unless `body` is given. */
10
+ json?: unknown;
11
+ /** Sent as is (a string, or URLSearchParams for a form). */
12
+ body?: string | URLSearchParams;
13
+ /** Overrides the gateway's timeout for this request. */
14
+ timeoutMs?: number;
15
+ /** Values to scrub out of what this request returns, besides the gateway's own (per-request credentials). */
16
+ secrets?: string[];
17
+ }
18
+ /**
19
+ * What a request answered — the `data` of the OpResult a request returns (on success AND on an HTTP refusal).
20
+ * ⚠ SCRUBBED: every secret of the gateway (and of the request) is replaced by `***` in the body and the headers, and
21
+ * `set-cookie` is dropped — the reply travels outward in the OpResult, and a service can echo a key back.
22
+ */
23
+ export interface ExternalApiReply {
24
+ status: number;
25
+ headers: Record<string, string>;
26
+ /** The parsed JSON body, else the text, else null — at most 64 KB of it. */
27
+ body: any;
28
+ }
29
+ /** The most of a reply that is read: a hostile receiver must not be able to stream until memory runs out. */
30
+ export declare const MAX_REPLY_BYTES: number;
31
+ /** The longest wait a `Retry-After` may ask for and still be retried — longer, and the failure is returned at once. */
32
+ export declare const MAX_RETRY_WAIT_MS = 10000;
33
+ /** The standard OpResult code for an HTTP status that is not a success. Pure. */
34
+ export declare const opResultCodeOfHttpStatus: (status: number) => number;
35
+ declare abstract class BaseExternalApiGateway<TSettings extends Record<string, any> = Record<string, any>> {
36
+ protected logger: Logger;
37
+ protected baseUrl: string;
38
+ protected timeoutMs: number;
39
+ protected retries: number;
40
+ protected retryDelaysMs: number[];
41
+ protected fetchImpl: ExternalApiFetch;
42
+ private _settings;
43
+ private _credentials;
44
+ private _credentialsSet;
45
+ constructor(props?: BaseExternalApiGatewayPropsInterface<TSettings>);
46
+ /**
47
+ * Sets the gateway up. REPLACES whatever was set before (never merges), so re-pointing a shared instance at another
48
+ * tenant keeps nothing of the last one. Never throws: a setting that is missing or malformed is reported by
49
+ * `getConfigProblems()`, and every operation refuses with VALIDATION_FAILED until it is fixed.
50
+ */
51
+ configure(settings: TSettings): this;
52
+ /** What is missing or malformed in the settings, in words — never a value. Empty when the gateway can be used. */
53
+ getConfigProblems(): string[];
54
+ /** True when the settings are complete and well-formed. */
55
+ isConfigured(): boolean;
56
+ /** The current settings. ⚠ They hold secrets: for the gateway itself, never to be logged or returned. */
57
+ protected get settings(): Readonly<Partial<TSettings>>;
58
+ /** What is wrong with these settings (override per gateway). */
59
+ protected validateSettings(_settings: Partial<TSettings>): string[];
60
+ /** The values to scrub out of every error message (override per gateway: keys, tokens, secret URLs). */
61
+ protected secretValues(): string[];
62
+ /** Called after every `configure` (override to rebuild an SDK client). */
63
+ protected onConfigured(): void;
64
+ /** The refusal every operation answers while the gateway is not set up. */
65
+ protected notConfigured(): OpResult;
66
+ /** `text` with every secret of this gateway (and `extra`) replaced by `***`. */
67
+ protected scrub(text: string, extra?: string[]): string;
68
+ /** `value` (a string, or anything JSON) with every secret replaced by `***`. */
69
+ protected scrubValue(value: any, extra?: string[]): any;
70
+ /** The words of a refusal, from the service's answer (override per gateway for its error shape). */
71
+ protected errorMessageOf(reply: ExternalApiReply): string;
72
+ /** Whether a failed attempt is worth repeating (override per gateway to refuse the hopeless ones). */
73
+ protected shouldRetry(result: OpResult): boolean;
74
+ /** How long the service asked us to wait before trying again, in ms (its `Retry-After`), or null. */
75
+ protected retryAfterMs(result: OpResult): number | null;
76
+ /**
77
+ * ONE attempt. OK with `{status, headers, body}` for a 2xx; else the standard code for the status (with the same data,
78
+ * so a gateway can read the service's own error), NETWORK_ERROR or TIMEOUT when nothing answered, VALIDATION_FAILED
79
+ * when the request itself could not be made (a malformed header). The reply is scrubbed and capped. Never throws.
80
+ * Redirects are not followed.
81
+ */
82
+ protected request(req: ExternalApiRequest): Promise<OpResult>;
83
+ /**
84
+ * `request`, repeated while `shouldRetry` says a failure is worth it — after the service's `Retry-After` when it gave
85
+ * one (and not at all when it asks for longer than MAX_RETRY_WAIT_MS), else after the configured waits. Never throws.
86
+ */
87
+ protected requestWithRetries(req: ExternalApiRequest): Promise<OpResult>;
88
+ setCredentials(credentials: string | Record<string, any>): this;
89
+ hasCredentials(): boolean;
90
+ protected get credentials(): string | Record<string, any>;
91
+ protected assertCredentials(): void;
92
+ protected onCredentialsSet(): void;
93
+ }
94
+ export { BaseExternalApiGateway };