@sylphx/sdk 0.27.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.
- package/LICENSE +21 -0
- package/README.md +30 -73
- package/dist/access.d.ts +659 -0
- package/dist/access.js +638 -0
- package/dist/access.js.map +1 -0
- package/dist/ai.d.ts +176 -0
- package/dist/ai.js +112 -0
- package/dist/ai.js.map +1 -0
- package/dist/artifacts.d.ts +165 -0
- package/dist/artifacts.js +129 -0
- package/dist/artifacts.js.map +1 -0
- package/dist/auth.d.ts +896 -0
- package/dist/auth.js +828 -0
- package/dist/auth.js.map +1 -0
- package/dist/billing.d.ts +758 -0
- package/dist/billing.js +553 -0
- package/dist/billing.js.map +1 -0
- package/dist/broker.d.ts +226 -0
- package/dist/broker.js +187 -0
- package/dist/broker.js.map +1 -0
- package/dist/build.d.ts +313 -0
- package/dist/build.js +271 -0
- package/dist/build.js.map +1 -0
- package/dist/common.d.ts +162 -0
- package/dist/common.js +41 -0
- package/dist/common.js.map +1 -0
- package/dist/config.d.ts +198 -0
- package/dist/config.js +168 -0
- package/dist/config.js.map +1 -0
- package/dist/connections.d.ts +354 -0
- package/dist/connections.js +313 -0
- package/dist/connections.js.map +1 -0
- package/dist/data.d.ts +858 -0
- package/dist/data.js +814 -0
- package/dist/data.js.map +1 -0
- package/dist/entitlement.d.ts +172 -0
- package/dist/entitlement.js +116 -0
- package/dist/entitlement.js.map +1 -0
- package/dist/events.d.ts +1324 -0
- package/dist/events.js +1227 -0
- package/dist/events.js.map +1 -0
- package/dist/hosting.d.ts +709 -0
- package/dist/hosting.js +611 -0
- package/dist/hosting.js.map +1 -0
- package/dist/index.d.ts +79 -11493
- package/dist/index.js +113 -0
- package/dist/index.js.map +1 -0
- package/dist/keys.d.ts +438 -0
- package/dist/keys.js +406 -0
- package/dist/keys.js.map +1 -0
- package/dist/methods.d.ts +2 -0
- package/dist/methods.js +3995 -0
- package/dist/methods.js.map +1 -0
- package/dist/network.d.ts +733 -0
- package/dist/network.js +711 -0
- package/dist/network.js.map +1 -0
- package/dist/notify.d.ts +1359 -0
- package/dist/notify.js +1282 -0
- package/dist/notify.js.map +1 -0
- package/dist/observability.d.ts +509 -0
- package/dist/observability.js +437 -0
- package/dist/observability.js.map +1 -0
- package/dist/release.d.ts +303 -0
- package/dist/release.js +214 -0
- package/dist/release.js.map +1 -0
- package/dist/runners.d.ts +262 -0
- package/dist/runners.js +238 -0
- package/dist/runners.js.map +1 -0
- package/dist/runtime.d.ts +88 -0
- package/dist/runtime.js +226 -0
- package/dist/runtime.js.map +1 -0
- package/dist/sandboxes.d.ts +1705 -0
- package/dist/sandboxes.js +1226 -0
- package/dist/sandboxes.js.map +1 -0
- package/dist/secrets.d.ts +508 -0
- package/dist/secrets.js +474 -0
- package/dist/secrets.js.map +1 -0
- package/dist/workflows.d.ts +678 -0
- package/dist/workflows.js +595 -0
- package/dist/workflows.js.map +1 -0
- package/package.json +33 -106
- package/dist/health/index.d.ts +0 -1394
- package/dist/health/index.mjs +0 -1394
- package/dist/health/index.mjs.map +0 -1
- package/dist/index.mjs +0 -10386
- package/dist/index.mjs.map +0 -1
- package/dist/nextjs/index.d.ts +0 -724
- package/dist/nextjs/index.mjs +0 -3329
- package/dist/nextjs/index.mjs.map +0 -1
- package/dist/react/index.d.ts +0 -14168
- package/dist/react/index.mjs +0 -37002
- package/dist/react/index.mjs.map +0 -1
- package/dist/server/index.d.ts +0 -2017
- package/dist/server/index.mjs +0 -3446
- package/dist/server/index.mjs.map +0 -1
- package/dist/tasks.d.ts +0 -1463
- package/dist/tasks.mjs +0 -1907
- package/dist/tasks.mjs.map +0 -1
- package/dist/web-analytics.d.ts +0 -90
- package/dist/web-analytics.mjs +0 -225
- package/dist/web-analytics.mjs.map +0 -1
package/dist/health/index.d.ts
DELETED
|
@@ -1,1394 +0,0 @@
|
|
|
1
|
-
import { Effect } from 'effect';
|
|
2
|
-
import { Meter, Tracer } from '@opentelemetry/api';
|
|
3
|
-
import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Audit-grade health history for `@sylphx/sdk/health` (ADR-144).
|
|
7
|
-
*
|
|
8
|
-
* Every `evaluate()` produces a tamper-evident `HistoryEntry` linked to
|
|
9
|
-
* the previous entry via a SHA-256 prev-hash chain (the same primitive
|
|
10
|
-
* AWS CloudTrail uses for digest-based log file integrity validation).
|
|
11
|
-
* Operators run `sylphx health verify` to walk the chain offline and
|
|
12
|
-
* detect any post-hoc tampering.
|
|
13
|
-
*
|
|
14
|
-
* # Storage is pluggable
|
|
15
|
-
*
|
|
16
|
-
* The SDK ships an `InMemoryHistoryStore` (ring buffer, FIFO eviction)
|
|
17
|
-
* as the reference implementation. Customers wanting compliance-grade
|
|
18
|
-
* durability (SOC 2 Type II, GDPR Article 32, HIPAA 164.312(b)) plug
|
|
19
|
-
* their own persistent `HistoryStore` — a thin interface that the SDK
|
|
20
|
-
* calls with each new entry. Adapter packages for Postgres / S3 / cold
|
|
21
|
-
* storage ship separately (Sylphx's own services use the Postgres
|
|
22
|
-
* adapter in `@sylphx/core/lib/health/history-store`, which doubles as
|
|
23
|
-
* the reference persistent implementation: warm-start chain continuity
|
|
24
|
-
* across restarts + ring-buffer row retention).
|
|
25
|
-
*
|
|
26
|
-
* # Cardinal rule (carried from ADR-141 / 142 / 143)
|
|
27
|
-
*
|
|
28
|
-
* Recording failures never throw upstream. The `/healthz` response is
|
|
29
|
-
* the load-bearing contract; the history record is observability
|
|
30
|
-
* augmentation. A store that throws during `append()` produces a logged
|
|
31
|
-
* warning (in dev) and is otherwise a no-op for that evaluation.
|
|
32
|
-
*
|
|
33
|
-
* # Wire format normative
|
|
34
|
-
*
|
|
35
|
-
* Per ADR-144 §3 — sorted-key canonical signal JSON, base16 SHA-256
|
|
36
|
-
* hashes, six-decimal-place score precision, `|` separator for the
|
|
37
|
-
* entry-hash preimage. Stable from day one.
|
|
38
|
-
*/
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* One tamper-evident history entry. The `prevHash` links to the previous
|
|
42
|
-
* entry's `entryHash`; entry 0 (`sequence === 0`) uses the genesis
|
|
43
|
-
* placeholder `"0".repeat(64)`. Stable wire shape — additive evolution
|
|
44
|
-
* only.
|
|
45
|
-
*/
|
|
46
|
-
interface HistoryEntry {
|
|
47
|
-
/** Monotonic, 0-indexed per service. */
|
|
48
|
-
readonly sequence: number;
|
|
49
|
-
/** ISO-8601 timestamp matching `HealthScore.lastTickAt`. */
|
|
50
|
-
readonly evaluatedAt: string;
|
|
51
|
-
/** Aggregate score in `[0, 1]`. */
|
|
52
|
-
readonly score: number;
|
|
53
|
-
/** Base16 SHA-256 of canonicalized signal map. */
|
|
54
|
-
readonly signalsDigest: string;
|
|
55
|
-
/** Base16 SHA-256 of previous entry's `entryHash` (`"0"*64` at sequence 0). */
|
|
56
|
-
readonly prevHash: string;
|
|
57
|
-
/** Base16 SHA-256 of `(sequence|evaluatedAt|score|signalsDigest|prevHash)`. */
|
|
58
|
-
readonly entryHash: string;
|
|
59
|
-
}
|
|
60
|
-
/** Query for `HistoryStore.range`. */
|
|
61
|
-
interface HistoryQuery {
|
|
62
|
-
/** Inclusive lower sequence. Omit for "from the beginning available". */
|
|
63
|
-
readonly fromSequence?: number;
|
|
64
|
-
/** Inclusive upper sequence. Omit for "to the most recent". */
|
|
65
|
-
readonly toSequence?: number;
|
|
66
|
-
/** Inclusive lower timestamp (ISO-8601). */
|
|
67
|
-
readonly fromTimestamp?: string;
|
|
68
|
-
/** Inclusive upper timestamp (ISO-8601). */
|
|
69
|
-
readonly toTimestamp?: string;
|
|
70
|
-
/** Maximum entries returned. Implementations may cap further. */
|
|
71
|
-
readonly limit?: number;
|
|
72
|
-
}
|
|
73
|
-
/** Pluggable persistence adapter. Implementations may be sync or async. */
|
|
74
|
-
interface HistoryStore {
|
|
75
|
-
/** Append one entry. MUST persist before resolving for compliance use. */
|
|
76
|
-
append(entry: HistoryEntry): Promise<void> | void;
|
|
77
|
-
/** Retrieve entries matching `query` in ascending sequence order. */
|
|
78
|
-
range(query: HistoryQuery): Promise<readonly HistoryEntry[]> | readonly HistoryEntry[];
|
|
79
|
-
/** Most recent entry, or null when empty. */
|
|
80
|
-
latest(): Promise<HistoryEntry | null> | HistoryEntry | null;
|
|
81
|
-
/** Optional capacity hint for ring-buffer stores. */
|
|
82
|
-
readonly capacity?: number;
|
|
83
|
-
}
|
|
84
|
-
/** Outcome of chain verification — `verified: false` always carries a reason. */
|
|
85
|
-
interface VerificationResult {
|
|
86
|
-
readonly verified: boolean;
|
|
87
|
-
readonly entriesChecked: number;
|
|
88
|
-
readonly firstBreakAtSequence: number | null;
|
|
89
|
-
readonly reason: string | null;
|
|
90
|
-
}
|
|
91
|
-
/** Options for the in-memory reference store. */
|
|
92
|
-
interface InMemoryHistoryStoreOptions {
|
|
93
|
-
/** Ring-buffer capacity. Default 1000. */
|
|
94
|
-
readonly capacity?: number;
|
|
95
|
-
}
|
|
96
|
-
/** Options for the recorder bound to a `sylphxHealth` instance. */
|
|
97
|
-
interface HistoryRecorderOptions {
|
|
98
|
-
/** Underlying store. Defaults to `InMemoryHistoryStore`. */
|
|
99
|
-
readonly store?: HistoryStore;
|
|
100
|
-
/** Capacity passed to the default in-memory store. Default 1000. */
|
|
101
|
-
readonly capacity?: number;
|
|
102
|
-
}
|
|
103
|
-
/** The flag value passed via `sylphxHealth({ history })`. */
|
|
104
|
-
type HistoryOption = boolean | HistoryRecorderOptions;
|
|
105
|
-
/** Genesis prev-hash for the very first entry per service. */
|
|
106
|
-
declare const GENESIS_PREV_HASH: string;
|
|
107
|
-
/** Default ring-buffer size when callers don't override. */
|
|
108
|
-
declare const DEFAULT_HISTORY_CAPACITY = 1000;
|
|
109
|
-
/**
|
|
110
|
-
* Sorted-key JSON canonicalization. Same signals in different insertion
|
|
111
|
-
* order produce the same string — guarantees `signalsDigest` stability
|
|
112
|
-
* across V8 / Bun / browser JSON.stringify implementations.
|
|
113
|
-
*/
|
|
114
|
-
declare function canonicalizeSignals(signals: Record<string, number | string | boolean>): string;
|
|
115
|
-
/** Build an in-memory ring-buffer history store. */
|
|
116
|
-
declare function createInMemoryHistoryStore(opts?: InMemoryHistoryStoreOptions): HistoryStore;
|
|
117
|
-
/**
|
|
118
|
-
* Records every `HealthScore` as a hash-chained entry. Owns a single
|
|
119
|
-
* `nextSequence` counter + the `prevHash` value carried forward across
|
|
120
|
-
* recordings. The recorder is per-instance (per-service); the chain is
|
|
121
|
-
* never shared across services.
|
|
122
|
-
*/
|
|
123
|
-
interface HistoryRecorder {
|
|
124
|
-
/** Backing store. Exposed for advanced callers (e.g. tests + verification). */
|
|
125
|
-
readonly store: HistoryStore;
|
|
126
|
-
/** Record one score. Resolves to the persisted entry (or null on failure). */
|
|
127
|
-
record(score: HealthScore): Promise<HistoryEntry | null>;
|
|
128
|
-
/** Convenience: store.range. */
|
|
129
|
-
range(query: HistoryQuery): Promise<readonly HistoryEntry[]>;
|
|
130
|
-
/** Convenience: store.latest. */
|
|
131
|
-
latest(): Promise<HistoryEntry | null>;
|
|
132
|
-
/**
|
|
133
|
-
* Verify the chain over a query window. Walks entries in sequence
|
|
134
|
-
* order, recomputing each `entryHash` and confirming it matches the
|
|
135
|
-
* next entry's `prevHash`. Returns the first break with a reason.
|
|
136
|
-
*/
|
|
137
|
-
verify(query: HistoryQuery): Promise<VerificationResult>;
|
|
138
|
-
/** Tear down internal references. Idempotent. */
|
|
139
|
-
dispose(): void;
|
|
140
|
-
}
|
|
141
|
-
/** Build a recorder bound to a (defaulted) in-memory store. */
|
|
142
|
-
declare function createHistoryRecorder(opts?: HistoryRecorderOptions): HistoryRecorder;
|
|
143
|
-
/**
|
|
144
|
-
* Walk an ordered (by sequence) chain of entries, recomputing each
|
|
145
|
-
* `entryHash` and confirming it matches the next entry's `prevHash`.
|
|
146
|
-
* Returns the first break encountered.
|
|
147
|
-
*
|
|
148
|
-
* Edge cases:
|
|
149
|
-
* - Empty input → `verified: true, entriesChecked: 0`. Vacuous truth.
|
|
150
|
-
* - First entry has `prevHash !== GENESIS_PREV_HASH` AND `sequence === 0`
|
|
151
|
-
* → break ("genesis prev-hash mismatch").
|
|
152
|
-
* - First entry's `sequence > 0` but `prevHash === GENESIS_PREV_HASH`
|
|
153
|
-
* → this is a sub-window query; we accept and chain forward from
|
|
154
|
-
* `entries[0]`.
|
|
155
|
-
*/
|
|
156
|
-
declare function verifyChain(entries: ReadonlyArray<HistoryEntry>): Promise<VerificationResult>;
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* Causality-aware health propagation for `@sylphx/sdk/health` (ADR-143).
|
|
160
|
-
*
|
|
161
|
-
* Reads + writes the OpenTelemetry Baggage entry `sylphx.health.cause`
|
|
162
|
-
* with value `<signal>@<service>[,<signal>@<service>...]` per ADR-143 §3.1.
|
|
163
|
-
* Append-only `sylphx.health.cause_chain` carries the hop chain so
|
|
164
|
-
* operators can reconstruct multi-hop incident paths.
|
|
165
|
-
*
|
|
166
|
-
* # Read side (downstream)
|
|
167
|
-
*
|
|
168
|
-
* On every `evaluate()`, the SDK reads `propagation.getActiveBaggage()`
|
|
169
|
-
* before computing the score. When the baggage carries an
|
|
170
|
-
* `sylphx.health.cause` entry, the resulting `HealthScore.upstreamCause`
|
|
171
|
-
* surfaces the parsed causes + chain. The OTel emitter then sets
|
|
172
|
-
* `service.health.cause_root` / `cause_signal` / `cause_chain` span
|
|
173
|
-
* attributes and increments the `health.downstream_cause` Counter.
|
|
174
|
-
*
|
|
175
|
-
* # Write side (upstream — the service whose signal is failing)
|
|
176
|
-
*
|
|
177
|
-
* `runWithCause(fn, score)` wraps an async function in a new OTel
|
|
178
|
-
* context where the cause baggage is set. Used by `withHealth.*`
|
|
179
|
-
* middleware to inject baggage on every non-/healthz request so that
|
|
180
|
-
* downstream calls within that request inherit the cause via standard
|
|
181
|
-
* OTel context propagation (W3C Baggage header on HTTP, native
|
|
182
|
-
* baggage on gRPC, queue metadata on Kafka/Cloud Tasks).
|
|
183
|
-
*
|
|
184
|
-
* # Graceful fallback
|
|
185
|
-
*
|
|
186
|
-
* `@opentelemetry/api` is an optional peer dependency (see ADR-142
|
|
187
|
-
* §2.3). When the dynamic import fails — or when the runtime exposes
|
|
188
|
-
* only a partial OTel API — the handle transitions to `'unavailable'`,
|
|
189
|
-
* every method becomes a no-op, and `runWithCause` runs the inner
|
|
190
|
-
* function with no context modification. The `/healthz` contract is
|
|
191
|
-
* unchanged in either case (ADR-143 §2.5 cardinal rule).
|
|
192
|
-
*
|
|
193
|
-
* # Cardinal rules (carried from ADR-141 / ADR-142)
|
|
194
|
-
*
|
|
195
|
-
* - Propagation never throws. Errors in `readCause`, `encodeCause`,
|
|
196
|
-
* `runWithCause` are caught and downgraded to no-op behaviour.
|
|
197
|
-
* - The HTTP response shape is unchanged. Baggage is augmentation;
|
|
198
|
-
* probe surface is the load-bearing contract.
|
|
199
|
-
*/
|
|
200
|
-
|
|
201
|
-
declare const BAGGAGE_KEY_CAUSE = "sylphx.health.cause";
|
|
202
|
-
declare const BAGGAGE_KEY_CHAIN = "sylphx.health.cause_chain";
|
|
203
|
-
/** Default threshold below which a signal triggers cause propagation. */
|
|
204
|
-
declare const DEFAULT_CAUSE_THRESHOLD = 0.5;
|
|
205
|
-
/** Maximum number of hops persisted in the chain baggage (ADR-143 §5). */
|
|
206
|
-
declare const MAX_CHAIN_LENGTH = 5;
|
|
207
|
-
/**
|
|
208
|
-
* The flag value passed by callers via `sylphxHealth({ causality })` /
|
|
209
|
-
* `withHealth.hono({ causality })`. `true` (default) enables propagation
|
|
210
|
-
* with sensible defaults; `false` disables it; an object configures it.
|
|
211
|
-
*/
|
|
212
|
-
type CausalityOption = boolean | CausalityOptions;
|
|
213
|
-
interface CausalityOptions {
|
|
214
|
-
/**
|
|
215
|
-
* Below this signal factor, the SDK considers the signal "causing
|
|
216
|
-
* degradation" and emits a cause entry. Default: `0.5` — matches the
|
|
217
|
-
* ADR-111 kill threshold. Range: `(0, 1]`.
|
|
218
|
-
*/
|
|
219
|
-
readonly threshold?: number;
|
|
220
|
-
/**
|
|
221
|
-
* Override the service name used in cause entries. Falls back to
|
|
222
|
-
* `process.env.OTEL_SERVICE_NAME` then `process.env.SERVICE_NAME`
|
|
223
|
-
* then `"unknown"`. Operators of multi-tenant runtimes typically
|
|
224
|
-
* override this per evaluator.
|
|
225
|
-
*/
|
|
226
|
-
readonly serviceName?: string;
|
|
227
|
-
/**
|
|
228
|
-
* When true (default), the SDK appends the local service name to
|
|
229
|
-
* `sylphx.health.cause_chain` baggage so downstream operators can
|
|
230
|
-
* reconstruct multi-hop incident paths.
|
|
231
|
-
*/
|
|
232
|
-
readonly propagateChain?: boolean;
|
|
233
|
-
}
|
|
234
|
-
/** Parsed view of an upstream cause read from baggage. */
|
|
235
|
-
interface UpstreamCause {
|
|
236
|
-
/**
|
|
237
|
-
* The list of `<signal>@<service>` pairs carried in the baggage entry.
|
|
238
|
-
* Operators read `causes[0]` for the most-significant root; the full
|
|
239
|
-
* list preserves multi-cause concurrent failures.
|
|
240
|
-
*/
|
|
241
|
-
readonly causes: ReadonlyArray<{
|
|
242
|
-
readonly signal: string;
|
|
243
|
-
readonly service: string;
|
|
244
|
-
}>;
|
|
245
|
-
/**
|
|
246
|
-
* The hop chain — services that observed this cause and forwarded it.
|
|
247
|
-
* Most recent service is at the tail. `chain.length === 0` means the
|
|
248
|
-
* baggage entry was just minted (no downstream services have observed
|
|
249
|
-
* it yet — typically only at the moment-of-incident origin).
|
|
250
|
-
*/
|
|
251
|
-
readonly chain: ReadonlyArray<string>;
|
|
252
|
-
}
|
|
253
|
-
/** Operational handle the SDK uses to read + write cause baggage. */
|
|
254
|
-
interface CausalityHandle {
|
|
255
|
-
/** Async loader state — exposed for tests + diagnostics. */
|
|
256
|
-
readonly state: 'loading' | 'ready' | 'unavailable' | 'disposed';
|
|
257
|
-
/** Read upstream cause from active OTel baggage. Returns null when absent. */
|
|
258
|
-
readCause(): UpstreamCause | null;
|
|
259
|
-
/**
|
|
260
|
-
* Encode the local cause string for baggage. Returns null when none of
|
|
261
|
-
* the signals' factors are below the configured threshold.
|
|
262
|
-
*/
|
|
263
|
-
encodeCause(score: HealthScore): string | null;
|
|
264
|
-
/**
|
|
265
|
-
* Run `fn` within a new OTel context that has our cause + chain
|
|
266
|
-
* baggage entries set. Used by the middleware to inject baggage on
|
|
267
|
-
* every non-/healthz request. When OTel API is unavailable, this
|
|
268
|
-
* degrades to `fn()` directly.
|
|
269
|
-
*/
|
|
270
|
-
runWithCause<T>(fn: () => T | Promise<T>, score: HealthScore): Promise<T>;
|
|
271
|
-
/** Tear down internal references. Idempotent. */
|
|
272
|
-
dispose(): void;
|
|
273
|
-
}
|
|
274
|
-
/**
|
|
275
|
-
* Build a causality handle. Returns a handle whose state starts at
|
|
276
|
-
* `'loading'`; emit / read operations are no-ops during loading. Once
|
|
277
|
-
* the dynamic import resolves, state transitions to `'ready'` (or
|
|
278
|
-
* `'unavailable'` when OTel API is absent).
|
|
279
|
-
*/
|
|
280
|
-
declare function createCausalityHandle(opts?: CausalityOptions): CausalityHandle;
|
|
281
|
-
|
|
282
|
-
/**
|
|
283
|
-
* Static attributes the emitter merges onto every metric / event /
|
|
284
|
-
* span-attribute it produces. Use to stamp deployment metadata
|
|
285
|
-
* (`deployment.env`, `git.sha`, …) that the OTel resource detector
|
|
286
|
-
* doesn't pick up automatically.
|
|
287
|
-
*/
|
|
288
|
-
type OtelStaticAttributes = Readonly<Record<string, string | number | boolean>>;
|
|
289
|
-
interface OtelEmitterOptions {
|
|
290
|
-
/**
|
|
291
|
-
* Pre-built OTel Meter. When provided, the emitter uses it directly and
|
|
292
|
-
* skips the async OTel API load. Common case: tests, sandboxes, multi-
|
|
293
|
-
* tenant runtimes wiring a custom MeterProvider per request.
|
|
294
|
-
*/
|
|
295
|
-
readonly meter?: Meter;
|
|
296
|
-
/**
|
|
297
|
-
* Pre-built OTel Tracer. Same intent as `meter`. The emitter uses the
|
|
298
|
-
* tracer only to read the active span when setting attributes /
|
|
299
|
-
* events; it does not create new spans.
|
|
300
|
-
*/
|
|
301
|
-
readonly tracer?: Tracer;
|
|
302
|
-
/**
|
|
303
|
-
* When true, the emitter records a `health.evaluated` span event on
|
|
304
|
-
* every evaluation (if a span is active). Default false — high-
|
|
305
|
-
* frequency probe paths produce many events and most operators only
|
|
306
|
-
* need the metric.
|
|
307
|
-
*/
|
|
308
|
-
readonly events?: boolean;
|
|
309
|
-
/** Static attributes merged onto every emitted metric / span attribute. */
|
|
310
|
-
readonly attributes?: OtelStaticAttributes;
|
|
311
|
-
}
|
|
312
|
-
/**
|
|
313
|
-
* The flag value passed by callers via `sylphxHealth({ otel })` /
|
|
314
|
-
* `withHealth.hono({ otel })`. `true` (default) enables emission with
|
|
315
|
-
* sensible defaults; `false` disables it; an object configures it.
|
|
316
|
-
*/
|
|
317
|
-
type OtelOption = boolean | OtelEmitterOptions;
|
|
318
|
-
interface OtelEmitter {
|
|
319
|
-
/**
|
|
320
|
-
* Emit metrics / span attributes / event for one HealthScore.
|
|
321
|
-
* `upstreamCause` (ADR-143) carries the parsed causality baggage so the
|
|
322
|
-
* emitter can record `health.downstream_cause` counter +
|
|
323
|
-
* `service.health.cause_*` span attributes. Non-throwing.
|
|
324
|
-
*/
|
|
325
|
-
emit(score: HealthScore, upstreamCause?: UpstreamCause | null): void;
|
|
326
|
-
/**
|
|
327
|
-
* Tear down any cached instruments. Called from `sylphxHealth.dispose()`
|
|
328
|
-
* during graceful shutdown. The OTel SDK owns the underlying meter
|
|
329
|
-
* lifecycle; this method only releases the emitter's caches.
|
|
330
|
-
*/
|
|
331
|
-
dispose(): void;
|
|
332
|
-
/** Readiness state — exposed for tests. `loading` is transient; `ready` and `unavailable` are terminal. */
|
|
333
|
-
readonly state: 'loading' | 'ready' | 'unavailable' | 'disposed';
|
|
334
|
-
}
|
|
335
|
-
/** Metric names — pinned by ADR-142 §3.1 + ADR-143 §3.3, stable from day one. */
|
|
336
|
-
declare const METRIC_NAMES: {
|
|
337
|
-
readonly score: "health.score";
|
|
338
|
-
readonly signalFactor: "health.signal.factor";
|
|
339
|
-
readonly signalValue: "health.signal.value";
|
|
340
|
-
readonly signalValueState: "health.signal.value_state";
|
|
341
|
-
/** ADR-143 §3.3 — increments per evaluation when an upstream cause is observed. */
|
|
342
|
-
readonly downstreamCause: "health.downstream_cause";
|
|
343
|
-
};
|
|
344
|
-
/** Span attribute names — pinned by ADR-142 §2.1.3 + ADR-143 §3.2, stable from day one. */
|
|
345
|
-
declare const SPAN_ATTRIBUTES: {
|
|
346
|
-
readonly score: "service.health.score";
|
|
347
|
-
readonly signalFactor: (name: string) => string;
|
|
348
|
-
/** ADR-143 §3.2 — the upstream service that originated the failure chain. */
|
|
349
|
-
readonly causeRoot: "service.health.cause_root";
|
|
350
|
-
/** ADR-143 §3.2 — the signal at the root that failed. */
|
|
351
|
-
readonly causeSignal: "service.health.cause_signal";
|
|
352
|
-
/** ADR-143 §3.2 — comma-delimited hop chain (oldest to newest). */
|
|
353
|
-
readonly causeChain: "service.health.cause_chain";
|
|
354
|
-
};
|
|
355
|
-
/** Span event name — pinned by ADR-142 §2.1.4. */
|
|
356
|
-
declare const EVENT_NAMES: {
|
|
357
|
-
readonly evaluated: "health.evaluated";
|
|
358
|
-
};
|
|
359
|
-
/**
|
|
360
|
-
* Build an OTel emitter.
|
|
361
|
-
*
|
|
362
|
-
* Returns a sealed emitter object whose `emit()` is initially a no-op
|
|
363
|
-
* while the OTel API loads in the background. Once loaded, all subsequent
|
|
364
|
-
* `emit()` calls produce metrics / span attributes / events per ADR-142.
|
|
365
|
-
*
|
|
366
|
-
* When `@opentelemetry/api` is not installed in the host project (the
|
|
367
|
-
* common case for hobby projects), the emitter transitions to
|
|
368
|
-
* `unavailable` and all `emit()` calls remain no-ops for the lifetime of
|
|
369
|
-
* the instance. No exceptions, no warnings.
|
|
370
|
-
*/
|
|
371
|
-
declare function createOtelEmitter(opts?: OtelEmitterOptions): OtelEmitter;
|
|
372
|
-
|
|
373
|
-
/**
|
|
374
|
-
* Type SSOT for `@sylphx/sdk/health` (ADR-111 §4).
|
|
375
|
-
*
|
|
376
|
-
* Pure runtime types — framework-free, no schema library required at the
|
|
377
|
-
* SDK boundary. Apps that want Standard Schema validation (per ADR-084)
|
|
378
|
-
* can wrap the wire-format `HealthSnapshot` in their own schema.
|
|
379
|
-
*
|
|
380
|
-
* The wire shape (`HealthSnapshot`) is the **stable contract** the
|
|
381
|
-
* `sylphx-health-agent` sidecar parses (see ADR-111 §3.2.4 +
|
|
382
|
-
* `apps/health-agent/src/app-poll.ts::parseAppHealthBody`). Do not break it.
|
|
383
|
-
*/
|
|
384
|
-
/**
|
|
385
|
-
* One reading produced by a `Signal.read()`. The aggregator turns each
|
|
386
|
-
* reading into a `factor` in `[0, 1]` then folds them into the score via
|
|
387
|
-
* the configured `ScoringStrategy`.
|
|
388
|
-
*
|
|
389
|
-
* `value` is the raw observation (ms, ratio, count, …) — surfaced verbatim
|
|
390
|
-
* in the wire snapshot so operators can debug from JSON without re-running
|
|
391
|
-
* the signal logic.
|
|
392
|
-
*
|
|
393
|
-
* `healthFactor` is the normalised health in `[0, 1]`:
|
|
394
|
-
* - `1` = fully healthy
|
|
395
|
-
* - `0` = dead (or "we don't know" if `unknown=true` and the policy says so)
|
|
396
|
-
*
|
|
397
|
-
* `unknown=true` means the signal **could not be measured this tick** (e.g.
|
|
398
|
-
* cgroup file unreadable). Scoring strategies treat unknown signals as
|
|
399
|
-
* `factor=1` (don't penalise an app for our own missing data).
|
|
400
|
-
*/
|
|
401
|
-
interface SignalReading {
|
|
402
|
-
readonly value: number | string | boolean;
|
|
403
|
-
readonly healthFactor: number;
|
|
404
|
-
readonly unknown?: boolean;
|
|
405
|
-
}
|
|
406
|
-
/**
|
|
407
|
-
* A health signal — one named, weighted measurement the score is built from.
|
|
408
|
-
*
|
|
409
|
-
* Two variants:
|
|
410
|
-
* - `SyncSignal` — `read(): SignalReading` (e.g. event-loop lag)
|
|
411
|
-
* - `AsyncSignal` — `read(): Promise<SignalReading>` (e.g. queue depth
|
|
412
|
-
* fetched over IPC)
|
|
413
|
-
*
|
|
414
|
-
* The discriminated `Signal` union accepts both. The aggregator awaits
|
|
415
|
-
* each reading uniformly via `Promise.resolve(signal.read())`.
|
|
416
|
-
*
|
|
417
|
-
* Implementations are pure — no internal mutation outside the closure-
|
|
418
|
-
* captured monitor state (e.g. `monitorEventLoopDelay()`). Stop /
|
|
419
|
-
* cleanup are exposed via `dispose()` for tests and graceful shutdown.
|
|
420
|
-
*/
|
|
421
|
-
interface SignalBase {
|
|
422
|
-
/** Unique stable identifier; appears in the wire `signals.<name>` map. */
|
|
423
|
-
readonly name: string;
|
|
424
|
-
/**
|
|
425
|
-
* Weight in the weighted-product score. Strictly `> 0` for active
|
|
426
|
-
* signals; `0` is a no-op signal (kept for compatibility with
|
|
427
|
-
* conditional registration but skipped in scoring).
|
|
428
|
-
*/
|
|
429
|
-
readonly weight: number;
|
|
430
|
-
/**
|
|
431
|
-
* Tear down any background work (timers, monitors, file watchers).
|
|
432
|
-
* Called during graceful shutdown and from test cleanup.
|
|
433
|
-
*/
|
|
434
|
-
dispose?(): void;
|
|
435
|
-
}
|
|
436
|
-
interface SyncSignal extends SignalBase {
|
|
437
|
-
read(): SignalReading;
|
|
438
|
-
}
|
|
439
|
-
interface AsyncSignal extends SignalBase {
|
|
440
|
-
read(): Promise<SignalReading>;
|
|
441
|
-
}
|
|
442
|
-
type Signal = SyncSignal | AsyncSignal;
|
|
443
|
-
/**
|
|
444
|
-
* The complete health score + signal breakdown produced by `health.evaluate()`.
|
|
445
|
-
*
|
|
446
|
-
* `score` is the normalised aggregate in `[0, 1]`. Signal payload is
|
|
447
|
-
* verbatim values from each `SignalReading.value` so operators can
|
|
448
|
-
* cross-reference Grafana dashboards with the JSON.
|
|
449
|
-
*/
|
|
450
|
-
interface HealthScore {
|
|
451
|
-
readonly score: number;
|
|
452
|
-
readonly signals: Record<string, number | string | boolean>;
|
|
453
|
-
/**
|
|
454
|
-
* Normalised per-signal health factors in [0, 1].
|
|
455
|
-
*
|
|
456
|
-
* Additive to the ADR-111 wire shape: existing readers can ignore it,
|
|
457
|
-
* while ADR-142 OTel emission uses it as the SSOT for
|
|
458
|
-
* `health.signal.factor`.
|
|
459
|
-
*/
|
|
460
|
-
readonly signalFactors?: Record<string, number>;
|
|
461
|
-
/**
|
|
462
|
-
* Non-secret release/deployment identity for live-build verification.
|
|
463
|
-
*
|
|
464
|
-
* Additive to the ADR-111 wire shape: probe sidecars ignore it, while
|
|
465
|
-
* operators and deployment monitors can prove which immutable build is
|
|
466
|
-
* answering `/healthz` without needing access to the deploy control plane.
|
|
467
|
-
*/
|
|
468
|
-
readonly release?: HealthRelease;
|
|
469
|
-
readonly lastTickAt: string;
|
|
470
|
-
}
|
|
471
|
-
/**
|
|
472
|
-
* Public, non-secret release identity attached to a health response.
|
|
473
|
-
*
|
|
474
|
-
* These fields intentionally mirror platform-injected runtime identity
|
|
475
|
-
* variables (`SYLPHX_*`) instead of arbitrary metadata. Health endpoints are
|
|
476
|
-
* commonly public, so this surface must stay provenance-focused and must not
|
|
477
|
-
* become a general key/value bag that can accidentally expose secrets.
|
|
478
|
-
*/
|
|
479
|
-
interface HealthRelease {
|
|
480
|
-
readonly version?: string | null;
|
|
481
|
-
readonly commitSha?: string | null;
|
|
482
|
-
readonly imageDigest?: string | null;
|
|
483
|
-
readonly imageTag?: string | null;
|
|
484
|
-
readonly deploymentId?: string | null;
|
|
485
|
-
readonly buildId?: string | null;
|
|
486
|
-
readonly replicaId?: string | null;
|
|
487
|
-
}
|
|
488
|
-
type HealthReleaseInput = HealthRelease | (() => HealthRelease | null | undefined);
|
|
489
|
-
/**
|
|
490
|
-
* Wire format the sidecar's `app-poll.ts::parseAppHealthBody` consumes.
|
|
491
|
-
*
|
|
492
|
-
* Pinned by ADR-111 §3.2.4 — keep stable. The sidecar tolerates extra
|
|
493
|
-
* keys; do NOT remove existing ones without sequencing the sidecar update
|
|
494
|
-
* first.
|
|
495
|
-
*/
|
|
496
|
-
type HealthSnapshot = HealthScore;
|
|
497
|
-
/**
|
|
498
|
-
* Tagged error type for the Effect API. Promise consumers see the same
|
|
499
|
-
* `message` via `Error.message` — the tag is for `Effect.catchTag`.
|
|
500
|
-
*/
|
|
501
|
-
declare class HealthError extends Error {
|
|
502
|
-
readonly _tag: "HealthError";
|
|
503
|
-
readonly cause?: unknown;
|
|
504
|
-
constructor(message: string, cause?: unknown);
|
|
505
|
-
}
|
|
506
|
-
/**
|
|
507
|
-
* `ScoringStrategy` collapses N readings → one `score` in `[0, 1]`.
|
|
508
|
-
*
|
|
509
|
-
* Default is `weightedProduct` (see `scoring.ts`). Custom strategies can
|
|
510
|
-
* be plugged in via `sylphxHealth({ scoringStrategy: myStrategy })`.
|
|
511
|
-
*/
|
|
512
|
-
type ScoringStrategy = (readings: ReadonlyArray<{
|
|
513
|
-
signal: Signal;
|
|
514
|
-
reading: SignalReading;
|
|
515
|
-
}>) => number;
|
|
516
|
-
interface SylphxHealthOptions {
|
|
517
|
-
/**
|
|
518
|
-
* Signals to register. If omitted, defaults to a single
|
|
519
|
-
* `eventLoopLagSignal({ degradedMs: 5000, deadMs: 30000 })` per
|
|
520
|
-
* ADR-111 §4.6 ("sane out-of-box").
|
|
521
|
-
*/
|
|
522
|
-
readonly signals?: ReadonlyArray<Signal>;
|
|
523
|
-
/**
|
|
524
|
-
* Strategy used to fold readings into a score. Defaults to
|
|
525
|
-
* `weightedProduct` from `scoring.ts`.
|
|
526
|
-
*/
|
|
527
|
-
readonly scoringStrategy?: ScoringStrategy;
|
|
528
|
-
/**
|
|
529
|
-
* Optional injected clock — used by tests for deterministic
|
|
530
|
-
* `lastTickAt` timestamps.
|
|
531
|
-
*/
|
|
532
|
-
readonly now?: () => Date;
|
|
533
|
-
/**
|
|
534
|
-
* OpenTelemetry emission (ADR-142). When `true` (default), every
|
|
535
|
-
* `evaluate()` records `health.score` / `health.signal.*` metrics and
|
|
536
|
-
* sets `service.health.score` on the active span. `false` disables
|
|
537
|
-
* emission entirely. An object configures advanced behaviour (custom
|
|
538
|
-
* meter, span events, static attributes).
|
|
539
|
-
*
|
|
540
|
-
* Graceful fallback: if `@opentelemetry/api` is not installed in the
|
|
541
|
-
* host project, the emitter no-ops cleanly — no warning, no exception.
|
|
542
|
-
*/
|
|
543
|
-
readonly otel?: OtelOption;
|
|
544
|
-
/**
|
|
545
|
-
* Causality-aware health propagation (ADR-143). When `true` (default),
|
|
546
|
-
* every `evaluate()` reads upstream cause from active OTel baggage
|
|
547
|
-
* and surfaces it on the metric stream (`health.downstream_cause`
|
|
548
|
-
* counter + `service.health.cause_root` span attribute). The
|
|
549
|
-
* `withHealth.*` middleware additionally writes the local cause into
|
|
550
|
-
* the request context baggage on every non-`/healthz` request so
|
|
551
|
-
* downstream services inherit causality via standard OTel
|
|
552
|
-
* propagation. `false` disables both read and write. An object
|
|
553
|
-
* tunes the threshold + service-name + chain behaviour.
|
|
554
|
-
*
|
|
555
|
-
* Graceful fallback: if `@opentelemetry/api` is not installed, the
|
|
556
|
-
* handle becomes `'unavailable'` and propagation is a no-op.
|
|
557
|
-
*/
|
|
558
|
-
readonly causality?: CausalityOption;
|
|
559
|
-
/**
|
|
560
|
-
* Audit-grade health history (ADR-144). When `true` (default), every
|
|
561
|
-
* `evaluate()` records a tamper-evident `HistoryEntry` into the
|
|
562
|
-
* configured `HistoryStore` (default: in-memory ring buffer with
|
|
563
|
-
* capacity 1000). Entries form a SHA-256 prev-hash chain — operators
|
|
564
|
-
* (and compliance auditors) can replay the chain to detect post-hoc
|
|
565
|
-
* tampering.
|
|
566
|
-
*
|
|
567
|
-
* Set `false` to disable recording. Pass an object to plug a
|
|
568
|
-
* persistent store (Postgres / S3 / OpenSearch) or override capacity.
|
|
569
|
-
*
|
|
570
|
-
* The in-memory store is suitable for testing + low-stakes single-pod
|
|
571
|
-
* deployments. SOC 2 / GDPR / HIPAA compliance requires a persistent
|
|
572
|
-
* adapter; the interface is public and stable so any backend works.
|
|
573
|
-
*/
|
|
574
|
-
readonly history?: HistoryOption;
|
|
575
|
-
/**
|
|
576
|
-
* Optional non-secret release identity to include in every HealthSnapshot.
|
|
577
|
-
*
|
|
578
|
-
* Accepts a static object or a synchronous resolver. Resolver failures are
|
|
579
|
-
* swallowed: release metadata must never block the load-bearing health
|
|
580
|
-
* response.
|
|
581
|
-
*/
|
|
582
|
-
readonly release?: HealthReleaseInput;
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
/**
|
|
586
|
-
* Effect TS integration for `@sylphx/sdk/health` (Rule 21 / ADR-058 Amendment).
|
|
587
|
-
*
|
|
588
|
-
* Effect-native services should NEVER call `Effect.runPromise` inside
|
|
589
|
-
* business logic — this module exposes `evaluateEffect` so they can fold
|
|
590
|
-
* the health computation into their own fiber graph.
|
|
591
|
-
*
|
|
592
|
-
* `effect` is an OPTIONAL peer dependency — apps that don't import this
|
|
593
|
-
* module never pull it in (sideEffects: false + tree-shaking guarantees
|
|
594
|
-
* this; verified in tests). The `Effect` type is imported from the
|
|
595
|
-
* peer-dep at runtime; consumers either provide it or never reach this
|
|
596
|
-
* code path.
|
|
597
|
-
*/
|
|
598
|
-
|
|
599
|
-
/**
|
|
600
|
-
* Lift a `() => Promise<HealthScore>` evaluator into an Effect-native value.
|
|
601
|
-
*
|
|
602
|
-
* Errors thrown by the evaluator are tagged `HealthError` so callers can
|
|
603
|
-
* use `Effect.catchTag('HealthError', …)` for typed recovery.
|
|
604
|
-
*
|
|
605
|
-
* @example
|
|
606
|
-
* ```ts
|
|
607
|
-
* import { Effect } from 'effect'
|
|
608
|
-
* import { sylphxHealth } from '@sylphx/sdk/health'
|
|
609
|
-
*
|
|
610
|
-
* const health = sylphxHealth({ signals: [...] })
|
|
611
|
-
*
|
|
612
|
-
* const program = Effect.gen(function* () {
|
|
613
|
-
* const { score, signals } = yield* health.evaluateEffect
|
|
614
|
-
* yield* Effect.log(`health=${score.toFixed(2)} signals=${JSON.stringify(signals)}`)
|
|
615
|
-
* return score
|
|
616
|
-
* })
|
|
617
|
-
*
|
|
618
|
-
* // Only the entry point runs the Effect (Rule 21).
|
|
619
|
-
* const finalScore = await Effect.runPromise(program)
|
|
620
|
-
* ```
|
|
621
|
-
*/
|
|
622
|
-
declare function evaluateEffect(evaluator: () => Promise<HealthScore>): Effect.Effect<HealthScore, HealthError, never>;
|
|
623
|
-
|
|
624
|
-
/**
|
|
625
|
-
* Universal HTTP handler for `@sylphx/sdk/health` (ADR-111 §4.2).
|
|
626
|
-
*
|
|
627
|
-
* Framework-agnostic: returns either a `Web Fetch API` `Response`
|
|
628
|
-
* (Hono / Bun.serve / itty-router / Next.js routes) or, via thin adapters,
|
|
629
|
-
* a Node `(req, res) => void` (Express / Fastify-as-classic-handler).
|
|
630
|
-
*
|
|
631
|
-
* The handler returns HTTP 200 for scores at or above the direct-probe
|
|
632
|
-
* liveness floor and HTTP 503 below it. The response body is always the
|
|
633
|
-
* complete HealthSnapshot, so the ADR-111 sidecar can still read the score
|
|
634
|
-
* even when direct kubelet probes need a status-coded failure.
|
|
635
|
-
*/
|
|
636
|
-
|
|
637
|
-
/**
|
|
638
|
-
* Minimal contract a `health` instance must expose for the handler to
|
|
639
|
-
* call. The full `health` object satisfies this implicitly via
|
|
640
|
-
* `evaluate()` from `./index.ts`.
|
|
641
|
-
*/
|
|
642
|
-
interface HealthEvaluator {
|
|
643
|
-
evaluate(): Promise<HealthScore>;
|
|
644
|
-
}
|
|
645
|
-
/**
|
|
646
|
-
* Build a Web-Fetch-style handler. Suitable for:
|
|
647
|
-
* - Hono: `app.get('/healthz', health.handler())`
|
|
648
|
-
* - Bun.serve: `fetch: health.handler()`
|
|
649
|
-
* - Next.js route.ts: `export const GET = health.handler()`
|
|
650
|
-
* - itty-router / Hattip / standard `(Request) => Response` runtimes
|
|
651
|
-
*/
|
|
652
|
-
declare function createWebHandler(source: HealthEvaluator): (req?: Request) => Promise<Response>;
|
|
653
|
-
/**
|
|
654
|
-
* Build a Node-style `(req, res)` handler — for Express / classic Fastify.
|
|
655
|
-
*
|
|
656
|
-
* Adapter that delegates to `createWebHandler()` so logic stays in one
|
|
657
|
-
* place. Imported lazily by callers that need it; doesn't drag any node
|
|
658
|
-
* types into Web-only code paths.
|
|
659
|
-
*/
|
|
660
|
-
interface NodeIncoming {
|
|
661
|
-
method?: string;
|
|
662
|
-
url?: string;
|
|
663
|
-
}
|
|
664
|
-
interface NodeOutgoing {
|
|
665
|
-
statusCode: number;
|
|
666
|
-
setHeader(name: string, value: string): void;
|
|
667
|
-
end(body?: string): void;
|
|
668
|
-
}
|
|
669
|
-
declare function createNodeHandler(source: HealthEvaluator): (req: NodeIncoming, res: NodeOutgoing) => Promise<void>;
|
|
670
|
-
|
|
671
|
-
/**
|
|
672
|
-
* Unix-socket server for `@sylphx/sdk/health` (ADR-111 §3.2.4 + §4.2).
|
|
673
|
-
*
|
|
674
|
-
* The sidecar polls the app over a Unix socket — `/var/run/sylphx/health.sock`
|
|
675
|
-
* by default. The shared volume (`emptyDir` mount, see ADR-111 §3.2.2) is
|
|
676
|
-
* provisioned by the reconciler when the sidecar is injected. This server
|
|
677
|
-
* binds Bun's native `Bun.serve({ unix: <path> })` and serves the same
|
|
678
|
-
* JSON the HTTP handler does.
|
|
679
|
-
*
|
|
680
|
-
* Graceful shutdown is essential — the socket file lingers on disk if not
|
|
681
|
-
* cleaned, and the sidecar's first reconnect attempt after a redeploy
|
|
682
|
-
* would hit a stale inode. `shutdown()` calls `server.stop()` AND
|
|
683
|
-
* unlinks the socket file. Process signal ownership stays with the app
|
|
684
|
-
* entry point; SDK library code only returns an explicit shutdown handle.
|
|
685
|
-
*/
|
|
686
|
-
|
|
687
|
-
/** Bun-typed minimum for the server we need to control. */
|
|
688
|
-
interface BunServer {
|
|
689
|
-
stop(force?: boolean): void;
|
|
690
|
-
url?: {
|
|
691
|
-
href: string;
|
|
692
|
-
} | null;
|
|
693
|
-
}
|
|
694
|
-
interface UnixSocketServerOptions {
|
|
695
|
-
/** Absolute path to bind. Defaults to `/var/run/sylphx/health.sock`. */
|
|
696
|
-
readonly path?: string;
|
|
697
|
-
/**
|
|
698
|
-
* Override unlink behavior — useful for tests where the test runner
|
|
699
|
-
* already owns the socket cleanup.
|
|
700
|
-
*/
|
|
701
|
-
readonly unlinkOnShutdown?: boolean;
|
|
702
|
-
/**
|
|
703
|
-
* Override the Bun runtime resolver. Used by tests to verify the
|
|
704
|
-
* "no-Bun" error path without leaving a Bun-only test environment.
|
|
705
|
-
* Production code reads `globalThis.Bun` directly.
|
|
706
|
-
*/
|
|
707
|
-
readonly bunRuntime?: {
|
|
708
|
-
serve: (cfg: unknown) => BunServer;
|
|
709
|
-
} | null;
|
|
710
|
-
}
|
|
711
|
-
interface UnixSocketServerHandle {
|
|
712
|
-
readonly path: string;
|
|
713
|
-
readonly server: BunServer;
|
|
714
|
-
/** Stop the server AND unlink the socket file (unless `unlinkOnShutdown=false`). */
|
|
715
|
-
shutdown(): Promise<void>;
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
/**
|
|
719
|
-
* Framework middleware helpers for `@sylphx/sdk/health` (ADR-141 Phase 0).
|
|
720
|
-
*
|
|
721
|
-
* Zero-Config one-liners for the most common JS server frameworks. Each
|
|
722
|
-
* helper creates a `sylphxHealth()` instance internally and returns a
|
|
723
|
-
* framework-idiomatic middleware / plugin / handler that serves `/healthz`.
|
|
724
|
-
*
|
|
725
|
-
* For advanced control (custom signals, scoring strategies, Unix-socket
|
|
726
|
-
* IPC for the sidecar), import `sylphxHealth` directly — these helpers
|
|
727
|
-
* are wrappers around the same factory.
|
|
728
|
-
*
|
|
729
|
-
* @example Hono
|
|
730
|
-
* ```ts
|
|
731
|
-
* import { Hono } from 'hono'
|
|
732
|
-
* import { withHealth } from '@sylphx/sdk/health'
|
|
733
|
-
*
|
|
734
|
-
* const app = new Hono()
|
|
735
|
-
* app.use('*', withHealth.hono())
|
|
736
|
-
* ```
|
|
737
|
-
*
|
|
738
|
-
* @example Express
|
|
739
|
-
* ```ts
|
|
740
|
-
* import express from 'express'
|
|
741
|
-
* import { withHealth } from '@sylphx/sdk/health'
|
|
742
|
-
*
|
|
743
|
-
* const app = express()
|
|
744
|
-
* app.use(withHealth.express())
|
|
745
|
-
* ```
|
|
746
|
-
*
|
|
747
|
-
* @example Fastify
|
|
748
|
-
* ```ts
|
|
749
|
-
* import Fastify from 'fastify'
|
|
750
|
-
* import { withHealth } from '@sylphx/sdk/health'
|
|
751
|
-
*
|
|
752
|
-
* const fastify = Fastify()
|
|
753
|
-
* await fastify.register(withHealth.fastify())
|
|
754
|
-
* ```
|
|
755
|
-
*
|
|
756
|
-
* @example Bun.serve / Next.js / Deno / edge runtimes
|
|
757
|
-
* ```ts
|
|
758
|
-
* import { withHealth } from '@sylphx/sdk/health'
|
|
759
|
-
*
|
|
760
|
-
* const handleHealth = withHealth.fetch()
|
|
761
|
-
* Bun.serve({
|
|
762
|
-
* port: 3000,
|
|
763
|
-
* fetch(req) {
|
|
764
|
-
* if (new URL(req.url).pathname === '/healthz') return handleHealth(req)
|
|
765
|
-
* return new Response('hello')
|
|
766
|
-
* },
|
|
767
|
-
* })
|
|
768
|
-
* ```
|
|
769
|
-
*
|
|
770
|
-
* Structural types are used for the framework signatures so this module
|
|
771
|
-
* has **zero peer dependencies** on Hono / Express / Fastify. The user's
|
|
772
|
-
* framework supplies the actual types at the call site via TypeScript's
|
|
773
|
-
* structural typing.
|
|
774
|
-
*/
|
|
775
|
-
|
|
776
|
-
/**
|
|
777
|
-
* Common options for every framework helper. Extends `SylphxHealthOptions`
|
|
778
|
-
* (signals, scoringStrategy, now) with a `path` override.
|
|
779
|
-
*/
|
|
780
|
-
interface WithHealthOptions extends SylphxHealthOptions {
|
|
781
|
-
/**
|
|
782
|
-
* HTTP path to serve the health endpoint on. Defaults to `/healthz` —
|
|
783
|
-
* the de-facto Kubernetes convention adopted by Spring Boot, FastAPI,
|
|
784
|
-
* and the IETF `application/health+json` draft.
|
|
785
|
-
*/
|
|
786
|
-
readonly path?: string;
|
|
787
|
-
/**
|
|
788
|
-
* Pre-built `SylphxHealth` instance. When provided, options other than
|
|
789
|
-
* `path` are ignored and the helper just wires the instance up. Use
|
|
790
|
-
* this when you need to share one health instance across multiple
|
|
791
|
-
* frameworks (e.g. Hono middleware + Unix-socket IPC for the sidecar).
|
|
792
|
-
*/
|
|
793
|
-
readonly instance?: SylphxHealth;
|
|
794
|
-
/**
|
|
795
|
-
* Bind the same health score on the sidecar IPC socket.
|
|
796
|
-
*
|
|
797
|
-
* Default: auto-enable when the platform injects
|
|
798
|
-
* `SYLPHX_HEALTH_APP_SOCKET` into the app container. This keeps the
|
|
799
|
-
* one-line helper enough for ADR-111 health-agent score polling while
|
|
800
|
-
* remaining a no-op on local/dev/edge runtimes without the env var.
|
|
801
|
-
*
|
|
802
|
-
* Set `false` to opt out, `true` to bind the default socket path, or
|
|
803
|
-
* pass `{ path, required }` for explicit control. `required` defaults
|
|
804
|
-
* to `false` so non-Bun runtimes never fail module import just because
|
|
805
|
-
* they share the public SDK.
|
|
806
|
-
*/
|
|
807
|
-
readonly unixSocket?: boolean | {
|
|
808
|
-
readonly path?: string;
|
|
809
|
-
readonly required?: boolean;
|
|
810
|
-
readonly unlinkOnShutdown?: boolean;
|
|
811
|
-
};
|
|
812
|
-
}
|
|
813
|
-
/**
|
|
814
|
-
* Minimal structural type for a Hono request context. We only need
|
|
815
|
-
* `c.req.path` to decide whether the request hits the health endpoint.
|
|
816
|
-
*/
|
|
817
|
-
interface HonoContextLike {
|
|
818
|
-
readonly req: {
|
|
819
|
-
readonly path: string;
|
|
820
|
-
};
|
|
821
|
-
}
|
|
822
|
-
/** Hono `Next` is a parameterless async callback that yields to the next middleware. */
|
|
823
|
-
type HonoNextLike = () => Promise<void>;
|
|
824
|
-
/**
|
|
825
|
-
* Hono middleware that responds to `GET /healthz` and yields otherwise.
|
|
826
|
-
*
|
|
827
|
-
* The returned function carries a `.health` reference (the underlying
|
|
828
|
-
* `SylphxHealth` instance) and a `.dispose()` method for graceful
|
|
829
|
-
* shutdown. Wire `.dispose()` into the app entry point's existing
|
|
830
|
-
* graceful-shutdown coordinator.
|
|
831
|
-
*
|
|
832
|
-
* ```ts
|
|
833
|
-
* const health = withHealth.hono()
|
|
834
|
-
* app.use('*', health)
|
|
835
|
-
* registerShutdown(() => health.dispose())
|
|
836
|
-
* ```
|
|
837
|
-
*/
|
|
838
|
-
interface HonoHealthMiddleware {
|
|
839
|
-
(c: HonoContextLike, next: HonoNextLike): Promise<Response | undefined>;
|
|
840
|
-
readonly health: SylphxHealth;
|
|
841
|
-
dispose(): void;
|
|
842
|
-
}
|
|
843
|
-
declare function honoHelper(opts?: WithHealthOptions): HonoHealthMiddleware;
|
|
844
|
-
/** Express-style request — only `url` is needed to match `/healthz`. */
|
|
845
|
-
interface ExpressRequestLike {
|
|
846
|
-
readonly url?: string;
|
|
847
|
-
readonly method?: string;
|
|
848
|
-
}
|
|
849
|
-
/** Express-style response — subset required by the Node handler. */
|
|
850
|
-
interface ExpressResponseLike {
|
|
851
|
-
statusCode: number;
|
|
852
|
-
setHeader(name: string, value: string): void;
|
|
853
|
-
end(body?: string): void;
|
|
854
|
-
}
|
|
855
|
-
/** Express-style next callback — called when the request is not for /healthz. */
|
|
856
|
-
type ExpressNextLike = (err?: unknown) => void;
|
|
857
|
-
interface ExpressHealthMiddleware {
|
|
858
|
-
(req: ExpressRequestLike, res: ExpressResponseLike, next: ExpressNextLike): void;
|
|
859
|
-
readonly health: SylphxHealth;
|
|
860
|
-
dispose(): void;
|
|
861
|
-
}
|
|
862
|
-
declare function expressHelper(opts?: WithHealthOptions): ExpressHealthMiddleware;
|
|
863
|
-
/**
|
|
864
|
-
* Minimal structural type for a Fastify instance — only the `.get` route
|
|
865
|
-
* registration is needed. The plugin signature matches Fastify's
|
|
866
|
-
* encapsulated-plugin contract: `(instance, opts) => Promise<void>`.
|
|
867
|
-
*/
|
|
868
|
-
interface FastifyInstanceLike {
|
|
869
|
-
get(path: string, handler: (req: unknown, reply: FastifyReplyLike) => Promise<unknown> | unknown): unknown;
|
|
870
|
-
}
|
|
871
|
-
/** Minimal Fastify reply — subset required by the health response. */
|
|
872
|
-
interface FastifyReplyLike {
|
|
873
|
-
code(code: number): FastifyReplyLike;
|
|
874
|
-
header(name: string, value: string): FastifyReplyLike;
|
|
875
|
-
send(body?: unknown): unknown;
|
|
876
|
-
}
|
|
877
|
-
interface FastifyHealthPlugin {
|
|
878
|
-
(instance: FastifyInstanceLike, opts?: unknown): Promise<void>;
|
|
879
|
-
readonly health: SylphxHealth;
|
|
880
|
-
dispose(): void;
|
|
881
|
-
}
|
|
882
|
-
declare function fastifyHelper(opts?: WithHealthOptions): FastifyHealthPlugin;
|
|
883
|
-
interface FetchHealthHandler {
|
|
884
|
-
(req?: Request): Promise<Response>;
|
|
885
|
-
readonly health: SylphxHealth;
|
|
886
|
-
dispose(): void;
|
|
887
|
-
}
|
|
888
|
-
declare function fetchHelper(opts?: WithHealthOptions): FetchHealthHandler;
|
|
889
|
-
/**
|
|
890
|
-
* One-line health-check wiring for popular JS server frameworks.
|
|
891
|
-
*
|
|
892
|
-
* All helpers internally create a `sylphxHealth()` instance with sane
|
|
893
|
-
* defaults (single event-loop-lag signal) and serve `/healthz` returning
|
|
894
|
-
* the standard `HealthScore` JSON.
|
|
895
|
-
*
|
|
896
|
-
* Each returned helper exposes the underlying `SylphxHealth` instance
|
|
897
|
-
* via `.health` and a `.dispose()` shortcut for graceful shutdown.
|
|
898
|
-
*
|
|
899
|
-
* See `sylphxHealth()` for advanced use (custom signals, scoring, IPC).
|
|
900
|
-
*/
|
|
901
|
-
declare const withHealth: {
|
|
902
|
-
/** Hono middleware. Mount with `app.use('*', withHealth.hono())`. */
|
|
903
|
-
readonly hono: typeof honoHelper;
|
|
904
|
-
/** Express / Connect / Polka middleware. Mount with `app.use(withHealth.express())`. */
|
|
905
|
-
readonly express: typeof expressHelper;
|
|
906
|
-
/** Fastify plugin. Register with `await fastify.register(withHealth.fastify())`. */
|
|
907
|
-
readonly fastify: typeof fastifyHelper;
|
|
908
|
-
/**
|
|
909
|
-
* Pure Web Fetch handler. Works with Bun.serve, Next.js route
|
|
910
|
-
* handlers, Deno, Cloudflare Workers, and any other `Request →
|
|
911
|
-
* Response` runtime.
|
|
912
|
-
*/
|
|
913
|
-
readonly fetch: typeof fetchHelper;
|
|
914
|
-
};
|
|
915
|
-
|
|
916
|
-
/**
|
|
917
|
-
* Scoring strategies (ADR-111 §4 — three-tier health gate).
|
|
918
|
-
*
|
|
919
|
-
* The default `weightedProduct` strategy is multiplicative — a single bad
|
|
920
|
-
* signal can drag the whole score down (any factor of 0 → score 0). This is
|
|
921
|
-
* the right semantic for **liveness**: one critical subsystem dead means
|
|
922
|
-
* the runtime is not ready, regardless of how healthy the rest is.
|
|
923
|
-
*
|
|
924
|
-
* Mathematics:
|
|
925
|
-
* score = ∏ factor_i ^ weight_i (over signals where weight > 0 AND
|
|
926
|
-
* reading is not `unknown`)
|
|
927
|
-
*
|
|
928
|
-
* Where weights are normalised to sum=1 first, so absolute weight values
|
|
929
|
-
* don't matter — only the ratios do. This keeps user expectations sane:
|
|
930
|
-
* `[w=2, w=2]` and `[w=10, w=10]` produce identical scores.
|
|
931
|
-
*
|
|
932
|
-
* Edge cases (deterministic, never throw):
|
|
933
|
-
* - empty input → 1 (perfect health, nothing to penalise)
|
|
934
|
-
* - all weights = 0 → 1 (no active signals)
|
|
935
|
-
* - all readings `unknown` → 1 (we can't see; cardinal-rule fallback
|
|
936
|
-
* lives at the sidecar boundary, not
|
|
937
|
-
* here — ADR-111 §3.2.5)
|
|
938
|
-
* - factor < 0 / NaN → clamped to 0
|
|
939
|
-
* - factor > 1 → clamped to 1
|
|
940
|
-
* - weight < 0 → clamped to 0 (ignored)
|
|
941
|
-
*
|
|
942
|
-
* The clamps make us **safe by construction** — a misconfigured signal
|
|
943
|
-
* cannot push the score outside `[0, 1]`. Tests exercise all branches.
|
|
944
|
-
*/
|
|
945
|
-
|
|
946
|
-
/**
|
|
947
|
-
* Weighted geometric mean — the default scoring strategy.
|
|
948
|
-
*
|
|
949
|
-
* @example
|
|
950
|
-
* weightedProduct([
|
|
951
|
-
* { signal: { name: 'lag', weight: 0.4 }, reading: { healthFactor: 0.4 } },
|
|
952
|
-
* { signal: { name: 'q', weight: 0.6 }, reading: { healthFactor: 1.0 } },
|
|
953
|
-
* ])
|
|
954
|
-
* // → 0.4^0.4 × 1.0^0.6 ≈ 0.693 — ADR-111 §4.5 worked example
|
|
955
|
-
*/
|
|
956
|
-
declare const weightedProduct: ScoringStrategy;
|
|
957
|
-
/**
|
|
958
|
-
* Convenience: build a default scoring strategy.
|
|
959
|
-
*
|
|
960
|
-
* Reserved for future: weighted-min, weighted-mean, etc. For now there's
|
|
961
|
-
* one strategy and `weightedProduct` is the only export — this keeps the
|
|
962
|
-
* surface narrow until a concrete second use-case appears.
|
|
963
|
-
*/
|
|
964
|
-
declare function defaultScoringStrategy(): ScoringStrategy;
|
|
965
|
-
|
|
966
|
-
/**
|
|
967
|
-
* `errorRateSignal` — request-error-rate over a sliding window (ADR-111 §4.3).
|
|
968
|
-
*
|
|
969
|
-
* Phase B uses an in-memory ring buffer of {timestamp, isError} samples.
|
|
970
|
-
* Phase C will replace this with an OTel collector subscription so the
|
|
971
|
-
* sidecar gets the same data without per-process bookkeeping; for now the
|
|
972
|
-
* in-memory path keeps the SDK self-contained.
|
|
973
|
-
*
|
|
974
|
-
* Mapping observed-rate → healthFactor:
|
|
975
|
-
*
|
|
976
|
-
* healthFactor
|
|
977
|
-
* ▲
|
|
978
|
-
* 1.0 ┤━━━━━━━━━━━━━━━━━━━┓
|
|
979
|
-
* │ ┃ linear interpolation
|
|
980
|
-
* 0.0 ┤ ┗━━━━━━━━━━
|
|
981
|
-
* ┼───────────────────┼────────► error rate (0..1)
|
|
982
|
-
* 0 degradedRate deadRate
|
|
983
|
-
*
|
|
984
|
-
* Default thresholds match ADR-111 §4.3 row 3:
|
|
985
|
-
* degradedRate = 0.05 (5 % errors → degraded)
|
|
986
|
-
* deadRate = 0.50 (50 % errors → dead)
|
|
987
|
-
*
|
|
988
|
-
* `recordSuccess()` / `recordError()` are pushed by the app on each
|
|
989
|
-
* request (or wired into Hono / Express middleware — the SDK provides
|
|
990
|
-
* primitives, not framework integrations). Zero-traffic windows produce
|
|
991
|
-
* `factor=1` (no requests = no errors = healthy by convention).
|
|
992
|
-
*/
|
|
993
|
-
|
|
994
|
-
interface ErrorRateOptions {
|
|
995
|
-
/** Sliding window length. Accepts ms (number) or '5s' / '1m' shorthand. */
|
|
996
|
-
readonly window: number | `${number}s` | `${number}m`;
|
|
997
|
-
/** Rate above this is considered degraded. Default 0.05 (5 %). */
|
|
998
|
-
readonly degradedRate?: number;
|
|
999
|
-
/** Rate at which the signal saturates to dead. Default 0.50 (50 %). */
|
|
1000
|
-
readonly deadRate?: number;
|
|
1001
|
-
/**
|
|
1002
|
-
* Soft minimum sample count: until this many samples land, factor=1
|
|
1003
|
-
* regardless of rate (avoids "1 error in 1 request → 100 %" panics).
|
|
1004
|
-
* Default 10.
|
|
1005
|
-
*/
|
|
1006
|
-
readonly minSamples?: number;
|
|
1007
|
-
/** Weight in the weighted-product score. Default 0.2 (ADR-111 §4.3). */
|
|
1008
|
-
readonly weight?: number;
|
|
1009
|
-
/** Optional injected clock for tests. */
|
|
1010
|
-
readonly now?: () => number;
|
|
1011
|
-
}
|
|
1012
|
-
interface ErrorRateSignalHandle extends SyncSignal {
|
|
1013
|
-
/** Record a successful request (call from app middleware). */
|
|
1014
|
-
recordSuccess(): void;
|
|
1015
|
-
/** Record a failed request (call from app middleware). */
|
|
1016
|
-
recordError(): void;
|
|
1017
|
-
/** Erase the window. Useful for tests. */
|
|
1018
|
-
reset(): void;
|
|
1019
|
-
}
|
|
1020
|
-
declare function errorRateSignal(opts: ErrorRateOptions): ErrorRateSignalHandle;
|
|
1021
|
-
|
|
1022
|
-
/**
|
|
1023
|
-
* `eventLoopLagSignal` — main-thread blocking detector (ADR-111 §4.3).
|
|
1024
|
-
*
|
|
1025
|
-
* Measures Node/Bun's libuv event-loop delay using `monitorEventLoopDelay()`
|
|
1026
|
-
* from `node:perf_hooks`. The monitor is a histogram updated by libuv at a
|
|
1027
|
-
* configurable resolution (default 10 ms here — every tick measures lag
|
|
1028
|
-
* between expected wake and actual wake). We report the **max** observed
|
|
1029
|
-
* since the last `read()` then `reset()` — that's the worst-case stall
|
|
1030
|
-
* the app suffered in the polling window.
|
|
1031
|
-
*
|
|
1032
|
-
* Mapping observed-lag-ms → healthFactor ∈ [0, 1]:
|
|
1033
|
-
*
|
|
1034
|
-
* healthFactor
|
|
1035
|
-
* ▲
|
|
1036
|
-
* 1.0 ┤━━━━━━━━━┓
|
|
1037
|
-
* │ ┃ linear interpolation
|
|
1038
|
-
* │ ┃
|
|
1039
|
-
* 0.0 ┤ ┗━━━━━━━━━━━━━
|
|
1040
|
-
* ┼─────────┼──────────┼──────► observed lag (ms)
|
|
1041
|
-
* 0 degradedMs deadMs
|
|
1042
|
-
*
|
|
1043
|
-
* Below `degradedMs` → factor 1 (healthy). Above `deadMs` → factor 0 (dead).
|
|
1044
|
-
* In-between → linear interpolation. ADR-111 §4.3 default thresholds:
|
|
1045
|
-
* degradedMs = 5000 (5 s — same order as ADR-110's 10 s probe timeout)
|
|
1046
|
-
* deadMs = 30000 (30 s — definitely wedged)
|
|
1047
|
-
*
|
|
1048
|
-
* Bun-compatibility: Bun ships `monitorEventLoopDelay()` with the same
|
|
1049
|
-
* shape as Node 16+. Verified against `bun:1.3` in this repo's CI.
|
|
1050
|
-
*/
|
|
1051
|
-
|
|
1052
|
-
interface EventLoopLagOptions {
|
|
1053
|
-
/** Lag below this is fully healthy (factor=1). Default 5000 ms. */
|
|
1054
|
-
readonly degradedMs?: number;
|
|
1055
|
-
/** Lag above this is fully dead (factor=0). Default 30000 ms. */
|
|
1056
|
-
readonly deadMs?: number;
|
|
1057
|
-
/**
|
|
1058
|
-
* Histogram resolution (ms). Default 10 ms — the smaller, the more
|
|
1059
|
-
* accurate the max but the higher the libuv accounting overhead.
|
|
1060
|
-
* Node defaults are also 10 ms.
|
|
1061
|
-
*/
|
|
1062
|
-
readonly resolutionMs?: number;
|
|
1063
|
-
/** Weight in the weighted-product score. Default 0.4 (ADR-111 §4.3). */
|
|
1064
|
-
readonly weight?: number;
|
|
1065
|
-
/**
|
|
1066
|
-
* Optional injected monitor (tests). Defaults to a fresh
|
|
1067
|
-
* `monitorEventLoopDelay()` instance.
|
|
1068
|
-
*/
|
|
1069
|
-
readonly monitor?: ReturnType<typeof monitorEventLoopDelay>;
|
|
1070
|
-
}
|
|
1071
|
-
/**
|
|
1072
|
-
* Build an `event-loop-lag` signal. The returned object owns a started
|
|
1073
|
-
* histogram monitor; call `dispose()` during shutdown / between tests.
|
|
1074
|
-
*/
|
|
1075
|
-
declare function eventLoopLagSignal(opts?: EventLoopLagOptions): SyncSignal;
|
|
1076
|
-
|
|
1077
|
-
/**
|
|
1078
|
-
* `memoryPressureSignal` — RSS / cgroup memory.max ratio (ADR-111 §4.3).
|
|
1079
|
-
*
|
|
1080
|
-
* On Linux containers we read the cgroup v2 memory limit from
|
|
1081
|
-
* `/sys/fs/cgroup/memory.max`. Then `pressure = process.memoryUsage().rss /
|
|
1082
|
-
* limit`. ADR-111 §4.3 default thresholds:
|
|
1083
|
-
* degradedRatio = 0.85 (85 % → degraded)
|
|
1084
|
-
* deadRatio = 0.95 (95 % → dead)
|
|
1085
|
-
*
|
|
1086
|
-
* Mapping observed-pressure → healthFactor:
|
|
1087
|
-
*
|
|
1088
|
-
* healthFactor
|
|
1089
|
-
* ▲
|
|
1090
|
-
* 1.0 ┤━━━━━━━━━━━━━━━━━━┓
|
|
1091
|
-
* │ ┃
|
|
1092
|
-
* 0.0 ┤ ┗━━━━━━━━━
|
|
1093
|
-
* ┼──────────────────┼─────────► pressure (0..1)
|
|
1094
|
-
* 0 degradedRatio deadRatio
|
|
1095
|
-
*
|
|
1096
|
-
* Graceful fallback (the cardinal-rule deference):
|
|
1097
|
-
* - cgroup file missing → unknown=true (signal ignored)
|
|
1098
|
-
* - cgroup file has 'max' → unlimited container, ratio undefined → unknown
|
|
1099
|
-
* - file unreadable / parse → unknown=true
|
|
1100
|
-
*
|
|
1101
|
-
* `unknown=true` makes the scoring strategy ignore the signal — we never
|
|
1102
|
-
* pretend to know memory pressure on a host where we can't measure it.
|
|
1103
|
-
*
|
|
1104
|
-
* cgroup v1 (legacy) lives at `/sys/fs/cgroup/memory/memory.limit_in_bytes`
|
|
1105
|
-
* — supported via `cgroupV1Path` for operators on older kernels.
|
|
1106
|
-
*/
|
|
1107
|
-
|
|
1108
|
-
interface MemoryPressureOptions {
|
|
1109
|
-
/** Pressure below this is fully healthy (factor=1). Default 0.85. */
|
|
1110
|
-
readonly degradedRatio?: number;
|
|
1111
|
-
/** Pressure above this is fully dead (factor=0). Default 0.95. */
|
|
1112
|
-
readonly deadRatio?: number;
|
|
1113
|
-
/**
|
|
1114
|
-
* Custom cgroup v2 memory limit path. Default `/sys/fs/cgroup/memory.max`.
|
|
1115
|
-
*/
|
|
1116
|
-
readonly cgroupV2Path?: string;
|
|
1117
|
-
/**
|
|
1118
|
-
* Optional cgroup v1 fallback path. Default
|
|
1119
|
-
* `/sys/fs/cgroup/memory/memory.limit_in_bytes`. Used when v2 path is
|
|
1120
|
-
* unreadable AND `cgroupV1Path` is set or v2 doesn't exist.
|
|
1121
|
-
*/
|
|
1122
|
-
readonly cgroupV1Path?: string;
|
|
1123
|
-
/** Weight in the weighted-product score. Default 0.2 (ADR-111 §4.3). */
|
|
1124
|
-
readonly weight?: number;
|
|
1125
|
-
/**
|
|
1126
|
-
* Optional injected `process.memoryUsage` for tests.
|
|
1127
|
-
* Default: `process.memoryUsage`.
|
|
1128
|
-
*/
|
|
1129
|
-
readonly memoryUsage?: () => {
|
|
1130
|
-
rss: number;
|
|
1131
|
-
};
|
|
1132
|
-
/** Optional injected file reader for tests. */
|
|
1133
|
-
readonly readFile?: (path: string) => string;
|
|
1134
|
-
}
|
|
1135
|
-
declare function memoryPressureSignal(opts?: MemoryPressureOptions): SyncSignal;
|
|
1136
|
-
|
|
1137
|
-
/**
|
|
1138
|
-
* `pingSignal` — generic binary readiness signal for any sub-system the
|
|
1139
|
-
* service depends on (Postgres, Redis, Kafka, S3, an upstream API, …).
|
|
1140
|
-
*
|
|
1141
|
-
* The signal calls `ping()` every poll tick and reports:
|
|
1142
|
-
* - `healthFactor: 1` if the ping resolves (any value) within the timeout
|
|
1143
|
-
* - `healthFactor: 0` if the ping throws OR times out
|
|
1144
|
-
*
|
|
1145
|
-
* Binary — no partial-credit semantics. For richer scoring use a custom
|
|
1146
|
-
* signal that returns a graded `healthFactor`; `pingSignal` is the
|
|
1147
|
-
* canonical "subsystem reachable yes/no" primitive that 99% of dependency
|
|
1148
|
-
* probes need.
|
|
1149
|
-
*
|
|
1150
|
-
* `databaseSignal` and `redisSignal` are thin convenience wrappers
|
|
1151
|
-
* with idiomatic defaults for those two ubiquitous dependencies.
|
|
1152
|
-
*
|
|
1153
|
-
* @example Generic
|
|
1154
|
-
* ```ts
|
|
1155
|
-
* import { pingSignal } from '@sylphx/sdk/health'
|
|
1156
|
-
*
|
|
1157
|
-
* app.use('*', withHealth.hono({
|
|
1158
|
-
* signals: [
|
|
1159
|
-
* pingSignal({
|
|
1160
|
-
* name: 'upstream-api',
|
|
1161
|
-
* ping: async () => { await fetch('https://upstream.example/_ping') },
|
|
1162
|
-
* }),
|
|
1163
|
-
* ],
|
|
1164
|
-
* }))
|
|
1165
|
-
* ```
|
|
1166
|
-
*
|
|
1167
|
-
* @example Database + Redis
|
|
1168
|
-
* ```ts
|
|
1169
|
-
* import { withHealth, databaseSignal, redisSignal } from '@sylphx/sdk/health'
|
|
1170
|
-
*
|
|
1171
|
-
* app.use('*', withHealth.hono({
|
|
1172
|
-
* signals: [
|
|
1173
|
-
* databaseSignal({ ping: () => pool.query('SELECT 1') }),
|
|
1174
|
-
* redisSignal({ ping: () => redis.ping() }),
|
|
1175
|
-
* ],
|
|
1176
|
-
* }))
|
|
1177
|
-
* ```
|
|
1178
|
-
*/
|
|
1179
|
-
|
|
1180
|
-
interface PingSignalOptions {
|
|
1181
|
-
/** Stable signal name. Appears in the wire JSON `signals.<name>` map. */
|
|
1182
|
-
readonly name: string;
|
|
1183
|
-
/**
|
|
1184
|
-
* Async function the SDK calls every poll tick. Resolve (any value) =
|
|
1185
|
-
* healthy. Throw / reject = unhealthy. Timeout → unhealthy.
|
|
1186
|
-
*/
|
|
1187
|
-
readonly ping: () => Promise<unknown>;
|
|
1188
|
-
/**
|
|
1189
|
-
* Per-tick timeout in milliseconds. Default 500ms — fast enough to
|
|
1190
|
-
* fold into a `/healthz` response without holding the event loop, slow
|
|
1191
|
-
* enough to avoid false negatives on a momentarily-slow dependency.
|
|
1192
|
-
* Tune up for dependencies that legitimately take longer (e.g. S3 list).
|
|
1193
|
-
*/
|
|
1194
|
-
readonly timeoutMs?: number;
|
|
1195
|
-
/** Weight in the weighted-product score. Default 1.0. */
|
|
1196
|
-
readonly weight?: number;
|
|
1197
|
-
}
|
|
1198
|
-
declare function pingSignal(opts: PingSignalOptions): AsyncSignal;
|
|
1199
|
-
interface DependencyPingOptions {
|
|
1200
|
-
readonly ping: () => Promise<unknown>;
|
|
1201
|
-
readonly timeoutMs?: number;
|
|
1202
|
-
readonly weight?: number;
|
|
1203
|
-
/** Override the signal name. Defaults to the subsystem name. */
|
|
1204
|
-
readonly name?: string;
|
|
1205
|
-
}
|
|
1206
|
-
/**
|
|
1207
|
-
* Postgres / SQL-database readiness — convenience over `pingSignal` with
|
|
1208
|
-
* `name: 'database'`. Wrap the caller's `pool.query('SELECT 1')` or
|
|
1209
|
-
* equivalent.
|
|
1210
|
-
*/
|
|
1211
|
-
declare function databaseSignal(opts: DependencyPingOptions): AsyncSignal;
|
|
1212
|
-
/**
|
|
1213
|
-
* Redis / KV readiness — convenience over `pingSignal` with `name: 'redis'`.
|
|
1214
|
-
* Wrap the caller's `redis.ping()` or equivalent.
|
|
1215
|
-
*/
|
|
1216
|
-
declare function redisSignal(opts: DependencyPingOptions): AsyncSignal;
|
|
1217
|
-
|
|
1218
|
-
/**
|
|
1219
|
-
* `queueDepthSignal` — backpressure indicator (ADR-111 §4.3).
|
|
1220
|
-
*
|
|
1221
|
-
* Generic signal: the app provides a `getter` that returns the current
|
|
1222
|
-
* length of whatever queue the operator wants probed (BullMQ, RabbitMQ,
|
|
1223
|
-
* in-memory work pool, …). The signal does NOT own the queue — the app
|
|
1224
|
-
* does. We just measure.
|
|
1225
|
-
*
|
|
1226
|
-
* Mapping observed-depth → healthFactor:
|
|
1227
|
-
*
|
|
1228
|
-
* healthFactor
|
|
1229
|
-
* ▲
|
|
1230
|
-
* 1.0 ┤━━━━━━━━━━━━━━━━━━┓
|
|
1231
|
-
* │ ┃ linear interpolation
|
|
1232
|
-
* 0.0 ┤ ┗━━━━━━━━━━━━
|
|
1233
|
-
* ┼──────────────────┼─────────► depth
|
|
1234
|
-
* 0 fullThreshold
|
|
1235
|
-
*
|
|
1236
|
-
* Below `fullThreshold` → factor 1. At `fullThreshold` → factor 0. Above
|
|
1237
|
-
* → factor 0. The implicit "degraded" zone is `[0.5 × fullThreshold,
|
|
1238
|
-
* fullThreshold]` — depth at half-full produces factor 0.5. Operators
|
|
1239
|
-
* tune `fullThreshold` to whatever their queue reasonably hits at peak
|
|
1240
|
-
* load; "100% full" means "drain new traffic", not "kill the workload" (the
|
|
1241
|
-
* three-tier gate at the sidecar handles the kill decision).
|
|
1242
|
-
*
|
|
1243
|
-
* `getter` errors are swallowed — a thrown getter produces `unknown=true`
|
|
1244
|
-
* (so the scoring strategy ignores this signal, instead of falsely
|
|
1245
|
-
* reporting score=0). The app's bug shouldn't masquerade as a sidecar
|
|
1246
|
-
* decision.
|
|
1247
|
-
*/
|
|
1248
|
-
|
|
1249
|
-
interface QueueDepthOptions {
|
|
1250
|
-
/**
|
|
1251
|
-
* Sync or async getter the SDK calls every poll tick. Must return a
|
|
1252
|
-
* non-negative integer. Throws → reading marked `unknown=true`.
|
|
1253
|
-
*/
|
|
1254
|
-
readonly getter: () => number | Promise<number>;
|
|
1255
|
-
/**
|
|
1256
|
-
* Depth at which the queue is considered "full" (factor=0). Linear
|
|
1257
|
-
* interp from 0..fullThreshold. No default — operator-specific.
|
|
1258
|
-
*/
|
|
1259
|
-
readonly fullThreshold: number;
|
|
1260
|
-
/**
|
|
1261
|
-
* Optional below-which factor is always 1 (a "soft floor"). Default 0
|
|
1262
|
-
* — the linear interp starts at depth 0.
|
|
1263
|
-
*/
|
|
1264
|
-
readonly healthyBelow?: number;
|
|
1265
|
-
/** Weight in the weighted-product score. Default 0.2 (ADR-111 §4.3). */
|
|
1266
|
-
readonly weight?: number;
|
|
1267
|
-
/** Custom signal name. Default `queueDepth`. */
|
|
1268
|
-
readonly name?: string;
|
|
1269
|
-
}
|
|
1270
|
-
declare function queueDepthSignal(opts: QueueDepthOptions): AsyncSignal;
|
|
1271
|
-
|
|
1272
|
-
/**
|
|
1273
|
-
* `@sylphx/sdk/health` — Phase B multi-signal health score (ADR-111 §4).
|
|
1274
|
-
*
|
|
1275
|
-
* Apps register signals (event-loop lag, queue depth, error rate, memory
|
|
1276
|
-
* pressure, …); the SDK folds them into a continuous score in `[0, 1]`;
|
|
1277
|
-
* the **sidecar** maps the score to liveness / readiness / drain via the
|
|
1278
|
-
* three-tier gate. The SDK's responsibility ends at exposing the score.
|
|
1279
|
-
*
|
|
1280
|
-
* The wire format the sidecar parses (ADR-111 §3.2.4):
|
|
1281
|
-
*
|
|
1282
|
-
* ```json
|
|
1283
|
-
* {
|
|
1284
|
-
* "score": 0.92,
|
|
1285
|
-
* "signals": {
|
|
1286
|
-
* "eventLoopLagMs": 12,
|
|
1287
|
-
* "queueDepth": 3,
|
|
1288
|
-
* "recent5sErrorRate": 0.001,
|
|
1289
|
-
* "memoryPressure": 0.45
|
|
1290
|
-
* },
|
|
1291
|
-
* "signalFactors": {
|
|
1292
|
-
* "eventLoopLagMs": 1,
|
|
1293
|
-
* "queueDepth": 0.8,
|
|
1294
|
-
* "recent5sErrorRate": 0.99,
|
|
1295
|
-
* "memoryPressure": 0.7
|
|
1296
|
-
* },
|
|
1297
|
-
* "lastTickAt": "2026-05-03T12:34:56.789Z"
|
|
1298
|
-
* }
|
|
1299
|
-
* ```
|
|
1300
|
-
*
|
|
1301
|
-
* Default signals (if `sylphxHealth()` called with no `signals`):
|
|
1302
|
-
* - `eventLoopLagSignal({ degradedMs: 5000, deadMs: 30000 })` (weight 1.0)
|
|
1303
|
-
*
|
|
1304
|
-
* Three-tier gate (decided by **sidecar**, not SDK; ADR-111 §4.4):
|
|
1305
|
-
*
|
|
1306
|
-
* | Score | Liveness | Readiness | Effect |
|
|
1307
|
-
* | -------------- | -------- | --------- | --------------------- |
|
|
1308
|
-
* | > 0.8 | 200 | 200 | Normal traffic |
|
|
1309
|
-
* | (0.5, 0.8] | 200 | 503 | Drain new, no kill |
|
|
1310
|
-
* | <= 0.5 | 503 | 503 | Kill after threshold |
|
|
1311
|
-
*
|
|
1312
|
-
* Apps don't need to think about probe semantics — that's the sidecar's
|
|
1313
|
-
* job. The app just exposes the score. See `apps/health-agent/` for the
|
|
1314
|
-
* sidecar implementation.
|
|
1315
|
-
*
|
|
1316
|
-
* @example Worked example — OpenClaw under PDF-extract load (ADR-111 §4.5):
|
|
1317
|
-
*
|
|
1318
|
-
* ```text
|
|
1319
|
-
* eventLoopLagMs = 6000 → factor 0.4
|
|
1320
|
-
* queueDepth = 12 → factor 1.0
|
|
1321
|
-
* errorRate = 0.002 → factor 1.0
|
|
1322
|
-
* memoryPressure = 0.55 → factor 1.0
|
|
1323
|
-
* score = 0.4^0.4 × 1.0^0.6 ≈ 0.69
|
|
1324
|
-
*
|
|
1325
|
-
* → falls in [0.5, 0.8] → sidecar drains traffic, doesn't kill.
|
|
1326
|
-
* Pod gets to finish PDF extraction.
|
|
1327
|
-
* ```
|
|
1328
|
-
*/
|
|
1329
|
-
|
|
1330
|
-
/**
|
|
1331
|
-
* The handle returned by `sylphxHealth()`. Owns the registered signals,
|
|
1332
|
-
* exposes evaluation in both Promise + Effect form, and produces an HTTP
|
|
1333
|
-
* handler / Unix-socket server.
|
|
1334
|
-
*
|
|
1335
|
-
* Call `dispose()` during graceful shutdown to release per-signal
|
|
1336
|
-
* resources (e.g. the `monitorEventLoopDelay()` histogram).
|
|
1337
|
-
*/
|
|
1338
|
-
interface SylphxHealth extends HealthEvaluator {
|
|
1339
|
-
/** All signals registered (read-only). */
|
|
1340
|
-
readonly signals: ReadonlyArray<Signal>;
|
|
1341
|
-
/** Snapshot evaluation as a Promise. */
|
|
1342
|
-
evaluate(): Promise<HealthScore>;
|
|
1343
|
-
/** Snapshot evaluation as an Effect (per Rule 21 / ADR-058 Amendment). */
|
|
1344
|
-
readonly evaluateEffect: ReturnType<typeof evaluateEffect>;
|
|
1345
|
-
/**
|
|
1346
|
-
* Web Fetch API HTTP handler — works under Hono, Bun.serve, Next.js
|
|
1347
|
-
* route.ts, itty-router, Hattip. Always returns 200 + JSON; the
|
|
1348
|
-
* sidecar applies the three-tier 200/503 gate.
|
|
1349
|
-
*/
|
|
1350
|
-
handler(): (req?: Request) => Promise<Response>;
|
|
1351
|
-
/** Node.js classic `(req, res)` handler — for Express / classic Fastify. */
|
|
1352
|
-
nodeHandler(): ReturnType<typeof createNodeHandler>;
|
|
1353
|
-
/**
|
|
1354
|
-
* Bind a Bun Unix-domain socket and serve the same JSON. The sidecar
|
|
1355
|
-
* polls `/var/run/sylphx/health.sock` by default (ADR-111 §3.2.4).
|
|
1356
|
-
*/
|
|
1357
|
-
serveUnixSocket(opts?: UnixSocketServerOptions): UnixSocketServerHandle;
|
|
1358
|
-
/**
|
|
1359
|
-
* Most recent score returned by `evaluate()`. Returns null before
|
|
1360
|
-
* the first evaluation. Used by `withHealth.*` middleware to inject
|
|
1361
|
-
* cause baggage on non-probe requests (ADR-143).
|
|
1362
|
-
*/
|
|
1363
|
-
getLastScore(): HealthScore | null;
|
|
1364
|
-
/**
|
|
1365
|
-
* Run `fn` within an OTel context that has our local cause baggage
|
|
1366
|
-
* set, derived from the most recent `evaluate()`. When causality is
|
|
1367
|
-
* disabled or the OTel API is unavailable, runs `fn()` directly.
|
|
1368
|
-
* Middleware consumers don't usually call this — they let
|
|
1369
|
-
* `withHealth.*` wire it automatically. Exposed for advanced users
|
|
1370
|
-
* who build custom transport wrappers.
|
|
1371
|
-
*/
|
|
1372
|
-
runWithCause<T>(fn: () => T | Promise<T>): Promise<T>;
|
|
1373
|
-
/**
|
|
1374
|
-
* Retrieve audit-grade history entries (ADR-144). Returns an empty
|
|
1375
|
-
* array when history is disabled. Operators use this for compliance
|
|
1376
|
-
* evidence + post-incident reconstruction.
|
|
1377
|
-
*/
|
|
1378
|
-
getHistory(query?: HistoryQuery): Promise<readonly HistoryEntry[]>;
|
|
1379
|
-
/**
|
|
1380
|
-
* Verify the integrity of the recorded history chain over `query`
|
|
1381
|
-
* (defaults to all available entries). Returns `verified: true`
|
|
1382
|
-
* when the SHA-256 chain matches end-to-end; otherwise reports the
|
|
1383
|
-
* first sequence where tampering is detected.
|
|
1384
|
-
*/
|
|
1385
|
-
verifyHistory(query?: HistoryQuery): Promise<VerificationResult>;
|
|
1386
|
-
/**
|
|
1387
|
-
* Tear down all registered signals. Idempotent. Call during graceful
|
|
1388
|
-
* shutdown to release histograms, file watchers, etc.
|
|
1389
|
-
*/
|
|
1390
|
-
dispose(): void;
|
|
1391
|
-
}
|
|
1392
|
-
declare function sylphxHealth(opts?: SylphxHealthOptions): SylphxHealth;
|
|
1393
|
-
|
|
1394
|
-
export { type AsyncSignal, BAGGAGE_KEY_CAUSE, BAGGAGE_KEY_CHAIN, type CausalityHandle, type CausalityOption, type CausalityOptions, DEFAULT_CAUSE_THRESHOLD, DEFAULT_HISTORY_CAPACITY, type DependencyPingOptions, type ErrorRateOptions, type ErrorRateSignalHandle, type EventLoopLagOptions, type ExpressHealthMiddleware, type ExpressNextLike, type ExpressRequestLike, type ExpressResponseLike, type FastifyHealthPlugin, type FastifyInstanceLike, type FastifyReplyLike, type FetchHealthHandler, GENESIS_PREV_HASH, HealthError, type HealthEvaluator, type HealthRelease, type HealthReleaseInput, type HealthScore, type HealthSnapshot, type HistoryEntry, type HistoryOption, type HistoryQuery, type HistoryRecorder, type HistoryRecorderOptions, type HistoryStore, type HonoContextLike, type HonoHealthMiddleware, type HonoNextLike, type InMemoryHistoryStoreOptions, MAX_CHAIN_LENGTH, type MemoryPressureOptions, EVENT_NAMES as OTEL_EVENT_NAMES, METRIC_NAMES as OTEL_METRIC_NAMES, SPAN_ATTRIBUTES as OTEL_SPAN_ATTRIBUTES, type OtelEmitter, type OtelEmitterOptions, type OtelOption, type OtelStaticAttributes, type PingSignalOptions, type QueueDepthOptions, type ScoringStrategy, type Signal, type SignalBase, type SignalReading, type SylphxHealth, type SylphxHealthOptions, type SyncSignal, type UnixSocketServerHandle, type UnixSocketServerOptions, type UpstreamCause, type VerificationResult, type WithHealthOptions, canonicalizeSignals, createCausalityHandle, createHistoryRecorder, createInMemoryHistoryStore, createNodeHandler, createOtelEmitter, createWebHandler, databaseSignal, defaultScoringStrategy, errorRateSignal, eventLoopLagSignal, memoryPressureSignal, pingSignal, queueDepthSignal, redisSignal, sylphxHealth, verifyChain, weightedProduct, withHealth };
|