@bleedingdev/modern-js-server-runtime-extensions 0.0.0-trusted-publisher-bootstrap

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +67 -0
  3. package/dist/cjs/contractGateAutopilot.js +162 -0
  4. package/dist/cjs/contractGateSnapshotStore.js +253 -0
  5. package/dist/cjs/env.js +58 -0
  6. package/dist/cjs/index.js +162 -0
  7. package/dist/cjs/mfCache.js +106 -0
  8. package/dist/cjs/moduleFederationCss.js +285 -0
  9. package/dist/cjs/runtimeFallbackSignal.js +311 -0
  10. package/dist/cjs/telemetry.js +373 -0
  11. package/dist/cjs/telemetryCore.js +819 -0
  12. package/dist/esm/contractGateAutopilot.mjs +124 -0
  13. package/dist/esm/contractGateSnapshotStore.mjs +190 -0
  14. package/dist/esm/env.mjs +17 -0
  15. package/dist/esm/index.mjs +6 -0
  16. package/dist/esm/mfCache.mjs +55 -0
  17. package/dist/esm/moduleFederationCss.mjs +225 -0
  18. package/dist/esm/runtimeFallbackSignal.mjs +222 -0
  19. package/dist/esm/telemetry.mjs +275 -0
  20. package/dist/esm/telemetryCore.mjs +759 -0
  21. package/dist/esm-node/contractGateAutopilot.mjs +125 -0
  22. package/dist/esm-node/contractGateSnapshotStore.mjs +192 -0
  23. package/dist/esm-node/env.mjs +18 -0
  24. package/dist/esm-node/index.mjs +7 -0
  25. package/dist/esm-node/mfCache.mjs +56 -0
  26. package/dist/esm-node/moduleFederationCss.mjs +226 -0
  27. package/dist/esm-node/runtimeFallbackSignal.mjs +223 -0
  28. package/dist/esm-node/telemetry.mjs +276 -0
  29. package/dist/esm-node/telemetryCore.mjs +760 -0
  30. package/dist/types/contractGateAutopilot.d.ts +35 -0
  31. package/dist/types/contractGateSnapshotStore.d.ts +57 -0
  32. package/dist/types/env.d.ts +40 -0
  33. package/dist/types/index.d.ts +6 -0
  34. package/dist/types/mfCache.d.ts +27 -0
  35. package/dist/types/moduleFederationCss.d.ts +87 -0
  36. package/dist/types/runtimeFallbackSignal.d.ts +94 -0
  37. package/dist/types/telemetry.d.ts +12 -0
  38. package/dist/types/telemetryCore.d.ts +257 -0
  39. package/package.json +69 -0
  40. package/rslib.config.mts +4 -0
  41. package/rstest.config.mts +7 -0
  42. package/src/contractGateAutopilot.ts +247 -0
  43. package/src/contractGateSnapshotStore.ts +420 -0
  44. package/src/env.ts +63 -0
  45. package/src/index.ts +84 -0
  46. package/src/mfCache.ts +119 -0
  47. package/src/moduleFederationCss.ts +473 -0
  48. package/src/runtimeFallbackSignal.ts +584 -0
  49. package/src/telemetry.ts +554 -0
  50. package/src/telemetryCore.ts +1332 -0
  51. package/tests/contractGateAutopilot.test.ts +203 -0
  52. package/tests/contractGateSnapshotStore.test.ts +223 -0
  53. package/tests/env.test.ts +73 -0
  54. package/tests/helpers.ts +19 -0
  55. package/tests/mfCache.test.ts +150 -0
  56. package/tests/moduleFederationCss.test.ts +392 -0
  57. package/tests/registration.test.ts +112 -0
  58. package/tests/telemetry.test.ts +360 -0
  59. package/tests/telemetryAutopilot.test.ts +993 -0
  60. package/tests/telemetryCanaryOrchestrator.test.ts +140 -0
  61. package/tests/telemetryLifecycle.test.ts +168 -0
  62. package/tests/telemetryTraceparent.test.ts +167 -0
  63. package/tests/tsconfig.json +11 -0
  64. package/tsconfig.json +10 -0
