@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.3 → 3.5.0-ultramodern.31
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/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
- package/dist/cjs/contract-gate-snapshot-store/http-store.js +142 -0
- package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
- package/dist/cjs/contract-gate-snapshot-store/resolve.js +122 -0
- package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
- package/dist/cjs/contractGateAutopilot.js +27 -6
- package/dist/cjs/index.js +13 -13
- package/dist/cjs/module-federation-css/collector.js +79 -0
- package/dist/cjs/module-federation-css/index.js +55 -0
- package/dist/cjs/module-federation-css/manifest.js +144 -0
- package/dist/cjs/module-federation-css/plugin.js +71 -0
- package/dist/cjs/module-federation-css/remote.js +133 -0
- package/dist/cjs/runtime-fallback-signal/auth.js +87 -0
- package/dist/cjs/runtime-fallback-signal/constants.js +72 -0
- package/dist/cjs/runtime-fallback-signal/contract-gate.js +64 -0
- package/dist/cjs/runtime-fallback-signal/endpoint.js +50 -0
- package/dist/cjs/runtime-fallback-signal/errors.js +44 -0
- package/dist/cjs/runtime-fallback-signal/index.js +99 -0
- package/dist/cjs/runtime-fallback-signal/payload.js +72 -0
- package/dist/cjs/runtime-fallback-signal/source.js +66 -0
- package/dist/cjs/runtime-fallback-signal/state.js +57 -0
- package/dist/cjs/runtime-fallback-signal/status.js +47 -0
- package/dist/cjs/runtime-fallback-signal/trust-policy.js +108 -0
- package/dist/cjs/runtime-fallback-signal/types.js +18 -0
- package/dist/cjs/runtimeFallbackSignal.js +32 -281
- package/dist/cjs/telemetry/canary.js +180 -0
- package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
- package/dist/cjs/telemetry/canarySetup.js +107 -0
- package/dist/cjs/telemetry/envelope.js +148 -0
- package/dist/cjs/telemetry/exporters.js +148 -0
- package/dist/cjs/telemetry/lifecycle.js +98 -0
- package/dist/cjs/telemetry/metrics.js +115 -0
- package/dist/cjs/telemetry/plugin.js +185 -0
- package/dist/cjs/telemetry/registry.js +348 -0
- package/dist/cjs/telemetry/registryTypes.js +46 -0
- package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
- package/dist/cjs/telemetry.js +32 -343
- package/dist/cjs/telemetryCore.js +14 -767
- package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
- package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
- package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
- package/dist/esm/contract-gate-snapshot-store/resolve.mjs +68 -0
- package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
- package/dist/esm/contractGateAutopilot.mjs +26 -5
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/module-federation-css/collector.mjs +38 -0
- package/dist/esm/module-federation-css/index.mjs +4 -0
- package/dist/esm/module-federation-css/manifest.mjs +69 -0
- package/dist/esm/module-federation-css/plugin.mjs +33 -0
- package/dist/esm/module-federation-css/remote.mjs +92 -0
- package/dist/esm/runtime-fallback-signal/auth.mjs +40 -0
- package/dist/esm/runtime-fallback-signal/constants.mjs +10 -0
- package/dist/esm/runtime-fallback-signal/contract-gate.mjs +26 -0
- package/dist/esm/runtime-fallback-signal/endpoint.mjs +12 -0
- package/dist/esm/runtime-fallback-signal/errors.mjs +6 -0
- package/dist/esm/runtime-fallback-signal/index.mjs +9 -0
- package/dist/esm/runtime-fallback-signal/payload.mjs +31 -0
- package/dist/esm/runtime-fallback-signal/source.mjs +22 -0
- package/dist/esm/runtime-fallback-signal/state.mjs +16 -0
- package/dist/esm/runtime-fallback-signal/status.mjs +9 -0
- package/dist/esm/runtime-fallback-signal/trust-policy.mjs +67 -0
- package/dist/esm/runtime-fallback-signal/types.mjs +0 -0
- package/dist/esm/runtimeFallbackSignal.mjs +1 -222
- package/dist/esm/telemetry/canary.mjs +142 -0
- package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
- package/dist/esm/telemetry/canarySetup.mjs +69 -0
- package/dist/esm/telemetry/envelope.mjs +101 -0
- package/dist/esm/telemetry/exporters.mjs +104 -0
- package/dist/esm/telemetry/lifecycle.mjs +60 -0
- package/dist/esm/telemetry/metrics.mjs +77 -0
- package/dist/esm/telemetry/plugin.mjs +87 -0
- package/dist/esm/telemetry/registry.mjs +310 -0
- package/dist/esm/telemetry/registryTypes.mjs +8 -0
- package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
- package/dist/esm/telemetry.mjs +1 -275
- package/dist/esm/telemetryCore.mjs +6 -759
- package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
- package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
- package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
- package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +70 -0
- package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
- package/dist/esm-node/contractGateAutopilot.mjs +26 -5
- package/dist/esm-node/index.mjs +2 -2
- package/dist/esm-node/module-federation-css/collector.mjs +39 -0
- package/dist/esm-node/module-federation-css/index.mjs +5 -0
- package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
- package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
- package/dist/esm-node/module-federation-css/remote.mjs +93 -0
- package/dist/esm-node/runtime-fallback-signal/auth.mjs +41 -0
- package/dist/esm-node/runtime-fallback-signal/constants.mjs +11 -0
- package/dist/esm-node/runtime-fallback-signal/contract-gate.mjs +27 -0
- package/dist/esm-node/runtime-fallback-signal/endpoint.mjs +13 -0
- package/dist/esm-node/runtime-fallback-signal/errors.mjs +7 -0
- package/dist/esm-node/runtime-fallback-signal/index.mjs +10 -0
- package/dist/esm-node/runtime-fallback-signal/payload.mjs +32 -0
- package/dist/esm-node/runtime-fallback-signal/source.mjs +23 -0
- package/dist/esm-node/runtime-fallback-signal/state.mjs +17 -0
- package/dist/esm-node/runtime-fallback-signal/status.mjs +10 -0
- package/dist/esm-node/runtime-fallback-signal/trust-policy.mjs +68 -0
- package/dist/esm-node/runtime-fallback-signal/types.mjs +1 -0
- package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
- package/dist/esm-node/telemetry/canary.mjs +143 -0
- package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
- package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
- package/dist/esm-node/telemetry/envelope.mjs +102 -0
- package/dist/esm-node/telemetry/exporters.mjs +105 -0
- package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
- package/dist/esm-node/telemetry/metrics.mjs +78 -0
- package/dist/esm-node/telemetry/plugin.mjs +88 -0
- package/dist/esm-node/telemetry/registry.mjs +311 -0
- package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
- package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
- package/dist/esm-node/telemetry.mjs +1 -275
- package/dist/esm-node/telemetryCore.mjs +6 -759
- package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
- package/dist/types/contract-gate-snapshot-store/http-store.d.ts +11 -0
- package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
- package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
- package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
- package/dist/types/contractGateAutopilot.d.ts +4 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/types/module-federation-css/collector.d.ts +25 -0
- package/dist/types/module-federation-css/index.d.ts +8 -0
- package/dist/types/module-federation-css/manifest.d.ts +33 -0
- package/dist/types/module-federation-css/plugin.d.ts +23 -0
- package/dist/types/module-federation-css/remote.d.ts +20 -0
- package/dist/types/runtime-fallback-signal/auth.d.ts +18 -0
- package/dist/types/runtime-fallback-signal/constants.d.ts +9 -0
- package/dist/types/runtime-fallback-signal/contract-gate.d.ts +2 -0
- package/dist/types/runtime-fallback-signal/endpoint.d.ts +1 -0
- package/dist/types/runtime-fallback-signal/errors.d.ts +2 -0
- package/dist/types/runtime-fallback-signal/index.d.ts +10 -0
- package/dist/types/runtime-fallback-signal/payload.d.ts +6 -0
- package/dist/types/runtime-fallback-signal/source.d.ts +3 -0
- package/dist/types/runtime-fallback-signal/state.d.ts +3 -0
- package/dist/types/runtime-fallback-signal/status.d.ts +2 -0
- package/dist/types/runtime-fallback-signal/trust-policy.d.ts +13 -0
- package/dist/types/runtime-fallback-signal/types.d.ts +50 -0
- package/dist/types/runtimeFallbackSignal.d.ts +1 -94
- package/dist/types/telemetry/canary.d.ts +85 -0
- package/dist/types/telemetry/canaryEvaluation.d.ts +19 -0
- package/dist/types/telemetry/canarySetup.d.ts +17 -0
- package/dist/types/telemetry/envelope.d.ts +45 -0
- package/dist/types/telemetry/exporters.d.ts +12 -0
- package/dist/types/telemetry/lifecycle.d.ts +18 -0
- package/dist/types/telemetry/metrics.d.ts +3 -0
- package/dist/types/telemetry/plugin.d.ts +12 -0
- package/dist/types/telemetry/registry.d.ts +72 -0
- package/dist/types/telemetry/registryTypes.d.ts +50 -0
- package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
- package/dist/types/telemetry.d.ts +1 -12
- package/dist/types/telemetryCore.d.ts +6 -257
- package/package.json +7 -7
- package/src/contract-gate-snapshot-store/file-store.ts +85 -0
- package/src/contract-gate-snapshot-store/http-store.ts +159 -0
- package/src/contract-gate-snapshot-store/index.ts +20 -0
- package/src/contract-gate-snapshot-store/resolve.ts +175 -0
- package/src/contract-gate-snapshot-store/types.ts +64 -0
- package/src/contractGateAutopilot.ts +45 -9
- package/src/index.ts +6 -6
- package/src/module-federation-css/collector.ts +82 -0
- package/src/module-federation-css/index.ts +14 -0
- package/src/module-federation-css/manifest.ts +166 -0
- package/src/module-federation-css/plugin.ts +86 -0
- package/src/module-federation-css/remote.ts +165 -0
- package/src/runtime-fallback-signal/auth.ts +117 -0
- package/src/runtime-fallback-signal/constants.ts +19 -0
- package/src/runtime-fallback-signal/contract-gate.ts +43 -0
- package/src/runtime-fallback-signal/endpoint.ts +22 -0
- package/src/runtime-fallback-signal/errors.ts +10 -0
- package/src/runtime-fallback-signal/index.ts +36 -0
- package/src/runtime-fallback-signal/payload.ts +79 -0
- package/src/runtime-fallback-signal/source.ts +49 -0
- package/src/runtime-fallback-signal/state.ts +34 -0
- package/src/runtime-fallback-signal/status.ts +22 -0
- package/src/runtime-fallback-signal/trust-policy.ts +179 -0
- package/src/runtime-fallback-signal/types.ts +66 -0
- package/src/runtimeFallbackSignal.ts +1 -584
- package/src/telemetry/canary.ts +291 -0
- package/src/telemetry/canaryEvaluation.ts +83 -0
- package/src/telemetry/canarySetup.ts +160 -0
- package/src/telemetry/envelope.ts +189 -0
- package/src/telemetry/exporters.ts +165 -0
- package/src/telemetry/lifecycle.ts +138 -0
- package/src/telemetry/metrics.ts +141 -0
- package/src/telemetry/plugin.ts +197 -0
- package/src/telemetry/registry.ts +467 -0
- package/src/telemetry/registryTypes.ts +63 -0
- package/src/telemetry/runtimeEndpoints.ts +172 -0
- package/src/telemetry.ts +1 -554
- package/src/telemetryCore.ts +34 -1332
- package/tests/contractGateAutopilot.test.ts +205 -0
- package/tests/contractGateSnapshotStore.test.ts +54 -1
- package/tests/helpers.ts +1 -0
- package/tests/moduleFederationCss.test.ts +1 -1
- package/tests/registration.test.ts +1 -1
- package/tests/telemetry.test.ts +40 -0
- package/tests/telemetryLifecycle.test.ts +253 -2
- package/dist/cjs/contractGateSnapshotStore.js +0 -253
- package/dist/cjs/moduleFederationCss.js +0 -285
- package/dist/esm/contractGateSnapshotStore.mjs +0 -190
- package/dist/esm/moduleFederationCss.mjs +0 -225
- package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
- package/dist/esm-node/moduleFederationCss.mjs +0 -226
- package/dist/types/moduleFederationCss.d.ts +0 -87
- package/src/contractGateSnapshotStore.ts +0 -420
- package/src/moduleFederationCss.ts +0 -473
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
export { enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig } from "./auth.mjs";
|
|
3
|
+
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 } from "./constants.mjs";
|
|
4
|
+
export { persistRuntimeFallbackContractGate } from "./contract-gate.mjs";
|
|
5
|
+
export { resolveRuntimeFallbackSignalEndpoint } from "./endpoint.mjs";
|
|
6
|
+
export { createRuntimeSignalError } from "./errors.mjs";
|
|
7
|
+
export { parseRuntimeFallbackSignalPayload, parseRuntimeFallbackSignalPayloadFromRawBody } from "./payload.mjs";
|
|
8
|
+
export { createRuntimeFallbackSignalRuntimeState } from "./state.mjs";
|
|
9
|
+
export { getRuntimeSignalErrorStatusCode } from "./status.mjs";
|
|
10
|
+
export { enforceRuntimeFallbackSignalTrustPolicy, normalizeRuntimeFallbackTrustPolicy } from "./trust-policy.mjs";
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { createRuntimeSignalError } from "./errors.mjs";
|
|
3
|
+
function getUtf8ByteLength(input) {
|
|
4
|
+
if ("u" > typeof Buffer) return Buffer.byteLength(input);
|
|
5
|
+
return new TextEncoder().encode(input).length;
|
|
6
|
+
}
|
|
7
|
+
async function parseRuntimeFallbackSignalPayload(c, maxBodyBytes) {
|
|
8
|
+
const contentLengthHeader = c.req.header('content-length');
|
|
9
|
+
if (contentLengthHeader) {
|
|
10
|
+
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
|
11
|
+
if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
|
|
12
|
+
}
|
|
13
|
+
const rawBody = await c.req.raw.text();
|
|
14
|
+
const payload = parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes);
|
|
15
|
+
return {
|
|
16
|
+
rawBody,
|
|
17
|
+
payload
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes) {
|
|
21
|
+
if (!rawBody || 0 === rawBody.trim().length) throw createRuntimeSignalError('runtime fallback signal body is empty', 'INVALID_PAYLOAD');
|
|
22
|
+
if (getUtf8ByteLength(rawBody) > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
|
|
23
|
+
let payload;
|
|
24
|
+
try {
|
|
25
|
+
payload = JSON.parse(rawBody);
|
|
26
|
+
} catch (_error) {
|
|
27
|
+
throw createRuntimeSignalError('runtime fallback signal body must be valid JSON', 'INVALID_PAYLOAD');
|
|
28
|
+
}
|
|
29
|
+
if (!payload || 'object' != typeof payload || Array.isArray(payload)) throw createRuntimeSignalError('runtime fallback signal body must be a JSON object', 'INVALID_PAYLOAD');
|
|
30
|
+
return payload;
|
|
31
|
+
}
|
|
32
|
+
export { parseRuntimeFallbackSignalPayload, parseRuntimeFallbackSignalPayloadFromRawBody };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
function normalizeRuntimeSignalOrigin(value) {
|
|
3
|
+
if ('string' != typeof value || 0 === value.trim().length) return;
|
|
4
|
+
try {
|
|
5
|
+
return new URL(value).origin;
|
|
6
|
+
} catch (_error) {
|
|
7
|
+
return;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
function normalizeRuntimeSignalAppName(payload) {
|
|
11
|
+
if ('string' != typeof payload.appName) return 'unknown';
|
|
12
|
+
const normalized = payload.appName.trim();
|
|
13
|
+
return normalized.length > 0 ? normalized : 'unknown';
|
|
14
|
+
}
|
|
15
|
+
function normalizeRuntimeSignalRuntimeDigest(payload) {
|
|
16
|
+
if ('string' == typeof payload.runtimeDigest && payload.runtimeDigest.trim()) return payload.runtimeDigest.trim();
|
|
17
|
+
const metadata = payload.metadata;
|
|
18
|
+
if (metadata && 'object' == typeof metadata && !Array.isArray(metadata) && 'string' == typeof metadata.runtimeDigest) {
|
|
19
|
+
const digest = String(metadata.runtimeDigest).trim();
|
|
20
|
+
if (digest) return digest;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export { normalizeRuntimeSignalAppName, normalizeRuntimeSignalOrigin, normalizeRuntimeSignalRuntimeDigest };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
function createRuntimeFallbackSignalRuntimeState() {
|
|
3
|
+
return {
|
|
4
|
+
rateLimitBySource: new Map(),
|
|
5
|
+
dedupeByFingerprint: new Map()
|
|
6
|
+
};
|
|
7
|
+
}
|
|
8
|
+
function cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy) {
|
|
9
|
+
const dedupeExpiryMs = Math.max(trustPolicy.dedupeWindowMs, trustPolicy.windowMs, 1000);
|
|
10
|
+
runtimeState.dedupeByFingerprint.forEach((lastSeenAt, fingerprint)=>{
|
|
11
|
+
if (now - lastSeenAt > dedupeExpiryMs) runtimeState.dedupeByFingerprint.delete(fingerprint);
|
|
12
|
+
});
|
|
13
|
+
runtimeState.rateLimitBySource.forEach((state, source)=>{
|
|
14
|
+
if (now - state.windowStartedAt > 2 * trustPolicy.windowMs) runtimeState.rateLimitBySource.delete(source);
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export { cleanupRuntimeFallbackSignalRuntimeState, createRuntimeFallbackSignalRuntimeState };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
function getRuntimeSignalErrorStatusCode(signalError) {
|
|
3
|
+
if ('PAYLOAD_TOO_LARGE' === signalError.code) return 413;
|
|
4
|
+
if ('INVALID_PAYLOAD' === signalError.code) return 400;
|
|
5
|
+
if ('UNAUTHORIZED' === signalError.code) return 401;
|
|
6
|
+
if ('RATE_LIMITED' === signalError.code) return 429;
|
|
7
|
+
if ('UNTRUSTED_SOURCE' === signalError.code) return 403;
|
|
8
|
+
return 500;
|
|
9
|
+
}
|
|
10
|
+
export { getRuntimeSignalErrorStatusCode };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS, DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW, DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS } from "./constants.mjs";
|
|
3
|
+
import { createRuntimeSignalError } from "./errors.mjs";
|
|
4
|
+
import { normalizeRuntimeSignalAppName, normalizeRuntimeSignalOrigin, normalizeRuntimeSignalRuntimeDigest } from "./source.mjs";
|
|
5
|
+
import { cleanupRuntimeFallbackSignalRuntimeState } from "./state.mjs";
|
|
6
|
+
function normalizeRuntimeFallbackTrustPolicy(configured) {
|
|
7
|
+
const allowedApps = Array.isArray(configured?.allowedApps) ? configured.allowedApps.map((item)=>'string' == typeof item ? item.trim() : '').filter(Boolean) : [];
|
|
8
|
+
const allowedEntryOrigins = Array.isArray(configured?.allowedEntryOrigins) ? configured.allowedEntryOrigins.map((item)=>normalizeRuntimeSignalOrigin(item)).filter((item)=>Boolean(item)) : [];
|
|
9
|
+
const expectedRuntimeDigestsRaw = configured?.expectedRuntimeDigests || {};
|
|
10
|
+
const expectedRuntimeDigests = {};
|
|
11
|
+
Object.entries(expectedRuntimeDigestsRaw).forEach(([appName, digest])=>{
|
|
12
|
+
if ('string' == typeof appName && appName.trim().length > 0 && 'string' == typeof digest && digest.trim().length > 0) expectedRuntimeDigests[appName.trim()] = digest.trim();
|
|
13
|
+
});
|
|
14
|
+
return {
|
|
15
|
+
allowedApps,
|
|
16
|
+
allowedEntryOrigins,
|
|
17
|
+
expectedRuntimeDigests,
|
|
18
|
+
enforceRuntimeDigest: configured?.enforceRuntimeDigest === true,
|
|
19
|
+
maxSignalsPerWindow: Math.max(1, Math.floor(configured?.maxSignalsPerWindow ?? DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW)),
|
|
20
|
+
windowMs: Math.max(1000, Math.floor(configured?.windowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS)),
|
|
21
|
+
dedupeWindowMs: Math.max(0, Math.floor(configured?.dedupeWindowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS))
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function enforceRuntimeFallbackSignalTrustPolicy(payload, runtimeSignalContext, source = {}) {
|
|
25
|
+
const { trustPolicy, runtimeState } = runtimeSignalContext;
|
|
26
|
+
const now = Date.now();
|
|
27
|
+
cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy);
|
|
28
|
+
const appName = normalizeRuntimeSignalAppName(payload);
|
|
29
|
+
const entryOrigin = normalizeRuntimeSignalOrigin(payload.entry);
|
|
30
|
+
const runtimeDigest = normalizeRuntimeSignalRuntimeDigest(payload);
|
|
31
|
+
if (trustPolicy.allowedApps.length > 0 && !trustPolicy.allowedApps.includes(appName)) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" is not trusted`, 'UNTRUSTED_SOURCE');
|
|
32
|
+
if (trustPolicy.allowedEntryOrigins.length > 0) {
|
|
33
|
+
if (!entryOrigin || !trustPolicy.allowedEntryOrigins.includes(entryOrigin)) throw createRuntimeSignalError(`runtime fallback signal entry origin "${entryOrigin || 'unknown'}" is not trusted`, 'UNTRUSTED_SOURCE');
|
|
34
|
+
}
|
|
35
|
+
const expectedDigest = trustPolicy.expectedRuntimeDigests[appName];
|
|
36
|
+
if (expectedDigest && runtimeDigest !== expectedDigest) throw createRuntimeSignalError(`runtime fallback runtimeDigest mismatch for app "${appName}"`, 'UNTRUSTED_SOURCE');
|
|
37
|
+
if (trustPolicy.enforceRuntimeDigest && !runtimeDigest) throw createRuntimeSignalError(`runtime fallback signal for app "${appName}" is missing runtimeDigest`, 'UNTRUSTED_SOURCE');
|
|
38
|
+
const dedupeFingerprint = JSON.stringify({
|
|
39
|
+
appName,
|
|
40
|
+
entryOrigin: entryOrigin || 'unknown',
|
|
41
|
+
reason: payload.reason || 'runtime_fallback',
|
|
42
|
+
phase: payload.phase || 'unknown',
|
|
43
|
+
runtimeDigest: runtimeDigest || 'unknown'
|
|
44
|
+
});
|
|
45
|
+
const dedupeWindowMs = trustPolicy.dedupeWindowMs;
|
|
46
|
+
if (dedupeWindowMs > 0) {
|
|
47
|
+
const lastSeenAt = runtimeState.dedupeByFingerprint.get(dedupeFingerprint);
|
|
48
|
+
runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
|
|
49
|
+
if ('number' == typeof lastSeenAt && now - lastSeenAt <= dedupeWindowMs) return {
|
|
50
|
+
deduped: true
|
|
51
|
+
};
|
|
52
|
+
} else runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
|
|
53
|
+
const remoteAddress = source.remoteAddress?.trim();
|
|
54
|
+
const sourceKey = remoteAddress || 'unknown-remote';
|
|
55
|
+
const rateState = runtimeState.rateLimitBySource.get(sourceKey);
|
|
56
|
+
if (!rateState || now - rateState.windowStartedAt > trustPolicy.windowMs) runtimeState.rateLimitBySource.set(sourceKey, {
|
|
57
|
+
count: 1,
|
|
58
|
+
windowStartedAt: now
|
|
59
|
+
});
|
|
60
|
+
else {
|
|
61
|
+
if (rateState.count >= trustPolicy.maxSignalsPerWindow) throw createRuntimeSignalError(`runtime fallback signal rate-limited for source "${sourceKey}"`, 'RATE_LIMITED');
|
|
62
|
+
rateState.count += 1;
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
deduped: false
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export { enforceRuntimeFallbackSignalTrustPolicy, normalizeRuntimeFallbackTrustPolicy };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "node:module";
|
|
@@ -1,223 +1,2 @@
|
|
|
1
1
|
import "node:module";
|
|
2
|
-
|
|
3
|
-
import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./contractGateSnapshotStore.mjs";
|
|
4
|
-
const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
|
|
5
|
-
const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
|
|
6
|
-
const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
|
|
7
|
-
const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
|
|
8
|
-
const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
|
|
9
|
-
const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
|
|
10
|
-
const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
|
|
11
|
-
const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60000;
|
|
12
|
-
const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10000;
|
|
13
|
-
function resolveRuntimeFallbackSignalEndpoint(configuredEndpoint) {
|
|
14
|
-
const rawEndpoint = configuredEndpoint?.trim();
|
|
15
|
-
if (!rawEndpoint) return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
|
|
16
|
-
if (rawEndpoint.startsWith('/')) return rawEndpoint;
|
|
17
|
-
try {
|
|
18
|
-
return new URL(rawEndpoint).pathname || DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
|
|
19
|
-
} catch (_error) {
|
|
20
|
-
return `/${rawEndpoint.replace(/^\/+/, '')}`;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
function createRuntimeSignalError(message, code) {
|
|
24
|
-
const error = new Error(message);
|
|
25
|
-
error.code = code;
|
|
26
|
-
return error;
|
|
27
|
-
}
|
|
28
|
-
function getUtf8ByteLength(input) {
|
|
29
|
-
if ("u" > typeof Buffer) return Buffer.byteLength(input);
|
|
30
|
-
return new TextEncoder().encode(input).length;
|
|
31
|
-
}
|
|
32
|
-
function normalizeRuntimeSignalOrigin(value) {
|
|
33
|
-
if ('string' != typeof value || 0 === value.trim().length) return;
|
|
34
|
-
try {
|
|
35
|
-
return new URL(value).origin;
|
|
36
|
-
} catch (_error) {
|
|
37
|
-
return;
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
function normalizeRuntimeSignalAppName(payload) {
|
|
41
|
-
if ('string' != typeof payload.appName) return 'unknown';
|
|
42
|
-
const normalized = payload.appName.trim();
|
|
43
|
-
return normalized.length > 0 ? normalized : 'unknown';
|
|
44
|
-
}
|
|
45
|
-
function normalizeRuntimeSignalRuntimeDigest(payload) {
|
|
46
|
-
if ('string' == typeof payload.runtimeDigest && payload.runtimeDigest.trim()) return payload.runtimeDigest.trim();
|
|
47
|
-
const metadata = payload.metadata;
|
|
48
|
-
if (metadata && 'object' == typeof metadata && !Array.isArray(metadata) && 'string' == typeof metadata.runtimeDigest) {
|
|
49
|
-
const digest = String(metadata.runtimeDigest).trim();
|
|
50
|
-
if (digest) return digest;
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
function normalizeRuntimeFallbackSignalAuthConfig(configured) {
|
|
54
|
-
const headerName = 'string' == typeof configured?.headerName && configured.headerName.trim() ? configured.headerName.trim().toLowerCase() : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
|
|
55
|
-
const expectedFromEnv = 'string' == typeof configured?.expectedValueEnv && configured.expectedValueEnv.trim().length > 0 ? process.env[configured.expectedValueEnv.trim()] : void 0;
|
|
56
|
-
const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
|
|
57
|
-
const expectedValue = expectedFromConfig || expectedFromEnv;
|
|
58
|
-
const enabled = configured?.enabled === true;
|
|
59
|
-
if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled is true but no expected token is configured');
|
|
60
|
-
return {
|
|
61
|
-
enabled,
|
|
62
|
-
headerName,
|
|
63
|
-
expectedValue
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
function normalizeRequiredRuntimeFallbackSignalAuthConfig(configured) {
|
|
67
|
-
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');
|
|
68
|
-
try {
|
|
69
|
-
return normalizeRuntimeFallbackSignalAuthConfig({
|
|
70
|
-
...configured,
|
|
71
|
-
enabled: true
|
|
72
|
-
});
|
|
73
|
-
} catch (_error) {
|
|
74
|
-
throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] enabling the endpoint requires an auth token; configure auth.expectedValue or auth.expectedValueEnv');
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
function safeTokenEquals(candidate, expected) {
|
|
78
|
-
const candidateDigest = createHash('sha256').update(candidate).digest();
|
|
79
|
-
const expectedDigest = createHash('sha256').update(expected).digest();
|
|
80
|
-
return timingSafeEqual(candidateDigest, expectedDigest);
|
|
81
|
-
}
|
|
82
|
-
function enforceRuntimeFallbackSignalAuthToken(token, authConfig) {
|
|
83
|
-
if (!authConfig.enabled) return;
|
|
84
|
-
if (!token || !authConfig.expectedValue || !safeTokenEquals(token, authConfig.expectedValue)) throw createRuntimeSignalError('runtime fallback signal auth failed', 'UNAUTHORIZED');
|
|
85
|
-
}
|
|
86
|
-
function enforceRuntimeFallbackSignalAuth(c, runtimeSignalConfig) {
|
|
87
|
-
enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
|
|
88
|
-
}
|
|
89
|
-
function normalizeRuntimeFallbackTrustPolicy(configured) {
|
|
90
|
-
const allowedApps = Array.isArray(configured?.allowedApps) ? configured.allowedApps.map((item)=>'string' == typeof item ? item.trim() : '').filter(Boolean) : [];
|
|
91
|
-
const allowedEntryOrigins = Array.isArray(configured?.allowedEntryOrigins) ? configured.allowedEntryOrigins.map((item)=>normalizeRuntimeSignalOrigin(item)).filter((item)=>Boolean(item)) : [];
|
|
92
|
-
const expectedRuntimeDigestsRaw = configured?.expectedRuntimeDigests || {};
|
|
93
|
-
const expectedRuntimeDigests = {};
|
|
94
|
-
Object.entries(expectedRuntimeDigestsRaw).forEach(([appName, digest])=>{
|
|
95
|
-
if ('string' == typeof appName && appName.trim().length > 0 && 'string' == typeof digest && digest.trim().length > 0) expectedRuntimeDigests[appName.trim()] = digest.trim();
|
|
96
|
-
});
|
|
97
|
-
return {
|
|
98
|
-
allowedApps,
|
|
99
|
-
allowedEntryOrigins,
|
|
100
|
-
expectedRuntimeDigests,
|
|
101
|
-
enforceRuntimeDigest: configured?.enforceRuntimeDigest === true,
|
|
102
|
-
maxSignalsPerWindow: Math.max(1, Math.floor(configured?.maxSignalsPerWindow ?? DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW)),
|
|
103
|
-
windowMs: Math.max(1000, Math.floor(configured?.windowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS)),
|
|
104
|
-
dedupeWindowMs: Math.max(0, Math.floor(configured?.dedupeWindowMs ?? DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS))
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
function createRuntimeFallbackSignalRuntimeState() {
|
|
108
|
-
return {
|
|
109
|
-
rateLimitBySource: new Map(),
|
|
110
|
-
dedupeByFingerprint: new Map()
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
function cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy) {
|
|
114
|
-
const dedupeExpiryMs = Math.max(trustPolicy.dedupeWindowMs, trustPolicy.windowMs, 1000);
|
|
115
|
-
runtimeState.dedupeByFingerprint.forEach((lastSeenAt, fingerprint)=>{
|
|
116
|
-
if (now - lastSeenAt > dedupeExpiryMs) runtimeState.dedupeByFingerprint.delete(fingerprint);
|
|
117
|
-
});
|
|
118
|
-
runtimeState.rateLimitBySource.forEach((state, source)=>{
|
|
119
|
-
if (now - state.windowStartedAt > 2 * trustPolicy.windowMs) runtimeState.rateLimitBySource.delete(source);
|
|
120
|
-
});
|
|
121
|
-
}
|
|
122
|
-
function enforceRuntimeFallbackSignalTrustPolicy(payload, runtimeSignalContext, source = {}) {
|
|
123
|
-
const { trustPolicy, runtimeState } = runtimeSignalContext;
|
|
124
|
-
const now = Date.now();
|
|
125
|
-
cleanupRuntimeFallbackSignalRuntimeState(now, runtimeState, trustPolicy);
|
|
126
|
-
const appName = normalizeRuntimeSignalAppName(payload);
|
|
127
|
-
const entryOrigin = normalizeRuntimeSignalOrigin(payload.entry);
|
|
128
|
-
const runtimeDigest = normalizeRuntimeSignalRuntimeDigest(payload);
|
|
129
|
-
if (trustPolicy.allowedApps.length > 0 && !trustPolicy.allowedApps.includes(appName)) throw createRuntimeSignalError(`runtime fallback signal app "${appName}" is not trusted`, 'UNTRUSTED_SOURCE');
|
|
130
|
-
if (trustPolicy.allowedEntryOrigins.length > 0) {
|
|
131
|
-
if (!entryOrigin || !trustPolicy.allowedEntryOrigins.includes(entryOrigin)) throw createRuntimeSignalError(`runtime fallback signal entry origin "${entryOrigin || 'unknown'}" is not trusted`, 'UNTRUSTED_SOURCE');
|
|
132
|
-
}
|
|
133
|
-
const expectedDigest = trustPolicy.expectedRuntimeDigests[appName];
|
|
134
|
-
if (expectedDigest && runtimeDigest !== expectedDigest) throw createRuntimeSignalError(`runtime fallback runtimeDigest mismatch for app "${appName}"`, 'UNTRUSTED_SOURCE');
|
|
135
|
-
if (trustPolicy.enforceRuntimeDigest && !runtimeDigest) throw createRuntimeSignalError(`runtime fallback signal for app "${appName}" is missing runtimeDigest`, 'UNTRUSTED_SOURCE');
|
|
136
|
-
const dedupeFingerprint = JSON.stringify({
|
|
137
|
-
appName,
|
|
138
|
-
entryOrigin: entryOrigin || 'unknown',
|
|
139
|
-
reason: payload.reason || 'runtime_fallback',
|
|
140
|
-
phase: payload.phase || 'unknown',
|
|
141
|
-
runtimeDigest: runtimeDigest || 'unknown'
|
|
142
|
-
});
|
|
143
|
-
const dedupeWindowMs = trustPolicy.dedupeWindowMs;
|
|
144
|
-
if (dedupeWindowMs > 0) {
|
|
145
|
-
const lastSeenAt = runtimeState.dedupeByFingerprint.get(dedupeFingerprint);
|
|
146
|
-
runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
|
|
147
|
-
if ('number' == typeof lastSeenAt && now - lastSeenAt <= dedupeWindowMs) return {
|
|
148
|
-
deduped: true
|
|
149
|
-
};
|
|
150
|
-
} else runtimeState.dedupeByFingerprint.set(dedupeFingerprint, now);
|
|
151
|
-
const remoteAddress = source.remoteAddress?.trim();
|
|
152
|
-
const sourceKey = remoteAddress || 'unknown-remote';
|
|
153
|
-
const rateState = runtimeState.rateLimitBySource.get(sourceKey);
|
|
154
|
-
if (!rateState || now - rateState.windowStartedAt > trustPolicy.windowMs) runtimeState.rateLimitBySource.set(sourceKey, {
|
|
155
|
-
count: 1,
|
|
156
|
-
windowStartedAt: now
|
|
157
|
-
});
|
|
158
|
-
else {
|
|
159
|
-
if (rateState.count >= trustPolicy.maxSignalsPerWindow) throw createRuntimeSignalError(`runtime fallback signal rate-limited for source "${sourceKey}"`, 'RATE_LIMITED');
|
|
160
|
-
rateState.count += 1;
|
|
161
|
-
}
|
|
162
|
-
return {
|
|
163
|
-
deduped: false
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
async function parseRuntimeFallbackSignalPayload(c, maxBodyBytes) {
|
|
167
|
-
const contentLengthHeader = c.req.header('content-length');
|
|
168
|
-
if (contentLengthHeader) {
|
|
169
|
-
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
|
170
|
-
if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
|
|
171
|
-
}
|
|
172
|
-
const rawBody = await c.req.raw.text();
|
|
173
|
-
const payload = parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes);
|
|
174
|
-
return {
|
|
175
|
-
rawBody,
|
|
176
|
-
payload
|
|
177
|
-
};
|
|
178
|
-
}
|
|
179
|
-
function parseRuntimeFallbackSignalPayloadFromRawBody(rawBody, maxBodyBytes) {
|
|
180
|
-
if (!rawBody || 0 === rawBody.trim().length) throw createRuntimeSignalError('runtime fallback signal body is empty', 'INVALID_PAYLOAD');
|
|
181
|
-
if (getUtf8ByteLength(rawBody) > maxBodyBytes) throw createRuntimeSignalError('runtime fallback signal payload too large', 'PAYLOAD_TOO_LARGE');
|
|
182
|
-
let payload;
|
|
183
|
-
try {
|
|
184
|
-
payload = JSON.parse(rawBody);
|
|
185
|
-
} catch (_error) {
|
|
186
|
-
throw createRuntimeSignalError('runtime fallback signal body must be valid JSON', 'INVALID_PAYLOAD');
|
|
187
|
-
}
|
|
188
|
-
if (!payload || 'object' != typeof payload || Array.isArray(payload)) throw createRuntimeSignalError('runtime fallback signal body must be a JSON object', 'INVALID_PAYLOAD');
|
|
189
|
-
return payload;
|
|
190
|
-
}
|
|
191
|
-
function getRuntimeSignalErrorStatusCode(signalError) {
|
|
192
|
-
if ('PAYLOAD_TOO_LARGE' === signalError.code) return 413;
|
|
193
|
-
if ('INVALID_PAYLOAD' === signalError.code) return 400;
|
|
194
|
-
if ('UNAUTHORIZED' === signalError.code) return 401;
|
|
195
|
-
if ('RATE_LIMITED' === signalError.code) return 429;
|
|
196
|
-
if ('UNTRUSTED_SOURCE' === signalError.code) return 403;
|
|
197
|
-
return 500;
|
|
198
|
-
}
|
|
199
|
-
async function persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
|
|
200
|
-
const now = Date.now();
|
|
201
|
-
const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
|
|
202
|
-
const snapshot = await gateSnapshotStore.readSnapshot() || {};
|
|
203
|
-
const existingGates = snapshot.gates && 'object' == typeof snapshot.gates ? snapshot.gates : {};
|
|
204
|
-
const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
|
|
205
|
-
const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
|
|
206
|
-
const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
|
|
207
|
-
const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
|
|
208
|
-
snapshot.schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
|
|
209
|
-
snapshot.updatedAt = now;
|
|
210
|
-
snapshot.gates = {
|
|
211
|
-
...existingGates,
|
|
212
|
-
[runtimeSignalConfig.gateName]: {
|
|
213
|
-
passed: false,
|
|
214
|
-
reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
|
|
215
|
-
updatedAt: now,
|
|
216
|
-
expiresAt: now + runtimeSignalConfig.failureHoldMs,
|
|
217
|
-
source: 'runtime-mf-fallback-signal',
|
|
218
|
-
metadata: payload
|
|
219
|
-
}
|
|
220
|
-
};
|
|
221
|
-
await gateSnapshotStore.writeSnapshot(snapshot);
|
|
222
|
-
}
|
|
223
|
-
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 };
|
|
2
|
+
export * from "./runtime-fallback-signal/index.mjs";
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { evaluateCanaryHealth } from "./canaryEvaluation.mjs";
|
|
3
|
+
import { clamp } from "./envelope.mjs";
|
|
4
|
+
class TelemetryCanaryOrchestrator {
|
|
5
|
+
setRequiredContractGates(gates) {
|
|
6
|
+
this.requiredContractGates = Array.from(new Set(gates.map((item)=>item.trim()).filter(Boolean)));
|
|
7
|
+
}
|
|
8
|
+
addRequiredContractGate(name) {
|
|
9
|
+
const normalizedName = name.trim();
|
|
10
|
+
if (!normalizedName) return;
|
|
11
|
+
if (!this.requiredContractGates.includes(normalizedName)) this.requiredContractGates.push(normalizedName);
|
|
12
|
+
}
|
|
13
|
+
setContractGate(name, passed, reason) {
|
|
14
|
+
this.contractGates.set(name, {
|
|
15
|
+
name,
|
|
16
|
+
passed,
|
|
17
|
+
reason,
|
|
18
|
+
updatedAt: Date.now()
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
setContractGates(gates) {
|
|
22
|
+
for (const [name, value] of Object.entries(gates)){
|
|
23
|
+
if ('boolean' == typeof value) {
|
|
24
|
+
this.setContractGate(name, value);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
this.setContractGate(name, value.passed, value.reason);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
resetToCanary() {
|
|
31
|
+
this.state = 'canary';
|
|
32
|
+
this.consecutiveHealthy = 0;
|
|
33
|
+
this.consecutiveFailures = 0;
|
|
34
|
+
}
|
|
35
|
+
collectFailures() {
|
|
36
|
+
const queueStats = this.registry.getQueueStats();
|
|
37
|
+
const unhealthyExporterCount = this.registry.getExporterHealth().filter((item)=>!item.healthy).length;
|
|
38
|
+
return evaluateCanaryHealth({
|
|
39
|
+
queueStats,
|
|
40
|
+
unhealthyExporterCount,
|
|
41
|
+
requiredContractGates: this.requiredContractGates,
|
|
42
|
+
contractGates: this.contractGates
|
|
43
|
+
}, {
|
|
44
|
+
maxQueueUtilization: this.maxQueueUtilization,
|
|
45
|
+
maxTotalDropped: this.maxTotalDropped,
|
|
46
|
+
maxUnhealthyExporters: this.maxUnhealthyExporters
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
evaluate() {
|
|
50
|
+
const now = Date.now();
|
|
51
|
+
const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
|
|
52
|
+
let action = 'hold';
|
|
53
|
+
if (failures.length > 0) {
|
|
54
|
+
this.consecutiveHealthy = 0;
|
|
55
|
+
this.consecutiveFailures += 1;
|
|
56
|
+
if ('rolled_back' !== this.state && this.consecutiveFailures >= this.rollbackConsecutiveFailures) {
|
|
57
|
+
this.state = 'rolled_back';
|
|
58
|
+
action = 'rollback';
|
|
59
|
+
}
|
|
60
|
+
} else {
|
|
61
|
+
this.consecutiveFailures = 0;
|
|
62
|
+
this.consecutiveHealthy += 1;
|
|
63
|
+
if ('canary' === this.state && this.consecutiveHealthy >= this.minConsecutiveHealthyEvaluations) {
|
|
64
|
+
this.state = 'promoted';
|
|
65
|
+
action = 'promote';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const decision = {
|
|
69
|
+
timestamp: now,
|
|
70
|
+
action,
|
|
71
|
+
state: this.state,
|
|
72
|
+
consecutiveHealthy: this.consecutiveHealthy,
|
|
73
|
+
consecutiveFailures: this.consecutiveFailures,
|
|
74
|
+
failures,
|
|
75
|
+
queueStats,
|
|
76
|
+
unhealthyExporterCount,
|
|
77
|
+
contractGates: Array.from(this.contractGates.values()).map((item)=>({
|
|
78
|
+
...item
|
|
79
|
+
}))
|
|
80
|
+
};
|
|
81
|
+
try {
|
|
82
|
+
this.onEvaluate?.(decision);
|
|
83
|
+
} catch (_error) {}
|
|
84
|
+
if ('promote' === action) try {
|
|
85
|
+
this.onPromote?.(decision);
|
|
86
|
+
} catch (_error) {}
|
|
87
|
+
if ('rollback' === action) try {
|
|
88
|
+
this.onRollback?.(decision);
|
|
89
|
+
} catch (_error) {}
|
|
90
|
+
return decision;
|
|
91
|
+
}
|
|
92
|
+
getStatusSnapshot() {
|
|
93
|
+
const now = Date.now();
|
|
94
|
+
const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
|
|
95
|
+
return {
|
|
96
|
+
timestamp: now,
|
|
97
|
+
state: this.state,
|
|
98
|
+
consecutiveHealthy: this.consecutiveHealthy,
|
|
99
|
+
consecutiveFailures: this.consecutiveFailures,
|
|
100
|
+
queueStats,
|
|
101
|
+
unhealthyExporterCount,
|
|
102
|
+
requiredContractGates: [
|
|
103
|
+
...this.requiredContractGates
|
|
104
|
+
],
|
|
105
|
+
contractGates: Array.from(this.contractGates.values()).map((item)=>({
|
|
106
|
+
...item
|
|
107
|
+
})),
|
|
108
|
+
failurePreview: failures
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
start() {
|
|
112
|
+
if (this.evaluationTimer) return;
|
|
113
|
+
this.evaluationTimer = setInterval(()=>{
|
|
114
|
+
this.evaluate();
|
|
115
|
+
}, this.evaluationIntervalMs);
|
|
116
|
+
if ('function' == typeof this.evaluationTimer.unref) this.evaluationTimer.unref();
|
|
117
|
+
}
|
|
118
|
+
stop() {
|
|
119
|
+
if (this.evaluationTimer) {
|
|
120
|
+
clearInterval(this.evaluationTimer);
|
|
121
|
+
this.evaluationTimer = void 0;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
constructor(options){
|
|
125
|
+
this.requiredContractGates = [];
|
|
126
|
+
this.contractGates = new Map();
|
|
127
|
+
this.state = 'canary';
|
|
128
|
+
this.consecutiveHealthy = 0;
|
|
129
|
+
this.consecutiveFailures = 0;
|
|
130
|
+
this.registry = options.registry;
|
|
131
|
+
this.evaluationIntervalMs = Math.max(250, options.evaluationIntervalMs ?? 15000);
|
|
132
|
+
this.minConsecutiveHealthyEvaluations = Math.max(1, options.minConsecutiveHealthyEvaluations ?? 3);
|
|
133
|
+
this.rollbackConsecutiveFailures = Math.max(1, options.rollbackConsecutiveFailures ?? 2);
|
|
134
|
+
this.maxQueueUtilization = clamp(options.maxQueueUtilization ?? 0.8, 0, 1);
|
|
135
|
+
this.maxTotalDropped = Math.max(0, options.maxTotalDropped ?? 0);
|
|
136
|
+
this.maxUnhealthyExporters = Math.max(0, options.maxUnhealthyExporters ?? 0);
|
|
137
|
+
this.setRequiredContractGates(options.requiredContractGates || []);
|
|
138
|
+
this.onEvaluate = options.onEvaluate;
|
|
139
|
+
this.onPromote = options.onPromote;
|
|
140
|
+
this.onRollback = options.onRollback;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
export { TelemetryCanaryOrchestrator };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const evaluateCanaryHealth = (metrics, thresholds)=>{
|
|
3
|
+
const failures = [];
|
|
4
|
+
const { queueStats, unhealthyExporterCount } = metrics;
|
|
5
|
+
if (queueStats.utilization > thresholds.maxQueueUtilization) failures.push({
|
|
6
|
+
reason: 'queue_utilization',
|
|
7
|
+
threshold: thresholds.maxQueueUtilization,
|
|
8
|
+
value: queueStats.utilization
|
|
9
|
+
});
|
|
10
|
+
if (queueStats.totalDropped > thresholds.maxTotalDropped) failures.push({
|
|
11
|
+
reason: 'queue_dropped',
|
|
12
|
+
threshold: thresholds.maxTotalDropped,
|
|
13
|
+
value: queueStats.totalDropped
|
|
14
|
+
});
|
|
15
|
+
if (unhealthyExporterCount > thresholds.maxUnhealthyExporters) failures.push({
|
|
16
|
+
reason: 'unhealthy_exporter',
|
|
17
|
+
threshold: thresholds.maxUnhealthyExporters,
|
|
18
|
+
value: unhealthyExporterCount
|
|
19
|
+
});
|
|
20
|
+
for (const gateName of metrics.requiredContractGates){
|
|
21
|
+
const gate = metrics.contractGates.get(gateName);
|
|
22
|
+
if (!gate) {
|
|
23
|
+
failures.push({
|
|
24
|
+
reason: 'contract_gate_missing',
|
|
25
|
+
gate: gateName,
|
|
26
|
+
message: `Contract gate "${gateName}" is missing`
|
|
27
|
+
});
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (!gate.passed) failures.push({
|
|
31
|
+
reason: 'contract_gate_failed',
|
|
32
|
+
gate: gateName,
|
|
33
|
+
message: gate.reason || `Contract gate "${gateName}" is not passing`
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
failures,
|
|
38
|
+
queueStats,
|
|
39
|
+
unhealthyExporterCount
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
export { evaluateCanaryHealth };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "../contract-gate-snapshot-store/index.mjs";
|
|
3
|
+
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";
|
|
4
|
+
import { TelemetryCanaryOrchestrator } from "../telemetryCore.mjs";
|
|
5
|
+
function emitCanaryDecisionMetric(registry, decision, action) {
|
|
6
|
+
try {
|
|
7
|
+
registry.enqueueMetric({
|
|
8
|
+
name: `telemetry.canary.${action}`,
|
|
9
|
+
value: 1,
|
|
10
|
+
unit: 'count',
|
|
11
|
+
tags: {
|
|
12
|
+
action,
|
|
13
|
+
state: decision.state,
|
|
14
|
+
failures: String(decision.failures.length)
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
} catch (_error) {}
|
|
18
|
+
}
|
|
19
|
+
const setupTelemetryCanary = ({ registry, appDirectory, canaryConfig })=>{
|
|
20
|
+
if (!canaryConfig?.enabled) return {};
|
|
21
|
+
const contractGates = canaryConfig.contractGates;
|
|
22
|
+
const canaryOrchestrator = new TelemetryCanaryOrchestrator({
|
|
23
|
+
registry,
|
|
24
|
+
evaluationIntervalMs: canaryConfig.evaluationIntervalMs,
|
|
25
|
+
minConsecutiveHealthyEvaluations: canaryConfig.minConsecutiveHealthyEvaluations,
|
|
26
|
+
rollbackConsecutiveFailures: canaryConfig.rollbackConsecutiveFailures,
|
|
27
|
+
maxQueueUtilization: canaryConfig.maxQueueUtilization,
|
|
28
|
+
maxTotalDropped: canaryConfig.maxTotalDropped,
|
|
29
|
+
maxUnhealthyExporters: canaryConfig.maxUnhealthyExporters,
|
|
30
|
+
requiredContractGates: Object.keys(contractGates || {}),
|
|
31
|
+
onPromote: (decision)=>{
|
|
32
|
+
emitCanaryDecisionMetric(registry, decision, 'promote');
|
|
33
|
+
},
|
|
34
|
+
onRollback: (decision)=>{
|
|
35
|
+
emitCanaryDecisionMetric(registry, decision, 'rollback');
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
if (contractGates) canaryOrchestrator.setContractGates(contractGates);
|
|
39
|
+
let gateSnapshotStorePromise;
|
|
40
|
+
let runtimeFallbackSignalConfig;
|
|
41
|
+
const autopilotEnabled = canaryConfig.autopilot?.enabled ?? true;
|
|
42
|
+
if (autopilotEnabled) {
|
|
43
|
+
const gateSnapshotPath = resolveContractGateSnapshotPath(appDirectory, canaryConfig.autopilot?.gateSnapshotPath);
|
|
44
|
+
gateSnapshotStorePromise = resolveContractGateSnapshotStore({
|
|
45
|
+
appDirectory,
|
|
46
|
+
gateSnapshotPath: gateSnapshotPath || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
|
|
47
|
+
stateStore: canaryConfig.autopilot?.stateStore
|
|
48
|
+
});
|
|
49
|
+
const runtimeSignalConfig = canaryConfig.autopilot?.runtimeFallbackSignal;
|
|
50
|
+
const runtimeSignalEnabled = runtimeSignalConfig?.enabled === true;
|
|
51
|
+
if (runtimeSignalEnabled && gateSnapshotStorePromise) runtimeFallbackSignalConfig = {
|
|
52
|
+
endpoint: resolveRuntimeFallbackSignalEndpoint(runtimeSignalConfig?.endpoint),
|
|
53
|
+
gateName: runtimeSignalConfig?.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
|
|
54
|
+
gateSnapshotStore: gateSnapshotStorePromise,
|
|
55
|
+
failureHoldMs: Math.max(1000, runtimeSignalConfig?.failureHoldMs ?? DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS),
|
|
56
|
+
maxBodyBytes: Math.max(512, runtimeSignalConfig?.maxBodyBytes ?? DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES),
|
|
57
|
+
auth: normalizeRequiredRuntimeFallbackSignalAuthConfig(runtimeSignalConfig?.auth),
|
|
58
|
+
trustPolicy: normalizeRuntimeFallbackTrustPolicy(runtimeSignalConfig?.trustPolicy),
|
|
59
|
+
runtimeState: createRuntimeFallbackSignalRuntimeState()
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const runtimeStatusAuthConfig = runtimeFallbackSignalConfig?.auth ?? normalizeRuntimeFallbackSignalAuthConfig(canaryConfig.autopilot?.runtimeFallbackSignal?.auth);
|
|
63
|
+
return {
|
|
64
|
+
canaryOrchestrator,
|
|
65
|
+
gateSnapshotStorePromise,
|
|
66
|
+
runtimeFallbackSignalConfig,
|
|
67
|
+
runtimeStatusAuthConfig
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
export { setupTelemetryCanary };
|