@bleedingdev/modern-js-server-runtime-extensions 3.8.2-ultramodern.9 → 3.8.3-ultramodern.2

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 (82) hide show
  1. package/dist/cjs/backend-federation-security/index.js +415 -0
  2. package/dist/cjs/backend-federation-security/node.js +74 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +1 -1
  4. package/dist/cjs/contract-gate-snapshot-store/resolve.js +4 -4
  5. package/dist/cjs/{contractGateAutopilot.js → contractGateSnapshotObserver.js} +14 -17
  6. package/dist/cjs/index.js +45 -13
  7. package/dist/cjs/runtime-fallback-signal/resolver.js +3 -3
  8. package/dist/cjs/runtimeLifecycle.js +129 -0
  9. package/dist/cjs/telemetry/{canaryEvaluation.js → healthEvaluation.js} +11 -13
  10. package/dist/cjs/telemetry/{canary.js → healthMonitor.js} +27 -44
  11. package/dist/cjs/telemetry/{canarySetup.js → healthSetup.js} +35 -39
  12. package/dist/cjs/telemetry/lifecycle.js +14 -14
  13. package/dist/cjs/telemetry/plugin.js +9 -9
  14. package/dist/cjs/telemetry/runtimeEndpoints.js +3 -3
  15. package/dist/cjs/telemetryCore.js +4 -4
  16. package/dist/esm/backend-federation-security/index.mjs +361 -0
  17. package/dist/esm/backend-federation-security/node.mjs +30 -0
  18. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -1
  19. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +4 -4
  20. package/dist/esm/{contractGateAutopilot.mjs → contractGateSnapshotObserver.mjs} +12 -15
  21. package/dist/esm/index.mjs +4 -2
  22. package/dist/esm/runtime-fallback-signal/resolver.mjs +3 -3
  23. package/dist/esm/runtimeLifecycle.mjs +82 -0
  24. package/dist/esm/telemetry/{canaryEvaluation.mjs → healthEvaluation.mjs} +9 -11
  25. package/dist/esm/telemetry/{canary.mjs → healthMonitor.mjs} +25 -42
  26. package/dist/esm/telemetry/healthSetup.mjs +65 -0
  27. package/dist/esm/telemetry/lifecycle.mjs +14 -14
  28. package/dist/esm/telemetry/plugin.mjs +8 -8
  29. package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -3
  30. package/dist/esm/telemetryCore.mjs +1 -1
  31. package/dist/esm-node/backend-federation-security/index.mjs +362 -0
  32. package/dist/esm-node/backend-federation-security/node.mjs +31 -0
  33. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -1
  34. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +4 -4
  35. package/dist/esm-node/{contractGateAutopilot.mjs → contractGateSnapshotObserver.mjs} +12 -15
  36. package/dist/esm-node/index.mjs +4 -2
  37. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +3 -3
  38. package/dist/esm-node/runtimeLifecycle.mjs +83 -0
  39. package/dist/esm-node/telemetry/{canaryEvaluation.mjs → healthEvaluation.mjs} +9 -11
  40. package/dist/esm-node/telemetry/{canary.mjs → healthMonitor.mjs} +25 -42
  41. package/dist/esm-node/telemetry/healthSetup.mjs +66 -0
  42. package/dist/esm-node/telemetry/lifecycle.mjs +14 -14
  43. package/dist/esm-node/telemetry/plugin.mjs +8 -8
  44. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -3
  45. package/dist/esm-node/telemetryCore.mjs +1 -1
  46. package/dist/types/backend-federation-security/index.d.ts +68 -0
  47. package/dist/types/backend-federation-security/node.d.ts +3 -0
  48. package/dist/types/{contractGateAutopilot.d.ts → contractGateSnapshotObserver.d.ts} +7 -6
  49. package/dist/types/index.d.ts +4 -2
  50. package/dist/types/runtime-fallback-signal/resolver.d.ts +2 -2
  51. package/dist/types/runtimeLifecycle.d.ts +10 -0
  52. package/dist/types/telemetry/healthEvaluation.d.ts +20 -0
  53. package/dist/types/telemetry/{canary.d.ts → healthMonitor.d.ts} +31 -28
  54. package/dist/types/telemetry/{canarySetup.d.ts → healthSetup.d.ts} +6 -6
  55. package/dist/types/telemetry/lifecycle.d.ts +4 -4
  56. package/dist/types/telemetry/plugin.d.ts +1 -1
  57. package/dist/types/telemetry/runtimeEndpoints.d.ts +3 -3
  58. package/dist/types/telemetryCore.d.ts +1 -1
  59. package/package.json +46 -8
  60. package/src/backend-federation-security/index.ts +831 -0
  61. package/src/backend-federation-security/node.ts +51 -0
  62. package/src/contract-gate-snapshot-store/http-store.ts +1 -1
  63. package/src/contract-gate-snapshot-store/resolve.ts +4 -4
  64. package/src/{contractGateAutopilot.ts → contractGateSnapshotObserver.ts} +18 -25
  65. package/src/index.ts +42 -6
  66. package/src/runtime-fallback-signal/resolver.ts +5 -5
  67. package/src/runtimeLifecycle.ts +125 -0
  68. package/src/telemetry/{canaryEvaluation.ts → healthEvaluation.ts} +14 -17
  69. package/src/telemetry/{canary.ts → healthMonitor.ts} +72 -84
  70. package/src/telemetry/{canarySetup.ts → healthSetup.ts} +50 -53
  71. package/src/telemetry/lifecycle.ts +20 -20
  72. package/src/telemetry/plugin.ts +16 -16
  73. package/src/telemetry/runtimeEndpoints.ts +6 -6
  74. package/src/telemetryCore.ts +11 -11
  75. package/tests/backendFederationSecurity.test.ts +416 -0
  76. package/tests/{contractGateAutopilot.test.ts → contractGateSnapshotObserver.test.ts} +59 -62
  77. package/tests/runtimeLifecycle.test.ts +107 -0
  78. package/tests/telemetryHealthMonitor.test.ts +187 -0
  79. package/dist/esm/telemetry/canarySetup.mjs +0 -69
  80. package/dist/esm-node/telemetry/canarySetup.mjs +0 -70
  81. package/dist/types/telemetry/canaryEvaluation.d.ts +0 -20
  82. package/tests/telemetryCanaryOrchestrator.test.ts +0 -365
