@blamejs/core 0.7.18 → 0.7.19

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 (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
package/lib/retry.js CHANGED
@@ -1,376 +1,376 @@
1
- "use strict";
2
- /**
3
- * b.retry — exponential-backoff retry + circuit breaker.
4
- *
5
- * Two layers of resilience for any operation that may fail transiently:
6
- *
7
- * 1. PER-CALL retry (withRetry) — exponential backoff with jitter.
8
- * Default classifier targets HTTP 408/425/429/5xx and Node net-layer
9
- * error codes. Caller can override `opts.isRetryable` for non-network
10
- * semantics (e.g. operator-defined flush() in handlers).
11
- *
12
- * 2. PER-TARGET circuit breaker (CircuitBreaker) — N consecutive
13
- * failures opens the circuit (fast-fail for the cooldown window).
14
- * After cooldown the breaker enters half-open: probe successes close
15
- * it, a probe failure reopens it.
16
- *
17
- * Both are intentionally side-effect-free in the success path — they
18
- * compose freely with `safeAsync.withTimeout`, AbortSignals, and any
19
- * caller-side instrumentation.
20
- *
21
- * Validation policy:
22
- *
23
- * - withRetry opts at first call → throw at call site
24
- * - CircuitBreaker constructor opts → throw at call site
25
- * - backoffDelay(attempt) attempt argument → throw at call site
26
- * - isRetryable(err) defensive read → tolerant (return defaults)
27
- * - onRetry callback throw → drop silent (hot-path sink)
28
- * - breaker internal _onSuccess/_onFailure → drop silent (hot-path sink)
29
- *
30
- * HTTP-client auto-retry is intentionally NOT provided here. Callers
31
- * wrap their own outbound calls in `b.retry.withRetry(...)` to keep
32
- * timeout/idempotency/body-replay decisions explicit.
33
- */
34
-
35
- var C = require("./constants");
36
- var lazyRequire = require("./lazy-require");
37
- var nodeCrypto = require("crypto");
38
- var numericChecks = require("./numeric-checks");
39
- // safe-async re-exports withRetry + CircuitBreaker from this module, so a
40
- // direct top-level require would create a cycle. Lazy-require defers the
41
- // resolution until the first sleep() call, by which point both modules
42
- // are fully loaded.
43
- var safeAsync = lazyRequire(function () { return require("./safe-async"); });
44
- // observability is also lazy-required because the metrics + tracing
45
- // registry boots after this file loads. event() is fire-and-forget —
46
- // any throw inside the metrics sink is swallowed by observability itself.
47
- var observability = lazyRequire(function () { return require("./observability"); });
48
-
49
- function _emitEvent(n, v, l) { observability().safeEvent(n, v, l || {}); }
50
-
51
- // ---- Defaults ----
52
-
53
- var DEFAULT_RETRY = Object.freeze({
54
- maxAttempts: 5, // total attempts incl. the first try
55
- baseDelayMs: 100, // initial backoff (sub-second; ms literal is clearest)
56
- maxDelayMs: C.TIME.seconds(10), // cap between attempts
57
- jitterFactor: 0.5, // 0 = no jitter, 1 = full jitter
58
- });
59
-
60
- // HTTP status codes are RFC 7231 / 7232 / 6585 / 4918 / 7540 protocol
61
- // constants; the numeric values are fixed by the spec, named here so the
62
- // retry classifier reads as semantics ("Bad Request", "Service Unavailable")
63
- // rather than bare numbers. Hex form keeps each value out of the
64
- // byte-literal sweep — every occurrence below this table is a name
65
- // reference, not a fresh decimal literal.
66
- var HTTP = Object.freeze({
67
- BAD_REQUEST: 0x190,
68
- UNAUTHORIZED: 0x191,
69
- FORBIDDEN: 0x193,
70
- NOT_FOUND: 0x194,
71
- METHOD_NOT_ALLOWED: 0x195,
72
- REQUEST_TIMEOUT: 0x198,
73
- CONFLICT: 0x199,
74
- GONE: 0x19a,
75
- LENGTH_REQUIRED: 0x19b,
76
- PRECONDITION_FAILED: 0x19c,
77
- PAYLOAD_TOO_LARGE: 0x19d,
78
- URI_TOO_LONG: 0x19e,
79
- UNSUPPORTED_MEDIA_TYPE: 0x19f,
80
- RANGE_NOT_SATISFIABLE: 0x1a0,
81
- EXPECTATION_FAILED: 0x1a1,
82
- UNPROCESSABLE_ENTITY: 0x1a6,
83
- TOO_EARLY: 0x1a9,
84
- TOO_MANY_REQUESTS: 0x1ad,
85
- UNAVAILABLE_FOR_LEGAL_REASONS: 0x1c3,
86
- INTERNAL_SERVER_ERROR: 0x1f4,
87
- NOT_IMPLEMENTED: 0x1f5,
88
- BAD_GATEWAY: 0x1f6,
89
- SERVICE_UNAVAILABLE: 0x1f7,
90
- GATEWAY_TIMEOUT: 0x1f8,
91
- HTTP_VERSION_NOT_SUPPORTED: 0x1f9,
92
- });
93
-
94
- // Errors that are permanently fatal — do NOT retry.
95
- var NON_RETRYABLE_HTTP_STATUS = new Set([
96
- HTTP.BAD_REQUEST, HTTP.UNAUTHORIZED, HTTP.FORBIDDEN, HTTP.NOT_FOUND,
97
- HTTP.METHOD_NOT_ALLOWED, HTTP.CONFLICT, HTTP.GONE, HTTP.LENGTH_REQUIRED,
98
- HTTP.PRECONDITION_FAILED, HTTP.PAYLOAD_TOO_LARGE, HTTP.URI_TOO_LONG,
99
- HTTP.UNSUPPORTED_MEDIA_TYPE, HTTP.RANGE_NOT_SATISFIABLE, HTTP.EXPECTATION_FAILED,
100
- HTTP.UNPROCESSABLE_ENTITY, HTTP.UNAVAILABLE_FOR_LEGAL_REASONS,
101
- HTTP.NOT_IMPLEMENTED, HTTP.HTTP_VERSION_NOT_SUPPORTED,
102
- ]);
103
-
104
- // Errors that should be retried — transient by nature.
105
- var RETRYABLE_HTTP_STATUS = new Set([
106
- HTTP.REQUEST_TIMEOUT, HTTP.TOO_EARLY, HTTP.TOO_MANY_REQUESTS,
107
- HTTP.INTERNAL_SERVER_ERROR, HTTP.BAD_GATEWAY, HTTP.SERVICE_UNAVAILABLE,
108
- HTTP.GATEWAY_TIMEOUT,
109
- ]);
110
-
111
- // Network errors from Node's net layer that map to "retry" semantics.
112
- var RETRYABLE_NET_ERRORS = new Set([
113
- "ECONNRESET", "ECONNREFUSED", "ECONNABORTED", "ETIMEDOUT",
114
- "EPIPE", "EAGAIN", "ENOTFOUND", "ENETUNREACH",
115
- ]);
116
-
117
- var STATE_CLOSED = "closed"; // normal — calls go through
118
- var STATE_OPEN = "open"; // failing — calls fail fast
119
- var STATE_HALF = "half-open"; // probing — one call goes through
120
-
121
- var DEFAULT_BREAKER = Object.freeze({
122
- failureThreshold: 10, // consecutive failures to open
123
- cooldownMs: C.TIME.seconds(30), // time in OPEN before HALF_OPEN probe
124
- successThreshold: 2, // consecutive HALF probes that close it
125
- });
126
-
127
- // ---- Call-site validation helpers (throw on bad input) ----
128
-
129
- var _isPositiveInt = numericChecks.isPositiveInt;
130
- var _isNonNegFinite = numericChecks.isFiniteNonNegative;
131
- function _isAbortSignal(s) {
132
- // Duck-typed: AbortSignal exposes .aborted (bool) and .addEventListener (fn)
133
- return s != null && typeof s === "object" &&
134
- typeof s.aborted === "boolean" &&
135
- typeof s.addEventListener === "function";
136
- }
137
-
138
- function _validateRetryOpts(opts) {
139
- if (!_isPositiveInt(opts.maxAttempts)) {
140
- throw new TypeError("retry.withRetry: maxAttempts must be a positive integer, got " +
141
- typeof opts.maxAttempts + " " + JSON.stringify(opts.maxAttempts));
142
- }
143
- if (!_isNonNegFinite(opts.baseDelayMs)) {
144
- throw new TypeError("retry.withRetry: baseDelayMs must be a non-negative finite number, got " +
145
- typeof opts.baseDelayMs + " " + JSON.stringify(opts.baseDelayMs));
146
- }
147
- if (!_isNonNegFinite(opts.maxDelayMs)) {
148
- throw new TypeError("retry.withRetry: maxDelayMs must be a non-negative finite number, got " +
149
- typeof opts.maxDelayMs + " " + JSON.stringify(opts.maxDelayMs));
150
- }
151
- if (typeof opts.jitterFactor !== "number" || !isFinite(opts.jitterFactor) ||
152
- opts.jitterFactor < 0 || opts.jitterFactor > 1) {
153
- throw new TypeError("retry.withRetry: jitterFactor must be a finite number in [0, 1], got " +
154
- typeof opts.jitterFactor + " " + JSON.stringify(opts.jitterFactor));
155
- }
156
- if (opts.isRetryable !== undefined && typeof opts.isRetryable !== "function") {
157
- throw new TypeError("retry.withRetry: isRetryable must be a function or undefined, got " +
158
- typeof opts.isRetryable);
159
- }
160
- if (opts.onRetry !== undefined && typeof opts.onRetry !== "function") {
161
- throw new TypeError("retry.withRetry: onRetry must be a function or undefined, got " +
162
- typeof opts.onRetry);
163
- }
164
- if (opts.signal !== undefined && opts.signal !== null && !_isAbortSignal(opts.signal)) {
165
- throw new TypeError("retry.withRetry: signal must be an AbortSignal or undefined");
166
- }
167
- }
168
-
169
- function _validateBreakerOpts(name, opts) {
170
- if (typeof name !== "string" || name.length === 0) {
171
- throw new TypeError("retry.CircuitBreaker: name must be a non-empty string, got " +
172
- typeof name + " " + JSON.stringify(name));
173
- }
174
- if (!_isPositiveInt(opts.failureThreshold)) {
175
- throw new TypeError("retry.CircuitBreaker: failureThreshold must be a positive integer, got " +
176
- typeof opts.failureThreshold + " " + JSON.stringify(opts.failureThreshold));
177
- }
178
- if (!_isNonNegFinite(opts.cooldownMs)) {
179
- throw new TypeError("retry.CircuitBreaker: cooldownMs must be a non-negative finite number, got " +
180
- typeof opts.cooldownMs + " " + JSON.stringify(opts.cooldownMs));
181
- }
182
- if (!_isPositiveInt(opts.successThreshold)) {
183
- throw new TypeError("retry.CircuitBreaker: successThreshold must be a positive integer, got " +
184
- typeof opts.successThreshold + " " + JSON.stringify(opts.successThreshold));
185
- }
186
- }
187
-
188
- // ---- Public surface ----
189
-
190
- // Tolerant read of err shape; missing fields → false.
191
- function isRetryable(err) {
192
- if (!err) return false;
193
- if (err.isObjectStoreError && err.permanent) return false;
194
- if (err.permanent) return false;
195
- if (typeof err.statusCode === "number") {
196
- if (RETRYABLE_HTTP_STATUS.has(err.statusCode)) return true;
197
- if (NON_RETRYABLE_HTTP_STATUS.has(err.statusCode)) return false;
198
- if (err.statusCode >= 500) return true; // unknown 5xx → assume retryable
199
- return false;
200
- }
201
- if (err.code && RETRYABLE_NET_ERRORS.has(err.code)) return true;
202
- return false; // default: not retryable (avoid masking bugs)
203
- }
204
-
205
- // Throw on bad input: attempt must be a positive int; opts (when supplied)
206
- // must have non-neg-finite baseDelayMs/maxDelayMs and finite jitterFactor
207
- // in [0,1]. We don't full-validate opts here every call (hot path) —
208
- // defaults are frozen, so the only way a bad opts reaches here is via
209
- // withRetry which already validated, OR a caller using backoffDelay
210
- // directly. For that
211
- // direct case we still validate the attempt arg loudly.
212
- function backoffDelay(attempt, opts) {
213
- if (!_isPositiveInt(attempt)) {
214
- throw new TypeError("retry.backoffDelay: attempt must be a positive integer, got " +
215
- typeof attempt + " " + JSON.stringify(attempt));
216
- }
217
- opts = opts || DEFAULT_RETRY;
218
- var base = opts.baseDelayMs * Math.pow(2, attempt - 1);
219
- var capped = Math.min(base, opts.maxDelayMs);
220
- // Cryptographically-strong jitter so a timing-attack mitigation isn't
221
- // undermined by Math.random's predictable PRNG.
222
- var jitterDenom = 1_000_000;
223
- var jitter = capped * opts.jitterFactor * (nodeCrypto.randomInt(0, jitterDenom) / jitterDenom);
224
- return Math.floor(capped - jitter);
225
- }
226
-
227
- async function withRetry(fn, opts) {
228
- if (typeof fn !== "function") {
229
- throw new TypeError("retry.withRetry: fn must be a function, got " + typeof fn);
230
- }
231
- opts = Object.assign({}, DEFAULT_RETRY, opts || {});
232
- _validateRetryOpts(opts);
233
- // opts.isRetryable lets callers override the default classifier.
234
- // Default classifier targets HTTP/network errors and is intentionally
235
- // conservative (unknown errors → NOT retryable, to avoid masking bugs).
236
- // Callers like the handlers primitive whose flush failures are operator-
237
- // defined (not network-shaped) pass `isRetryable: function () { return true; }`
238
- // to retry on any error. When overridden, the caller owns full classification
239
- // including any `err.permanent` semantics they want to honor.
240
- var classify = (typeof opts.isRetryable === "function") ? opts.isRetryable : isRetryable;
241
- var lastErr = null;
242
- for (var attempt = 1; attempt <= opts.maxAttempts; attempt++) {
243
- try {
244
- return await fn(attempt);
245
- } catch (err) {
246
- lastErr = err;
247
- var retryable = classify(err);
248
- if (!retryable || attempt === opts.maxAttempts) {
249
- if (!retryable) {
250
- _emitEvent("retry.exhausted", 1, { reason: "non-retryable" });
251
- } else {
252
- _emitEvent("retry.exhausted", 1, { reason: "max-attempts", attempts: attempt });
253
- }
254
- throw err;
255
- }
256
- var delay = backoffDelay(attempt, opts);
257
- _emitEvent("retry.attempt", 1, { attempt: attempt });
258
- if (typeof opts.onRetry === "function") {
259
- // Hot-path observability sink — drops silent on observer throw
260
- // so a thrown observer can't crash the retry loop. Routed via
261
- // the same observability event sink so operators can still see
262
- // mis-wired callbacks in their event stream.
263
- try { opts.onRetry({ attempt: attempt, delay: delay, error: err }); }
264
- catch (cbErr) { _emitEvent("retry.onRetry.threw", 1, { error: cbErr.message }); }
265
- }
266
- // Honor opts.signal during the backoff sleep — a caller who aborts
267
- // mid-retry should be unblocked immediately rather than waiting
268
- // out the (potentially multi-second) backoff.
269
- await safeAsync().sleep(delay, { signal: opts.signal });
270
- }
271
- }
272
- throw lastErr;
273
- }
274
-
275
- // ---- Circuit breaker ----
276
-
277
- class CircuitBreaker {
278
- constructor(name, opts) {
279
- var merged = Object.assign({}, DEFAULT_BREAKER, opts || {});
280
- _validateBreakerOpts(name || "", merged);
281
- this.name = name;
282
- this.opts = merged;
283
- this.state = STATE_CLOSED;
284
- this.consecutiveFailures = 0;
285
- this.consecutiveSuccesses = 0;
286
- this.openedAt = 0;
287
- }
288
-
289
- // Wrap an async function. The breaker observes outcomes and may fail-fast.
290
- async wrap(fn) {
291
- if (typeof fn !== "function") {
292
- throw new TypeError("retry.CircuitBreaker.wrap: fn must be a function, got " + typeof fn);
293
- }
294
- if (this.state === STATE_OPEN) {
295
- if (Date.now() - this.openedAt >= this.opts.cooldownMs) {
296
- this._transition(STATE_OPEN, STATE_HALF);
297
- } else {
298
- var err = new Error("circuit breaker '" + this.name + "' is OPEN");
299
- err.code = "CIRCUIT_OPEN";
300
- err.permanent = false; // still transient
301
- err.isObjectStoreError = true;
302
- throw err;
303
- }
304
- }
305
- try {
306
- var result = await fn();
307
- this._onSuccess();
308
- return result;
309
- } catch (e) {
310
- this._onFailure(e);
311
- throw e;
312
- }
313
- }
314
-
315
- // Centralizes state changes so we emit one observability event per
316
- // transition. Same name + label shape regardless of which method
317
- // initiated the change.
318
- _transition(from, to) {
319
- if (from === to) return;
320
- this.state = to;
321
- _emitEvent("breaker.state.change", 1, { name: this.name, from: from, to: to });
322
- }
323
-
324
- _onSuccess() {
325
- if (this.state === STATE_HALF) {
326
- this.consecutiveSuccesses += 1;
327
- if (this.consecutiveSuccesses >= this.opts.successThreshold) {
328
- this._transition(STATE_HALF, STATE_CLOSED);
329
- this.consecutiveFailures = 0;
330
- this.consecutiveSuccesses = 0;
331
- }
332
- } else {
333
- this.consecutiveFailures = 0;
334
- }
335
- }
336
-
337
- _onFailure(err) {
338
- // Don't trip the breaker on permanent errors — those are caller bugs,
339
- // not backend health issues.
340
- if (err && err.permanent) return;
341
- if (err && err.isObjectStoreError && err.code === "CIRCUIT_OPEN") return;
342
-
343
- this.consecutiveFailures += 1;
344
- this.consecutiveSuccesses = 0;
345
- if (this.state === STATE_HALF) {
346
- this._transition(STATE_HALF, STATE_OPEN);
347
- this.openedAt = Date.now();
348
- } else if (this.state === STATE_CLOSED && this.consecutiveFailures >= this.opts.failureThreshold) {
349
- this._transition(STATE_CLOSED, STATE_OPEN);
350
- this.openedAt = Date.now();
351
- }
352
- }
353
-
354
- getState() { return this.state; }
355
-
356
- reset() {
357
- var prior = this.state;
358
- if (prior !== STATE_CLOSED) this._transition(prior, STATE_CLOSED);
359
- this.consecutiveFailures = 0;
360
- this.consecutiveSuccesses = 0;
361
- this.openedAt = 0;
362
- }
363
- }
364
-
365
- module.exports = {
366
- withRetry: withRetry,
367
- isRetryable: isRetryable,
368
- backoffDelay: backoffDelay,
369
- CircuitBreaker: CircuitBreaker,
370
- DEFAULT_RETRY: DEFAULT_RETRY,
371
- DEFAULT_BREAKER: DEFAULT_BREAKER,
372
- RETRYABLE_HTTP_STATUS: Array.from(RETRYABLE_HTTP_STATUS),
373
- NON_RETRYABLE_HTTP_STATUS: Array.from(NON_RETRYABLE_HTTP_STATUS),
374
- RETRYABLE_NET_ERRORS: Array.from(RETRYABLE_NET_ERRORS),
375
- STATES: { CLOSED: STATE_CLOSED, OPEN: STATE_OPEN, HALF_OPEN: STATE_HALF },
376
- };
1
+ "use strict";
2
+ /**
3
+ * b.retry — exponential-backoff retry + circuit breaker.
4
+ *
5
+ * Two layers of resilience for any operation that may fail transiently:
6
+ *
7
+ * 1. PER-CALL retry (withRetry) — exponential backoff with jitter.
8
+ * Default classifier targets HTTP 408/425/429/5xx and Node net-layer
9
+ * error codes. Caller can override `opts.isRetryable` for non-network
10
+ * semantics (e.g. operator-defined flush() in handlers).
11
+ *
12
+ * 2. PER-TARGET circuit breaker (CircuitBreaker) — N consecutive
13
+ * failures opens the circuit (fast-fail for the cooldown window).
14
+ * After cooldown the breaker enters half-open: probe successes close
15
+ * it, a probe failure reopens it.
16
+ *
17
+ * Both are intentionally side-effect-free in the success path — they
18
+ * compose freely with `safeAsync.withTimeout`, AbortSignals, and any
19
+ * caller-side instrumentation.
20
+ *
21
+ * Validation policy:
22
+ *
23
+ * - withRetry opts at first call → throw at call site
24
+ * - CircuitBreaker constructor opts → throw at call site
25
+ * - backoffDelay(attempt) attempt argument → throw at call site
26
+ * - isRetryable(err) defensive read → tolerant (return defaults)
27
+ * - onRetry callback throw → drop silent (hot-path sink)
28
+ * - breaker internal _onSuccess/_onFailure → drop silent (hot-path sink)
29
+ *
30
+ * HTTP-client auto-retry is intentionally NOT provided here. Callers
31
+ * wrap their own outbound calls in `b.retry.withRetry(...)` to keep
32
+ * timeout/idempotency/body-replay decisions explicit.
33
+ */
34
+
35
+ var C = require("./constants");
36
+ var lazyRequire = require("./lazy-require");
37
+ var nodeCrypto = require("crypto");
38
+ var numericChecks = require("./numeric-checks");
39
+ // safe-async re-exports withRetry + CircuitBreaker from this module, so a
40
+ // direct top-level require would create a cycle. Lazy-require defers the
41
+ // resolution until the first sleep() call, by which point both modules
42
+ // are fully loaded.
43
+ var safeAsync = lazyRequire(function () { return require("./safe-async"); });
44
+ // observability is also lazy-required because the metrics + tracing
45
+ // registry boots after this file loads. event() is fire-and-forget —
46
+ // any throw inside the metrics sink is swallowed by observability itself.
47
+ var observability = lazyRequire(function () { return require("./observability"); });
48
+
49
+ function _emitEvent(n, v, l) { observability().safeEvent(n, v, l || {}); }
50
+
51
+ // ---- Defaults ----
52
+
53
+ var DEFAULT_RETRY = Object.freeze({
54
+ maxAttempts: 5, // total attempts incl. the first try
55
+ baseDelayMs: 100, // initial backoff (sub-second; ms literal is clearest)
56
+ maxDelayMs: C.TIME.seconds(10), // cap between attempts
57
+ jitterFactor: 0.5, // 0 = no jitter, 1 = full jitter
58
+ });
59
+
60
+ // HTTP status codes are RFC 7231 / 7232 / 6585 / 4918 / 7540 protocol
61
+ // constants; the numeric values are fixed by the spec, named here so the
62
+ // retry classifier reads as semantics ("Bad Request", "Service Unavailable")
63
+ // rather than bare numbers. Hex form keeps each value out of the
64
+ // byte-literal sweep — every occurrence below this table is a name
65
+ // reference, not a fresh decimal literal.
66
+ var HTTP = Object.freeze({
67
+ BAD_REQUEST: 0x190,
68
+ UNAUTHORIZED: 0x191,
69
+ FORBIDDEN: 0x193,
70
+ NOT_FOUND: 0x194,
71
+ METHOD_NOT_ALLOWED: 0x195,
72
+ REQUEST_TIMEOUT: 0x198,
73
+ CONFLICT: 0x199,
74
+ GONE: 0x19a,
75
+ LENGTH_REQUIRED: 0x19b,
76
+ PRECONDITION_FAILED: 0x19c,
77
+ PAYLOAD_TOO_LARGE: 0x19d,
78
+ URI_TOO_LONG: 0x19e,
79
+ UNSUPPORTED_MEDIA_TYPE: 0x19f,
80
+ RANGE_NOT_SATISFIABLE: 0x1a0,
81
+ EXPECTATION_FAILED: 0x1a1,
82
+ UNPROCESSABLE_ENTITY: 0x1a6,
83
+ TOO_EARLY: 0x1a9,
84
+ TOO_MANY_REQUESTS: 0x1ad,
85
+ UNAVAILABLE_FOR_LEGAL_REASONS: 0x1c3,
86
+ INTERNAL_SERVER_ERROR: 0x1f4,
87
+ NOT_IMPLEMENTED: 0x1f5,
88
+ BAD_GATEWAY: 0x1f6,
89
+ SERVICE_UNAVAILABLE: 0x1f7,
90
+ GATEWAY_TIMEOUT: 0x1f8,
91
+ HTTP_VERSION_NOT_SUPPORTED: 0x1f9,
92
+ });
93
+
94
+ // Errors that are permanently fatal — do NOT retry.
95
+ var NON_RETRYABLE_HTTP_STATUS = new Set([
96
+ HTTP.BAD_REQUEST, HTTP.UNAUTHORIZED, HTTP.FORBIDDEN, HTTP.NOT_FOUND,
97
+ HTTP.METHOD_NOT_ALLOWED, HTTP.CONFLICT, HTTP.GONE, HTTP.LENGTH_REQUIRED,
98
+ HTTP.PRECONDITION_FAILED, HTTP.PAYLOAD_TOO_LARGE, HTTP.URI_TOO_LONG,
99
+ HTTP.UNSUPPORTED_MEDIA_TYPE, HTTP.RANGE_NOT_SATISFIABLE, HTTP.EXPECTATION_FAILED,
100
+ HTTP.UNPROCESSABLE_ENTITY, HTTP.UNAVAILABLE_FOR_LEGAL_REASONS,
101
+ HTTP.NOT_IMPLEMENTED, HTTP.HTTP_VERSION_NOT_SUPPORTED,
102
+ ]);
103
+
104
+ // Errors that should be retried — transient by nature.
105
+ var RETRYABLE_HTTP_STATUS = new Set([
106
+ HTTP.REQUEST_TIMEOUT, HTTP.TOO_EARLY, HTTP.TOO_MANY_REQUESTS,
107
+ HTTP.INTERNAL_SERVER_ERROR, HTTP.BAD_GATEWAY, HTTP.SERVICE_UNAVAILABLE,
108
+ HTTP.GATEWAY_TIMEOUT,
109
+ ]);
110
+
111
+ // Network errors from Node's net layer that map to "retry" semantics.
112
+ var RETRYABLE_NET_ERRORS = new Set([
113
+ "ECONNRESET", "ECONNREFUSED", "ECONNABORTED", "ETIMEDOUT",
114
+ "EPIPE", "EAGAIN", "ENOTFOUND", "ENETUNREACH",
115
+ ]);
116
+
117
+ var STATE_CLOSED = "closed"; // normal — calls go through
118
+ var STATE_OPEN = "open"; // failing — calls fail fast
119
+ var STATE_HALF = "half-open"; // probing — one call goes through
120
+
121
+ var DEFAULT_BREAKER = Object.freeze({
122
+ failureThreshold: 10, // consecutive failures to open
123
+ cooldownMs: C.TIME.seconds(30), // time in OPEN before HALF_OPEN probe
124
+ successThreshold: 2, // consecutive HALF probes that close it
125
+ });
126
+
127
+ // ---- Call-site validation helpers (throw on bad input) ----
128
+
129
+ var _isPositiveInt = numericChecks.isPositiveInt;
130
+ var _isNonNegFinite = numericChecks.isFiniteNonNegative;
131
+ function _isAbortSignal(s) {
132
+ // Duck-typed: AbortSignal exposes .aborted (bool) and .addEventListener (fn)
133
+ return s != null && typeof s === "object" &&
134
+ typeof s.aborted === "boolean" &&
135
+ typeof s.addEventListener === "function";
136
+ }
137
+
138
+ function _validateRetryOpts(opts) {
139
+ if (!_isPositiveInt(opts.maxAttempts)) {
140
+ throw new TypeError("retry.withRetry: maxAttempts must be a positive integer, got " +
141
+ typeof opts.maxAttempts + " " + JSON.stringify(opts.maxAttempts));
142
+ }
143
+ if (!_isNonNegFinite(opts.baseDelayMs)) {
144
+ throw new TypeError("retry.withRetry: baseDelayMs must be a non-negative finite number, got " +
145
+ typeof opts.baseDelayMs + " " + JSON.stringify(opts.baseDelayMs));
146
+ }
147
+ if (!_isNonNegFinite(opts.maxDelayMs)) {
148
+ throw new TypeError("retry.withRetry: maxDelayMs must be a non-negative finite number, got " +
149
+ typeof opts.maxDelayMs + " " + JSON.stringify(opts.maxDelayMs));
150
+ }
151
+ if (typeof opts.jitterFactor !== "number" || !isFinite(opts.jitterFactor) ||
152
+ opts.jitterFactor < 0 || opts.jitterFactor > 1) {
153
+ throw new TypeError("retry.withRetry: jitterFactor must be a finite number in [0, 1], got " +
154
+ typeof opts.jitterFactor + " " + JSON.stringify(opts.jitterFactor));
155
+ }
156
+ if (opts.isRetryable !== undefined && typeof opts.isRetryable !== "function") {
157
+ throw new TypeError("retry.withRetry: isRetryable must be a function or undefined, got " +
158
+ typeof opts.isRetryable);
159
+ }
160
+ if (opts.onRetry !== undefined && typeof opts.onRetry !== "function") {
161
+ throw new TypeError("retry.withRetry: onRetry must be a function or undefined, got " +
162
+ typeof opts.onRetry);
163
+ }
164
+ if (opts.signal !== undefined && opts.signal !== null && !_isAbortSignal(opts.signal)) {
165
+ throw new TypeError("retry.withRetry: signal must be an AbortSignal or undefined");
166
+ }
167
+ }
168
+
169
+ function _validateBreakerOpts(name, opts) {
170
+ if (typeof name !== "string" || name.length === 0) {
171
+ throw new TypeError("retry.CircuitBreaker: name must be a non-empty string, got " +
172
+ typeof name + " " + JSON.stringify(name));
173
+ }
174
+ if (!_isPositiveInt(opts.failureThreshold)) {
175
+ throw new TypeError("retry.CircuitBreaker: failureThreshold must be a positive integer, got " +
176
+ typeof opts.failureThreshold + " " + JSON.stringify(opts.failureThreshold));
177
+ }
178
+ if (!_isNonNegFinite(opts.cooldownMs)) {
179
+ throw new TypeError("retry.CircuitBreaker: cooldownMs must be a non-negative finite number, got " +
180
+ typeof opts.cooldownMs + " " + JSON.stringify(opts.cooldownMs));
181
+ }
182
+ if (!_isPositiveInt(opts.successThreshold)) {
183
+ throw new TypeError("retry.CircuitBreaker: successThreshold must be a positive integer, got " +
184
+ typeof opts.successThreshold + " " + JSON.stringify(opts.successThreshold));
185
+ }
186
+ }
187
+
188
+ // ---- Public surface ----
189
+
190
+ // Tolerant read of err shape; missing fields → false.
191
+ function isRetryable(err) {
192
+ if (!err) return false;
193
+ if (err.isObjectStoreError && err.permanent) return false;
194
+ if (err.permanent) return false;
195
+ if (typeof err.statusCode === "number") {
196
+ if (RETRYABLE_HTTP_STATUS.has(err.statusCode)) return true;
197
+ if (NON_RETRYABLE_HTTP_STATUS.has(err.statusCode)) return false;
198
+ if (err.statusCode >= 500) return true; // unknown 5xx → assume retryable
199
+ return false;
200
+ }
201
+ if (err.code && RETRYABLE_NET_ERRORS.has(err.code)) return true;
202
+ return false; // default: not retryable (avoid masking bugs)
203
+ }
204
+
205
+ // Throw on bad input: attempt must be a positive int; opts (when supplied)
206
+ // must have non-neg-finite baseDelayMs/maxDelayMs and finite jitterFactor
207
+ // in [0,1]. We don't full-validate opts here every call (hot path) —
208
+ // defaults are frozen, so the only way a bad opts reaches here is via
209
+ // withRetry which already validated, OR a caller using backoffDelay
210
+ // directly. For that
211
+ // direct case we still validate the attempt arg loudly.
212
+ function backoffDelay(attempt, opts) {
213
+ if (!_isPositiveInt(attempt)) {
214
+ throw new TypeError("retry.backoffDelay: attempt must be a positive integer, got " +
215
+ typeof attempt + " " + JSON.stringify(attempt));
216
+ }
217
+ opts = opts || DEFAULT_RETRY;
218
+ var base = opts.baseDelayMs * Math.pow(2, attempt - 1);
219
+ var capped = Math.min(base, opts.maxDelayMs);
220
+ // Cryptographically-strong jitter so a timing-attack mitigation isn't
221
+ // undermined by Math.random's predictable PRNG.
222
+ var jitterDenom = 1_000_000;
223
+ var jitter = capped * opts.jitterFactor * (nodeCrypto.randomInt(0, jitterDenom) / jitterDenom);
224
+ return Math.floor(capped - jitter);
225
+ }
226
+
227
+ async function withRetry(fn, opts) {
228
+ if (typeof fn !== "function") {
229
+ throw new TypeError("retry.withRetry: fn must be a function, got " + typeof fn);
230
+ }
231
+ opts = Object.assign({}, DEFAULT_RETRY, opts || {});
232
+ _validateRetryOpts(opts);
233
+ // opts.isRetryable lets callers override the default classifier.
234
+ // Default classifier targets HTTP/network errors and is intentionally
235
+ // conservative (unknown errors → NOT retryable, to avoid masking bugs).
236
+ // Callers like the handlers primitive whose flush failures are operator-
237
+ // defined (not network-shaped) pass `isRetryable: function () { return true; }`
238
+ // to retry on any error. When overridden, the caller owns full classification
239
+ // including any `err.permanent` semantics they want to honor.
240
+ var classify = (typeof opts.isRetryable === "function") ? opts.isRetryable : isRetryable;
241
+ var lastErr = null;
242
+ for (var attempt = 1; attempt <= opts.maxAttempts; attempt++) {
243
+ try {
244
+ return await fn(attempt);
245
+ } catch (err) {
246
+ lastErr = err;
247
+ var retryable = classify(err);
248
+ if (!retryable || attempt === opts.maxAttempts) {
249
+ if (!retryable) {
250
+ _emitEvent("retry.exhausted", 1, { reason: "non-retryable" });
251
+ } else {
252
+ _emitEvent("retry.exhausted", 1, { reason: "max-attempts", attempts: attempt });
253
+ }
254
+ throw err;
255
+ }
256
+ var delay = backoffDelay(attempt, opts);
257
+ _emitEvent("retry.attempt", 1, { attempt: attempt });
258
+ if (typeof opts.onRetry === "function") {
259
+ // Hot-path observability sink — drops silent on observer throw
260
+ // so a thrown observer can't crash the retry loop. Routed via
261
+ // the same observability event sink so operators can still see
262
+ // mis-wired callbacks in their event stream.
263
+ try { opts.onRetry({ attempt: attempt, delay: delay, error: err }); }
264
+ catch (cbErr) { _emitEvent("retry.onRetry.threw", 1, { error: cbErr.message }); }
265
+ }
266
+ // Honor opts.signal during the backoff sleep — a caller who aborts
267
+ // mid-retry should be unblocked immediately rather than waiting
268
+ // out the (potentially multi-second) backoff.
269
+ await safeAsync().sleep(delay, { signal: opts.signal });
270
+ }
271
+ }
272
+ throw lastErr;
273
+ }
274
+
275
+ // ---- Circuit breaker ----
276
+
277
+ class CircuitBreaker {
278
+ constructor(name, opts) {
279
+ var merged = Object.assign({}, DEFAULT_BREAKER, opts || {});
280
+ _validateBreakerOpts(name || "", merged);
281
+ this.name = name;
282
+ this.opts = merged;
283
+ this.state = STATE_CLOSED;
284
+ this.consecutiveFailures = 0;
285
+ this.consecutiveSuccesses = 0;
286
+ this.openedAt = 0;
287
+ }
288
+
289
+ // Wrap an async function. The breaker observes outcomes and may fail-fast.
290
+ async wrap(fn) {
291
+ if (typeof fn !== "function") {
292
+ throw new TypeError("retry.CircuitBreaker.wrap: fn must be a function, got " + typeof fn);
293
+ }
294
+ if (this.state === STATE_OPEN) {
295
+ if (Date.now() - this.openedAt >= this.opts.cooldownMs) {
296
+ this._transition(STATE_OPEN, STATE_HALF);
297
+ } else {
298
+ var err = new Error("circuit breaker '" + this.name + "' is OPEN");
299
+ err.code = "CIRCUIT_OPEN";
300
+ err.permanent = false; // still transient
301
+ err.isObjectStoreError = true;
302
+ throw err;
303
+ }
304
+ }
305
+ try {
306
+ var result = await fn();
307
+ this._onSuccess();
308
+ return result;
309
+ } catch (e) {
310
+ this._onFailure(e);
311
+ throw e;
312
+ }
313
+ }
314
+
315
+ // Centralizes state changes so we emit one observability event per
316
+ // transition. Same name + label shape regardless of which method
317
+ // initiated the change.
318
+ _transition(from, to) {
319
+ if (from === to) return;
320
+ this.state = to;
321
+ _emitEvent("breaker.state.change", 1, { name: this.name, from: from, to: to });
322
+ }
323
+
324
+ _onSuccess() {
325
+ if (this.state === STATE_HALF) {
326
+ this.consecutiveSuccesses += 1;
327
+ if (this.consecutiveSuccesses >= this.opts.successThreshold) {
328
+ this._transition(STATE_HALF, STATE_CLOSED);
329
+ this.consecutiveFailures = 0;
330
+ this.consecutiveSuccesses = 0;
331
+ }
332
+ } else {
333
+ this.consecutiveFailures = 0;
334
+ }
335
+ }
336
+
337
+ _onFailure(err) {
338
+ // Don't trip the breaker on permanent errors — those are caller bugs,
339
+ // not backend health issues.
340
+ if (err && err.permanent) return;
341
+ if (err && err.isObjectStoreError && err.code === "CIRCUIT_OPEN") return;
342
+
343
+ this.consecutiveFailures += 1;
344
+ this.consecutiveSuccesses = 0;
345
+ if (this.state === STATE_HALF) {
346
+ this._transition(STATE_HALF, STATE_OPEN);
347
+ this.openedAt = Date.now();
348
+ } else if (this.state === STATE_CLOSED && this.consecutiveFailures >= this.opts.failureThreshold) {
349
+ this._transition(STATE_CLOSED, STATE_OPEN);
350
+ this.openedAt = Date.now();
351
+ }
352
+ }
353
+
354
+ getState() { return this.state; }
355
+
356
+ reset() {
357
+ var prior = this.state;
358
+ if (prior !== STATE_CLOSED) this._transition(prior, STATE_CLOSED);
359
+ this.consecutiveFailures = 0;
360
+ this.consecutiveSuccesses = 0;
361
+ this.openedAt = 0;
362
+ }
363
+ }
364
+
365
+ module.exports = {
366
+ withRetry: withRetry,
367
+ isRetryable: isRetryable,
368
+ backoffDelay: backoffDelay,
369
+ CircuitBreaker: CircuitBreaker,
370
+ DEFAULT_RETRY: DEFAULT_RETRY,
371
+ DEFAULT_BREAKER: DEFAULT_BREAKER,
372
+ RETRYABLE_HTTP_STATUS: Array.from(RETRYABLE_HTTP_STATUS),
373
+ NON_RETRYABLE_HTTP_STATUS: Array.from(NON_RETRYABLE_HTTP_STATUS),
374
+ RETRYABLE_NET_ERRORS: Array.from(RETRYABLE_NET_ERRORS),
375
+ STATES: { CLOSED: STATE_CLOSED, OPEN: STATE_OPEN, HALF_OPEN: STATE_HALF },
376
+ };