@sdflc/backend-helpers 1.0.138 → 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 (58) hide show
  1. package/README.md +176 -20
  2. package/build/BaseGateway.js +18 -2
  3. package/build/EmergencyAlerter.d.ts +140 -0
  4. package/build/EmergencyAlerter.js +465 -0
  5. package/build/esm/BaseGateway.js +18 -2
  6. package/build/esm/EmergencyAlerter.d.ts +140 -0
  7. package/build/esm/EmergencyAlerter.js +454 -0
  8. package/build/esm/gateways/BaseExternalApiGateway.d.ts +94 -0
  9. package/build/esm/gateways/BaseExternalApiGateway.js +319 -0
  10. package/build/esm/gateways/DiscordWebhookGw.d.ts +50 -0
  11. package/build/esm/gateways/DiscordWebhookGw.js +70 -0
  12. package/build/esm/gateways/HttpWebhookGw.d.ts +43 -0
  13. package/build/esm/gateways/HttpWebhookGw.js +131 -0
  14. package/build/esm/gateways/SendGridGw.d.ts +41 -0
  15. package/build/esm/gateways/SendGridGw.js +116 -0
  16. package/build/esm/gateways/SlackWebhookGw.d.ts +23 -0
  17. package/build/esm/gateways/SlackWebhookGw.js +59 -0
  18. package/build/esm/gateways/TelegramGw.d.ts +45 -0
  19. package/build/esm/gateways/TelegramGw.js +110 -0
  20. package/build/esm/gateways/TwilioGw.d.ts +33 -0
  21. package/build/esm/gateways/TwilioGw.js +107 -0
  22. package/build/esm/gateways/externalUrl.d.ts +16 -0
  23. package/build/esm/gateways/externalUrl.js +116 -0
  24. package/build/esm/gateways/guardedFetch.d.ts +15 -0
  25. package/build/esm/gateways/guardedFetch.js +133 -0
  26. package/build/esm/gateways/index.d.ts +9 -0
  27. package/build/esm/gateways/index.js +9 -0
  28. package/build/esm/index.d.ts +2 -1
  29. package/build/esm/index.js +2 -1
  30. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  31. package/build/gateways/BaseExternalApiGateway.d.ts +94 -0
  32. package/build/gateways/BaseExternalApiGateway.js +326 -0
  33. package/build/gateways/DiscordWebhookGw.d.ts +50 -0
  34. package/build/gateways/DiscordWebhookGw.js +73 -0
  35. package/build/gateways/HttpWebhookGw.d.ts +43 -0
  36. package/build/gateways/HttpWebhookGw.js +135 -0
  37. package/build/gateways/SendGridGw.d.ts +41 -0
  38. package/build/gateways/SendGridGw.js +119 -0
  39. package/build/gateways/SlackWebhookGw.d.ts +23 -0
  40. package/build/gateways/SlackWebhookGw.js +62 -0
  41. package/build/gateways/TelegramGw.d.ts +45 -0
  42. package/build/gateways/TelegramGw.js +115 -0
  43. package/build/gateways/TwilioGw.d.ts +33 -0
  44. package/build/gateways/TwilioGw.js +110 -0
  45. package/build/gateways/externalUrl.d.ts +16 -0
  46. package/build/gateways/externalUrl.js +121 -0
  47. package/build/gateways/guardedFetch.d.ts +15 -0
  48. package/build/gateways/guardedFetch.js +141 -0
  49. package/build/gateways/index.d.ts +9 -0
  50. package/build/gateways/index.js +25 -0
  51. package/build/index.d.ts +2 -1
  52. package/build/index.js +2 -1
  53. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  54. package/package.json +2 -1
  55. package/build/BaseExternalApiGateway.d.ts +0 -16
  56. package/build/BaseExternalApiGateway.js +0 -54
  57. package/build/esm/BaseExternalApiGateway.d.ts +0 -16
  58. package/build/esm/BaseExternalApiGateway.js +0 -48