@@ -0,0 +1,222 @@
1
+ import { createHash, timingSafeEqual } from "node:crypto";
2
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./contractGateSnapshotStore.mjs";
3
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
4
+ const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
5
+ const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
6
+ const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
7
+ const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
8
+ const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
9
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
10
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60000;
11
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10000;
12
+ function resolveRuntimeFallbackSignalEndpoint(configuredEndpoint) {
13
+ const rawEndpoint = configuredEndpoint?.trim();
14
+ if (!rawEndpoint) return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
15
+ if (rawEndpoint.startsWith('/')) return rawEndpoint;
16
+ try {
17
+ return new URL(rawEndpoint).pathname || DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
18
+ } catch (_error) {
19
+ return `/${rawEndpoint.replace(/^\/+/, '')}`;
20
+ }
21
+ }
22
+ function createRuntimeSignalError(message, code) {
23
+ const error = new Error(message);
24
+ error.code = code;
25
+ return error;
26
+ }
27
+ function getUtf8ByteLength(input) {
28
+ if ("u" > typeof Buffer) return Buffer.byteLength(input);
29
+ return new TextEncoder().encode(input).length;
30
+ }
31
+ function normalizeRuntimeSignalOrigin(value) {
32
+ if ('string' != typeof value || 0 === value.trim().length) return;
33
+ try {
34
+ return new URL(value).origin;
35
+ } catch (_error) {
36
+ return;
37
+ }
38
+ }
39
+ function normalizeRuntimeSignalAppName(payload) {
40
+ if ('string' != typeof payload.appName) return 'unknown';
41
+ const normalized = payload.appName.trim();
42
+ return normalized.length > 0 ? normalized : 'unknown';
43
+ }
44
+ function normalizeRuntimeSignalRuntimeDigest(payload) {
45
+ if ('string' == typeof payload.runtimeDigest && payload.runtimeDigest.trim()) return payload.runtimeDigest.trim();
46
+ const metadata = payload.metadata;
47
+ if (metadata && 'object' == typeof metadata && !Array.isArray(metadata) && 'string' == typeof metadata.runtimeDigest) {
48
+ const digest = String(metadata.runtimeDigest).trim();
49
+ if (digest) return digest;
50
+ }
51
+ }
52
+ function normalizeRuntimeFallbackSignalAuthConfig(configured) {
53
+ const headerName = 'string' == typeof configured?.headerName && configured.headerName.trim() ? configured.headerName.trim().toLowerCase() : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
54
+ const expectedFromEnv = 'string' == typeof configured?.expectedValueEnv && configured.expectedValueEnv.trim().length > 0 ? process.env[configured.expectedValueEnv.trim()] : void 0;
55
+ const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
56
+ const expectedValue = expectedFromConfig || expectedFromEnv;
57
+ const enabled = configured?.enabled === true;
58
+ if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled is true but no expected token is configured');
59
+ return {
60
+ enabled,
61
+ headerName,
62
+ expectedValue
63
+ };
64
+ }
65
+ function normalizeRequiredRuntimeFallbackSignalAuthConfig(configured) {
66
+ if (configured?.enabled === false) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] the endpoint cannot be enabled with auth disabled; configure auth.expectedValue or auth.expectedValueEnv');
67
+ try {
68
+ return normalizeRuntimeFallbackSignalAuthConfig({
69
+ ...configured,
70
+ enabled: true
71
+ });
72
+ } catch (_error) {
73
+ throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] enabling the endpoint requires an auth token; configure auth.expectedValue or auth.expectedValueEnv');
74
+ }
75
+ }
76
+ function safeTokenEquals(candidate, expected) {
77
+ const candidateDigest = createHash('sha256').update(candidate).digest();
78
+ const expectedDigest = createHash('sha256').update(expected).digest();
79
+ return timingSafeEqual(candidateDigest, expectedDigest);
80
+ }
81
+ function enforceRuntimeFallbackSignalAuthToken(token, authConfig) {
82
+ if (!authConfig.enabled) return;
83
+ if (!token || !authConfig.expectedValue || !safeTokenEquals(token, authConfig.expectedValue)) throw createRuntimeSignalError('runtime fallback signal auth failed', 'UNAUTHORIZED');
84
+ }
85
+ function enforceRuntimeFallbackSignalAuth(c, runtimeSignalConfig) {
86
+ enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
87
+ }
88
+ function normalizeRuntimeFallbackTrustPolicy(configured) {
89
+ const allowedApps = Array.isArray(configured?.allowedApps) ? configured.allowedApps.map((item)=>'string' == typeof item ? item.trim() : '').filter(Boolean) : [];
90
+ const allowedEntryOrigins = Array.isArray(configured?.allowedEntryOrigins) ? configured.allowedEntryOrigins.map((item)=>normalizeRuntimeSignalOrigin(item)).filter((item)=>Boolean(item)) : [];
91
+ const expectedRuntimeDigestsRaw = configured?.expectedRuntimeDigests || {};
92
+ const expectedRuntimeDigests = {};
93
+ Object.entries(expectedRuntimeDigestsRaw).forEach(([appName, digest])=>{
94
+ if ('string' == typeof appName && appName.trim().length > 0 && 'string' == typeof digest && digest.trim().length > 0) expectedRuntimeDigests[appName.trim()] = digest.trim();
95
+ });
96
+ return {
97
+ allowedApps,
98
+ allowedEntryOrigins,
99
+ expectedRuntimeDigests,
100
+ enforceRuntimeDigest: configured?.enforceRuntimeDigest === true,
101
+ maxSignalsPerWindow: Math.max(1, Math.floor(configured?.maxSignalsPerWindow ?? DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW)),
102
+ windowMs: Math.max(1000, Math.floor(configured?.windowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS)),
103
+ dedupeWindowMs: Math.max(0, Math.floor(configured?.dedupeWindowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS))
104
+ };
105
+ }
106
+ function createRuntimeFallbackSignalRuntimeState() {
107
+ return {
108
+ rateLimitBySource: new Map(),
109
+ dedupeByFingerprint: new Map()
110
+ };
111
+ }
112
+ function cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy) {
113
+ const dedupeExpiryMs = Math.max(trustPolicy.dedupeWindowMs, trustPolicy.windowMs, 1000);
114
+ runtimeState.dedupeByFingerprint.forEach((lastSeenAt, fingerprint)=>{
115
+ if (now - lastSeenAt > dedupeExpiryMs) runtimeState.dedupeByFingerprint.delete(fingerprint);
116
+ });
117
+ runtimeState.rateLimitBySource.forEach((state, source)=>{
118
+ if (now - state.windowStartedAt > 2 * trustPolicy.windowMs) runtimeState.rateLimitBySource.delete(source);
119
+ });
120
+ }
121
+ function enforceRuntimeFallbackSignalTrustPolicy(payload, runtimeSignalContext, source = {}) {
122
+ const { trustPolicy, runtimeState } = runtimeSignalContext;
123
+ const now = Date.now();
124
+ cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy);
125
+ const appName = normalizeRuntimeSignalAppName(payload);
126
+ const entryOrigin = normalizeRuntimeSignalOrigin(payload.entry);
127
+ const runtimeDigest = normalizeRuntimeSignalRuntimeDigest(payload);
128
+ if (trustPolicy.allowedApps.length > 0 && !trustPolicy.allowedApps.includes(appName)) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" is not trusted`, 'UNTRUSTED_SOURCE');
129
+ if (trustPolicy.allowedEntryOrigins.length > 0) {
130
+ if (!entryOrigin || !trustPolicy.allowedEntryOrigins.includes(entryOrigin)) throw createRuntimeSignalError(`runtime fallback signal entry origin "${entryOrigin || 'unknown'}" is not trusted`, 'UNTRUSTED_SOURCE');
131
+ }
132
+ const expectedDigest = trustPolicy.expectedRuntimeDigests[appName];
133
+ if (expectedDigest && runtimeDigest !== expectedDigest) throw createRuntimeSignalError(`runtime fallback runtimeDigest mismatch for app "${appName}"`, 'UNTRUSTED_SOURCE');
134
+ if (trustPolicy.enforceRuntimeDigest && !runtimeDigest) throw createRuntimeSignalError(`runtime fallback signal for app "${appName}" is missing runtimeDigest`, 'UNTRUSTED_SOURCE');
135
+ const dedupeFingerprint = JSON.stringify({
136
+ appName,
137
+ entryOrigin: entryOrigin || 'unknown',
138
+ reason: payload.reason || 'runtime_fallback',
139
+ phase: payload.phase || 'unknown',
140
+ runtimeDigest: runtimeDigest || 'unknown'
141
+ });
142
+ const dedupeWindowMs = trustPolicy.dedupeWindowMs;
143
+ if (dedupeWindowMs > 0) {
144
+ const lastSeenAt = runtimeState.dedupeByFingerprint.get(dedupeFingerprint);
145
+ runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
146
+ if ('number' == typeof lastSeenAt && now - lastSeenAt <= dedupeWindowMs) return {
147
+ deduped: true
148
+ };
149
+ } else runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
150
+ const remoteAddress = source.remoteAddress?.trim();
151
+ const sourceKey = remoteAddress || 'unknown-remote';
152
+ const rateState = runtimeState.rateLimitBySource.get(sourceKey);
153
+ if (!rateState || now - rateState.windowStartedAt > trustPolicy.windowMs) runtimeState.rateLimitBySource.set(sourceKey, {
154
+ count: 1,
155
+ windowStartedAt: now
156
+ });
157
+ else {
158
+ if (rateState.count >= trustPolicy.maxSignalsPerWindow) throw createRuntimeSignalError(`runtime fallback signal rate-limited for source "${sourceKey}"`, 'RATE_LIMITED');
159
+ rateState.count += 1;
160
+ }
161
+ return {
162
+ deduped: false
163
+ };
164
+ }
165
+ async function parseRuntimeFallbackSignalPayload(c, maxBodyBytes) {
166
+ const contentLengthHeader = c.req.header('content-length');
167
+ if (contentLengthHeader) {
168
+ const contentLength = Number.parseInt(contentLengthHeader, 10);
169
+ if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
170
+ }
171
+ const rawBody = await c.req.raw.text();
172
+ const payload = parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes);
173
+ return {
174
+ rawBody,
175
+ payload
176
+ };
177
+ }
178
+ function parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes) {
179
+ if (!rawBody || 0 === rawBody.trim().length) throw createRuntimeSignalError('runtime fallback signal body is empty', 'INVALID_PAYLOAD');
180
+ if (getUtf8ByteLength(rawBody) > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
181
+ let payload;
182
+ try {
183
+ payload = JSON.parse(rawBody);
184
+ } catch (_error) {
185
+ throw createRuntimeSignalError('runtime fallback signal body must be valid JSON', 'INVALID_PAYLOAD');
186
+ }
187
+ if (!payload || 'object' != typeof payload || Array.isArray(payload)) throw createRuntimeSignalError('runtime fallback signal body must be a JSON object', 'INVALID_PAYLOAD');
188
+ return payload;
189
+ }
190
+ function getRuntimeSignalErrorStatusCode(signalError) {
191
+ if ('PAYLOAD_TOO_LARGE' === signalError.code) return 413;
192
+ if ('INVALID_PAYLOAD' === signalError.code) return 400;
193
+ if ('UNAUTHORIZED' === signalError.code) return 401;
194
+ if ('RATE_LIMITED' === signalError.code) return 429;
195
+ if ('UNTRUSTED_SOURCE' === signalError.code) return 403;
196
+ return 500;
197
+ }
198
+ async function persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
199
+ const now = Date.now();
200
+ const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
201
+ const snapshot = await gateSnapshotStore.readSnapshot() || {};
202
+ const existingGates = snapshot.gates && 'object' == typeof snapshot.gates ? snapshot.gates : {};
203
+ const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
204
+ const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
205
+ const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
206
+ const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
207
+ snapshot.schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
208
+ snapshot.updatedAt = now;
209
+ snapshot.gates = {
210
+ ...existingGates,
211
+ [runtimeSignalConfig.gateName]: {
212
+ passed: false,
213
+ reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
214
+ updatedAt: now,
215
+ expiresAt: now + runtimeSignalConfig.failureHoldMs,
216
+ source: 'runtime-mf-fallback-signal',
217
+ metadata: payload
218
+ }
219
+ };
220
+ await gateSnapshotStore.writeSnapshot(snapshot);
221
+ }
222
+ export { DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayload, parseRuntimeFallbackSignalPayloadFromRawBody, persistRuntimeFallbackContractGate, resolveRuntimeFallbackSignalEndpoint };
@@ -0,0 +1,275 @@
1
+ import { parseTraceparent } from "@modern-js/create-request/server";
2
+ import { logger } from "@modern-js/utils";
3
+ import { ContractGateAutopilot } from "./contractGateAutopilot.mjs";
4
+ import { DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "./contractGateSnapshotStore.mjs";
5
+ import { parseServerRuntimeExtensionsEnv } from "./env.mjs";
6
+ import { DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayload, parseRuntimeFallbackSignalPayloadFromRawBody, persistRuntimeFallbackContractGate, resolveRuntimeFallbackSignalEndpoint } from "./runtimeFallbackSignal.mjs";
7
+ import { TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint, toTelemetryEnvelope } from "./telemetryCore.mjs";
8
+ function emitCanaryDecisionMetric(registry, decision, action) {
9
+ try {
10
+ registry.enqueueMetric({
11
+ name: `telemetry.canary.${action}`,
12
+ value: 1,
13
+ unit: 'count',
14
+ tags: {
15
+ action,
16
+ state: decision.state,
17
+ failures: String(decision.failures.length)
18
+ }
19
+ });
20
+ } catch (_error) {}
21
+ }
22
+ const hasEnabledTelemetryExporters = (config)=>Boolean(config?.exporters?.otlp?.enabled || config?.exporters?.victoriaMetrics?.enabled);
23
+ const resolveTelemetrySloOptions = (sloConfig, warnSink = (message)=>logger.warn(message))=>({
24
+ queueUtilizationWarnThreshold: sloConfig?.queueUtilizationWarnThreshold,
25
+ queueDroppedWarnThreshold: sloConfig?.queueDroppedWarnThreshold,
26
+ alertCooldownMs: sloConfig?.alertCooldownMs,
27
+ onAlert: (alert)=>{
28
+ warnSink(`[telemetry.slo] ${alert.type} threshold=${alert.threshold} value=${alert.value} depth=${alert.queueDepth}/${alert.queueCapacity} dropped=${alert.totalDropped}`);
29
+ }
30
+ });
31
+ const getRequestRemoteAddress = (c)=>{
32
+ const env = c.env;
33
+ const remoteAddress = env?.node?.req?.socket?.remoteAddress;
34
+ return 'string' == typeof remoteAddress && remoteAddress.trim().length > 0 ? remoteAddress.trim() : void 0;
35
+ };
36
+ const activeTelemetryLaneClosers = new Set();
37
+ let telemetryBeforeExitHookInstalled = false;
38
+ const ensureTelemetryBeforeExitHook = ()=>{
39
+ if (telemetryBeforeExitHookInstalled) return;
40
+ telemetryBeforeExitHookInstalled = true;
41
+ process.on('beforeExit', ()=>{
42
+ for (const close of [
43
+ ...activeTelemetryLaneClosers
44
+ ])close();
45
+ });
46
+ };
47
+ const injectTelemetryPlugin = ()=>({
48
+ name: '@modern-js/inject-telemetry',
49
+ setup (api) {
50
+ const serverConfig = api.getServerConfig();
51
+ const telemetryConfig = serverConfig?.server?.telemetry;
52
+ if (!telemetryConfig) return;
53
+ if (true !== telemetryConfig.enabled && !hasEnabledTelemetryExporters(telemetryConfig)) return;
54
+ const { middlewares, metaName, appDirectory } = api.getServerContext();
55
+ const serviceName = telemetryConfig.service || metaName || 'modern-js';
56
+ const moduleName = telemetryConfig.module || 'server';
57
+ const environmentName = telemetryConfig.environment || parseServerRuntimeExtensionsEnv().environmentName;
58
+ const registry = new TelemetryRegistry({
59
+ service: serviceName,
60
+ module: moduleName,
61
+ environment: environmentName,
62
+ samplingRate: telemetryConfig.samplingRate,
63
+ flushIntervalMs: telemetryConfig.flushIntervalMs,
64
+ maxBatchSize: telemetryConfig.maxBatchSize,
65
+ maxQueueSize: telemetryConfig.maxQueueSize,
66
+ redactionKeys: telemetryConfig.redactionKeys,
67
+ slo: resolveTelemetrySloOptions(telemetryConfig.slo)
68
+ });
69
+ let canaryOrchestrator;
70
+ let contractGateAutopilot;
71
+ let runtimeFallbackSignalConfig;
72
+ let runtimeStatusAuthConfig;
73
+ let gateSnapshotStorePromise;
74
+ const canaryConfig = telemetryConfig.canary;
75
+ if (canaryConfig?.enabled) {
76
+ const contractGates = canaryConfig.contractGates;
77
+ canaryOrchestrator = new TelemetryCanaryOrchestrator({
78
+ registry,
79
+ evaluationIntervalMs: canaryConfig.evaluationIntervalMs,
80
+ minConsecutiveHealthyEvaluations: canaryConfig.minConsecutiveHealthyEvaluations,
81
+ rollbackConsecutiveFailures: canaryConfig.rollbackConsecutiveFailures,
82
+ maxQueueUtilization: canaryConfig.maxQueueUtilization,
83
+ maxTotalDropped: canaryConfig.maxTotalDropped,
84
+ maxUnhealthyExporters: canaryConfig.maxUnhealthyExporters,
85
+ requiredContractGates: Object.keys(contractGates || {}),
86
+ onPromote: (decision)=>{
87
+ emitCanaryDecisionMetric(registry, decision, 'promote');
88
+ },
89
+ onRollback: (decision)=>{
90
+ emitCanaryDecisionMetric(registry, decision, 'rollback');
91
+ }
92
+ });
93
+ if (contractGates) canaryOrchestrator.setContractGates(contractGates);
94
+ const autopilotEnabled = canaryConfig.autopilot?.enabled ?? true;
95
+ if (autopilotEnabled) {
96
+ const gateSnapshotPath = resolveContractGateSnapshotPath(appDirectory, canaryConfig.autopilot?.gateSnapshotPath);
97
+ gateSnapshotStorePromise = resolveContractGateSnapshotStore({
98
+ appDirectory,
99
+ gateSnapshotPath: gateSnapshotPath || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
100
+ stateStore: canaryConfig.autopilot?.stateStore
101
+ });
102
+ const runtimeSignalConfig = canaryConfig.autopilot?.runtimeFallbackSignal;
103
+ const runtimeSignalEnabled = runtimeSignalConfig?.enabled === true;
104
+ if (runtimeSignalEnabled && gateSnapshotStorePromise) runtimeFallbackSignalConfig = {
105
+ endpoint: resolveRuntimeFallbackSignalEndpoint(runtimeSignalConfig?.endpoint),
106
+ gateName: runtimeSignalConfig?.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
107
+ gateSnapshotStore: gateSnapshotStorePromise,
108
+ failureHoldMs: Math.max(1000, runtimeSignalConfig?.failureHoldMs ?? DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS),
109
+ maxBodyBytes: Math.max(512, runtimeSignalConfig?.maxBodyBytes ?? DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES),
110
+ auth: normalizeRequiredRuntimeFallbackSignalAuthConfig(runtimeSignalConfig?.auth),
111
+ trustPolicy: normalizeRuntimeFallbackTrustPolicy(runtimeSignalConfig?.trustPolicy),
112
+ runtimeState: createRuntimeFallbackSignalRuntimeState()
113
+ };
114
+ }
115
+ runtimeStatusAuthConfig = runtimeFallbackSignalConfig?.auth ?? normalizeRuntimeFallbackSignalAuthConfig(canaryConfig.autopilot?.runtimeFallbackSignal?.auth);
116
+ }
117
+ if (runtimeFallbackSignalConfig) {
118
+ const signalConfig = runtimeFallbackSignalConfig;
119
+ middlewares.push({
120
+ name: 'telemetry-runtime-fallback-signal',
121
+ path: signalConfig.endpoint,
122
+ method: 'post',
123
+ order: 'pre',
124
+ handler: async (c)=>{
125
+ try {
126
+ enforceRuntimeFallbackSignalAuth(c, signalConfig);
127
+ const { payload } = await parseRuntimeFallbackSignalPayload(c, signalConfig.maxBodyBytes);
128
+ const trustResult = enforceRuntimeFallbackSignalTrustPolicy(payload, signalConfig, {
129
+ remoteAddress: getRequestRemoteAddress(c)
130
+ });
131
+ if (trustResult.deduped) return c.json({
132
+ ok: true,
133
+ deduped: true
134
+ }, 202);
135
+ await persistRuntimeFallbackContractGate(payload, signalConfig);
136
+ return c.json({
137
+ ok: true
138
+ }, 202);
139
+ } catch (error) {
140
+ const signalError = error;
141
+ const status = getRuntimeSignalErrorStatusCode(signalError);
142
+ return c.json({
143
+ ok: false,
144
+ error: signalError instanceof Error ? signalError.message : String(signalError)
145
+ }, status);
146
+ }
147
+ }
148
+ });
149
+ }
150
+ middlewares.push({
151
+ name: 'telemetry-runtime-status',
152
+ path: DEFAULT_RUNTIME_STATUS_ENDPOINT,
153
+ method: 'get',
154
+ order: 'pre',
155
+ handler: async (c)=>{
156
+ try {
157
+ if (!runtimeStatusAuthConfig?.enabled) return c.json({
158
+ ok: true,
159
+ timestamp: Date.now()
160
+ });
161
+ enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeStatusAuthConfig.headerName), runtimeStatusAuthConfig);
162
+ return c.json({
163
+ ok: true,
164
+ timestamp: Date.now(),
165
+ telemetry: {
166
+ queueStats: registry.getQueueStats(),
167
+ exporterHealth: registry.getExporterHealth()
168
+ },
169
+ canary: canaryOrchestrator ? {
170
+ enabled: true,
171
+ ...canaryOrchestrator.getStatusSnapshot()
172
+ } : {
173
+ enabled: false
174
+ },
175
+ runtimeFallbackSignal: runtimeFallbackSignalConfig ? {
176
+ enabled: true,
177
+ endpoint: runtimeFallbackSignalConfig.endpoint,
178
+ gateName: runtimeFallbackSignalConfig.gateName,
179
+ failureHoldMs: runtimeFallbackSignalConfig.failureHoldMs,
180
+ maxBodyBytes: runtimeFallbackSignalConfig.maxBodyBytes,
181
+ auth: {
182
+ enabled: runtimeFallbackSignalConfig.auth.enabled,
183
+ headerName: runtimeFallbackSignalConfig.auth.headerName
184
+ },
185
+ trustPolicy: {
186
+ allowedApps: runtimeFallbackSignalConfig.trustPolicy.allowedApps,
187
+ allowedEntryOrigins: runtimeFallbackSignalConfig.trustPolicy.allowedEntryOrigins,
188
+ enforceRuntimeDigest: runtimeFallbackSignalConfig.trustPolicy.enforceRuntimeDigest,
189
+ expectedRuntimeDigestsCount: Object.keys(runtimeFallbackSignalConfig.trustPolicy.expectedRuntimeDigests).length,
190
+ maxSignalsPerWindow: runtimeFallbackSignalConfig.trustPolicy.maxSignalsPerWindow,
191
+ windowMs: runtimeFallbackSignalConfig.trustPolicy.windowMs,
192
+ dedupeWindowMs: runtimeFallbackSignalConfig.trustPolicy.dedupeWindowMs
193
+ }
194
+ } : {
195
+ enabled: false
196
+ }
197
+ });
198
+ } catch (error) {
199
+ const signalError = error;
200
+ return c.json({
201
+ ok: false,
202
+ error: signalError instanceof Error ? signalError.message : String(signalError)
203
+ }, getRuntimeSignalErrorStatusCode(signalError));
204
+ }
205
+ }
206
+ });
207
+ middlewares.push({
208
+ name: 'inject-telemetry',
209
+ handler: async (c, next)=>{
210
+ const monitors = c.get('monitors');
211
+ if (monitors) {
212
+ const traceContext = parseTraceparent(c.req.header('traceparent'));
213
+ const monitor = (event)=>{
214
+ registry.enqueue(toTelemetryEnvelope(event, {
215
+ service: serviceName,
216
+ module: moduleName,
217
+ environment: environmentName,
218
+ traceId: traceContext?.traceId,
219
+ spanId: traceContext?.spanId,
220
+ attributes: {
221
+ requestMethod: c.req.method,
222
+ requestPath: c.req.path
223
+ }
224
+ }));
225
+ };
226
+ monitors.push(monitor);
227
+ }
228
+ await next();
229
+ }
230
+ });
231
+ let telemetryLaneClosed = false;
232
+ const closeTelemetryLane = async ()=>{
233
+ if (telemetryLaneClosed) return;
234
+ telemetryLaneClosed = true;
235
+ activeTelemetryLaneClosers.delete(closeTelemetryLane);
236
+ contractGateAutopilot?.stop();
237
+ canaryOrchestrator?.stop();
238
+ await registry.shutdown();
239
+ };
240
+ let prepared = false;
241
+ api.onPrepare(async ()=>{
242
+ if (prepared) return;
243
+ prepared = true;
244
+ const { nodeServer } = api.getServerContext();
245
+ if (nodeServer && 'function' == typeof nodeServer.once) nodeServer.once('close', ()=>{
246
+ closeTelemetryLane();
247
+ });
248
+ activeTelemetryLaneClosers.add(closeTelemetryLane);
249
+ ensureTelemetryBeforeExitHook();
250
+ if (telemetryConfig.exporters?.otlp?.enabled) {
251
+ maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
252
+ await registry.register(createOtlpTelemetryExporter(telemetryConfig.exporters.otlp));
253
+ }
254
+ if (telemetryConfig.exporters?.victoriaMetrics?.enabled) await registry.register(createVictoriaMetricsTelemetryExporter(telemetryConfig.exporters.victoriaMetrics));
255
+ await registry.startupHealthCheck({
256
+ failLoud: telemetryConfig.failLoudStartup ?? true
257
+ });
258
+ if (!canaryOrchestrator) return;
259
+ canaryOrchestrator.start();
260
+ if (gateSnapshotStorePromise) {
261
+ const gateSnapshotStore = await gateSnapshotStorePromise;
262
+ contractGateAutopilot = new ContractGateAutopilot({
263
+ orchestrator: canaryOrchestrator,
264
+ gateSnapshotPath: resolveContractGateSnapshotPath(appDirectory, canaryConfig?.autopilot?.gateSnapshotPath),
265
+ gateSnapshotStore,
266
+ pollIntervalMs: canaryConfig?.autopilot?.pollIntervalMs,
267
+ gateStaleAfterMs: canaryConfig?.autopilot?.gateStaleAfterMs
268
+ });
269
+ }
270
+ if (contractGateAutopilot) await contractGateAutopilot.start();
271
+ canaryOrchestrator.evaluate();
272
+ });
273
+ }
274
+ });
275
+ export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, hasEnabledTelemetryExporters, injectTelemetryPlugin, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayloadFromRawBody, resolveRuntimeFallbackSignalEndpoint, resolveTelemetrySloOptions };