@sylphx/sdk 0.28.0 → 0.30.0

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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +30 -118
  3. package/dist/access.d.ts +659 -0
  4. package/dist/access.js +638 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/ai.d.ts +176 -0
  7. package/dist/ai.js +112 -0
  8. package/dist/ai.js.map +1 -0
  9. package/dist/artifacts.d.ts +165 -0
  10. package/dist/artifacts.js +129 -0
  11. package/dist/artifacts.js.map +1 -0
  12. package/dist/auth.d.ts +896 -0
  13. package/dist/auth.js +828 -0
  14. package/dist/auth.js.map +1 -0
  15. package/dist/billing.d.ts +758 -0
  16. package/dist/billing.js +553 -0
  17. package/dist/billing.js.map +1 -0
  18. package/dist/broker.d.ts +226 -0
  19. package/dist/broker.js +187 -0
  20. package/dist/broker.js.map +1 -0
  21. package/dist/build.d.ts +313 -0
  22. package/dist/build.js +271 -0
  23. package/dist/build.js.map +1 -0
  24. package/dist/common.d.ts +162 -0
  25. package/dist/common.js +41 -0
  26. package/dist/common.js.map +1 -0
  27. package/dist/config.d.ts +198 -0
  28. package/dist/config.js +168 -0
  29. package/dist/config.js.map +1 -0
  30. package/dist/connections.d.ts +354 -0
  31. package/dist/connections.js +313 -0
  32. package/dist/connections.js.map +1 -0
  33. package/dist/data.d.ts +858 -0
  34. package/dist/data.js +814 -0
  35. package/dist/data.js.map +1 -0
  36. package/dist/entitlement.d.ts +172 -0
  37. package/dist/entitlement.js +116 -0
  38. package/dist/entitlement.js.map +1 -0
  39. package/dist/events.d.ts +1324 -0
  40. package/dist/events.js +1227 -0
  41. package/dist/events.js.map +1 -0
  42. package/dist/hosting.d.ts +709 -0
  43. package/dist/hosting.js +611 -0
  44. package/dist/hosting.js.map +1 -0
  45. package/dist/index.d.ts +79 -33656
  46. package/dist/index.js +113 -0
  47. package/dist/index.js.map +1 -0
  48. package/dist/keys.d.ts +438 -0
  49. package/dist/keys.js +406 -0
  50. package/dist/keys.js.map +1 -0
  51. package/dist/methods.d.ts +2 -0
  52. package/dist/methods.js +3995 -0
  53. package/dist/methods.js.map +1 -0
  54. package/dist/network.d.ts +733 -0
  55. package/dist/network.js +711 -0
  56. package/dist/network.js.map +1 -0
  57. package/dist/notify.d.ts +1359 -0
  58. package/dist/notify.js +1282 -0
  59. package/dist/notify.js.map +1 -0
  60. package/dist/observability.d.ts +509 -0
  61. package/dist/observability.js +437 -0
  62. package/dist/observability.js.map +1 -0
  63. package/dist/release.d.ts +303 -0
  64. package/dist/release.js +214 -0
  65. package/dist/release.js.map +1 -0
  66. package/dist/runners.d.ts +262 -0
  67. package/dist/runners.js +238 -0
  68. package/dist/runners.js.map +1 -0
  69. package/dist/runtime.d.ts +88 -0
  70. package/dist/runtime.js +226 -0
  71. package/dist/runtime.js.map +1 -0
  72. package/dist/sandboxes.d.ts +1705 -0
  73. package/dist/sandboxes.js +1226 -0
  74. package/dist/sandboxes.js.map +1 -0
  75. package/dist/secrets.d.ts +508 -0
  76. package/dist/secrets.js +474 -0
  77. package/dist/secrets.js.map +1 -0
  78. package/dist/workflows.d.ts +678 -0
  79. package/dist/workflows.js +595 -0
  80. package/dist/workflows.js.map +1 -0
  81. package/package.json +33 -112
  82. package/dist/connect.d.ts +0 -2838
  83. package/dist/connect.mjs +0 -220
  84. package/dist/connect.mjs.map +0 -1
  85. package/dist/health/index.d.ts +0 -1394
  86. package/dist/health/index.mjs +0 -1394
  87. package/dist/health/index.mjs.map +0 -1
  88. package/dist/index.mjs +0 -38429
  89. package/dist/index.mjs.map +0 -1
  90. package/dist/nextjs/index.d.ts +0 -724
  91. package/dist/nextjs/index.mjs +0 -3332
  92. package/dist/nextjs/index.mjs.map +0 -1
  93. package/dist/react/index.d.ts +0 -13066
  94. package/dist/react/index.mjs +0 -35329
  95. package/dist/react/index.mjs.map +0 -1
  96. package/dist/server/index.d.ts +0 -2000
  97. package/dist/server/index.mjs +0 -3446
  98. package/dist/server/index.mjs.map +0 -1
  99. package/dist/web-analytics.d.ts +0 -90
  100. package/dist/web-analytics.mjs +0 -225
  101. package/dist/web-analytics.mjs.map +0 -1
