@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.
- package/README.md +176 -20
- package/build/BaseGateway.js +18 -2
- package/build/EmergencyAlerter.d.ts +140 -0
- package/build/EmergencyAlerter.js +465 -0
- package/build/esm/BaseGateway.js +18 -2
- package/build/esm/EmergencyAlerter.d.ts +140 -0
- package/build/esm/EmergencyAlerter.js +454 -0
- package/build/esm/gateways/BaseExternalApiGateway.d.ts +94 -0
- package/build/esm/gateways/BaseExternalApiGateway.js +319 -0
- package/build/esm/gateways/DiscordWebhookGw.d.ts +50 -0
- package/build/esm/gateways/DiscordWebhookGw.js +70 -0
- package/build/esm/gateways/HttpWebhookGw.d.ts +43 -0
- package/build/esm/gateways/HttpWebhookGw.js +131 -0
- package/build/esm/gateways/SendGridGw.d.ts +41 -0
- package/build/esm/gateways/SendGridGw.js +116 -0
- package/build/esm/gateways/SlackWebhookGw.d.ts +23 -0
- package/build/esm/gateways/SlackWebhookGw.js +59 -0
- package/build/esm/gateways/TelegramGw.d.ts +45 -0
- package/build/esm/gateways/TelegramGw.js +110 -0
- package/build/esm/gateways/TwilioGw.d.ts +33 -0
- package/build/esm/gateways/TwilioGw.js +107 -0
- package/build/esm/gateways/externalUrl.d.ts +16 -0
- package/build/esm/gateways/externalUrl.js +116 -0
- package/build/esm/gateways/guardedFetch.d.ts +15 -0
- package/build/esm/gateways/guardedFetch.js +133 -0
- package/build/esm/gateways/index.d.ts +9 -0
- package/build/esm/gateways/index.js +9 -0
- package/build/esm/index.d.ts +2 -1
- package/build/esm/index.js +2 -1
- package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
- package/build/gateways/BaseExternalApiGateway.d.ts +94 -0
- package/build/gateways/BaseExternalApiGateway.js +326 -0
- package/build/gateways/DiscordWebhookGw.d.ts +50 -0
- package/build/gateways/DiscordWebhookGw.js +73 -0
- package/build/gateways/HttpWebhookGw.d.ts +43 -0
- package/build/gateways/HttpWebhookGw.js +135 -0
- package/build/gateways/SendGridGw.d.ts +41 -0
- package/build/gateways/SendGridGw.js +119 -0
- package/build/gateways/SlackWebhookGw.d.ts +23 -0
- package/build/gateways/SlackWebhookGw.js +62 -0
- package/build/gateways/TelegramGw.d.ts +45 -0
- package/build/gateways/TelegramGw.js +115 -0
- package/build/gateways/TwilioGw.d.ts +33 -0
- package/build/gateways/TwilioGw.js +110 -0
- package/build/gateways/externalUrl.d.ts +16 -0
- package/build/gateways/externalUrl.js +121 -0
- package/build/gateways/guardedFetch.d.ts +15 -0
- package/build/gateways/guardedFetch.js +141 -0
- package/build/gateways/index.d.ts +9 -0
- package/build/gateways/index.js +25 -0
- package/build/index.d.ts +2 -1
- package/build/index.js +2 -1
- package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
- package/package.json +2 -1
- package/build/BaseExternalApiGateway.d.ts +0 -16
- package/build/BaseExternalApiGateway.js +0 -54
- package/build/esm/BaseExternalApiGateway.d.ts +0 -16
- package/build/esm/BaseExternalApiGateway.js +0 -48
package/README.md
CHANGED
|
@@ -25,7 +25,8 @@ A comprehensive backend framework for Node.js applications providing database ac
|
|
|
25
25
|
- [BaseGateway](#basegateway)
|
|
26
26
|
- [BaseController](#basecontroller)
|
|
27
27
|
- [BaseRestApiCrudController](#baserestapicrudcontroller)
|
|
28
|
-
- [BaseExternalApiGateway](#
|
|
28
|
+
- [BaseExternalApiGateway](#baseexternalapigateway)
|
|
29
|
+
- [Gateways to outside services](#gateways-to-outside-services)
|
|
29
30
|
- [IP rate limiting](#ip-rate-limiting)
|
|
30
31
|
- [How it works](#how-it-works)
|
|
31
32
|
- [Setup](#setup)
|
|
@@ -56,6 +57,7 @@ A comprehensive backend framework for Node.js applications providing database ac
|
|
|
56
57
|
- [Utility functions](#utility-functions)
|
|
57
58
|
- [downloadFile](#downloadfile)
|
|
58
59
|
- [passwordHelpers](#passwordhelpers)
|
|
60
|
+
- [Emergency alerts](#emergency-alerts)
|
|
59
61
|
- [Constants](#constants)
|
|
60
62
|
- [Interfaces reference](#interfaces-reference)
|
|
61
63
|
|
|
@@ -1101,38 +1103,119 @@ Routes registered for `root = '/api/notes'`:
|
|
|
1101
1103
|
|
|
1102
1104
|
### BaseExternalApiGateway
|
|
1103
1105
|
|
|
1104
|
-
|
|
1106
|
+
The base of every gateway to an outside service. **One way to set it up** — `configure(settings)` — and **one way to
|
|
1107
|
+
answer** — an `OpResult`, never a throw.
|
|
1108
|
+
|
|
1109
|
+
- A gateway is created **once** and configured — and re-configured — at run time: per brand, per tenant, per request.
|
|
1110
|
+
`configure` **replaces** the settings (it never merges), so a shared instance re-pointed at another tenant keeps
|
|
1111
|
+
nothing of the last one.
|
|
1112
|
+
- `isConfigured()` / `getConfigProblems()` say what is missing or malformed, in words — never a value. Every operation
|
|
1113
|
+
refuses with `VALIDATION_FAILED` until it is fixed.
|
|
1114
|
+
- `configure(settings)` takes the gateway's FULL settings type, so a missing required setting is a compile error.
|
|
1115
|
+
- HTTP refusals map onto the standard codes — 401 `UNAUTHORIZED`, 403 `FORBIDDEN`, 404 `NOT_FOUND`, 408 `TIMEOUT`,
|
|
1116
|
+
409 `CONFLICT`, 429 `TOO_MANY_REQUESTS`, 5xx `FAILED`, any other 4xx `VALIDATION_FAILED`; no answer `NETWORK_ERROR` /
|
|
1117
|
+
`TIMEOUT`; a request that cannot even be made (a malformed header, a refused address) `VALIDATION_FAILED` — so
|
|
1118
|
+
`result.isRetryableError()` means the same thing for every gateway.
|
|
1119
|
+
- Retries (default 2, after 1 s and 2 s) on network errors, timeouts, 429 and 5xx — after the service's own
|
|
1120
|
+
`Retry-After` when it gives one, and not at all when it asks for longer than 10 s. A gateway refuses to retry the
|
|
1121
|
+
hopeless ones (a chat that does not exist, an unknown webhook), and email/SMS never retry after a TIMEOUT (it may have
|
|
1122
|
+
gone out — a retry would send it twice).
|
|
1123
|
+
- Redirects are never followed; every request has a timeout (default 10 s); a reply is read at most 64 KB.
|
|
1124
|
+
- The secrets a gateway names (keys, tokens, webhook URLs) — and a request's own (per-request headers) — are scrubbed out
|
|
1125
|
+
of EVERYTHING it returns: the error message AND the reply in the data (body and headers; `set-cookie` is dropped).
|
|
1126
|
+
|
|
1127
|
+
Constructor props (all optional): `settings`, `timeoutMs`, `retries`, `retryDelaysMs`, `fetch` (a test passes its
|
|
1128
|
+
own), `logger`, `baseUrl`.
|
|
1129
|
+
|
|
1130
|
+
Writing a gateway:
|
|
1105
1131
|
|
|
1106
1132
|
```typescript
|
|
1107
|
-
|
|
1108
|
-
import { BaseExternalApiGateway } from '@sdflc/backend-helpers';
|
|
1109
|
-
import Stripe from 'stripe';
|
|
1133
|
+
import { BaseExternalApiGateway, OpResult } from '@sdflc/backend-helpers';
|
|
1110
1134
|
|
|
1111
|
-
interface
|
|
1112
|
-
|
|
1135
|
+
interface AcmeSettings {
|
|
1136
|
+
apiKey: string;
|
|
1113
1137
|
}
|
|
1114
1138
|
|
|
1115
|
-
class
|
|
1116
|
-
|
|
1139
|
+
class AcmeGw extends BaseExternalApiGateway<AcmeSettings> {
|
|
1140
|
+
protected validateSettings(settings: Partial<AcmeSettings>): string[] {
|
|
1141
|
+
return settings.apiKey ? [] : ['the API key is missing'];
|
|
1142
|
+
}
|
|
1117
1143
|
|
|
1118
|
-
protected
|
|
1119
|
-
|
|
1120
|
-
this.client = new Stripe(secretKey);
|
|
1144
|
+
protected secretValues(): string[] {
|
|
1145
|
+
return [String(this.settings.apiKey ?? '')];
|
|
1121
1146
|
}
|
|
1122
1147
|
|
|
1123
|
-
async
|
|
1124
|
-
this.
|
|
1125
|
-
|
|
1148
|
+
public async ping(): Promise<OpResult> {
|
|
1149
|
+
if (!this.isConfigured()) {
|
|
1150
|
+
return this.notConfigured();
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
return this.requestWithRetries({
|
|
1154
|
+
url: 'https://api.acme.test/ping',
|
|
1155
|
+
headers: { Authorization: `Bearer ${this.settings.apiKey}` },
|
|
1156
|
+
json: { hello: 'world' },
|
|
1157
|
+
});
|
|
1126
1158
|
}
|
|
1127
1159
|
}
|
|
1128
1160
|
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
const
|
|
1132
|
-
gw.setCredentials(creds); // accepts string or Record<string, any>
|
|
1133
|
-
await gw.chargeCard(1000, 'usd');
|
|
1161
|
+
const acme = new AcmeGw(); // once
|
|
1162
|
+
acme.configure({ apiKey: await keyOf(spaceId) }); // per tenant, whenever
|
|
1163
|
+
const result = await acme.ping();
|
|
1134
1164
|
```
|
|
1135
1165
|
|
|
1166
|
+
Override `errorMessageOf(reply)` to read the service's own error shape, and `shouldRetry(result)` to refuse hopeless
|
|
1167
|
+
retries. ⓘ `setCredentials()` / `onCredentialsSet()` still work for gateways written before `configure()`.
|
|
1168
|
+
|
|
1169
|
+
---
|
|
1170
|
+
|
|
1171
|
+
## Gateways to outside services
|
|
1172
|
+
|
|
1173
|
+
Ready-made gateways on `BaseExternalApiGateway` — no SDKs, one REST call each, `OpResult` out.
|
|
1174
|
+
|
|
1175
|
+
| Gateway | `configure({...})` | Operation → OK data |
|
|
1176
|
+
|---|---|---|
|
|
1177
|
+
| `SendGridGw` | `apiKey`, `fromEmail?`, `fromName?` | `sendEmail({ to, cc?, bcc?, from?, replyTo?, subject?, text?, html?, templateId?, dynamicTemplateData?, categories?, customArgs? })` → `{ messageId }` |
|
|
1178
|
+
| `TelegramGw` | `botToken`, `chatId?`, `parseMode?` | `sendMessage({ text, chatId?, parseMode?, disableWebPagePreview?, disableNotification?, inlineKeyboard? })` → `{ messageId }` |
|
|
1179
|
+
| `TwilioGw` | `accountSid`, `authToken`, `from?`, `messagingServiceSid?` | `sendMessage({ to, body, from?, statusCallback?, mediaUrl? })` → `{ sid, status }` (SMS, or WhatsApp with `whatsapp:+…`) |
|
|
1180
|
+
| `SlackWebhookGw` | `webhookUrl` | `postMessage({ text, blocks?, attachments? })` → `{ messageId: null }` (Slack gives none) |
|
|
1181
|
+
| `DiscordWebhookGw` | `webhookUrl`, `username?`, `avatarUrl?` | `postMessage({ content?, embeds?, username?, avatarUrl?, allowedMentions? })` → `{ messageId }` |
|
|
1182
|
+
| `HttpWebhookGw` | `url`, `method?`, `headers?`, `signingSecret?` | `send({ payload, headers? })` → `{ status, body }` |
|
|
1183
|
+
|
|
1184
|
+
```typescript
|
|
1185
|
+
import { SendGridGw, TelegramGw } from '@sdflc/backend-helpers';
|
|
1186
|
+
|
|
1187
|
+
const mail = new SendGridGw().configure({ apiKey, fromEmail: 'hello@brand.com', fromName: 'Brand' });
|
|
1188
|
+
const sent = await mail.sendEmail({ to: 'guest@example.com', subject: 'Welcome', html: '<p>Hi</p>' });
|
|
1189
|
+
|
|
1190
|
+
if (sent.didFail()) {
|
|
1191
|
+
logger.error(sent.getErrorSummary(''));
|
|
1192
|
+
}
|
|
1193
|
+
```
|
|
1194
|
+
|
|
1195
|
+
Rules each one keeps:
|
|
1196
|
+
|
|
1197
|
+
- **SendGrid** — the From must be on a domain authenticated in that SendGrid account.
|
|
1198
|
+
- **SendGrid** — a malformed recipient is **refused**, never silently dropped.
|
|
1199
|
+
- **Telegram** — a text over 4096 characters (counted as Telegram counts: tags free, an entity one character) is
|
|
1200
|
+
**refused, not cut** (cutting finished HTML can split an entity, and Telegram then refuses the whole message): cut
|
|
1201
|
+
your text before adding markup. A 200 with `ok: false` is a failure. `isTelegramChatId(value)` is exported.
|
|
1202
|
+
- **Twilio** — numbers are checked as E.164 before anything is sent; a body over 1600 characters is refused.
|
|
1203
|
+
- **Slack / Discord** — the webhook URL **is** the credential: it is scrubbed out of errors. Discord pings **nobody**
|
|
1204
|
+
unless `allowedMentions` says so (`@everyone` in a text stays text).
|
|
1205
|
+
- **HTTP webhook** — a URL a **user** typed must not reach your own network or the cloud metadata service. It is
|
|
1206
|
+
checked twice: before the request (`checkExternalUrl` — every address the host resolves to, however it is written,
|
|
1207
|
+
IPv4-mapped IPv6 included — for a clear refusal), and **at the moment the socket connects** (`createGuardedFetch`: the
|
|
1208
|
+
address actually connected to is checked, so a DNS server that answers differently the second time — DNS rebinding —
|
|
1209
|
+
is refused too). `allowPrivateNetwork` is a **constructor** prop, never a setting: settings often come from a
|
|
1210
|
+
tenant's own row, and a tenant must not be able to switch the protection off. Every send carries `X-Webhook-Id`
|
|
1211
|
+
(the same on its retries, so a receiver can drop a duplicate). With `signingSecret`, also `X-Webhook-Timestamp` and
|
|
1212
|
+
`X-Webhook-Signature: sha256=<hex HMAC-SHA256 of "<timestamp>.<body>">` (`webhookSignatureOf(secret, timestamp, body)`
|
|
1213
|
+
computes it for a receiver); a configured header can never replace these. A header with a line break, or a payload
|
|
1214
|
+
that is not JSON, is refused.
|
|
1215
|
+
|
|
1216
|
+
`checkExternalUrl(url, { protocols?, lookup?, field? })`, `isBlockedAddress(ip)` and `createGuardedFetch()` are exported
|
|
1217
|
+
for any code that takes a URL from a user.
|
|
1218
|
+
|
|
1136
1219
|
---
|
|
1137
1220
|
|
|
1138
1221
|
## IP rate limiting
|
|
@@ -1984,6 +2067,79 @@ const isCorrect = await checkPassword(plaintextPassword, storedHash);
|
|
|
1984
2067
|
|
|
1985
2068
|
---
|
|
1986
2069
|
|
|
2070
|
+
## Emergency alerts
|
|
2071
|
+
|
|
2072
|
+
A service raises an alarm **by itself** — by email and/or Telegram — when it starts with missing configuration or
|
|
2073
|
+
crashes. `EmergencyAlerter` decides **what** is said, **to whom** and **how often**; it sends through the gateways above
|
|
2074
|
+
(`SendGridGw`, `TelegramGw`). Each alert names the app, the service and the environment
|
|
2075
|
+
(`[partylabz · ms_storage · production]`), because several apps can run the same services side by side on one machine.
|
|
2076
|
+
|
|
2077
|
+
```typescript
|
|
2078
|
+
import { EmergencyAlerter, CriticalConfigItem } from '@sdflc/backend-helpers';
|
|
2079
|
+
|
|
2080
|
+
// What this service starts WITHOUT (optional to the config loader) but cannot fully work without.
|
|
2081
|
+
// APP_NAME is always checked as well; `key` (the built-config name) is derived from `env`.
|
|
2082
|
+
const CRITICAL_CONFIG: CriticalConfigItem[] = [
|
|
2083
|
+
{ env: 'INTERSERVICE_API_KEY', effect: 'Every call from our other services is refused.' },
|
|
2084
|
+
];
|
|
2085
|
+
|
|
2086
|
+
const alerter = EmergencyAlerter.fromConfig(config, 'ms_storage', { log: (m) => logger.error(m) });
|
|
2087
|
+
|
|
2088
|
+
alerter.installCrashHandlers(process); // uncaught exception / unhandled rejection → alert, then exit(1)
|
|
2089
|
+
|
|
2090
|
+
httpServer.listen(port, async () => {
|
|
2091
|
+
await alerter.checkConfig(config, CRITICAL_CONFIG); // the service still starts; it says loudly what is missing
|
|
2092
|
+
});
|
|
2093
|
+
|
|
2094
|
+
const result = await alerter.send({ key: 'queue:stalled', subject: 'The queue stopped draining', lines: ['…'] });
|
|
2095
|
+
// OK → data [{ status: 'sent', channels: { email: 'sent', telegram: 'failed' } }] or [{ status: 'recently-sent' }]
|
|
2096
|
+
// VALIDATION_FAILED → no channel can be used; FAILED → no channel delivered it (each channel's error merged in)
|
|
2097
|
+
```
|
|
2098
|
+
|
|
2099
|
+
Or build it yourself — credentials live in the gateways, the addressing in the alerter:
|
|
2100
|
+
|
|
2101
|
+
```typescript
|
|
2102
|
+
const alerter = new EmergencyAlerter({
|
|
2103
|
+
email: new SendGridGw().configure({ apiKey }),
|
|
2104
|
+
telegram: new TelegramGw().configure({ botToken }),
|
|
2105
|
+
settings: { appName: 'partylabz', serviceName: 'ms_storage', environment: 'production',
|
|
2106
|
+
emailTo: ['ops@brand.com'], emailFrom: 'alerts@brand.com', telegramChatId: '-100123' },
|
|
2107
|
+
});
|
|
2108
|
+
```
|
|
2109
|
+
|
|
2110
|
+
Settings `fromConfig` reads (all optional; each channel needs all of its own):
|
|
2111
|
+
|
|
2112
|
+
| Env | Meaning |
|
|
2113
|
+
|---|---|
|
|
2114
|
+
| `APP_NAME` | The app this service belongs to; alerts say `unknown-app` without it (and `checkConfig` reports it) |
|
|
2115
|
+
| `EMERGENCY_SENDGRID_API_KEY` | Email: a SendGrid key allowed to send mail |
|
|
2116
|
+
| `EMERGENCY_EMAIL_FROM` | Email: a sender on a domain authenticated in that SendGrid account (required — a guessed one is refused) |
|
|
2117
|
+
| `EMERGENCY_EMAIL_TO` | Email: recipients, comma-separated |
|
|
2118
|
+
| `TELEGRAM_BOT_ID` | Telegram: the bot token `<id>:<secret>` from @BotFather |
|
|
2119
|
+
| `TELEGRAM_CHAT_ID` | Telegram: the chat id (negative for a group) or `@channel` |
|
|
2120
|
+
| `EMERGENCY_EMAIL_MIN_INTERVAL_MINUTES` | The same alert at most once per this many minutes, on every channel (default 60; 0 = always) |
|
|
2121
|
+
|
|
2122
|
+
Rules it keeps:
|
|
2123
|
+
|
|
2124
|
+
- **Never throws, never blocks for long.** `fromConfig` gives each provider a 4 s timeout (one short retry); a crash
|
|
2125
|
+
waits for its alert at most 10 s, then exits — and **always** exits, whatever was thrown.
|
|
2126
|
+
- **A channel set up wrongly is said once, at the start** — never silently skipped (`getChannelProblems()`).
|
|
2127
|
+
- **What leaves is redacted:** `fromConfig` removes every config value whose NAME looks secret (password, secret,
|
|
2128
|
+
token, key…) from every subject, line and log line — an error message can carry SQL with its values. Pass `redact`
|
|
2129
|
+
for more.
|
|
2130
|
+
- **A crash's key names which crash** (its message and top frame): one crash never silences a different one.
|
|
2131
|
+
- **One alert per key per interval across all channels**, remembered in a file under the OS temp folder named after
|
|
2132
|
+
the app and service — a crash loop sends one message, not one per restart. Sends of the same key **at the same time**
|
|
2133
|
+
go out once; a send no channel delivered is not remembered, so the next one tries again.
|
|
2134
|
+
- **Goes straight to the providers**, never through another service — it has to work when the rest does not.
|
|
2135
|
+
- **Subjects are one line**; the Telegram text is cut **before** it is escaped, to what the heading and footer leave,
|
|
2136
|
+
so a long stack trace neither splits an entity nor overruns Telegram's limit.
|
|
2137
|
+
- **Never put a secret, a token or a database row in an alert** — it leaves your infrastructure.
|
|
2138
|
+
|
|
2139
|
+
Proofs: `npm run build && npm run prove` (the gateways and the alerter, each against a stub `fetch`).
|
|
2140
|
+
|
|
2141
|
+
---
|
|
2142
|
+
|
|
1987
2143
|
## Constants
|
|
1988
2144
|
|
|
1989
2145
|
```typescript
|
package/build/BaseGateway.js
CHANGED
|
@@ -1230,10 +1230,26 @@ class BaseGateway {
|
|
|
1230
1230
|
if (!args || objects.length === 0) {
|
|
1231
1231
|
return [];
|
|
1232
1232
|
}
|
|
1233
|
+
// The framework's OWN id is applied AFTER transformOnCreate, never through it.
|
|
1234
|
+
// transformOnCreate strips `id` — deliberately, so a CALLER-supplied id is never
|
|
1235
|
+
// honoured — and it cannot tell the caller's id from ours once both are merged into
|
|
1236
|
+
// one payload. Passing the generated id in that payload (as this did until now) meant
|
|
1237
|
+
// the strip deleted the id we had just made: `generateId()` became inert, every insert
|
|
1238
|
+
// silently fell back to the column's own default, and every create logged
|
|
1239
|
+
// `field "id" is not writable on create and was stripped from the payload`.
|
|
1240
|
+
// A caller id is still dropped — it is stripped before we get here.
|
|
1241
|
+
// Mirrors what `set()` below already does, and restores the pre-1.0.135 insert payload
|
|
1242
|
+
// (the strip landed in 1.0.135 and started swallowing this id).
|
|
1243
|
+
const idField = String(this.getIdField()).split('.').pop();
|
|
1233
1244
|
for (let idx = 0, len = objects.length; idx < len; ++idx) {
|
|
1234
1245
|
const object = objects[idx];
|
|
1235
|
-
const
|
|
1236
|
-
|
|
1246
|
+
const transformed = await this.transformOnCreate({ ...object });
|
|
1247
|
+
// Only when nothing else has set it — `hasLang` + `localizationForField` builds a
|
|
1248
|
+
// COMPOSITE id in transformOnCreate, and that one must stand.
|
|
1249
|
+
if (transformed[idField] == null) {
|
|
1250
|
+
transformed[idField] = await this.generateId(object);
|
|
1251
|
+
}
|
|
1252
|
+
objects[idx] = transformed;
|
|
1237
1253
|
}
|
|
1238
1254
|
const result = [];
|
|
1239
1255
|
const chunks = (0, utils_1.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 };
|