@@ -2,17 +2,14 @@ import fs from 'fs';
2
2
  import os from 'os';
3
3
  import path from 'path';
4
4
  import type { GateSnapshot } from '../src/contract-gate-snapshot-store';
5
- import { ContractGateAutopilot } from '../src/contractGateAutopilot';
6
- import {
7
- TelemetryCanaryOrchestrator,
8
- TelemetryRegistry,
9
- } from '../src/telemetry';
5
+ import { ContractGateSnapshotObserver } from '../src/contractGateSnapshotObserver';
6
+ import { TelemetryHealthMonitor, TelemetryRegistry } from '../src/telemetry';
10
7
 
11
8
  const makeTempDir = () =>
12
- fs.mkdtempSync(path.join(os.tmpdir(), 'modern-contract-gate-autopilot-'));
9
+ fs.mkdtempSync(path.join(os.tmpdir(), 'modern-contract-gate-observer-'));
13
10
 
14
- describe('contract gate autopilot', () => {
15
- test('syncs gate snapshot and updates canary decisions automatically', async () => {
11
+ describe('contract gate observer', () => {
12
+ test('syncs gate snapshot and updates health observations', async () => {
16
13
  const dir = makeTempDir();
17
14
  const snapshotPath = path.join(dir, 'contract-gates.json');
18
15
 
@@ -22,12 +19,12 @@ describe('contract gate autopilot', () => {
22
19
  environment: 'test',
23
20
  flushIntervalMs: 60_000,
24
21
  });
25
- const orchestrator = new TelemetryCanaryOrchestrator({
22
+ const monitor = new TelemetryHealthMonitor({
26
23
  registry,
27
- rollbackConsecutiveFailures: 1,
24
+ minConsecutiveFailedEvaluations: 1,
28
25
  });
29
- const autopilot = new ContractGateAutopilot({
30
- orchestrator,
26
+ const observer = new ContractGateSnapshotObserver({
27
+ monitor,
31
28
  gateSnapshotPath: snapshotPath,
32
29
  pollIntervalMs: 50,
33
30
  gateStaleAfterMs: 60_000,
@@ -52,8 +49,8 @@ describe('contract gate autopilot', () => {
52
49
  ),
53
50
  );
54
51
 
55
- await autopilot.start();
56
- const healthyDecision = orchestrator.evaluate();
52
+ await observer.start();
53
+ const healthyDecision = monitor.evaluate();
57
54
  expect(healthyDecision.failures).toHaveLength(0);
58
55
 
59
56
  fs.writeFileSync(
@@ -75,9 +72,9 @@ describe('contract gate autopilot', () => {
75
72
  ),
76
73
  );
77
74
 
78
- await autopilot.syncOnce();
79
- const rollbackDecision = orchestrator.evaluate();
80
- expect(rollbackDecision.action).toBe('rollback');
75
+ await observer.syncOnce();
76
+ const rollbackDecision = monitor.evaluate();
77
+ expect(rollbackDecision.state).toBe('unhealthy');
81
78
  expect(
82
79
  rollbackDecision.failures.some(
83
80
  item =>
@@ -86,7 +83,7 @@ describe('contract gate autopilot', () => {
86
83
  ),
87
84
  ).toBe(true);
88
85
  } finally {
89
- autopilot.stop();
86
+ observer.stop();
90
87
  await registry.shutdown();
91
88
  fs.rmSync(dir, { recursive: true, force: true });
92
89
  }
@@ -102,9 +99,9 @@ describe('contract gate autopilot', () => {
102
99
  environment: 'test',
103
100
  flushIntervalMs: 60_000,
104
101
  });
105
- const orchestrator = new TelemetryCanaryOrchestrator({
102
+ const monitor = new TelemetryHealthMonitor({
106
103
  registry,
107
- rollbackConsecutiveFailures: 1,
104
+ minConsecutiveFailedEvaluations: 1,
108
105
  });
109
106
 
110
107
  const staleUpdatedAt = Date.now() - 10_000;
@@ -126,16 +123,16 @@ describe('contract gate autopilot', () => {
126
123
  ),
127
124
  );
128
125
 
129
- const autopilot = new ContractGateAutopilot({
130
- orchestrator,
126
+ const observer = new ContractGateSnapshotObserver({
127
+ monitor,
131
128
  gateSnapshotPath: snapshotPath,
132
129
  gateStaleAfterMs: 1_000,
133
130
  });
134
131
 
135
132
  try {
136
- await autopilot.syncOnce();
137
- const decision = orchestrator.evaluate();
138
- expect(decision.action).toBe('rollback');
133
+ await observer.syncOnce();
134
+ const decision = monitor.evaluate();
135
+ expect(decision.state).toBe('unhealthy');
139
136
  expect(
140
137
  decision.failures.some(
141
138
  item =>
@@ -144,7 +141,7 @@ describe('contract gate autopilot', () => {
144
141
  ),
145
142
  ).toBe(true);
146
143
  } finally {
147
- autopilot.stop();
144
+ observer.stop();
148
145
  await registry.shutdown();
149
146
  fs.rmSync(dir, { recursive: true, force: true });
150
147
  }
@@ -163,9 +160,9 @@ describe('contract gate autopilot', () => {
163
160
  environment: 'test',
164
161
  flushIntervalMs: 60_000,
165
162
  });
166
- const orchestrator = new TelemetryCanaryOrchestrator({
163
+ const monitor = new TelemetryHealthMonitor({
167
164
  registry,
168
- rollbackConsecutiveFailures: 1,
165
+ minConsecutiveFailedEvaluations: 1,
169
166
  });
170
167
  fs.writeFileSync(
171
168
  snapshotPath,
@@ -185,21 +182,21 @@ describe('contract gate autopilot', () => {
185
182
  ),
186
183
  );
187
184
 
188
- const autopilot = new ContractGateAutopilot({
189
- orchestrator,
185
+ const observer = new ContractGateSnapshotObserver({
186
+ monitor,
190
187
  gateSnapshotPath: snapshotPath,
191
188
  gateStaleAfterMs: 1_000,
192
189
  });
193
190
 
194
191
  try {
195
- await autopilot.syncOnce();
196
- expect(orchestrator.evaluate().failures).toHaveLength(0);
192
+ await observer.syncOnce();
193
+ expect(monitor.evaluate().failures).toHaveLength(0);
197
194
 
198
195
  now += 1_001;
199
- await autopilot.syncOnce();
196
+ await observer.syncOnce();
200
197
 
201
- const decision = orchestrator.evaluate();
202
- expect(decision.action).toBe('rollback');
198
+ const decision = monitor.evaluate();
199
+ expect(decision.state).toBe('unhealthy');
203
200
  expect(
204
201
  decision.failures.some(
205
202
  item =>
@@ -209,7 +206,7 @@ describe('contract gate autopilot', () => {
209
206
  ).toBe(true);
210
207
  } finally {
211
208
  Date.now = originalDateNow;
212
- autopilot.stop();
209
+ observer.stop();
213
210
  await registry.shutdown();
214
211
  fs.rmSync(dir, { recursive: true, force: true });
215
212
  }
@@ -222,15 +219,15 @@ describe('contract gate autopilot', () => {
222
219
  environment: 'test',
223
220
  flushIntervalMs: 60_000,
224
221
  });
225
- const orchestrator = new TelemetryCanaryOrchestrator({
222
+ const monitor = new TelemetryHealthMonitor({
226
223
  registry,
227
- rollbackConsecutiveFailures: 1,
224
+ minConsecutiveFailedEvaluations: 1,
228
225
  });
229
226
  const snapshotResolvers: Array<
230
227
  (snapshot: GateSnapshot | undefined) => void
231
228
  > = [];
232
- const autopilot = new ContractGateAutopilot({
233
- orchestrator,
229
+ const observer = new ContractGateSnapshotObserver({
230
+ monitor,
234
231
  gateSnapshotStore: {
235
232
  name: 'deferred',
236
233
  readSnapshot: () =>
@@ -243,8 +240,8 @@ describe('contract gate autopilot', () => {
243
240
  });
244
241
 
245
242
  try {
246
- const olderSync = autopilot.syncOnce();
247
- const newerSync = autopilot.syncOnce();
243
+ const olderSync = observer.syncOnce();
244
+ const newerSync = observer.syncOnce();
248
245
  expect(snapshotResolvers).toHaveLength(2);
249
246
 
250
247
  snapshotResolvers[1]?.({
@@ -258,7 +255,7 @@ describe('contract gate autopilot', () => {
258
255
  },
259
256
  });
260
257
  await newerSync;
261
- expect(orchestrator.evaluate().failures).toHaveLength(0);
258
+ expect(monitor.evaluate().failures).toHaveLength(0);
262
259
 
263
260
  snapshotResolvers[0]?.({
264
261
  schemaVersion: 1,
@@ -273,9 +270,9 @@ describe('contract gate autopilot', () => {
273
270
  });
274
271
  await olderSync;
275
272
 
276
- expect(orchestrator.evaluate().failures).toHaveLength(0);
273
+ expect(monitor.evaluate().failures).toHaveLength(0);
277
274
  } finally {
278
- autopilot.stop();
275
+ observer.stop();
279
276
  await registry.shutdown();
280
277
  }
281
278
  });
@@ -290,12 +287,12 @@ describe('contract gate autopilot', () => {
290
287
  environment: 'test',
291
288
  flushIntervalMs: 60_000,
292
289
  });
293
- const orchestrator = new TelemetryCanaryOrchestrator({
290
+ const monitor = new TelemetryHealthMonitor({
294
291
  registry,
295
- rollbackConsecutiveFailures: 1,
292
+ minConsecutiveFailedEvaluations: 1,
296
293
  });
297
- const autopilot = new ContractGateAutopilot({
298
- orchestrator,
294
+ const observer = new ContractGateSnapshotObserver({
295
+ monitor,
299
296
  gateSnapshotPath: snapshotPath,
300
297
  gateStaleAfterMs: 60_000,
301
298
  });
@@ -321,9 +318,9 @@ describe('contract gate autopilot', () => {
321
318
  ),
322
319
  );
323
320
 
324
- await autopilot.syncOnce();
321
+ await observer.syncOnce();
325
322
  expect(
326
- orchestrator
323
+ monitor
327
324
  .evaluate()
328
325
  .failures.some(
329
326
  item =>
@@ -345,16 +342,16 @@ describe('contract gate autopilot', () => {
345
342
  ),
346
343
  );
347
344
 
348
- await autopilot.syncOnce();
349
- expect(orchestrator.evaluate().failures).toHaveLength(0);
345
+ await observer.syncOnce();
346
+ expect(monitor.evaluate().failures).toHaveLength(0);
350
347
  } finally {
351
- autopilot.stop();
348
+ observer.stop();
352
349
  await registry.shutdown();
353
350
  fs.rmSync(dir, { recursive: true, force: true });
354
351
  }
355
352
  });
356
353
 
357
- test('auto-recovers runtime fallback gates after expiry window', async () => {
354
+ test('observes recovered runtime fallback gates after expiry window', async () => {
358
355
  const dir = makeTempDir();
359
356
  const snapshotPath = path.join(dir, 'contract-gates.json');
360
357
 
@@ -364,9 +361,9 @@ describe('contract gate autopilot', () => {
364
361
  environment: 'test',
365
362
  flushIntervalMs: 60_000,
366
363
  });
367
- const orchestrator = new TelemetryCanaryOrchestrator({
364
+ const monitor = new TelemetryHealthMonitor({
368
365
  registry,
369
- rollbackConsecutiveFailures: 1,
366
+ minConsecutiveFailedEvaluations: 1,
370
367
  });
371
368
  const now = Date.now();
372
369
  fs.writeFileSync(
@@ -389,18 +386,18 @@ describe('contract gate autopilot', () => {
389
386
  ),
390
387
  );
391
388
 
392
- const autopilot = new ContractGateAutopilot({
393
- orchestrator,
389
+ const observer = new ContractGateSnapshotObserver({
390
+ monitor,
394
391
  gateSnapshotPath: snapshotPath,
395
392
  gateStaleAfterMs: 60_000,
396
393
  });
397
394
 
398
395
  try {
399
- await autopilot.syncOnce();
400
- const decision = orchestrator.evaluate();
396
+ await observer.syncOnce();
397
+ const decision = monitor.evaluate();
401
398
  expect(decision.failures).toHaveLength(0);
402
399
  } finally {
403
- autopilot.stop();
400
+ observer.stop();
404
401
  await registry.shutdown();
405
402
  fs.rmSync(dir, { recursive: true, force: true });
406
403
  }
@@ -0,0 +1,107 @@
1
+ import {
2
+ createDisposableServerRuntimeHandle,
3
+ disposeServerRuntime,
4
+ initializeDisposableServerRuntime,
5
+ registerServerRuntimeDisposer,
6
+ } from '../src/runtimeLifecycle';
7
+
8
+ const deferred = () => {
9
+ let resolve!: () => void;
10
+ const promise = new Promise<void>(next => {
11
+ resolve = next;
12
+ });
13
+ return { promise, resolve };
14
+ };
15
+
16
+ describe('server runtime lifecycle', () => {
17
+ test('shares one disposal across concurrent and repeated callers', async () => {
18
+ const owner = {};
19
+ const release = deferred();
20
+ const dispose = rstest.fn(async () => release.promise);
21
+ registerServerRuntimeDisposer(owner, dispose);
22
+
23
+ const first = disposeServerRuntime(owner);
24
+ const second = disposeServerRuntime(owner);
25
+ expect(first).toBe(second);
26
+ await Promise.resolve();
27
+ expect(dispose).toHaveBeenCalledTimes(1);
28
+
29
+ release.resolve();
30
+ await Promise.all([first, second, disposeServerRuntime(owner)]);
31
+ expect(dispose).toHaveBeenCalledTimes(1);
32
+ });
33
+
34
+ test('attempts every owned disposer when one fails synchronously', async () => {
35
+ const owner = {};
36
+ const completed = rstest.fn();
37
+ registerServerRuntimeDisposer(owner, completed);
38
+ registerServerRuntimeDisposer(owner, () => {
39
+ throw new Error('close failed');
40
+ });
41
+
42
+ await expect(disposeServerRuntime(owner)).rejects.toMatchObject({
43
+ errors: [expect.objectContaining({ message: 'close failed' })],
44
+ });
45
+ expect(completed).toHaveBeenCalledTimes(1);
46
+ });
47
+
48
+ test('retires ownership before a disposer can register re-entrantly', async () => {
49
+ const owner = {};
50
+ registerServerRuntimeDisposer(owner, () => {
51
+ expect(() => registerServerRuntimeDisposer(owner, () => {})).toThrow(
52
+ 'retired server runtime',
53
+ );
54
+ });
55
+
56
+ await disposeServerRuntime(owner);
57
+ await disposeServerRuntime(owner);
58
+ });
59
+
60
+ test('drains in-flight requests before releasing their runtime', async () => {
61
+ const owner = {};
62
+ const releaseRequest = deferred();
63
+ const dispose = rstest.fn(async () => {});
64
+ registerServerRuntimeDisposer(owner, dispose);
65
+ const handle = createDisposableServerRuntimeHandle(owner, async () => {
66
+ await releaseRequest.promise;
67
+ return new Response('done');
68
+ });
69
+
70
+ const response = handle(new Request('https://example.com/slow'));
71
+ const retiring = handle.dispose();
72
+ await Promise.resolve();
73
+ expect(dispose).not.toHaveBeenCalled();
74
+
75
+ releaseRequest.resolve();
76
+ await expect(response).resolves.toBeInstanceOf(Response);
77
+ await retiring;
78
+ expect(dispose).toHaveBeenCalledTimes(1);
79
+ await expect(
80
+ handle(new Request('https://example.com/late')),
81
+ ).rejects.toThrow('retired server runtime');
82
+ });
83
+
84
+ test('releases a failed candidate without touching the active runtime', async () => {
85
+ const activeOwner = {};
86
+ const candidateOwner = {};
87
+ const activeDispose = rstest.fn(async () => {});
88
+ const candidateDispose = rstest.fn(async () => {});
89
+ registerServerRuntimeDisposer(activeOwner, activeDispose);
90
+ registerServerRuntimeDisposer(candidateOwner, candidateDispose);
91
+ const setupError = new Error('candidate setup failed');
92
+
93
+ await expect(
94
+ initializeDisposableServerRuntime(
95
+ candidateOwner,
96
+ () => new Response('candidate'),
97
+ async () => {
98
+ throw setupError;
99
+ },
100
+ ),
101
+ ).rejects.toBe(setupError);
102
+
103
+ expect(candidateDispose).toHaveBeenCalledTimes(1);
104
+ expect(activeDispose).not.toHaveBeenCalled();
105
+ await disposeServerRuntime(activeOwner);
106
+ });
107
+ });
@@ -0,0 +1,187 @@
1
+ import {
2
+ type TelemetryEnvelope,
3
+ TelemetryHealthMonitor,
4
+ TelemetryRegistry,
5
+ } from '../src/telemetry';
6
+
7
+ const createEnvelope = (
8
+ partial: Partial<TelemetryEnvelope> = {},
9
+ ): TelemetryEnvelope => ({
10
+ timestamp: Date.now(),
11
+ service: 'svc',
12
+ module: 'server',
13
+ environment: 'test',
14
+ signalType: 'metric',
15
+ name: 'server.handle.request',
16
+ value: 10,
17
+ unit: 'ms',
18
+ ...partial,
19
+ });
20
+
21
+ const createRegistry = (maxQueueSize = 1_000) =>
22
+ new TelemetryRegistry({
23
+ service: 'svc',
24
+ module: 'server',
25
+ environment: 'test',
26
+ maxQueueSize,
27
+ flushIntervalMs: 60_000,
28
+ });
29
+
30
+ describe('telemetry health monitor', () => {
31
+ test('reports hysteretic health transitions without deployment actions', async () => {
32
+ const registry = createRegistry();
33
+ const onEvaluate = rs.fn();
34
+ const onTransition = rs.fn();
35
+ const monitor = new TelemetryHealthMonitor({
36
+ registry,
37
+ minConsecutiveHealthyEvaluations: 2,
38
+ minConsecutiveFailedEvaluations: 2,
39
+ requiredContractGates: ['contracts'],
40
+ onEvaluate,
41
+ onTransition,
42
+ });
43
+
44
+ monitor.setContractGate('contracts', false, 'schema drift');
45
+ const firstFailure = monitor.evaluate();
46
+ const unhealthy = monitor.evaluate();
47
+ const stillUnhealthy = monitor.evaluate();
48
+
49
+ expect(firstFailure).toMatchObject({
50
+ state: 'pending',
51
+ transition: 'none',
52
+ consecutiveFailures: 1,
53
+ });
54
+ expect(unhealthy).toMatchObject({
55
+ state: 'unhealthy',
56
+ transition: 'became_unhealthy',
57
+ consecutiveFailures: 2,
58
+ });
59
+ expect(stillUnhealthy).toMatchObject({
60
+ state: 'unhealthy',
61
+ transition: 'none',
62
+ consecutiveFailures: 3,
63
+ });
64
+
65
+ monitor.setContractGate('contracts', true);
66
+ const firstRecovery = monitor.evaluate();
67
+ const recovered = monitor.evaluate();
68
+ const stillHealthy = monitor.evaluate();
69
+
70
+ expect(firstRecovery).toMatchObject({
71
+ state: 'unhealthy',
72
+ transition: 'none',
73
+ consecutiveHealthy: 1,
74
+ });
75
+ expect(recovered).toMatchObject({
76
+ state: 'healthy',
77
+ transition: 'became_healthy',
78
+ consecutiveHealthy: 2,
79
+ });
80
+ expect(stillHealthy).toMatchObject({
81
+ state: 'healthy',
82
+ transition: 'none',
83
+ consecutiveHealthy: 3,
84
+ });
85
+
86
+ expect('action' in recovered).toBe(false);
87
+ expect(JSON.stringify(recovered)).not.toMatch(/promot|rollback/i);
88
+ expect(onEvaluate).toHaveBeenCalledTimes(6);
89
+ expect(onTransition).toHaveBeenCalledTimes(2);
90
+ expect(onTransition).toHaveBeenNthCalledWith(1, unhealthy);
91
+ expect(onTransition).toHaveBeenNthCalledWith(2, recovered);
92
+
93
+ await registry.shutdown();
94
+ });
95
+
96
+ test('observes missing and failed required contract gates', async () => {
97
+ const registry = createRegistry();
98
+ const monitor = new TelemetryHealthMonitor({
99
+ registry,
100
+ minConsecutiveHealthyEvaluations: 1,
101
+ minConsecutiveFailedEvaluations: 1,
102
+ });
103
+
104
+ monitor.addRequiredContractGate('runtime-contracts');
105
+ const missing = monitor.evaluate();
106
+ expect(missing.state).toBe('unhealthy');
107
+ expect(missing.failures).toContainEqual(
108
+ expect.objectContaining({
109
+ reason: 'contract_gate_missing',
110
+ gate: 'runtime-contracts',
111
+ }),
112
+ );
113
+
114
+ monitor.setContractGate('runtime-contracts', false, 'incompatible schema');
115
+ const failed = monitor.evaluate();
116
+ expect(failed.failures).toContainEqual(
117
+ expect.objectContaining({
118
+ reason: 'contract_gate_failed',
119
+ gate: 'runtime-contracts',
120
+ message: 'incompatible schema',
121
+ }),
122
+ );
123
+
124
+ monitor.setContractGate('runtime-contracts', true);
125
+ const healthy = monitor.evaluate();
126
+ expect(healthy).toMatchObject({
127
+ state: 'healthy',
128
+ transition: 'became_healthy',
129
+ failures: [],
130
+ });
131
+
132
+ await registry.shutdown();
133
+ });
134
+
135
+ test('observes telemetry queue drops', async () => {
136
+ const registry = createRegistry(2);
137
+ registry.enqueue(createEnvelope({ name: 'a' }));
138
+ registry.enqueue(createEnvelope({ name: 'b' }));
139
+ registry.enqueue(createEnvelope({ name: 'c' }));
140
+
141
+ const monitor = new TelemetryHealthMonitor({
142
+ registry,
143
+ maxTotalDropped: 0,
144
+ minConsecutiveFailedEvaluations: 1,
145
+ });
146
+ const evaluation = monitor.evaluate();
147
+
148
+ expect(evaluation).toMatchObject({
149
+ state: 'unhealthy',
150
+ transition: 'became_unhealthy',
151
+ });
152
+ expect(evaluation.failures).toContainEqual(
153
+ expect.objectContaining({ reason: 'queue_dropped' }),
154
+ );
155
+
156
+ await registry.shutdown();
157
+ });
158
+
159
+ test('isolates health observer failures from the server path', async () => {
160
+ const registry = createRegistry();
161
+ const onEvaluate = rs.fn(() => {
162
+ throw new Error('evaluate observer failed');
163
+ });
164
+ const onTransition = rs.fn(() => {
165
+ throw new Error('transition observer failed');
166
+ });
167
+ const monitor = new TelemetryHealthMonitor({
168
+ registry,
169
+ minConsecutiveHealthyEvaluations: 1,
170
+ onEvaluate,
171
+ onTransition,
172
+ });
173
+
174
+ let evaluation: ReturnType<TelemetryHealthMonitor['evaluate']> | undefined;
175
+ expect(() => {
176
+ evaluation = monitor.evaluate();
177
+ }).not.toThrow();
178
+ expect(evaluation).toMatchObject({
179
+ state: 'healthy',
180
+ transition: 'became_healthy',
181
+ });
182
+ expect(onEvaluate).toHaveBeenCalledTimes(1);
183
+ expect(onTransition).toHaveBeenCalledTimes(1);
184
+
185
+ await registry.shutdown();
186
+ });
187
+ });
@@ -1,69 +0,0 @@
1
- import { DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "../contract-gate-snapshot-store/index.mjs";
2
- import { DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, createRuntimeFallbackSignalRuntimeState, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, resolveRuntimeFallbackSignalEndpoint } from "../runtimeFallbackSignal.mjs";
3
- import { TelemetryCanaryOrchestrator } from "../telemetryCore.mjs";
4
- function emitCanaryDecisionMetric(registry, decision, action) {
5
- try {
6
- registry.enqueueMetric({
7
- name: `telemetry.canary.${action}`,
8
- value: 1,
9
- unit: 'count',
10
- tags: {
11
- action,
12
- state: decision.state,
13
- failures: String(decision.failures.length)
14
- }
15
- });
16
- } catch (_error) {}
17
- }
18
- const setupTelemetryCanary = ({ registry, appDirectory, canaryConfig })=>{
19
- if (!canaryConfig?.enabled) return {};
20
- const contractGates = canaryConfig.contractGates;
21
- const canaryOrchestrator = new TelemetryCanaryOrchestrator({
22
- registry,
23
- evaluationIntervalMs: canaryConfig.evaluationIntervalMs,
24
- minConsecutiveHealthyEvaluations: canaryConfig.minConsecutiveHealthyEvaluations,
25
- rollbackConsecutiveFailures: canaryConfig.rollbackConsecutiveFailures,
26
- maxQueueUtilization: canaryConfig.maxQueueUtilization,
27
- maxTotalDropped: canaryConfig.maxTotalDropped,
28
- maxUnhealthyExporters: canaryConfig.maxUnhealthyExporters,
29
- requiredContractGates: Object.keys(contractGates || {}),
30
- onPromote: (decision)=>{
31
- emitCanaryDecisionMetric(registry, decision, 'promote');
32
- },
33
- onRollback: (decision)=>{
34
- emitCanaryDecisionMetric(registry, decision, 'rollback');
35
- }
36
- });
37
- if (contractGates) canaryOrchestrator.setContractGates(contractGates);
38
- let gateSnapshotStorePromise;
39
- let runtimeFallbackSignalConfig;
40
- const autopilotEnabled = canaryConfig.autopilot?.enabled ?? true;
41
- if (autopilotEnabled) {
42
- const gateSnapshotPath = resolveContractGateSnapshotPath(appDirectory, canaryConfig.autopilot?.gateSnapshotPath);
43
- gateSnapshotStorePromise = resolveContractGateSnapshotStore({
44
- appDirectory,
45
- gateSnapshotPath: gateSnapshotPath || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
46
- stateStore: canaryConfig.autopilot?.stateStore
47
- });
48
- const runtimeSignalConfig = canaryConfig.autopilot?.runtimeFallbackSignal;
49
- const runtimeSignalEnabled = runtimeSignalConfig?.enabled === true;
50
- if (runtimeSignalEnabled && gateSnapshotStorePromise) runtimeFallbackSignalConfig = {
51
- endpoint: resolveRuntimeFallbackSignalEndpoint(runtimeSignalConfig?.endpoint),
52
- gateName: runtimeSignalConfig?.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
53
- gateSnapshotStore: gateSnapshotStorePromise,
54
- failureHoldMs: Math.max(1000, runtimeSignalConfig?.failureHoldMs ?? DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS),
55
- maxBodyBytes: Math.max(512, runtimeSignalConfig?.maxBodyBytes ?? DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES),
56
- auth: normalizeRequiredRuntimeFallbackSignalAuthConfig(runtimeSignalConfig?.auth),
57
- trustPolicy: normalizeRuntimeFallbackTrustPolicy(runtimeSignalConfig?.trustPolicy),
58
- runtimeState: createRuntimeFallbackSignalRuntimeState()
59
- };
60
- }
61
- const runtimeStatusAuthConfig = runtimeFallbackSignalConfig?.auth ?? normalizeRuntimeFallbackSignalAuthConfig(canaryConfig.autopilot?.runtimeFallbackSignal?.auth);
62
- return {
63
- canaryOrchestrator,
64
- gateSnapshotStorePromise,
65
- runtimeFallbackSignalConfig,
66
- runtimeStatusAuthConfig
67
- };
68
- };
69
- export { setupTelemetryCanary };