@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
@@ -0,0 +1,51 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { builtinModules, createRequire } from 'node:module';
3
+
4
+ import {
5
+ type BackendFederationCommonJsEvaluator,
6
+ type BackendFederationEntryIntegrity,
7
+ BackendFederationRemoteEntryError,
8
+ } from './index';
9
+
10
+ const nodeRequire = createRequire(import.meta.url);
11
+ const nodeBuiltins = new Set([
12
+ ...builtinModules,
13
+ ...builtinModules.map(name => `node:${name}`),
14
+ ]);
15
+
16
+ const toBytes = (value: string | Uint8Array) =>
17
+ typeof value === 'string' ? new TextEncoder().encode(value) : value;
18
+
19
+ export function createBackendFederationEntryIntegrity(
20
+ value: string | Uint8Array,
21
+ ): BackendFederationEntryIntegrity {
22
+ const bytes = toBytes(value);
23
+ return {
24
+ byteLength: bytes.byteLength,
25
+ sha256: createHash('sha256').update(bytes).digest('hex'),
26
+ };
27
+ }
28
+
29
+ export const evaluateNodeBackendFederationCommonJs: BackendFederationCommonJsEvaluator =
30
+ (source, { remote }) => {
31
+ const module = { exports: {} as Record<string, unknown> };
32
+ const exports = module.exports;
33
+ const requireBuiltin = (specifier: string) => {
34
+ if (!nodeBuiltins.has(specifier)) {
35
+ throw new BackendFederationRemoteEntryError(
36
+ 'unsupported_entry',
37
+ `[Module Federation] Backend remote ${remote.name} attempted to require non-builtin module ${specifier}. Bundle package dependencies into the remote entry.`,
38
+ );
39
+ }
40
+ return nodeRequire(specifier);
41
+ };
42
+ const evaluate = new Function(
43
+ 'module',
44
+ 'exports',
45
+ 'globalThis',
46
+ 'require',
47
+ source,
48
+ );
49
+ evaluate(module, exports, globalThis, requireBuiltin);
50
+ return module.exports;
51
+ };
@@ -25,7 +25,7 @@ const normalizeHttpStoreOptions = (
25
25
  typeof options?.endpoint === 'string' ? options.endpoint.trim() : '';
26
26
  if (!endpoint) {
27
27
  throw new Error(
28
- '[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint',
28
+ '[telemetry.health.snapshot] HTTP stateStore requires options.endpoint',
29
29
  );
30
30
  }
31
31
 
@@ -141,7 +141,7 @@ export const resolveContractGateSnapshotStore = async (input: {
141
141
  const builtinStore = tryResolveBuiltinSnapshotStore({ stateStore });
142
142
  if (builtinStore) {
143
143
  logger?.info?.(
144
- `[telemetry.canary.autopilot] using built-in contract gate snapshot store "${builtinStore.name}"`,
144
+ `[telemetry.health.snapshot] using built-in contract gate snapshot store "${builtinStore.name}"`,
145
145
  );
146
146
  return builtinStore;
147
147
  }
@@ -154,14 +154,14 @@ export const resolveContractGateSnapshotStore = async (input: {
154
154
  )) as ContractGateSnapshotStoreModule;
155
155
  } catch (error) {
156
156
  throw new Error(
157
- `[telemetry.canary.autopilot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`,
157
+ `[telemetry.health.snapshot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`,
158
158
  );
159
159
  }
160
160
 
161
161
  const factory = pickStoreFactory(mod);
162
162
  if (!factory) {
163
163
  throw new Error(
164
- `[telemetry.canary.autopilot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`,
164
+ `[telemetry.health.snapshot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`,
165
165
  );
166
166
  }
167
167
 
@@ -173,7 +173,7 @@ export const resolveContractGateSnapshotStore = async (input: {
173
173
  });
174
174
  ensureStoreShape(store, modulePath);
175
175
  logger?.info?.(
176
- `[telemetry.canary.autopilot] using contract gate snapshot store "${store.name || modulePath}"`,
176
+ `[telemetry.health.snapshot] using contract gate snapshot store "${store.name || modulePath}"`,
177
177
  );
178
178
  return store;
179
179
  };
@@ -7,7 +7,7 @@ import type {
7
7
  ContractGateSnapshotStore,
8
8
  GateSnapshot,
9
9
  } from './contract-gate-snapshot-store/types';
10
- import type { TelemetryCanaryOrchestrator } from './telemetryCore';
10
+ import type { TelemetryHealthMonitor } from './telemetry/healthMonitor';
11
11
 
12
12
  const DEFAULT_POLL_INTERVAL_MS = 15_000;
13
13
  const DEFAULT_GATE_STALE_AFTER_MS = 10 * 60_000;
@@ -17,8 +17,8 @@ type LoggerLike = {
17
17
  warn?: (message: string) => void;
18
18
  };
19
19
 
20
- export type ContractGateAutopilotOptions = {
21
- orchestrator: TelemetryCanaryOrchestrator;
20
+ export type ContractGateSnapshotObserverOptions = {
21
+ monitor: TelemetryHealthMonitor;
22
22
  gateSnapshotPath?: string;
23
23
  gateSnapshotStore?: ContractGateSnapshotStore;
24
24
  pollIntervalMs?: number;
@@ -26,8 +26,9 @@ export type ContractGateAutopilotOptions = {
26
26
  logger?: LoggerLike;
27
27
  };
28
28
 
29
- export class ContractGateAutopilot {
30
- private readonly orchestrator: TelemetryCanaryOrchestrator;
29
+ /** Polls contract-gate snapshots and exposes them to telemetry health checks. */
30
+ export class ContractGateSnapshotObserver {
31
+ private readonly monitor: TelemetryHealthMonitor;
31
32
  private readonly gateSnapshotStore: ContractGateSnapshotStore;
32
33
  private readonly gateSnapshotPath?: string;
33
34
  private readonly pollIntervalMs: number;
@@ -37,11 +38,11 @@ export class ContractGateAutopilot {
37
38
  private syncGeneration = 0;
38
39
  private readonly appliedGateFingerprints = new Map<string, string>();
39
40
 
40
- constructor(options: ContractGateAutopilotOptions) {
41
- this.orchestrator = options.orchestrator;
41
+ constructor(options: ContractGateSnapshotObserverOptions) {
42
+ this.monitor = options.monitor;
42
43
  if (!options.gateSnapshotStore && !options.gateSnapshotPath) {
43
44
  throw new Error(
44
- 'ContractGateAutopilot requires gateSnapshotPath or gateSnapshotStore',
45
+ 'ContractGateSnapshotObserver requires gateSnapshotPath or gateSnapshotStore',
45
46
  );
46
47
  }
47
48
  this.gateSnapshotPath = options.gateSnapshotPath;
@@ -84,10 +85,7 @@ export class ContractGateAutopilot {
84
85
  async syncOnce() {
85
86
  const syncGeneration = ++this.syncGeneration;
86
87
  const snapshot = await this.loadSnapshot();
87
- if (syncGeneration !== this.syncGeneration) {
88
- return 0;
89
- }
90
- if (!snapshot) {
88
+ if (syncGeneration !== this.syncGeneration || !snapshot) {
91
89
  return 0;
92
90
  }
93
91
 
@@ -100,17 +98,17 @@ export class ContractGateAutopilot {
100
98
  ? this.clearOmittedGates(snapshotGateNames)
101
99
  : 0;
102
100
  for (const gate of gates) {
103
- this.orchestrator.addRequiredContractGate(gate.name);
101
+ this.monitor.addRequiredContractGate(gate.name);
104
102
  const fingerprint = `${gate.passed ? '1' : '0'}:${gate.reason || ''}`;
105
103
  if (this.appliedGateFingerprints.get(gate.name) === fingerprint) {
106
104
  continue;
107
105
  }
108
106
 
109
- this.orchestrator.setContractGate(gate.name, gate.passed, gate.reason);
107
+ this.monitor.setContractGate(gate.name, gate.passed, gate.reason);
110
108
  this.appliedGateFingerprints.set(gate.name, fingerprint);
111
109
  updatedCount += 1;
112
110
  this.logger?.info?.(
113
- `[telemetry.canary.autopilot] gate=${gate.name} passed=${String(gate.passed)} reason=${gate.reason || 'none'}`,
111
+ `[telemetry.health.snapshot] gate=${gate.name} passed=${String(gate.passed)} reason=${gate.reason || 'none'}`,
114
112
  );
115
113
  }
116
114
 
@@ -124,30 +122,25 @@ export class ContractGateAutopilot {
124
122
  continue;
125
123
  }
126
124
 
127
- this.orchestrator.setContractGate(gateName, true);
125
+ this.monitor.setContractGate(gateName, true);
128
126
  this.appliedGateFingerprints.delete(gateName);
129
127
  updatedCount += 1;
130
128
  this.logger?.info?.(
131
- `[telemetry.canary.autopilot] gate=${gateName} passed=true reason=omitted`,
129
+ `[telemetry.health.snapshot] gate=${gateName} passed=true reason=omitted`,
132
130
  );
133
131
  }
134
132
 
135
133
  return updatedCount;
136
134
  }
137
135
 
138
- private async loadSnapshot() {
136
+ private async loadSnapshot(): Promise<GateSnapshot | undefined> {
139
137
  try {
140
- const snapshot = await this.gateSnapshotStore.readSnapshot();
141
- if (!snapshot) {
142
- return undefined;
143
- }
144
-
145
- return snapshot;
138
+ return (await this.gateSnapshotStore.readSnapshot()) || undefined;
146
139
  } catch (error) {
147
140
  const source =
148
141
  this.gateSnapshotPath || this.gateSnapshotStore.name || 'stateStore';
149
142
  this.logger?.warn?.(
150
- `[telemetry.canary.autopilot] failed to load gate snapshot ${source}: ${error instanceof Error ? error.message : String(error)}`,
143
+ `[telemetry.health.snapshot] failed to load gate snapshot ${source}: ${error instanceof Error ? error.message : String(error)}`,
151
144
  );
152
145
  return undefined;
153
146
  }
package/src/index.ts CHANGED
@@ -1,7 +1,29 @@
1
1
  export {
2
- ContractGateAutopilot,
3
- type ContractGateAutopilotOptions,
4
- } from './contractGateAutopilot';
2
+ type BackendFederationCommonJsEvaluator,
3
+ type BackendFederationEntryExports,
4
+ type BackendFederationEntryIntegrity,
5
+ type BackendFederationRemoteEntry,
6
+ BackendFederationRemoteEntryError,
7
+ type BackendFederationRemoteEntryErrorCode,
8
+ type BackendFederationRemoteEntryExpectation,
9
+ type BackendFederationRemoteEntryFetch,
10
+ type BackendFederationRemoteEntryPolicy,
11
+ type BackendFederationRemoteEntryVerification,
12
+ type BackendFederationResourceFetch,
13
+ type BackendFederationResourcePolicy,
14
+ type BackendFederationResourceResponse,
15
+ evaluateBackendFederationCommonJsEntry,
16
+ type LoadBoundedBackendFederationResourceOptions,
17
+ type LoadVerifiedBackendFederationEntryOptions,
18
+ loadBoundedBackendFederationResource,
19
+ loadVerifiedBackendFederationEntry,
20
+ redactBackendFederationUrl,
21
+ resolveBackendFederationRemoteEntryVerification,
22
+ } from './backend-federation-security';
23
+ export {
24
+ ContractGateSnapshotObserver,
25
+ type ContractGateSnapshotObserverOptions,
26
+ } from './contractGateSnapshotObserver';
5
27
  export {
6
28
  DEFAULT_ENVIRONMENT_NAME,
7
29
  parseServerRuntimeExtensionsEnv,
@@ -26,6 +48,14 @@ export {
26
48
  type ModuleFederationManifest,
27
49
  type RemoteModuleFederationCssCollection,
28
50
  } from './module-federation-css';
51
+ export {
52
+ createDisposableServerRuntimeHandle,
53
+ type DisposableServerRuntimeHandle,
54
+ disposeServerRuntime,
55
+ initializeDisposableServerRuntime,
56
+ registerServerRuntimeDisposer,
57
+ type ServerRuntimeHandle,
58
+ } from './runtimeLifecycle';
29
59
  export {
30
60
  createOtlpTelemetryExporter,
31
61
  createRuntimeFallbackSignalRuntimeState,
@@ -53,11 +83,17 @@ export {
53
83
  type RuntimeSignalErrorCode,
54
84
  resolveRuntimeFallbackSignalEndpoint,
55
85
  resolveTelemetrySloOptions,
56
- type TelemetryCanaryDecision,
57
- TelemetryCanaryOrchestrator,
58
- type TelemetryCanaryStatusSnapshot,
86
+ type TelemetryContractGateStatus,
59
87
  type TelemetryEnvelope,
60
88
  type TelemetryExporter,
89
+ type TelemetryHealthEvaluation,
90
+ type TelemetryHealthFailure,
91
+ type TelemetryHealthFailureReason,
92
+ TelemetryHealthMonitor,
93
+ type TelemetryHealthMonitorOptions,
94
+ type TelemetryHealthState,
95
+ type TelemetryHealthStatusSnapshot,
96
+ type TelemetryHealthTransition,
61
97
  type TelemetryQueueStats,
62
98
  TelemetryRegistry,
63
99
  type TelemetryRegistryOptions,
@@ -59,7 +59,7 @@ export function normalizeRuntimeFallbackSignalAuthConfig(
59
59
 
60
60
  if (enabled && !expectedValue) {
61
61
  throw new Error(
62
- '[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled true but no expected token configured',
62
+ '[telemetry.health.runtimeFallbackSignal] auth.enabled true but no expected token configured',
63
63
  );
64
64
  }
65
65
 
@@ -72,22 +72,22 @@ export function normalizeRuntimeFallbackSignalAuthConfig(
72
72
 
73
73
  /**
74
74
  * Normalizes auth config for the runtime fallback signal endpoint when the
75
- * endpoint itself is enabled. The endpoint can persist failing contract gates
76
- * (a canary kill switch), so it always requires a token.
75
+ * endpoint itself is enabled. The endpoint records observed failing contract
76
+ * gates, so it always requires a token.
77
77
  */
78
78
  export function normalizeRequiredRuntimeFallbackSignalAuthConfig(
79
79
  configured: Parameters<typeof normalizeRuntimeFallbackSignalAuthConfig>[0],
80
80
  ): RuntimeFallbackSignalAuthConfig {
81
81
  if (configured?.enabled === false) {
82
82
  throw new Error(
83
- '[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled cannot be false when runtimeFallbackSignal.enabled is true',
83
+ '[telemetry.health.runtimeFallbackSignal] auth.enabled cannot be false when runtimeFallbackSignal.enabled is true',
84
84
  );
85
85
  }
86
86
 
87
87
  const authConfig = normalizeRuntimeFallbackSignalAuthConfig(configured);
88
88
  if (!authConfig.expectedValue) {
89
89
  throw new Error(
90
- '[telemetry.canary.autopilot.runtimeFallbackSignal] auth.expectedValue or auth.expectedValueEnv is required when runtimeFallbackSignal.enabled is true',
90
+ '[telemetry.health.runtimeFallbackSignal] auth.expectedValue or auth.expectedValueEnv is required when runtimeFallbackSignal.enabled is true',
91
91
  );
92
92
  }
93
93
 
@@ -0,0 +1,125 @@
1
+ export type ServerRuntimeHandle = (
2
+ request: Request,
3
+ ...args: any[]
4
+ ) => Response | Promise<Response>;
5
+
6
+ export type DisposableServerRuntimeHandle = ServerRuntimeHandle & {
7
+ dispose: () => Promise<void>;
8
+ };
9
+
10
+ type RuntimeDisposer = () => void | Promise<void>;
11
+
12
+ type RuntimeLifecycleState = {
13
+ disposers: Set<RuntimeDisposer>;
14
+ disposePromise?: Promise<void>;
15
+ retired: boolean;
16
+ };
17
+
18
+ const runtimeLifecycleStates = new WeakMap<object, RuntimeLifecycleState>();
19
+
20
+ const getRuntimeLifecycleState = (owner: object) => {
21
+ let state = runtimeLifecycleStates.get(owner);
22
+ if (!state) {
23
+ state = { disposers: new Set(), retired: false };
24
+ runtimeLifecycleStates.set(owner, state);
25
+ }
26
+ return state;
27
+ };
28
+
29
+ export const registerServerRuntimeDisposer = (
30
+ owner: object,
31
+ disposer: RuntimeDisposer,
32
+ ) => {
33
+ const state = getRuntimeLifecycleState(owner);
34
+ if (state.retired) {
35
+ throw new Error('Cannot register a disposer on a retired server runtime.');
36
+ }
37
+ state.disposers.add(disposer);
38
+ return () => {
39
+ state.disposers.delete(disposer);
40
+ };
41
+ };
42
+
43
+ export const disposeServerRuntime = (owner: object): Promise<void> => {
44
+ const state = getRuntimeLifecycleState(owner);
45
+ if (state.disposePromise) {
46
+ return state.disposePromise;
47
+ }
48
+ state.retired = true;
49
+ state.disposePromise = Promise.resolve().then(async () => {
50
+ const disposers = [...state.disposers].reverse();
51
+ state.disposers.clear();
52
+ const errors: unknown[] = [];
53
+ for (const disposer of disposers) {
54
+ try {
55
+ await disposer();
56
+ } catch (error) {
57
+ errors.push(error);
58
+ }
59
+ }
60
+ if (errors.length > 0) {
61
+ throw new AggregateError(errors, 'Failed to dispose server runtime.');
62
+ }
63
+ });
64
+ return state.disposePromise;
65
+ };
66
+
67
+ export const createDisposableServerRuntimeHandle = (
68
+ owner: object,
69
+ handle: ServerRuntimeHandle,
70
+ ): DisposableServerRuntimeHandle => {
71
+ let activeRequests = 0;
72
+ let retired = false;
73
+ let resolveDrained: (() => void) | undefined;
74
+ let drained: Promise<void> | undefined;
75
+ let disposePromise: Promise<void> | undefined;
76
+
77
+ const disposableHandle = (async (request: Request, ...args: any[]) => {
78
+ if (retired) {
79
+ throw new Error('Cannot dispatch through a retired server runtime.');
80
+ }
81
+ activeRequests += 1;
82
+ try {
83
+ return await handle(request, ...args);
84
+ } finally {
85
+ activeRequests -= 1;
86
+ if (activeRequests === 0) {
87
+ resolveDrained?.();
88
+ }
89
+ }
90
+ }) as DisposableServerRuntimeHandle;
91
+
92
+ disposableHandle.dispose = () => {
93
+ disposePromise ??= (async () => {
94
+ retired = true;
95
+ if (activeRequests > 0) {
96
+ drained ??= new Promise<void>(resolve => {
97
+ resolveDrained = resolve;
98
+ });
99
+ await drained;
100
+ }
101
+ await disposeServerRuntime(owner);
102
+ })();
103
+ return disposePromise;
104
+ };
105
+
106
+ return disposableHandle;
107
+ };
108
+
109
+ export const initializeDisposableServerRuntime = async (
110
+ owner: object,
111
+ handle: ServerRuntimeHandle,
112
+ initialize: () => Promise<void>,
113
+ ): Promise<DisposableServerRuntimeHandle> => {
114
+ try {
115
+ await initialize();
116
+ } catch (error) {
117
+ try {
118
+ await disposeServerRuntime(owner);
119
+ } catch {
120
+ // Preserve the setup failure that makes this candidate ineligible.
121
+ }
122
+ throw error;
123
+ }
124
+ return createDisposableServerRuntimeHandle(owner, handle);
125
+ };
@@ -1,34 +1,34 @@
1
1
  import type {
2
- TelemetryCanaryContractGateStatus,
3
- TelemetryCanaryFailure,
4
- } from './canary';
2
+ TelemetryContractGateStatus,
3
+ TelemetryHealthFailure,
4
+ } from './healthMonitor';
5
5
 
6
6
  import type { TelemetryQueueStats } from './registryTypes';
7
7
 
8
- interface TelemetryCanaryHealthMetrics {
8
+ interface TelemetryHealthMetrics {
9
9
  queueStats: TelemetryQueueStats;
10
10
  unhealthyExporterCount: number;
11
11
  requiredContractGates: readonly string[];
12
- contractGates: ReadonlyMap<string, TelemetryCanaryContractGateStatus>;
12
+ contractGates: ReadonlyMap<string, TelemetryContractGateStatus>;
13
13
  }
14
14
 
15
- interface TelemetryCanaryHealthThresholds {
15
+ interface TelemetryHealthThresholds {
16
16
  maxQueueUtilization: number;
17
17
  maxTotalDropped: number;
18
18
  maxUnhealthyExporters: number;
19
19
  }
20
20
 
21
- export interface TelemetryCanaryHealthEvaluation {
22
- failures: TelemetryCanaryFailure[];
21
+ export interface TelemetryHealthEvaluationResult {
22
+ failures: TelemetryHealthFailure[];
23
23
  queueStats: TelemetryQueueStats;
24
24
  unhealthyExporterCount: number;
25
25
  }
26
26
 
27
- export const evaluateCanaryHealth = (
28
- metrics: TelemetryCanaryHealthMetrics,
29
- thresholds: TelemetryCanaryHealthThresholds,
30
- ): TelemetryCanaryHealthEvaluation => {
31
- const failures: TelemetryCanaryFailure[] = [];
27
+ export const evaluateTelemetryHealth = (
28
+ metrics: TelemetryHealthMetrics,
29
+ thresholds: TelemetryHealthThresholds,
30
+ ): TelemetryHealthEvaluationResult => {
31
+ const failures: TelemetryHealthFailure[] = [];
32
32
  const { queueStats, unhealthyExporterCount } = metrics;
33
33
 
34
34
  if (queueStats.utilization > thresholds.maxQueueUtilization) {
@@ -63,10 +63,7 @@ export const evaluateCanaryHealth = (
63
63
  gate: gateName,
64
64
  message: `Contract gate "${gateName}" is missing`,
65
65
  });
66
- continue;
67
- }
68
-
69
- if (!gate.passed) {
66
+ } else if (!gate.passed) {
70
67
  failures.push({
71
68
  reason: 'contract_gate_failed',
72
69
  gate: gateName,