@@ -1,1394 +0,0 @@
1
- // src/health/causality.ts
2
- var BAGGAGE_KEY_CAUSE = "sylphx.health.cause";
3
- var BAGGAGE_KEY_CHAIN = "sylphx.health.cause_chain";
4
- var DEFAULT_CAUSE_THRESHOLD = 0.5;
5
- var MAX_CHAIN_LENGTH = 5;
6
- var cachedApi;
7
- async function tryLoadCausalityApi() {
8
- if (cachedApi !== void 0) return cachedApi;
9
- try {
10
- const api = await import("@opentelemetry/api");
11
- if (!api?.context || !api?.propagation) {
12
- cachedApi = null;
13
- return cachedApi;
14
- }
15
- cachedApi = { context: api.context, propagation: api.propagation };
16
- } catch {
17
- cachedApi = null;
18
- }
19
- return cachedApi;
20
- }
21
- function defaultServiceName() {
22
- if (typeof process !== "undefined" && process.env) {
23
- if (process.env.OTEL_SERVICE_NAME !== void 0) return process.env.OTEL_SERVICE_NAME;
24
- if (process.env.SERVICE_NAME !== void 0) return process.env.SERVICE_NAME;
25
- }
26
- return "unknown";
27
- }
28
- function isSafeIdentifier(part) {
29
- return part.length > 0 && !/[,@\s]/.test(part);
30
- }
31
- function encodeCauseFromScore(score, threshold, serviceName) {
32
- const factors = score.signalFactors;
33
- if (!factors) return null;
34
- const entries = [];
35
- for (const [signalName, factor] of Object.entries(factors)) {
36
- if (typeof factor !== "number" || !Number.isFinite(factor)) continue;
37
- if (factor >= threshold) continue;
38
- if (!isSafeIdentifier(signalName) || !isSafeIdentifier(serviceName)) continue;
39
- entries.push(`${signalName}@${serviceName}`);
40
- }
41
- if (entries.length === 0) return null;
42
- return entries.join(",");
43
- }
44
- function parseCauseValue(value) {
45
- const out = [];
46
- for (const raw of value.split(",")) {
47
- const piece = raw.trim();
48
- if (piece.length === 0) continue;
49
- const atIdx = piece.indexOf("@");
50
- if (atIdx <= 0 || atIdx === piece.length - 1) continue;
51
- const signal = piece.slice(0, atIdx);
52
- const service = piece.slice(atIdx + 1);
53
- if (!isSafeIdentifier(signal) || !isSafeIdentifier(service)) continue;
54
- out.push({ signal, service });
55
- }
56
- return out;
57
- }
58
- function parseChainValue(value) {
59
- return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0 && isSafeIdentifier(s));
60
- }
61
- function appendChain(prev, serviceName, maxLen) {
62
- if (!isSafeIdentifier(serviceName)) return prev;
63
- if (prev[prev.length - 1] === serviceName) return prev;
64
- const next = [...prev, serviceName];
65
- if (next.length <= maxLen) return next;
66
- return next.slice(next.length - maxLen);
67
- }
68
- var CausalityHandleImpl = class {
69
- _state = "loading";
70
- apiRef = null;
71
- threshold;
72
- serviceName;
73
- propagateChain;
74
- constructor(opts) {
75
- const threshold = opts.threshold ?? DEFAULT_CAUSE_THRESHOLD;
76
- if (!Number.isFinite(threshold) || threshold <= 0 || threshold > 1) {
77
- throw new Error(`createCausalityHandle: threshold must be in (0, 1], got ${threshold}`);
78
- }
79
- this.threshold = threshold;
80
- this.serviceName = opts.serviceName ?? defaultServiceName();
81
- this.propagateChain = opts.propagateChain !== false;
82
- void this.initialize();
83
- }
84
- get state() {
85
- return this._state;
86
- }
87
- async initialize() {
88
- const api = await tryLoadCausalityApi();
89
- if (this._state === "disposed") return;
90
- if (api === null) {
91
- this._state = "unavailable";
92
- return;
93
- }
94
- this.apiRef = api;
95
- this._state = "ready";
96
- }
97
- readCause() {
98
- if (this._state !== "ready" || !this.apiRef) return null;
99
- try {
100
- const baggage = this.apiRef.propagation.getActiveBaggage();
101
- if (!baggage) return null;
102
- const causeEntry = baggage.getEntry(BAGGAGE_KEY_CAUSE);
103
- if (!causeEntry || typeof causeEntry.value !== "string") return null;
104
- const causes = parseCauseValue(causeEntry.value);
105
- if (causes.length === 0) return null;
106
- const chainEntry = baggage.getEntry(BAGGAGE_KEY_CHAIN);
107
- const chain = chainEntry && typeof chainEntry.value === "string" ? parseChainValue(chainEntry.value) : [];
108
- return { causes, chain };
109
- } catch {
110
- return null;
111
- }
112
- }
113
- encodeCause(score) {
114
- try {
115
- return encodeCauseFromScore(score, this.threshold, this.serviceName);
116
- } catch {
117
- return null;
118
- }
119
- }
120
- async runWithCause(fn, score) {
121
- if (this._state !== "ready" || !this.apiRef) {
122
- return await fn();
123
- }
124
- try {
125
- const localCause = this.encodeCause(score);
126
- const existing = this.apiRef.propagation.getActiveBaggage();
127
- const existingChain = existing?.getEntry(BAGGAGE_KEY_CHAIN)?.value ? parseChainValue(existing.getEntry(BAGGAGE_KEY_CHAIN).value) : [];
128
- if (!localCause && !existing) {
129
- return await fn();
130
- }
131
- const baseBaggage = existing ?? this.apiRef.propagation.createBaggage();
132
- let nextBaggage = baseBaggage;
133
- if (localCause) {
134
- const newEntry = { value: localCause };
135
- const upstream = existing?.getEntry(BAGGAGE_KEY_CAUSE)?.value;
136
- const mergedValue = upstream ? mergeCauseValues(upstream, localCause) : localCause;
137
- nextBaggage = nextBaggage.setEntry(BAGGAGE_KEY_CAUSE, {
138
- ...newEntry,
139
- value: mergedValue
140
- });
141
- }
142
- if (this.propagateChain && (localCause || existingChain.length > 0)) {
143
- const nextChain = localCause ? appendChain(existingChain, this.serviceName, MAX_CHAIN_LENGTH) : existingChain;
144
- if (nextChain.length > 0) {
145
- nextBaggage = nextBaggage.setEntry(BAGGAGE_KEY_CHAIN, {
146
- value: nextChain.join(",")
147
- });
148
- }
149
- }
150
- const ctxWithBaggage = this.apiRef.propagation.setBaggage(
151
- this.apiRef.context.active(),
152
- nextBaggage
153
- );
154
- return await this.apiRef.context.with(ctxWithBaggage, fn);
155
- } catch {
156
- return await fn();
157
- }
158
- }
159
- dispose() {
160
- this._state = "disposed";
161
- this.apiRef = null;
162
- }
163
- };
164
- function mergeCauseValues(existing, local) {
165
- const seen = /* @__PURE__ */ new Set();
166
- const out = [];
167
- for (const piece of [...existing.split(","), ...local.split(",")]) {
168
- const trimmed = piece.trim();
169
- if (trimmed.length === 0 || seen.has(trimmed)) continue;
170
- seen.add(trimmed);
171
- out.push(trimmed);
172
- }
173
- return out.join(",");
174
- }
175
- function createCausalityHandle(opts = {}) {
176
- return new CausalityHandleImpl(opts);
177
- }
178
-
179
- // src/health/effects.ts
180
- import { Effect } from "effect";
181
-
182
- // src/health/types.ts
183
- var HealthError = class extends Error {
184
- _tag = "HealthError";
185
- cause;
186
- constructor(message, cause) {
187
- super(message);
188
- this.name = "HealthError";
189
- this.cause = cause;
190
- }
191
- };
192
-
193
- // src/health/effects.ts
194
- function evaluateEffect(evaluator) {
195
- return Effect.tryPromise({
196
- try: () => evaluator(),
197
- catch: (err) => new HealthError("health evaluation failed", err)
198
- });
199
- }
200
-
201
- // src/health/handler.ts
202
- var DIRECT_PROBE_LIVENESS_FLOOR = 0.5;
203
- function statusForScore(score) {
204
- return Number.isFinite(score) && score >= DIRECT_PROBE_LIVENESS_FLOOR ? 200 : 503;
205
- }
206
- function createWebHandler(source) {
207
- return async (_req) => {
208
- try {
209
- const score = await source.evaluate();
210
- return new Response(JSON.stringify(score), {
211
- status: statusForScore(score.score),
212
- headers: {
213
- "Content-Type": "application/json",
214
- // Cache-Control: never cache. Even 1-second cache on a
215
- // CDN edge would mask a fast-moving health collapse.
216
- "Cache-Control": "no-store, no-cache, must-revalidate"
217
- }
218
- });
219
- } catch (err) {
220
- const message = err instanceof Error ? err.message : String(err);
221
- return new Response(
222
- JSON.stringify({
223
- error: "health_evaluator_failed",
224
- message
225
- }),
226
- {
227
- status: 500,
228
- headers: {
229
- "Content-Type": "application/json",
230
- "Cache-Control": "no-store, no-cache, must-revalidate"
231
- }
232
- }
233
- );
234
- }
235
- };
236
- }
237
- function createNodeHandler(source) {
238
- return async (_req, res) => {
239
- try {
240
- const score = await source.evaluate();
241
- res.statusCode = statusForScore(score.score);
242
- res.setHeader("Content-Type", "application/json");
243
- res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
244
- res.end(JSON.stringify(score));
245
- } catch (err) {
246
- const message = err instanceof Error ? err.message : String(err);
247
- res.statusCode = 500;
248
- res.setHeader("Content-Type", "application/json");
249
- res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
250
- res.end(JSON.stringify({ error: "health_evaluator_failed", message }));
251
- }
252
- };
253
- }
254
-
255
- // src/health/history.ts
256
- var GENESIS_PREV_HASH = "0".repeat(64);
257
- var DEFAULT_HISTORY_CAPACITY = 1e3;
258
- var HASH_TEXT_ENCODER = new TextEncoder();
259
- var HEX_BYTE = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
260
- var nodeCreateHash;
261
- function canonicalizeSignals(signals) {
262
- const keys = Object.keys(signals).sort();
263
- const pairs = keys.map((k) => {
264
- const value = signals[k];
265
- return [k, value];
266
- });
267
- return JSON.stringify(Object.fromEntries(pairs));
268
- }
269
- function encodeScore(score) {
270
- return score.toFixed(6);
271
- }
272
- function hasNodeCryptoRuntime() {
273
- const versions = globalThis.process?.versions;
274
- return typeof versions?.node === "string" || typeof versions?.bun === "string";
275
- }
276
- async function resolveNodeCreateHash() {
277
- if (nodeCreateHash !== void 0) return nodeCreateHash;
278
- if (!hasNodeCryptoRuntime()) {
279
- nodeCreateHash = null;
280
- return null;
281
- }
282
- try {
283
- const cryptoModule = await import("crypto");
284
- nodeCreateHash = cryptoModule.createHash;
285
- return nodeCreateHash;
286
- } catch {
287
- nodeCreateHash = null;
288
- return null;
289
- }
290
- }
291
- async function sha256Hex(input) {
292
- const createHash = await resolveNodeCreateHash();
293
- if (createHash) {
294
- return createHash("sha256").update(input).digest("hex");
295
- }
296
- const subtle = globalThis.crypto?.subtle;
297
- if (!subtle || typeof subtle.digest !== "function") {
298
- return "";
299
- }
300
- const buf = HASH_TEXT_ENCODER.encode(input);
301
- const digest = await subtle.digest("SHA-256", buf);
302
- const bytes = new Uint8Array(digest);
303
- let out = "";
304
- for (let i = 0; i < bytes.length; i++) {
305
- out += HEX_BYTE[bytes[i]];
306
- }
307
- return out;
308
- }
309
- async function computeEntryHash(prehash) {
310
- const canonical = [
311
- prehash.sequence.toString(10),
312
- prehash.evaluatedAt,
313
- encodeScore(prehash.score),
314
- prehash.signalsDigest,
315
- prehash.prevHash
316
- ].join("|");
317
- return await sha256Hex(canonical);
318
- }
319
- var InMemoryHistoryStoreImpl = class {
320
- capacity;
321
- buf = [];
322
- constructor(opts = {}) {
323
- const cap = opts.capacity ?? DEFAULT_HISTORY_CAPACITY;
324
- if (!Number.isFinite(cap) || cap <= 0 || cap > 1e7) {
325
- throw new Error(`InMemoryHistoryStore: capacity must be in (0, 10000000], got ${cap}`);
326
- }
327
- this.capacity = cap;
328
- }
329
- append(entry) {
330
- this.buf.push(entry);
331
- if (this.buf.length > this.capacity) {
332
- this.buf.shift();
333
- }
334
- }
335
- range(query) {
336
- const out = [];
337
- for (const e of this.buf) {
338
- if (query.fromSequence !== void 0 && e.sequence < query.fromSequence) continue;
339
- if (query.toSequence !== void 0 && e.sequence > query.toSequence) continue;
340
- if (query.fromTimestamp !== void 0 && e.evaluatedAt < query.fromTimestamp) continue;
341
- if (query.toTimestamp !== void 0 && e.evaluatedAt > query.toTimestamp) continue;
342
- out.push(e);
343
- if (query.limit !== void 0 && out.length >= query.limit) break;
344
- }
345
- return out;
346
- }
347
- latest() {
348
- return this.buf[this.buf.length - 1] ?? null;
349
- }
350
- };
351
- function createInMemoryHistoryStore(opts = {}) {
352
- return new InMemoryHistoryStoreImpl(opts);
353
- }
354
- var HistoryRecorderImpl = class {
355
- store;
356
- nextSequence = 0;
357
- prevHash = GENESIS_PREV_HASH;
358
- disposed = false;
359
- initPromise;
360
- /**
361
- * Serializes record() calls so concurrent `evaluate()` invocations
362
- * don't race on `nextSequence` / `prevHash`. Each new call chains off
363
- * the previous; the chain itself never propagates errors (catch in the
364
- * tail so one failed record doesn't poison subsequent ones).
365
- */
366
- inFlight = Promise.resolve();
367
- constructor(opts) {
368
- this.store = opts.store ?? createInMemoryHistoryStore({ capacity: opts.capacity });
369
- this.initPromise = this.warmStart();
370
- }
371
- async warmStart() {
372
- try {
373
- const latest = await this.store.latest();
374
- if (latest && Number.isFinite(latest.sequence)) {
375
- this.nextSequence = latest.sequence + 1;
376
- this.prevHash = latest.entryHash || GENESIS_PREV_HASH;
377
- }
378
- } catch {
379
- }
380
- }
381
- async recordInternal(score) {
382
- if (this.disposed) return null;
383
- await this.initPromise;
384
- try {
385
- const signalsDigest = await sha256Hex(canonicalizeSignals(score.signals));
386
- const prehash = {
387
- sequence: this.nextSequence,
388
- evaluatedAt: score.lastTickAt,
389
- score: score.score,
390
- signalsDigest,
391
- prevHash: this.prevHash
392
- };
393
- const entryHash = await computeEntryHash(prehash);
394
- const entry = { ...prehash, entryHash };
395
- await this.store.append(entry);
396
- this.nextSequence += 1;
397
- this.prevHash = entryHash || GENESIS_PREV_HASH;
398
- return entry;
399
- } catch {
400
- await this.warmStart();
401
- return null;
402
- }
403
- }
404
- async record(score) {
405
- const job = this.inFlight.then(() => this.recordInternal(score));
406
- this.inFlight = job.catch(() => void 0);
407
- return await job;
408
- }
409
- async drainPendingRecords() {
410
- try {
411
- await this.inFlight;
412
- } catch {
413
- }
414
- }
415
- async range(query) {
416
- await this.drainPendingRecords();
417
- try {
418
- return await this.store.range(query);
419
- } catch {
420
- return [];
421
- }
422
- }
423
- async latest() {
424
- await this.drainPendingRecords();
425
- try {
426
- return await this.store.latest();
427
- } catch {
428
- return null;
429
- }
430
- }
431
- async verify(query) {
432
- const entries = await this.range(query);
433
- return await verifyChain(entries);
434
- }
435
- dispose() {
436
- this.disposed = true;
437
- }
438
- };
439
- function createHistoryRecorder(opts = {}) {
440
- return new HistoryRecorderImpl(opts);
441
- }
442
- async function verifyChain(entries) {
443
- if (entries.length === 0) {
444
- return { verified: true, entriesChecked: 0, firstBreakAtSequence: null, reason: null };
445
- }
446
- let expectedPrev = null;
447
- let checked = 0;
448
- for (let i = 0; i < entries.length; i++) {
449
- const entry = entries[i];
450
- if (i === 0 && entry.sequence === 0 && entry.prevHash !== GENESIS_PREV_HASH) {
451
- return {
452
- verified: false,
453
- entriesChecked: checked,
454
- firstBreakAtSequence: entry.sequence,
455
- reason: `genesis entry must have prevHash="${GENESIS_PREV_HASH}", got ${entry.prevHash}`
456
- };
457
- }
458
- if (i > 0 && expectedPrev !== null && entry.prevHash !== expectedPrev) {
459
- return {
460
- verified: false,
461
- entriesChecked: checked,
462
- firstBreakAtSequence: entry.sequence,
463
- reason: `prevHash mismatch at sequence ${entry.sequence}: expected ${expectedPrev}, got ${entry.prevHash}`
464
- };
465
- }
466
- const recomputedHash = await computeEntryHash({
467
- sequence: entry.sequence,
468
- evaluatedAt: entry.evaluatedAt,
469
- score: entry.score,
470
- signalsDigest: entry.signalsDigest,
471
- prevHash: entry.prevHash
472
- });
473
- if (entry.entryHash && recomputedHash && recomputedHash !== entry.entryHash) {
474
- return {
475
- verified: false,
476
- entriesChecked: checked,
477
- firstBreakAtSequence: entry.sequence,
478
- reason: `entryHash mismatch at sequence ${entry.sequence}: stored=${entry.entryHash} recomputed=${recomputedHash}`
479
- };
480
- }
481
- expectedPrev = entry.entryHash || null;
482
- checked += 1;
483
- }
484
- return {
485
- verified: true,
486
- entriesChecked: checked,
487
- firstBreakAtSequence: null,
488
- reason: null
489
- };
490
- }
491
-
492
- // src/health/otel.ts
493
- var SDK_NAME = "@sylphx/sdk/health";
494
- var SDK_VERSION = "0.11.0";
495
- var METRIC_NAMES = {
496
- score: "health.score",
497
- signalFactor: "health.signal.factor",
498
- signalValue: "health.signal.value",
499
- signalValueState: "health.signal.value_state",
500
- /** ADR-143 §3.3 — increments per evaluation when an upstream cause is observed. */
501
- downstreamCause: "health.downstream_cause"
502
- };
503
- var SPAN_ATTRIBUTES = {
504
- score: "service.health.score",
505
- signalFactor: (name) => `service.health.signal.${name}.factor`,
506
- /** ADR-143 §3.2 — the upstream service that originated the failure chain. */
507
- causeRoot: "service.health.cause_root",
508
- /** ADR-143 §3.2 — the signal at the root that failed. */
509
- causeSignal: "service.health.cause_signal",
510
- /** ADR-143 §3.2 — comma-delimited hop chain (oldest to newest). */
511
- causeChain: "service.health.cause_chain"
512
- };
513
- var EVENT_NAMES = {
514
- evaluated: "health.evaluated"
515
- };
516
- function createOtelEmitter(opts = {}) {
517
- return new OtelEmitterImpl(opts);
518
- }
519
- var OtelEmitterImpl = class {
520
- constructor(opts) {
521
- this.opts = opts;
522
- this.staticAttrs = opts.attributes ?? {};
523
- this.events = opts.events === true;
524
- if (opts.meter) {
525
- this.instruments = buildInstruments(opts.meter);
526
- this._state = "ready";
527
- return;
528
- }
529
- void this.initialize();
530
- }
531
- _state = "loading";
532
- instruments = null;
533
- traceApi = null;
534
- staticAttrs;
535
- events;
536
- get state() {
537
- return this._state;
538
- }
539
- async initialize() {
540
- const api = await tryLoadOtelApi();
541
- if (api === null) {
542
- this._state = "unavailable";
543
- return;
544
- }
545
- if (this._state === "disposed") return;
546
- try {
547
- const meter = api.metrics.getMeter(SDK_NAME, SDK_VERSION);
548
- this.instruments = buildInstruments(meter);
549
- this.traceApi = api.trace;
550
- this._state = "ready";
551
- } catch {
552
- this._state = "unavailable";
553
- }
554
- }
555
- emit(score, upstreamCause) {
556
- if (this._state !== "ready" || !this.instruments) return;
557
- const baseAttrs = { ...this.staticAttrs };
558
- try {
559
- this.instruments.scoreGauge.record(score.score, baseAttrs);
560
- for (const [signalName, rawValue] of Object.entries(score.signals)) {
561
- const signalAttrs = { ...baseAttrs, "signal.name": signalName };
562
- const factor = score.signalFactors?.[signalName];
563
- if (typeof factor === "number" && Number.isFinite(factor)) {
564
- this.instruments.factorGauge.record(factor, signalAttrs);
565
- }
566
- if (typeof rawValue === "number" && Number.isFinite(rawValue)) {
567
- this.instruments.valueGauge.record(rawValue, signalAttrs);
568
- } else {
569
- const stateAttrs = {
570
- ...signalAttrs,
571
- state: String(rawValue)
572
- };
573
- this.instruments.valueStateCounter.add(1, stateAttrs);
574
- }
575
- }
576
- if (upstreamCause && upstreamCause.causes.length > 0) {
577
- for (const cause of upstreamCause.causes) {
578
- this.instruments.downstreamCauseCounter.add(1, {
579
- ...baseAttrs,
580
- cause_root: cause.service,
581
- cause_signal: cause.signal
582
- });
583
- }
584
- }
585
- if (this.traceApi) {
586
- const span = this.traceApi.getActiveSpan?.();
587
- maybeAttachToSpan(span, score, this.events, upstreamCause);
588
- }
589
- } catch {
590
- }
591
- }
592
- dispose() {
593
- this._state = "disposed";
594
- this.instruments = null;
595
- this.traceApi = null;
596
- }
597
- };
598
- var cachedApi2;
599
- async function tryLoadOtelApi() {
600
- if (cachedApi2 !== void 0) return cachedApi2;
601
- try {
602
- cachedApi2 = await import("@opentelemetry/api");
603
- } catch {
604
- cachedApi2 = null;
605
- }
606
- return cachedApi2;
607
- }
608
- function buildInstruments(meter) {
609
- return {
610
- scoreGauge: meter.createGauge(METRIC_NAMES.score, {
611
- description: "Multi-signal health score per ADR-141 \xA74. Range [0, 1]. Higher = healthier.",
612
- unit: "1"
613
- }),
614
- factorGauge: meter.createGauge(METRIC_NAMES.signalFactor, {
615
- description: "Per-signal health factor; folded into health.score by the SDK scoring strategy (default: weightedProduct, ADR-111 \xA74.3).",
616
- unit: "1"
617
- }),
618
- valueGauge: meter.createGauge(METRIC_NAMES.signalValue, {
619
- description: "Raw observation behind a health signal (ms, count, rate). Numeric values only; string-valued signals emit health.signal.value_state instead."
620
- }),
621
- valueStateCounter: meter.createCounter(METRIC_NAMES.signalValueState, {
622
- description: 'Per-evaluation counter for non-numeric signal readings (e.g. "ok" / "timeout"). state attribute carries the string label.'
623
- }),
624
- downstreamCauseCounter: meter.createCounter(METRIC_NAMES.downstreamCause, {
625
- description: "Per-evaluation counter incremented when this service observes an upstream cause via OTel baggage (ADR-143). Operators read rate() to size the blast radius of an incident."
626
- })
627
- };
628
- }
629
- function maybeAttachToSpan(span, score, events, upstreamCause) {
630
- if (!span || typeof span !== "object") return;
631
- const setAttribute = span.setAttribute;
632
- if (typeof setAttribute === "function") {
633
- setAttribute.call(span, SPAN_ATTRIBUTES.score, score.score);
634
- for (const [signalName, factor] of Object.entries(score.signalFactors ?? {})) {
635
- if (typeof factor === "number" && Number.isFinite(factor)) {
636
- setAttribute.call(span, SPAN_ATTRIBUTES.signalFactor(signalName), factor);
637
- }
638
- }
639
- if (upstreamCause && upstreamCause.causes.length > 0) {
640
- const primary = upstreamCause.causes[0];
641
- if (primary) {
642
- setAttribute.call(span, SPAN_ATTRIBUTES.causeRoot, primary.service);
643
- setAttribute.call(span, SPAN_ATTRIBUTES.causeSignal, primary.signal);
644
- }
645
- if (upstreamCause.chain.length > 0) {
646
- setAttribute.call(span, SPAN_ATTRIBUTES.causeChain, upstreamCause.chain.join(","));
647
- }
648
- }
649
- }
650
- if (events) {
651
- const addEvent = span.addEvent;
652
- if (typeof addEvent === "function") {
653
- addEvent.call(span, EVENT_NAMES.evaluated, {
654
- [SPAN_ATTRIBUTES.score]: score.score,
655
- "service.health.lastTickAt": score.lastTickAt
656
- });
657
- }
658
- }
659
- }
660
-
661
- // src/health/scoring.ts
662
- function clamp01(x) {
663
- if (!Number.isFinite(x)) return 0;
664
- if (x < 0) return 0;
665
- if (x > 1) return 1;
666
- return x;
667
- }
668
- var weightedProduct = (readings) => {
669
- if (readings.length === 0) return 1;
670
- const active = [];
671
- for (const { signal, reading } of readings) {
672
- const w = signal.weight;
673
- if (!Number.isFinite(w) || w <= 0) continue;
674
- if (reading.unknown === true) continue;
675
- active.push({
676
- factor: clamp01(reading.healthFactor),
677
- weight: w
678
- });
679
- }
680
- if (active.length === 0) return 1;
681
- const totalWeight = active.reduce((sum, a) => sum + a.weight, 0);
682
- if (totalWeight <= 0 || !Number.isFinite(totalWeight)) return 1;
683
- let logSum = 0;
684
- for (const { factor, weight } of active) {
685
- const normalisedWeight = weight / totalWeight;
686
- if (factor <= 0) {
687
- return 0;
688
- }
689
- logSum += normalisedWeight * Math.log(factor);
690
- }
691
- const score = Math.exp(logSum);
692
- return clamp01(score);
693
- };
694
- function defaultScoringStrategy() {
695
- return weightedProduct;
696
- }
697
-
698
- // src/health/signals/event-loop-lag.ts
699
- import { monitorEventLoopDelay } from "perf_hooks";
700
- function eventLoopLagSignal(opts = {}) {
701
- const degradedMs = opts.degradedMs ?? 5e3;
702
- const deadMs = opts.deadMs ?? 3e4;
703
- const resolutionMs = opts.resolutionMs ?? 10;
704
- const weight = opts.weight ?? 0.4;
705
- if (!Number.isFinite(degradedMs) || degradedMs < 0) {
706
- throw new Error(`eventLoopLagSignal: degradedMs must be >= 0, got ${degradedMs}`);
707
- }
708
- if (!Number.isFinite(deadMs) || deadMs <= degradedMs) {
709
- throw new Error(
710
- `eventLoopLagSignal: deadMs must be > degradedMs (${degradedMs}), got ${deadMs}`
711
- );
712
- }
713
- if (!Number.isFinite(resolutionMs) || resolutionMs < 1) {
714
- throw new Error(`eventLoopLagSignal: resolutionMs must be >= 1, got ${resolutionMs}`);
715
- }
716
- const monitor = opts.monitor ?? monitorEventLoopDelay({ resolution: resolutionMs });
717
- monitor.enable();
718
- return {
719
- name: "eventLoopLagMs",
720
- weight,
721
- read() {
722
- const maxNs = monitor.max;
723
- if (!Number.isFinite(maxNs) || maxNs <= 0 || maxNs >= Number.MAX_SAFE_INTEGER) {
724
- monitor.reset();
725
- return { value: 0, healthFactor: 1, unknown: true };
726
- }
727
- const observedMs = maxNs / 1e6;
728
- monitor.reset();
729
- let factor;
730
- if (observedMs <= degradedMs) factor = 1;
731
- else if (observedMs >= deadMs) factor = 0;
732
- else {
733
- const span = deadMs - degradedMs;
734
- factor = 1 - (observedMs - degradedMs) / span;
735
- }
736
- return {
737
- value: Math.round(observedMs),
738
- healthFactor: factor
739
- };
740
- },
741
- dispose() {
742
- monitor.disable();
743
- }
744
- };
745
- }
746
-
747
- // src/health/unix-socket-server.ts
748
- import { unlinkSync } from "fs";
749
- function startUnixSocketServer(source, opts = {}) {
750
- const bun = opts.bunRuntime !== void 0 ? opts.bunRuntime : globalThis.Bun;
751
- if (bun === null || bun === void 0 || typeof bun.serve !== "function") {
752
- throw new Error(
753
- "startUnixSocketServer: Bun.serve is unavailable \u2014 Unix-socket transport requires a Bun runtime"
754
- );
755
- }
756
- const path = opts.path ?? "/var/run/sylphx/health.sock";
757
- const unlinkOnShutdown = opts.unlinkOnShutdown ?? true;
758
- try {
759
- unlinkSync(path);
760
- } catch {
761
- }
762
- const handler = createWebHandler(source);
763
- const server = bun.serve({
764
- unix: path,
765
- fetch: async (req) => handler(req)
766
- });
767
- const handle = {
768
- path,
769
- server,
770
- async shutdown() {
771
- try {
772
- server.stop(true);
773
- } catch {
774
- }
775
- if (unlinkOnShutdown) {
776
- try {
777
- unlinkSync(path);
778
- } catch {
779
- }
780
- }
781
- }
782
- };
783
- return handle;
784
- }
785
-
786
- // src/health/middleware.ts
787
- var DEFAULT_PATH = "/healthz";
788
- var DEFAULT_SOCKET_PATH = "/var/run/sylphx/health.sock";
789
- var AUTO_SOCKET_HANDLES = /* @__PURE__ */ new WeakMap();
790
- function resolveInstance(opts) {
791
- if (opts.instance) return opts.instance;
792
- const { path: _path, instance: _instance, unixSocket: _unixSocket, ...sylphxOpts } = opts;
793
- return sylphxHealth(sylphxOpts);
794
- }
795
- function normalizePath(input) {
796
- if (!input) return DEFAULT_PATH;
797
- return input.startsWith("/") ? input : `/${input}`;
798
- }
799
- function getEnvSocketPath() {
800
- const proc = globalThis.process;
801
- const value = proc?.env?.SYLPHX_HEALTH_APP_SOCKET;
802
- return value && value.trim().length > 0 ? value.trim() : void 0;
803
- }
804
- function resolveUnixSocketPath(inputPath, envPath) {
805
- if (inputPath !== void 0) return inputPath;
806
- if (envPath !== void 0) return envPath;
807
- return DEFAULT_SOCKET_PATH;
808
- }
809
- function resolveUnixSocketOption(input) {
810
- if (input === false) return null;
811
- const envPath = getEnvSocketPath();
812
- if (input === void 0) {
813
- return envPath ? { path: envPath, required: false } : null;
814
- }
815
- if (input === true) {
816
- return { path: envPath ?? DEFAULT_SOCKET_PATH, required: false };
817
- }
818
- return {
819
- path: resolveUnixSocketPath(input.path, envPath),
820
- required: input.required ?? false,
821
- ...input.unlinkOnShutdown !== void 0 ? { unlinkOnShutdown: input.unlinkOnShutdown } : {}
822
- };
823
- }
824
- function bindUnixSocketIfRequested(health, opts) {
825
- const socket = resolveUnixSocketOption(opts.unixSocket);
826
- if (!socket) return () => void 0;
827
- const existing = AUTO_SOCKET_HANDLES.get(health);
828
- if (existing) return () => void 0;
829
- try {
830
- const handle = health.serveUnixSocket({
831
- path: socket.path,
832
- ...socket.unlinkOnShutdown !== void 0 ? { unlinkOnShutdown: socket.unlinkOnShutdown } : {}
833
- });
834
- AUTO_SOCKET_HANDLES.set(health, handle);
835
- return () => {
836
- if (AUTO_SOCKET_HANDLES.get(health) === handle) {
837
- AUTO_SOCKET_HANDLES.delete(health);
838
- }
839
- void handle.shutdown();
840
- };
841
- } catch (err) {
842
- if (socket.required) throw err;
843
- return () => void 0;
844
- }
845
- }
846
- function honoHelper(opts = {}) {
847
- const path = normalizePath(opts.path);
848
- const health = resolveInstance(opts);
849
- const disposeSocket = bindUnixSocketIfRequested(health, opts);
850
- const respond = health.handler();
851
- const middleware = (async (c, next) => {
852
- if (c.req.path === path) return respond();
853
- await health.runWithCause(() => next());
854
- return void 0;
855
- });
856
- Object.defineProperty(middleware, "health", { value: health, enumerable: true });
857
- Object.defineProperty(middleware, "dispose", {
858
- value: () => {
859
- disposeSocket();
860
- health.dispose();
861
- },
862
- enumerable: false
863
- });
864
- return middleware;
865
- }
866
- function pathOf(url) {
867
- if (!url) return "/";
868
- const q = url.indexOf("?");
869
- return q === -1 ? url : url.slice(0, q);
870
- }
871
- function expressHelper(opts = {}) {
872
- const path = normalizePath(opts.path);
873
- const health = resolveInstance(opts);
874
- const disposeSocket = bindUnixSocketIfRequested(health, opts);
875
- const respond = health.nodeHandler();
876
- const middleware = ((req, res, next) => {
877
- if (pathOf(req.url) === path) {
878
- void respond(req, res);
879
- return;
880
- }
881
- void health.runWithCause(async () => next());
882
- });
883
- Object.defineProperty(middleware, "health", { value: health, enumerable: true });
884
- Object.defineProperty(middleware, "dispose", {
885
- value: () => {
886
- disposeSocket();
887
- health.dispose();
888
- },
889
- enumerable: false
890
- });
891
- return middleware;
892
- }
893
- function fastifyHelper(opts = {}) {
894
- const path = normalizePath(opts.path);
895
- const health = resolveInstance(opts);
896
- const disposeSocket = bindUnixSocketIfRequested(health, opts);
897
- const respond = health.handler();
898
- const plugin = (async (instance) => {
899
- instance.get(path, async (_req, reply) => {
900
- const response = await respond();
901
- const body = await response.text();
902
- reply.code(response.status);
903
- reply.header("Content-Type", "application/json");
904
- reply.header("Cache-Control", "no-store, no-cache, must-revalidate");
905
- reply.send(body);
906
- });
907
- });
908
- Object.defineProperty(plugin, "health", { value: health, enumerable: true });
909
- Object.defineProperty(plugin, "dispose", {
910
- value: () => {
911
- disposeSocket();
912
- health.dispose();
913
- },
914
- enumerable: false
915
- });
916
- return plugin;
917
- }
918
- function fetchHelper(opts = {}) {
919
- const health = resolveInstance(opts);
920
- const disposeSocket = bindUnixSocketIfRequested(health, opts);
921
- const respond = health.handler();
922
- const handler = ((req) => respond(req));
923
- Object.defineProperty(handler, "health", { value: health, enumerable: true });
924
- Object.defineProperty(handler, "dispose", {
925
- value: () => {
926
- disposeSocket();
927
- health.dispose();
928
- },
929
- enumerable: false
930
- });
931
- return handler;
932
- }
933
- var withHealth = {
934
- /** Hono middleware. Mount with `app.use('*', withHealth.hono())`. */
935
- hono: honoHelper,
936
- /** Express / Connect / Polka middleware. Mount with `app.use(withHealth.express())`. */
937
- express: expressHelper,
938
- /** Fastify plugin. Register with `await fastify.register(withHealth.fastify())`. */
939
- fastify: fastifyHelper,
940
- /**
941
- * Pure Web Fetch handler. Works with Bun.serve, Next.js route
942
- * handlers, Deno, Cloudflare Workers, and any other `Request →
943
- * Response` runtime.
944
- */
945
- fetch: fetchHelper
946
- };
947
-
948
- // src/health/signals/error-rate.ts
949
- function parseWindow(w) {
950
- if (typeof w === "number") {
951
- if (!Number.isFinite(w) || w <= 0) {
952
- throw new Error(`errorRateSignal: window must be > 0, got ${w}`);
953
- }
954
- return w;
955
- }
956
- const m = /^(\d+)(s|m)$/.exec(w);
957
- if (m === null) {
958
- throw new Error(`errorRateSignal: invalid window '${w}', expected '5s' / '1m' / number`);
959
- }
960
- const n = Number.parseInt(m[1], 10);
961
- const unit = m[2];
962
- const ms = unit === "s" ? n * 1e3 : n * 6e4;
963
- if (ms <= 0) {
964
- throw new Error(`errorRateSignal: parsed window ${ms}ms must be > 0`);
965
- }
966
- return ms;
967
- }
968
- function errorRateSignal(opts) {
969
- const windowMs = parseWindow(opts.window);
970
- const degradedRate = opts.degradedRate ?? 0.05;
971
- const deadRate = opts.deadRate ?? 0.5;
972
- const minSamples = opts.minSamples ?? 10;
973
- const weight = opts.weight ?? 0.2;
974
- const now = opts.now ?? Date.now;
975
- if (degradedRate < 0 || degradedRate > 1) {
976
- throw new Error(`errorRateSignal: degradedRate must be in [0, 1], got ${degradedRate}`);
977
- }
978
- if (deadRate <= degradedRate || deadRate > 1) {
979
- throw new Error(`errorRateSignal: deadRate must be in (degradedRate, 1], got ${deadRate}`);
980
- }
981
- if (!Number.isFinite(minSamples) || minSamples < 1) {
982
- throw new Error(`errorRateSignal: minSamples must be >= 1, got ${minSamples}`);
983
- }
984
- const samples = [];
985
- function pruneExpired(t) {
986
- const cutoff = t - windowMs;
987
- while (samples.length > 0 && samples[0].t < cutoff) {
988
- samples.shift();
989
- }
990
- }
991
- return {
992
- name: `recent${Math.round(windowMs / 1e3)}sErrorRate`,
993
- weight,
994
- recordSuccess() {
995
- samples.push({ t: now(), e: false });
996
- },
997
- recordError() {
998
- samples.push({ t: now(), e: true });
999
- },
1000
- reset() {
1001
- samples.length = 0;
1002
- },
1003
- read() {
1004
- const t = now();
1005
- pruneExpired(t);
1006
- if (samples.length === 0 || samples.length < minSamples) {
1007
- return { value: 0, healthFactor: 1 };
1008
- }
1009
- let errors = 0;
1010
- for (const s of samples) {
1011
- if (s.e) errors++;
1012
- }
1013
- const rate = errors / samples.length;
1014
- let factor;
1015
- if (rate <= degradedRate) factor = 1;
1016
- else if (rate >= deadRate) factor = 0;
1017
- else {
1018
- const span = deadRate - degradedRate;
1019
- factor = 1 - (rate - degradedRate) / span;
1020
- }
1021
- const valueRounded = Math.round(rate * 1e4) / 1e4;
1022
- return {
1023
- value: valueRounded,
1024
- healthFactor: factor
1025
- };
1026
- }
1027
- };
1028
- }
1029
-
1030
- // src/health/signals/memory-pressure.ts
1031
- import { readFileSync } from "fs";
1032
- var CGROUP_V1_UNLIMITED_FLOOR = 1e18;
1033
- function tryRead(reader, path) {
1034
- try {
1035
- return reader(path);
1036
- } catch {
1037
- return null;
1038
- }
1039
- }
1040
- function readContainerMemoryLimit(reader, v2Path, v1Path) {
1041
- const v2 = tryRead(reader, v2Path);
1042
- if (v2 !== null) {
1043
- const trimmed2 = v2.trim();
1044
- if (trimmed2 === "max" || trimmed2 === "") return null;
1045
- const n2 = Number.parseInt(trimmed2, 10);
1046
- if (!Number.isFinite(n2) || n2 <= 0) return null;
1047
- if (n2 > CGROUP_V1_UNLIMITED_FLOOR) return null;
1048
- return n2;
1049
- }
1050
- const v1 = tryRead(reader, v1Path);
1051
- if (v1 === null) return null;
1052
- const trimmed = v1.trim();
1053
- const n = Number.parseInt(trimmed, 10);
1054
- if (!Number.isFinite(n) || n <= 0) return null;
1055
- if (n > CGROUP_V1_UNLIMITED_FLOOR) return null;
1056
- return n;
1057
- }
1058
- function memoryPressureSignal(opts = {}) {
1059
- const degradedRatio = opts.degradedRatio ?? 0.85;
1060
- const deadRatio = opts.deadRatio ?? 0.95;
1061
- const v2Path = opts.cgroupV2Path ?? "/sys/fs/cgroup/memory.max";
1062
- const v1Path = opts.cgroupV1Path ?? "/sys/fs/cgroup/memory/memory.limit_in_bytes";
1063
- const weight = opts.weight ?? 0.2;
1064
- const memoryUsage = opts.memoryUsage ?? (() => {
1065
- const m = process.memoryUsage();
1066
- return { rss: m.rss };
1067
- });
1068
- const readFile = opts.readFile ?? ((p) => readFileSync(p, "utf8"));
1069
- if (degradedRatio <= 0 || degradedRatio >= 1) {
1070
- throw new Error(`memoryPressureSignal: degradedRatio must be in (0, 1), got ${degradedRatio}`);
1071
- }
1072
- if (deadRatio <= degradedRatio || deadRatio > 1) {
1073
- throw new Error(
1074
- `memoryPressureSignal: deadRatio must be in (degradedRatio, 1], got ${deadRatio}`
1075
- );
1076
- }
1077
- let cachedLimit;
1078
- function getLimit() {
1079
- if (cachedLimit === void 0) {
1080
- cachedLimit = readContainerMemoryLimit(readFile, v2Path, v1Path);
1081
- }
1082
- return cachedLimit;
1083
- }
1084
- return {
1085
- name: "memoryPressure",
1086
- weight,
1087
- read() {
1088
- const limit = getLimit();
1089
- if (limit === null) {
1090
- return { value: 0, healthFactor: 1, unknown: true };
1091
- }
1092
- let rss;
1093
- try {
1094
- rss = memoryUsage().rss;
1095
- } catch {
1096
- return { value: 0, healthFactor: 1, unknown: true };
1097
- }
1098
- if (!Number.isFinite(rss) || rss < 0) {
1099
- return { value: 0, healthFactor: 1, unknown: true };
1100
- }
1101
- const ratio = rss / limit;
1102
- let factor;
1103
- if (ratio <= degradedRatio) factor = 1;
1104
- else if (ratio >= deadRatio) factor = 0;
1105
- else {
1106
- const span = deadRatio - degradedRatio;
1107
- factor = 1 - (ratio - degradedRatio) / span;
1108
- }
1109
- const valueRounded = Math.round(ratio * 1e3) / 1e3;
1110
- return { value: valueRounded, healthFactor: factor };
1111
- }
1112
- };
1113
- }
1114
-
1115
- // src/health/signals/ping.ts
1116
- var DEFAULT_TIMEOUT_MS = 500;
1117
- function pingSignal(opts) {
1118
- if (typeof opts.ping !== "function") {
1119
- throw new Error(`pingSignal[${opts.name}]: ping must be a function`);
1120
- }
1121
- if (typeof opts.name !== "string" || opts.name.length === 0) {
1122
- throw new Error("pingSignal: name must be a non-empty string");
1123
- }
1124
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1125
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
1126
- throw new Error(`pingSignal[${opts.name}]: timeoutMs must be > 0, got ${timeoutMs}`);
1127
- }
1128
- const weight = opts.weight ?? 1;
1129
- return {
1130
- name: opts.name,
1131
- weight,
1132
- async read() {
1133
- let timer;
1134
- const timeoutPromise = new Promise((resolve) => {
1135
- timer = setTimeout(() => resolve("timeout"), timeoutMs);
1136
- });
1137
- try {
1138
- const result = await Promise.race([opts.ping().then(() => "ok"), timeoutPromise]);
1139
- if (result === "timeout") {
1140
- return { value: "timeout", healthFactor: 0 };
1141
- }
1142
- return { value: "ok", healthFactor: 1 };
1143
- } catch (err) {
1144
- const message = err instanceof Error ? err.message : String(err);
1145
- return { value: message.slice(0, 120), healthFactor: 0 };
1146
- } finally {
1147
- if (timer) clearTimeout(timer);
1148
- }
1149
- }
1150
- };
1151
- }
1152
- function databaseSignal(opts) {
1153
- return pingSignal({
1154
- name: opts.name ?? "database",
1155
- ping: opts.ping,
1156
- ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {},
1157
- ...opts.weight !== void 0 ? { weight: opts.weight } : {}
1158
- });
1159
- }
1160
- function redisSignal(opts) {
1161
- return pingSignal({
1162
- name: opts.name ?? "redis",
1163
- ping: opts.ping,
1164
- ...opts.timeoutMs !== void 0 ? { timeoutMs: opts.timeoutMs } : {},
1165
- ...opts.weight !== void 0 ? { weight: opts.weight } : {}
1166
- });
1167
- }
1168
-
1169
- // src/health/signals/queue-depth.ts
1170
- function queueDepthSignal(opts) {
1171
- if (typeof opts.getter !== "function") {
1172
- throw new Error("queueDepthSignal: getter must be a function");
1173
- }
1174
- if (!Number.isFinite(opts.fullThreshold) || opts.fullThreshold <= 0) {
1175
- throw new Error(`queueDepthSignal: fullThreshold must be > 0, got ${opts.fullThreshold}`);
1176
- }
1177
- const healthyBelow = opts.healthyBelow ?? 0;
1178
- if (!Number.isFinite(healthyBelow) || healthyBelow < 0 || healthyBelow >= opts.fullThreshold) {
1179
- throw new Error(
1180
- `queueDepthSignal: healthyBelow must be in [0, fullThreshold), got ${healthyBelow}`
1181
- );
1182
- }
1183
- const weight = opts.weight ?? 0.2;
1184
- return {
1185
- name: opts.name ?? "queueDepth",
1186
- weight,
1187
- async read() {
1188
- let raw;
1189
- try {
1190
- raw = await opts.getter();
1191
- } catch {
1192
- return { value: 0, healthFactor: 1, unknown: true };
1193
- }
1194
- if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) {
1195
- return { value: 0, healthFactor: 1, unknown: true };
1196
- }
1197
- const depth = raw;
1198
- let factor;
1199
- if (depth <= healthyBelow) factor = 1;
1200
- else if (depth >= opts.fullThreshold) factor = 0;
1201
- else {
1202
- const span = opts.fullThreshold - healthyBelow;
1203
- factor = 1 - (depth - healthyBelow) / span;
1204
- }
1205
- return {
1206
- value: depth,
1207
- healthFactor: factor
1208
- };
1209
- }
1210
- };
1211
- }
1212
-
1213
- // src/health/index.ts
1214
- function resolveOtelEmitter(otelOpt) {
1215
- if (otelOpt === false) return null;
1216
- const emitterOpts = otelOpt && typeof otelOpt === "object" ? otelOpt : {};
1217
- return createOtelEmitter(emitterOpts);
1218
- }
1219
- function resolveCausalityHandle(opt) {
1220
- if (opt === false) return null;
1221
- const causalityOpts = opt && typeof opt === "object" ? opt : {};
1222
- return createCausalityHandle(causalityOpts);
1223
- }
1224
- function resolveHistoryRecorder(opt) {
1225
- if (opt === false) return null;
1226
- const recorderOpts = opt && typeof opt === "object" ? opt : {};
1227
- return createHistoryRecorder(recorderOpts);
1228
- }
1229
- function clampHealthFactor(value) {
1230
- if (!Number.isFinite(value)) return 0;
1231
- if (value < 0) return 0;
1232
- if (value > 1) return 1;
1233
- return value;
1234
- }
1235
- var HEALTH_RELEASE_KEYS = [
1236
- "version",
1237
- "commitSha",
1238
- "imageDigest",
1239
- "imageTag",
1240
- "deploymentId",
1241
- "buildId",
1242
- "replicaId"
1243
- ];
1244
- function resolveHealthRelease(input) {
1245
- if (!input) return void 0;
1246
- try {
1247
- const value = typeof input === "function" ? input() : input;
1248
- if (!value) return void 0;
1249
- const release = {};
1250
- for (const key of HEALTH_RELEASE_KEYS) {
1251
- const raw = value[key];
1252
- if (raw === null) {
1253
- release[key] = null;
1254
- } else if (typeof raw === "string") {
1255
- const trimmed = raw.trim();
1256
- if (trimmed.length > 0) release[key] = trimmed;
1257
- }
1258
- }
1259
- return Object.keys(release).length > 0 ? release : void 0;
1260
- } catch {
1261
- return void 0;
1262
- }
1263
- }
1264
- function sylphxHealth(opts = {}) {
1265
- const signals = opts.signals && opts.signals.length > 0 ? [...opts.signals] : [eventLoopLagSignal({ degradedMs: 5e3, deadMs: 3e4, weight: 1 })];
1266
- const scoringStrategy = opts.scoringStrategy ?? defaultScoringStrategy();
1267
- const now = opts.now ?? (() => /* @__PURE__ */ new Date());
1268
- const otelEmitter = resolveOtelEmitter(opts.otel);
1269
- const causality = resolveCausalityHandle(opts.causality);
1270
- const historyRecorder = resolveHistoryRecorder(opts.history);
1271
- let disposed = false;
1272
- let lastScore = null;
1273
- const evaluate = async () => {
1274
- if (disposed) {
1275
- throw new Error("sylphxHealth: instance disposed");
1276
- }
1277
- const upstreamCause = causality ? causality.readCause() : null;
1278
- const readings = await Promise.all(
1279
- signals.map(async (signal) => ({
1280
- signal,
1281
- reading: await signal.read()
1282
- }))
1283
- );
1284
- const score = scoringStrategy(readings);
1285
- const signalsMap = {};
1286
- const signalFactors = {};
1287
- for (const { signal, reading } of readings) {
1288
- signalsMap[signal.name] = reading.value;
1289
- signalFactors[signal.name] = reading.unknown === true ? 1 : clampHealthFactor(reading.healthFactor);
1290
- }
1291
- const release = resolveHealthRelease(opts.release);
1292
- const result = {
1293
- score,
1294
- signals: signalsMap,
1295
- signalFactors,
1296
- ...release ? { release } : {},
1297
- lastTickAt: now().toISOString()
1298
- };
1299
- lastScore = result;
1300
- if (otelEmitter) {
1301
- otelEmitter.emit(result, upstreamCause);
1302
- }
1303
- if (historyRecorder) {
1304
- void historyRecorder.record(result);
1305
- }
1306
- return result;
1307
- };
1308
- const evaluator = { evaluate };
1309
- const evaluateEffect2 = evaluateEffect(evaluate);
1310
- const runWithCause = async (fn) => {
1311
- if (!causality || !lastScore) return await fn();
1312
- return await causality.runWithCause(fn, lastScore);
1313
- };
1314
- const getHistory = async (query = {}) => {
1315
- if (!historyRecorder) return [];
1316
- return await historyRecorder.range(query);
1317
- };
1318
- const verifyHistory = async (query = {}) => {
1319
- if (!historyRecorder) {
1320
- return {
1321
- verified: false,
1322
- entriesChecked: 0,
1323
- firstBreakAtSequence: null,
1324
- reason: "history recording is disabled on this instance"
1325
- };
1326
- }
1327
- return await historyRecorder.verify(query);
1328
- };
1329
- return {
1330
- signals,
1331
- evaluate,
1332
- evaluateEffect: evaluateEffect2,
1333
- handler() {
1334
- return createWebHandler(evaluator);
1335
- },
1336
- nodeHandler() {
1337
- return createNodeHandler(evaluator);
1338
- },
1339
- serveUnixSocket(unixOpts) {
1340
- return startUnixSocketServer(evaluator, unixOpts);
1341
- },
1342
- getLastScore() {
1343
- return lastScore;
1344
- },
1345
- runWithCause,
1346
- getHistory,
1347
- verifyHistory,
1348
- dispose() {
1349
- if (disposed) return;
1350
- disposed = true;
1351
- if (otelEmitter) otelEmitter.dispose();
1352
- if (causality) causality.dispose();
1353
- if (historyRecorder) historyRecorder.dispose();
1354
- for (const s of signals) {
1355
- try {
1356
- s.dispose?.();
1357
- } catch {
1358
- }
1359
- }
1360
- }
1361
- };
1362
- }
1363
- export {
1364
- BAGGAGE_KEY_CAUSE,
1365
- BAGGAGE_KEY_CHAIN,
1366
- DEFAULT_CAUSE_THRESHOLD,
1367
- DEFAULT_HISTORY_CAPACITY,
1368
- GENESIS_PREV_HASH,
1369
- HealthError,
1370
- MAX_CHAIN_LENGTH,
1371
- EVENT_NAMES as OTEL_EVENT_NAMES,
1372
- METRIC_NAMES as OTEL_METRIC_NAMES,
1373
- SPAN_ATTRIBUTES as OTEL_SPAN_ATTRIBUTES,
1374
- canonicalizeSignals,
1375
- createCausalityHandle,
1376
- createHistoryRecorder,
1377
- createInMemoryHistoryStore,
1378
- createNodeHandler,
1379
- createOtelEmitter,
1380
- createWebHandler,
1381
- databaseSignal,
1382
- defaultScoringStrategy,
1383
- errorRateSignal,
1384
- eventLoopLagSignal,
1385
- memoryPressureSignal,
1386
- pingSignal,
1387
- queueDepthSignal,
1388
- redisSignal,
1389
- sylphxHealth,
1390
- verifyChain,
1391
- weightedProduct,
1392
- withHealth
1393
- };
1394
- //# sourceMappingURL=index.mjs.map