@@ -0,0 +1,465 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.EmergencyAlerter = exports.emergencyFileMemory = exports.missingConfigAlert = exports.missingCriticalConfig = exports.emergencyIntervalText = exports.emergencyOneLine = exports.APP_NAME_CONFIG = exports.UNKNOWN_APP_NAME = void 0;
7
+ // ./src/EmergencyAlerter.ts
8
+ //
9
+ // An EMERGENCY alert a service sends BY ITSELF — for what nobody would otherwise notice until somebody trips over it: a
10
+ // missing configuration value, a crash. It sends through the library's gateways (./gateways — SendGridGw for email,
11
+ // TelegramGw for Telegram); this class decides WHAT is said, to WHOM, and HOW OFTEN — never how it travels.
12
+ //
13
+ // const alerter = EmergencyAlerter.fromConfig(config, 'ms_storage', { log: (m) => logger.error(m) });
14
+ // alerter.installCrashHandlers(process);
15
+ // … after the server listens: await alerter.checkConfig(config, CRITICAL_CONFIG);
16
+ //
17
+ // Every alert names its app, service and environment — `[partylabz · ms_storage · production]` — because several apps
18
+ // run the same services side by side on one machine, and "ms_storage crashed" alone does not say whose.
19
+ //
20
+ // ⚠ It goes STRAIGHT to the providers, never through another service of ours: it has to work when the rest does not.
21
+ // ⚠ It never throws, and every operation answers an OpResult.
22
+ // ⚠ One alert per KEY per interval (default an hour) across ALL channels, remembered in a file under the OS temp folder
23
+ // named after the app and service — so a crash loop, where every restart is a fresh process, sends one message, not one
24
+ // per restart. Sends of the same key AT ONCE go out once (claimed before the network call). It counts as sent when ANY
25
+ // channel delivered it; a send that failed everywhere is not remembered, so the next one tries again.
26
+ // ⚠ Never put a secret, a token or a database row into an alert: it leaves our infrastructure.
27
+ //
28
+ // The settings `fromConfig` reads (env names as in .env; all optional — each channel needs all of its own):
29
+ // APP_NAME — the app this service belongs to (alerts say 'unknown-app' without it)
30
+ // EMERGENCY_SENDGRID_API_KEY — email: a SendGrid key allowed to send mail
31
+ // EMERGENCY_EMAIL_FROM — email: an address on a domain authenticated in that SendGrid account
32
+ // EMERGENCY_EMAIL_TO — email: where alerts go; several addresses separated by commas
33
+ // TELEGRAM_BOT_ID — Telegram: the bot's token (`<id>:<secret>`, from @BotFather)
34
+ // TELEGRAM_CHAT_ID — Telegram: the chat the bot writes to (the bot must be in it)
35
+ // EMERGENCY_EMAIL_MIN_INTERVAL_MINUTES — the same alert at most once per this many minutes, every channel (default 60)
36
+ const crypto_1 = require("crypto");
37
+ const fs_1 = __importDefault(require("fs"));
38
+ const os_1 = __importDefault(require("os"));
39
+ const path_1 = __importDefault(require("path"));
40
+ const promises_1 = require("timers/promises");
41
+ const lodash_1 = require("lodash");
42
+ const api_helpers_1 = require("@sdflc/api-helpers");
43
+ const SendGridGw_1 = require("./gateways/SendGridGw");
44
+ const TelegramGw_1 = require("./gateways/TelegramGw");
45
+ /** What an alert says when APP_NAME is not set. */
46
+ exports.UNKNOWN_APP_NAME = 'unknown-app';
47
+ /** Checked in every service: without it no alert can say which app it comes from. */
48
+ exports.APP_NAME_CONFIG = {
49
+ env: 'APP_NAME',
50
+ effect: `Emergency alerts cannot say which app they come from (they say '${exports.UNKNOWN_APP_NAME}').`,
51
+ };
52
+ const textOf = (value) => (value === undefined || value === null ? '' : String(value)).trim();
53
+ /**
54
+ * One line of at most `max` characters: line breaks, tabs and other control characters become spaces, runs of spaces one.
55
+ * ⚠ For every SUBJECT and label part — a crash's subject is the error's message, which often spans lines, and a line
56
+ * break in a mail subject or the Telegram heading breaks it. Pure.
57
+ */
58
+ const emergencyOneLine = (value, max) => Array.from(textOf(value))
59
+ .map((char) => (char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127 ? ' ' : char))
60
+ .join('')
61
+ .replace(/\s+/g, ' ')
62
+ .trim()
63
+ .slice(0, max);
64
+ exports.emergencyOneLine = emergencyOneLine;
65
+ /** `15 minutes`, `30 seconds` — how long the same alert stays quiet. Pure. */
66
+ const emergencyIntervalText = (ms) => ms < 60_000 ? `${Math.round(ms / 1000)} seconds` : `${Math.round(ms / 60_000)} minutes`;
67
+ exports.emergencyIntervalText = emergencyIntervalText;
68
+ /** The critical values that are missing (unset or blank) — APP_NAME always among those checked. Pure. */
69
+ const missingCriticalConfig = (config, items = []) => [...items, exports.APP_NAME_CONFIG]
70
+ .map((item) => ({ ...item, key: item.key || (0, lodash_1.camelCase)(item.env) }))
71
+ .filter((item, index, all) => all.findIndex((other) => other.key === item.key) === index)
72
+ // ⚠ buildConfig turns 'false'/'0' into false: a value of false is SET (textOf gives 'false'); only absent or blank is
73
+ // missing — a falsy test would report it.
74
+ .filter((item) => textOf(config?.[item.key]) === '')
75
+ .map(({ env, effect }) => ({ env, effect }));
76
+ exports.missingCriticalConfig = missingCriticalConfig;
77
+ /** The alert for missing configuration, or null when nothing is missing. Pure. */
78
+ const missingConfigAlert = (config, items = []) => {
79
+ const missing = (0, exports.missingCriticalConfig)(config, items);
80
+ if (missing.length === 0) {
81
+ return null;
82
+ }
83
+ return {
84
+ key: `config:${missing.map((one) => one.env).join(',')}`,
85
+ subject: `Started with missing configuration: ${missing.map((one) => one.env).join(', ')}`,
86
+ lines: [
87
+ 'The service started and is answering, but these values are not set:',
88
+ ...missing.map((one) => `• ${one.env} — ${one.effect}`),
89
+ 'Set them in the service environment and restart it.',
90
+ ],
91
+ };
92
+ };
93
+ exports.missingConfigAlert = missingConfigAlert;
94
+ const escapeHtml = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
95
+ /** Kept under Telegram's 4096 with room to spare (it counts after parsing; we count before). */
96
+ const TELEGRAM_TEXT_MAX = Math.min(4000, TelegramGw_1.TELEGRAM_MAX_MESSAGE_LENGTH);
97
+ const CUT_MARK = '\n… (cut)';
98
+ /** The longest start of `text` whose ESCAPED form fits `budget` — never splitting a surrogate pair. Pure. */
99
+ const escapedPrefix = (text, budget) => {
100
+ let low = 0;
101
+ let high = text.length;
102
+ // Escaping only lengthens, so the escaped length grows with the prefix: a binary search finds the longest that fits.
103
+ while (low < high) {
104
+ const middle = Math.ceil((low + high) / 2);
105
+ if (escapeHtml(text.slice(0, middle)).length <= budget) {
106
+ low = middle;
107
+ }
108
+ else {
109
+ high = middle - 1;
110
+ }
111
+ }
112
+ const code = text.charCodeAt(low - 1);
113
+ const keep = low > 0 && code >= 0xd800 && code <= 0xdbff ? low - 1 : low;
114
+ return escapeHtml(text.slice(0, keep));
115
+ };
116
+ /** The memory in a file under the OS temp folder, one per app AND service (several may share a temp folder). */
117
+ const emergencyFileMemory = (appName, serviceName, dir = os_1.default.tmpdir()) => {
118
+ const safe = (name) => name.replace(/[^A-Za-z0-9_.-]/g, '_');
119
+ const file = path_1.default.join(dir, `${safe(appName)}-${safe(serviceName)}-emergency-alerts.json`);
120
+ return {
121
+ read: () => {
122
+ try {
123
+ return JSON.parse(fs_1.default.readFileSync(file, 'utf8')) || {};
124
+ }
125
+ catch {
126
+ return {};
127
+ }
128
+ },
129
+ write: (sent) => {
130
+ try {
131
+ fs_1.default.writeFileSync(file, JSON.stringify(sent));
132
+ }
133
+ catch {
134
+ // A read-only temp folder costs the interval, not the alert.
135
+ }
136
+ },
137
+ };
138
+ };
139
+ exports.emergencyFileMemory = emergencyFileMemory;
140
+ /** One provider call's budget in `fromConfig` — both channels together fit the crash wait (10 s). */
141
+ const PROVIDER_TIMEOUT_MS = 4000;
142
+ class EmergencyAlerter {
143
+ settings = { serviceName: 'unknown-service' };
144
+ email;
145
+ telegram;
146
+ log;
147
+ redact;
148
+ memoryOverride;
149
+ now;
150
+ hostname;
151
+ /** Keys being sent right now → when they were claimed. */
152
+ claims = new Map();
153
+ constructor(props = {}) {
154
+ this.email = props.email ?? null;
155
+ this.telegram = props.telegram ?? null;
156
+ const log = props.log ?? ((message) => console.error(message));
157
+ // ⚠ A log that throws must not make `send` throw: the alerter is what runs when everything else is broken.
158
+ this.log = (message) => {
159
+ try {
160
+ log(message);
161
+ }
162
+ catch {
163
+ // Nowhere left to say it.
164
+ }
165
+ };
166
+ const redact = props.redact ?? ((text) => text);
167
+ this.redact = (text) => {
168
+ try {
169
+ return String(redact(String(text ?? '')));
170
+ }
171
+ catch {
172
+ return '[redacted: the redact hook failed]';
173
+ }
174
+ };
175
+ this.memoryOverride = props.memory ?? null;
176
+ this.now = props.now ?? (() => Date.now());
177
+ this.hostname = props.hostname ?? (() => os_1.default.hostname());
178
+ if (props.settings) {
179
+ this.configure(props.settings);
180
+ }
181
+ }
182
+ /**
183
+ * One service's alerter from its built config (buildConfig) — the gateways created and configured from the env names in
184
+ * the file header, with a short timeout so a crash's alert fits its wait. Says once, through `log`, when a channel was
185
+ * set up but cannot be used.
186
+ */
187
+ static fromConfig(config, serviceName, props = {}) {
188
+ const gatewayProps = { timeoutMs: PROVIDER_TIMEOUT_MS, retries: 1, retryDelaysMs: [500] };
189
+ const raw = config?.emergencyEmailMinIntervalMinutes;
190
+ // ⚠ buildConfig turns '0' into false and '1' into true — Number() reads them back as 0 and 1.
191
+ const minutes = textOf(raw) === '' ? NaN : Number(raw);
192
+ // Every config value whose NAME looks secret, longest first — removed from whatever an alert says.
193
+ const secrets = Object.entries(config ?? {})
194
+ .filter(([key, value]) => /secret|password|passwd|token|apikey|api_key|botid|credential|connectionstring|dsn|key$/i.test(key) &&
195
+ typeof value === 'string' &&
196
+ value.trim().length >= 8)
197
+ .map(([, value]) => String(value))
198
+ .sort((a, b) => b.length - a.length);
199
+ const scrubSecrets = (text) => secrets.reduce((out, secret) => out.split(secret).join('***'), text);
200
+ const alerter = new EmergencyAlerter({
201
+ ...props,
202
+ redact: props.redact ? (text) => props.redact(scrubSecrets(text)) : scrubSecrets,
203
+ email: textOf(config?.emergencySendgridApiKey)
204
+ ? new SendGridGw_1.SendGridGw(gatewayProps).configure({ apiKey: textOf(config.emergencySendgridApiKey) })
205
+ : null,
206
+ telegram: textOf(config?.telegramBotId)
207
+ ? new TelegramGw_1.TelegramGw(gatewayProps).configure({ botToken: textOf(config.telegramBotId) })
208
+ : null,
209
+ settings: {
210
+ appName: textOf(config?.appName),
211
+ serviceName,
212
+ environment: textOf(config?.nodeEnv),
213
+ minIntervalMinutes: Number.isFinite(minutes) && minutes >= 0 ? minutes : undefined,
214
+ emailTo: textOf(config?.emergencyEmailTo)
215
+ .split(',')
216
+ .map((one) => one.trim())
217
+ .filter(Boolean),
218
+ emailFrom: textOf(config?.emergencyEmailFrom),
219
+ telegramChatId: textOf(config?.telegramChatId),
220
+ },
221
+ });
222
+ const emailTouched = ['emergencySendgridApiKey', 'emergencyEmailTo', 'emergencyEmailFrom'].some((key) => textOf(config?.[key]));
223
+ const telegramTouched = ['telegramBotId', 'telegramChatId'].some((key) => textOf(config?.[key]));
224
+ for (const problem of alerter.getChannelProblems()) {
225
+ if ((problem.startsWith('Email') && emailTouched) || (problem.startsWith('Telegram') && telegramTouched)) {
226
+ alerter.log(`[EMERGENCY] ${problem}`);
227
+ }
228
+ }
229
+ return alerter;
230
+ }
231
+ /** Sets the alerter up. REPLACES what was set before. Never throws. */
232
+ configure(settings) {
233
+ this.settings = { ...settings };
234
+ this.claims.clear();
235
+ return this;
236
+ }
237
+ /** Sends email through this gateway (configured with its API key), or not at all (null). */
238
+ useEmail(gateway) {
239
+ this.email = gateway;
240
+ return this;
241
+ }
242
+ /** Sends to Telegram through this gateway (configured with its bot token), or not at all (null). */
243
+ useTelegram(gateway) {
244
+ this.telegram = gateway;
245
+ return this;
246
+ }
247
+ getAppName() {
248
+ return (0, exports.emergencyOneLine)(this.settings.appName, 64) || exports.UNKNOWN_APP_NAME;
249
+ }
250
+ /** `eventsmagic · ms_auth · production` — who is raising the alerts. */
251
+ getLabel() {
252
+ const service = (0, exports.emergencyOneLine)(this.settings.serviceName, 64) || 'unknown-service';
253
+ const environment = (0, exports.emergencyOneLine)(this.settings.environment, 32) || 'unknown';
254
+ return `${this.getAppName()} · ${service} · ${environment}`;
255
+ }
256
+ getMinIntervalMs() {
257
+ const minutes = Number(this.settings.minIntervalMinutes);
258
+ return (Number.isFinite(minutes) && minutes >= 0 ? minutes : 60) * 60_000;
259
+ }
260
+ /** Why each channel cannot be used, in words (never a value). Empty when both can. */
261
+ getChannelProblems() {
262
+ const problems = [];
263
+ const emailTo = (this.settings.emailTo ?? []).filter((one) => String(one).includes('@'));
264
+ if (!this.email) {
265
+ problems.push('Email is not used: no SendGrid API key (EMERGENCY_SENDGRID_API_KEY).');
266
+ }
267
+ else if (!this.email.isConfigured()) {
268
+ problems.push(`Email is not used: ${this.email.getConfigProblems().join('; ')}.`);
269
+ }
270
+ else if (emailTo.length === 0) {
271
+ problems.push('Email is not used: no recipient (EMERGENCY_EMAIL_TO).');
272
+ }
273
+ else if (!textOf(this.settings.emailFrom).includes('@')) {
274
+ problems.push('Email is not used: no sender (EMERGENCY_EMAIL_FROM — a guessed one is refused by SendGrid).');
275
+ }
276
+ if (!this.telegram) {
277
+ problems.push('Telegram is not used: no bot token (TELEGRAM_BOT_ID).');
278
+ }
279
+ else if (!this.telegram.isConfigured()) {
280
+ problems.push(`Telegram is not used: ${this.telegram.getConfigProblems().join('; ')}.`);
281
+ }
282
+ else if (!(0, TelegramGw_1.isTelegramChatId)(this.settings.telegramChatId)) {
283
+ problems.push('Telegram is not used: no chat, or a malformed one (TELEGRAM_CHAT_ID).');
284
+ }
285
+ return problems;
286
+ }
287
+ /** The email for one alert. */
288
+ emailOf(alert, host, at) {
289
+ return {
290
+ to: (this.settings.emailTo ?? []).filter((one) => String(one).includes('@')),
291
+ from: {
292
+ email: textOf(this.settings.emailFrom),
293
+ name: `${this.getAppName()} ${(0, exports.emergencyOneLine)(this.settings.serviceName, 64)} alerts`,
294
+ },
295
+ subject: `[${this.getLabel()}] ${(0, exports.emergencyOneLine)(alert.subject, 200)}`,
296
+ text: [
297
+ alert.subject,
298
+ '',
299
+ ...alert.lines,
300
+ '',
301
+ `${this.getLabel()} · host: ${host}`,
302
+ `When: ${at.toISOString()}`,
303
+ `The same alert is not sent again for ${(0, exports.emergencyIntervalText)(this.getMinIntervalMs())}.`,
304
+ ].join('\n'),
305
+ };
306
+ }
307
+ /**
308
+ * The Telegram message for one alert (HTML), always under Telegram's limit. ⚠ The text is cut BEFORE it is escaped and
309
+ * wrapped, to what the heading and footer leave: cutting finished HTML can split an entity, and Telegram then refuses
310
+ * the whole message — a long stack trace would silence exactly the crash it reports.
311
+ */
312
+ telegramTextOf(alert, host, at) {
313
+ const heading = `🔴 <b>[${escapeHtml(this.getLabel())}] ${escapeHtml((0, exports.emergencyOneLine)(alert.subject, 200))}</b>`;
314
+ const footer = [
315
+ `🖥 ${escapeHtml((0, exports.emergencyOneLine)(host, 100))} · ${at.toISOString()}`,
316
+ `<i>The same alert is not sent again for ${(0, exports.emergencyIntervalText)(this.getMinIntervalMs())}.</i>`,
317
+ ].join('\n');
318
+ const wrap = (block) => [heading, '', `<pre>${block}</pre>`, '', footer].join('\n');
319
+ const body = alert.lines.join('\n');
320
+ const whole = escapeHtml(body);
321
+ if (wrap(whole).length <= TELEGRAM_TEXT_MAX) {
322
+ return wrap(whole);
323
+ }
324
+ const budget = Math.max(0, TELEGRAM_TEXT_MAX - wrap('').length - CUT_MARK.length);
325
+ return wrap(`${escapedPrefix(body, budget)}${CUT_MARK}`);
326
+ }
327
+ memory() {
328
+ return (this.memoryOverride ??
329
+ (0, exports.emergencyFileMemory)(this.getAppName(), (0, exports.emergencyOneLine)(this.settings.serviceName, 64) || 'unknown-service'));
330
+ }
331
+ /**
332
+ * Sends one alert. ALWAYS logs it; sends it to every usable channel unless the same key went out within the interval.
333
+ * OK with `{ status: 'sent', channels }` or `{ status: 'recently-sent' }`; VALIDATION_FAILED when no channel can be
334
+ * used; FAILED (every channel's error merged in) when none delivered it. Never throws.
335
+ */
336
+ async send(given) {
337
+ try {
338
+ const alert = {
339
+ key: String(given?.key ?? 'alert'),
340
+ subject: this.redact(given?.subject ?? ''),
341
+ lines: (Array.isArray(given?.lines) ? given.lines : []).map((line) => this.redact(line)),
342
+ };
343
+ this.log(`[EMERGENCY] [${this.getLabel()}] ${(0, exports.emergencyOneLine)(alert.subject, 200)} — ${alert.lines.join(' | ')}`);
344
+ const problems = this.getChannelProblems();
345
+ const emailOn = !problems.some((one) => one.startsWith('Email'));
346
+ const telegramOn = !problems.some((one) => one.startsWith('Telegram'));
347
+ if (!emailOn && !telegramOn) {
348
+ this.log(`[EMERGENCY] not sent: ${problems.join(' ')}`);
349
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, [{ status: 'unconfigured' }], 'No emergency channel can be used');
350
+ }
351
+ const memory = this.memory();
352
+ const now = this.now();
353
+ // ⚠ A time AFTER now (a clock moved back, a hand-edited file) is stale — it must not silence alerts until then.
354
+ const remembered = Number(memory.read()[alert.key]) || 0;
355
+ const last = Math.max(remembered <= now ? remembered : 0, this.claims.get(alert.key) ?? 0);
356
+ if (last > 0 && now - last < this.getMinIntervalMs()) {
357
+ return api_helpers_1.OpResult.ok([{ status: 'recently-sent' }]);
358
+ }
359
+ // Claimed BEFORE the first await, so a second send of the same key meanwhile finds it.
360
+ this.claims.set(alert.key, now);
361
+ const host = this.hostname();
362
+ const at = new Date(now);
363
+ // Both at once: a crash waits for the alert only a few seconds before the process exits.
364
+ const [email, telegram] = await Promise.all([
365
+ emailOn ? this.email.sendEmail(this.emailOf(alert, host, at)).catch((e) => api_helpers_1.OpResult.fromException(e)) : null,
366
+ telegramOn
367
+ ? this.telegram.sendMessage({
368
+ chatId: textOf(this.settings.telegramChatId),
369
+ text: this.telegramTextOf(alert, host, at),
370
+ parseMode: 'HTML',
371
+ }).catch((e) => api_helpers_1.OpResult.fromException(e))
372
+ : null,
373
+ ]);
374
+ const channels = {
375
+ email: email ? (email.didSucceed() ? 'sent' : 'failed') : 'off',
376
+ telegram: telegram ? (telegram.didSucceed() ? 'sent' : 'failed') : 'off',
377
+ };
378
+ for (const [name, result] of [
379
+ ['SendGrid', email],
380
+ ['Telegram', telegram],
381
+ ]) {
382
+ if (result && result.didFail()) {
383
+ this.log(`[EMERGENCY] ${name} refused the alert: ${result.getErrorSummary('') || result.getErrorSummary()}`);
384
+ }
385
+ }
386
+ if (channels.email !== 'sent' && channels.telegram !== 'sent') {
387
+ // Not delivered: the next one tries again.
388
+ if (this.claims.get(alert.key) === now) {
389
+ this.claims.delete(alert.key);
390
+ }
391
+ const failed = api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.FAILED, [{ status: 'failed', channels }], 'The alert was not delivered by any channel');
392
+ for (const result of [email, telegram]) {
393
+ if (result) {
394
+ failed.mergeErrorsIn(result);
395
+ }
396
+ }
397
+ return failed;
398
+ }
399
+ // Read again just before writing: another key may have been written while this one was in flight.
400
+ memory.write({ ...memory.read(), [alert.key]: now });
401
+ return api_helpers_1.OpResult.ok([{ status: 'sent', channels }]);
402
+ }
403
+ catch (e) {
404
+ this.log(`[EMERGENCY] the alert could not be sent: ${e?.message ?? e}`);
405
+ return api_helpers_1.OpResult.fromException(e);
406
+ }
407
+ }
408
+ /**
409
+ * Sends the missing-configuration alert when something critical is missing (APP_NAME is always checked). OK with `[]`
410
+ * when nothing is missing; otherwise what `send` answered. Never throws.
411
+ */
412
+ async checkConfig(config, items = []) {
413
+ const alert = (0, exports.missingConfigAlert)(config, items);
414
+ return alert ? this.send(alert) : api_helpers_1.OpResult.ok([]);
415
+ }
416
+ /**
417
+ * Alerts on an uncaught exception or an unhandled rejection, then exits 1 — the process is in an unknown state after an
418
+ * uncaught error, and a restart is the recovery (what Node would have done without the handler). The exit waits for the
419
+ * alert at most `waitMs`. ⚠ The exit is GUARANTEED, whatever was thrown: a handler that failed after marking itself as
420
+ * exiting would ignore its own error and leave a broken process running for ever.
421
+ */
422
+ installCrashHandlers(proc, waitMs = 10_000) {
423
+ let exiting = false;
424
+ const crash = (kind) => (error) => {
425
+ if (exiting) {
426
+ return;
427
+ }
428
+ exiting = true;
429
+ try {
430
+ const { message, stack } = describeError(error);
431
+ // ⚠ The key names WHICH crash (its message and top frame): one crash must not silence a different one for an hour.
432
+ const fingerprint = (0, crypto_1.createHash)('sha256')
433
+ .update(`${message}\n${stack[1] ?? ''}`)
434
+ .digest('hex')
435
+ .slice(0, 12);
436
+ const alert = {
437
+ key: `crash:${kind}:${fingerprint}`,
438
+ subject: `Crashed (${kind}): ${(0, exports.emergencyOneLine)(message, 120)}`,
439
+ lines: [message, '', ...stack],
440
+ };
441
+ void Promise.race([this.send(alert), (0, promises_1.setTimeout)(waitMs)])
442
+ .catch(() => null)
443
+ .finally(() => proc.exit(1));
444
+ }
445
+ catch {
446
+ proc.exit(1);
447
+ }
448
+ };
449
+ proc.on('uncaughtException', crash('uncaughtException'));
450
+ proc.on('unhandledRejection', crash('unhandledRejection'));
451
+ return this;
452
+ }
453
+ }
454
+ exports.EmergencyAlerter = EmergencyAlerter;
455
+ /** What an error says, whatever was thrown — `String()` itself throws for some values (`Object.create(null)`). Pure. */
456
+ const describeError = (error) => {
457
+ try {
458
+ const message = error instanceof Error ? String(error.message) : String(error);
459
+ const stack = error instanceof Error && error.stack ? String(error.stack).split('\n').slice(0, 12) : [];
460
+ return { message, stack };
461
+ }
462
+ catch {
463
+ return { message: 'an error that cannot be printed', stack: [] };
464
+ }
465
+ };
@@ -1224,10 +1224,26 @@ class BaseGateway {
1224
1224
  if (!args || objects.length === 0) {
1225
1225
  return [];
1226
1226
  }
1227
+ // The framework's OWN id is applied AFTER transformOnCreate, never through it.
1228
+ // transformOnCreate strips `id` — deliberately, so a CALLER-supplied id is never
1229
+ // honoured — and it cannot tell the caller's id from ours once both are merged into
1230
+ // one payload. Passing the generated id in that payload (as this did until now) meant
1231
+ // the strip deleted the id we had just made: `generateId()` became inert, every insert
1232
+ // silently fell back to the column's own default, and every create logged
1233
+ // `field "id" is not writable on create and was stripped from the payload`.
1234
+ // A caller id is still dropped — it is stripped before we get here.
1235
+ // Mirrors what `set()` below already does, and restores the pre-1.0.135 insert payload
1236
+ // (the strip landed in 1.0.135 and started swallowing this id).
1237
+ const idField = String(this.getIdField()).split('.').pop();
1227
1238
  for (let idx = 0, len = objects.length; idx < len; ++idx) {
1228
1239
  const object = objects[idx];
1229
- const id = await this.generateId(object);
1230
- objects[idx] = await this.transformOnCreate({ id, ...object });
1240
+ const transformed = await this.transformOnCreate({ ...object });
1241
+ // Only when nothing else has set it — `hasLang` + `localizationForField` builds a
1242
+ // COMPOSITE id in transformOnCreate, and that one must stand.
1243
+ if (transformed[idField] == null) {
1244
+ transformed[idField] = await this.generateId(object);
1245
+ }
1246
+ objects[idx] = transformed;
1231
1247
  }
1232
1248
  const result = [];
1233
1249
  const chunks = arrToChunks(objects, this.config?.insertChunkSize || DEFAULT_CHUNCK_SIZE);
@@ -0,0 +1,140 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { SendGridGw, SendGridEmail } from './gateways/SendGridGw';
3
+ import { TelegramGw } from './gateways/TelegramGw';
4
+ /** What an alert says when APP_NAME is not set. */
5
+ export declare const UNKNOWN_APP_NAME = "unknown-app";
6
+ export interface EmergencyAlert {
7
+ /** What makes two alerts "the same" for the interval: `config:INTERSERVICE_API_KEY`, `crash:uncaughtException`, … */
8
+ key: string;
9
+ subject: string;
10
+ lines: string[];
11
+ }
12
+ /** A setting a service starts WITHOUT (it is optional to the config loader) but cannot fully work without. */
13
+ export interface CriticalConfigItem {
14
+ /** The env name, as written in .env: `INTERSERVICE_API_KEY` */
15
+ env: string;
16
+ /** The key in the built config; derived from `env` (`interserviceApiKey`) when omitted — omit it: a typo here is an
17
+ * item that is always reported missing. */
18
+ key?: string;
19
+ /** What stops working without it, in a sentence a person on call understands. */
20
+ effect: string;
21
+ }
22
+ /** Checked in every service: without it no alert can say which app it comes from. */
23
+ export declare const APP_NAME_CONFIG: CriticalConfigItem;
24
+ export interface EmergencyAlerterSettings {
25
+ /** The app this service belongs to; 'unknown-app' when blank. */
26
+ appName?: string;
27
+ /** `ms_auth`, `ms_storage`, … — fixed per service, in its code. */
28
+ serviceName: string;
29
+ environment?: string;
30
+ /** The same alert at most once per this many minutes, every channel. Default 60; 0 = every alert. */
31
+ minIntervalMinutes?: number;
32
+ /** Email: where alerts go. */
33
+ emailTo?: string[];
34
+ /** Email: the sender — on a domain authenticated in the SendGrid account (a guessed one is refused). */
35
+ emailFrom?: string;
36
+ /** Telegram: the chat the bot writes to. */
37
+ telegramChatId?: string;
38
+ }
39
+ /** What the alerter remembers between processes: when each key was last sent (epoch ms). */
40
+ export interface EmergencyAlertMemory {
41
+ read: () => Record<string, number>;
42
+ write: (sent: Record<string, number>) => void;
43
+ }
44
+ export interface EmergencyAlerterProps {
45
+ settings?: EmergencyAlerterSettings;
46
+ /** A configured SendGridGw (its API key), or none. */
47
+ email?: SendGridGw | null;
48
+ /** A configured TelegramGw (its bot token), or none. */
49
+ telegram?: TelegramGw | null;
50
+ /** Where the alerter's own lines go — every alert is logged, delivered or not. Default console.error. */
51
+ log?: (message: string) => void;
52
+ /** Tests replace the memory, the clock and the host name. */
53
+ memory?: EmergencyAlertMemory;
54
+ /**
55
+ * Applied to every subject and line before it leaves (email, Telegram, the log): an error message can carry SQL with
56
+ * its values, or a connection string. `fromConfig` already removes every config value whose NAME looks secret.
57
+ */
58
+ redact?: (text: string) => string;
59
+ now?: () => number;
60
+ hostname?: () => string;
61
+ }
62
+ /**
63
+ * One line of at most `max` characters: line breaks, tabs and other control characters become spaces, runs of spaces one.
64
+ * ⚠ For every SUBJECT and label part — a crash's subject is the error's message, which often spans lines, and a line
65
+ * break in a mail subject or the Telegram heading breaks it. Pure.
66
+ */
67
+ export declare const emergencyOneLine: (value: any, max: number) => string;
68
+ /** `15 minutes`, `30 seconds` — how long the same alert stays quiet. Pure. */
69
+ export declare const emergencyIntervalText: (ms: number) => string;
70
+ /** The critical values that are missing (unset or blank) — APP_NAME always among those checked. Pure. */
71
+ export declare const missingCriticalConfig: (config: any, items?: CriticalConfigItem[]) => Array<{
72
+ env: string;
73
+ effect: string;
74
+ }>;
75
+ /** The alert for missing configuration, or null when nothing is missing. Pure. */
76
+ export declare const missingConfigAlert: (config: any, items?: CriticalConfigItem[]) => EmergencyAlert | null;
77
+ /** The memory in a file under the OS temp folder, one per app AND service (several may share a temp folder). */
78
+ export declare const emergencyFileMemory: (appName: string, serviceName: string, dir?: string) => EmergencyAlertMemory;
79
+ declare class EmergencyAlerter {
80
+ private settings;
81
+ private email;
82
+ private telegram;
83
+ private log;
84
+ private redact;
85
+ private memoryOverride;
86
+ private now;
87
+ private hostname;
88
+ /** Keys being sent right now → when they were claimed. */
89
+ private claims;
90
+ constructor(props?: EmergencyAlerterProps);
91
+ /**
92
+ * One service's alerter from its built config (buildConfig) — the gateways created and configured from the env names in
93
+ * the file header, with a short timeout so a crash's alert fits its wait. Says once, through `log`, when a channel was
94
+ * set up but cannot be used.
95
+ */
96
+ static fromConfig(config: any, serviceName: string, props?: Omit<EmergencyAlerterProps, 'settings' | 'email' | 'telegram'>): EmergencyAlerter;
97
+ /** Sets the alerter up. REPLACES what was set before. Never throws. */
98
+ configure(settings: EmergencyAlerterSettings): this;
99
+ /** Sends email through this gateway (configured with its API key), or not at all (null). */
100
+ useEmail(gateway: SendGridGw | null): this;
101
+ /** Sends to Telegram through this gateway (configured with its bot token), or not at all (null). */
102
+ useTelegram(gateway: TelegramGw | null): this;
103
+ getAppName(): string;
104
+ /** `eventsmagic · ms_auth · production` — who is raising the alerts. */
105
+ getLabel(): string;
106
+ getMinIntervalMs(): number;
107
+ /** Why each channel cannot be used, in words (never a value). Empty when both can. */
108
+ getChannelProblems(): string[];
109
+ /** The email for one alert. */
110
+ emailOf(alert: EmergencyAlert, host: string, at: Date): SendGridEmail;
111
+ /**
112
+ * The Telegram message for one alert (HTML), always under Telegram's limit. ⚠ The text is cut BEFORE it is escaped and
113
+ * wrapped, to what the heading and footer leave: cutting finished HTML can split an entity, and Telegram then refuses
114
+ * the whole message — a long stack trace would silence exactly the crash it reports.
115
+ */
116
+ telegramTextOf(alert: EmergencyAlert, host: string, at: Date): string;
117
+ private memory;
118
+ /**
119
+ * Sends one alert. ALWAYS logs it; sends it to every usable channel unless the same key went out within the interval.
120
+ * OK with `{ status: 'sent', channels }` or `{ status: 'recently-sent' }`; VALIDATION_FAILED when no channel can be
121
+ * used; FAILED (every channel's error merged in) when none delivered it. Never throws.
122
+ */
123
+ send(given: EmergencyAlert): Promise<OpResult>;
124
+ /**
125
+ * Sends the missing-configuration alert when something critical is missing (APP_NAME is always checked). OK with `[]`
126
+ * when nothing is missing; otherwise what `send` answered. Never throws.
127
+ */
128
+ checkConfig(config: any, items?: CriticalConfigItem[]): Promise<OpResult>;
129
+ /**
130
+ * Alerts on an uncaught exception or an unhandled rejection, then exits 1 — the process is in an unknown state after an
131
+ * uncaught error, and a restart is the recovery (what Node would have done without the handler). The exit waits for the
132
+ * alert at most `waitMs`. ⚠ The exit is GUARANTEED, whatever was thrown: a handler that failed after marking itself as
133
+ * exiting would ignore its own error and leave a broken process running for ever.
134
+ */
135
+ installCrashHandlers(proc: {
136
+ on: (event: string, handler: (...args: any[]) => void) => any;
137
+ exit: (code: number) => any;
138
+ }, waitMs?: number): this;
139
+ }
140
+ export { EmergencyAlerter };