@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.6 → 3.5.0-ultramodern.75

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 (179) hide show
  1. package/dist/cjs/contract-gate-snapshot-normalization.js +122 -0
  2. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +133 -0
  4. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  5. package/dist/cjs/contract-gate-snapshot-store/resolve.js +124 -0
  6. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  7. package/dist/cjs/contractGateAutopilot.js +22 -70
  8. package/dist/cjs/index.js +6 -25
  9. package/dist/cjs/mfCache.js +2 -2
  10. package/dist/cjs/module-federation-css/collector.js +79 -0
  11. package/dist/cjs/module-federation-css/index.js +55 -0
  12. package/dist/cjs/module-federation-css/manifest.js +129 -0
  13. package/dist/cjs/module-federation-css/plugin.js +71 -0
  14. package/dist/cjs/module-federation-css/remote.js +133 -0
  15. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  16. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  17. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  18. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  19. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  20. package/dist/cjs/telemetry/canary.js +180 -0
  21. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  22. package/dist/cjs/telemetry/canarySetup.js +107 -0
  23. package/dist/cjs/telemetry/envelope.js +223 -0
  24. package/dist/cjs/telemetry/exporters.js +148 -0
  25. package/dist/cjs/telemetry/lifecycle.js +98 -0
  26. package/dist/cjs/telemetry/metrics.js +115 -0
  27. package/dist/cjs/telemetry/plugin.js +185 -0
  28. package/dist/cjs/telemetry/registry.js +296 -0
  29. package/dist/cjs/telemetry/registryTypes.js +46 -0
  30. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  31. package/dist/cjs/telemetry.js +32 -343
  32. package/dist/cjs/telemetryCore.js +14 -767
  33. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  34. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  35. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  36. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  37. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  38. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  39. package/dist/esm/contractGateAutopilot.mjs +21 -69
  40. package/dist/esm/index.mjs +1 -2
  41. package/dist/esm/mfCache.mjs +2 -2
  42. package/dist/esm/module-federation-css/collector.mjs +38 -0
  43. package/dist/esm/module-federation-css/index.mjs +4 -0
  44. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  45. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  46. package/dist/esm/module-federation-css/remote.mjs +92 -0
  47. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  48. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  49. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  50. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  51. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  52. package/dist/esm/telemetry/canary.mjs +142 -0
  53. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  54. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  55. package/dist/esm/telemetry/envelope.mjs +164 -0
  56. package/dist/esm/telemetry/exporters.mjs +104 -0
  57. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  58. package/dist/esm/telemetry/metrics.mjs +77 -0
  59. package/dist/esm/telemetry/plugin.mjs +87 -0
  60. package/dist/esm/telemetry/registry.mjs +258 -0
  61. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  62. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  63. package/dist/esm/telemetry.mjs +1 -275
  64. package/dist/esm/telemetryCore.mjs +6 -759
  65. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  69. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  70. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  71. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  72. package/dist/esm-node/index.mjs +1 -2
  73. package/dist/esm-node/mfCache.mjs +2 -2
  74. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  75. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  76. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  77. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  78. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  79. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  80. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  81. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  82. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  83. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  84. package/dist/esm-node/telemetry/canary.mjs +143 -0
  85. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  86. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  87. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  88. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  89. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  90. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  91. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  92. package/dist/esm-node/telemetry/registry.mjs +259 -0
  93. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  94. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  95. package/dist/esm-node/telemetry.mjs +1 -275
  96. package/dist/esm-node/telemetryCore.mjs +6 -759
  97. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  98. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  99. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  100. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  101. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  102. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  103. package/dist/types/contractGateAutopilot.d.ts +3 -6
  104. package/dist/types/index.d.ts +1 -2
  105. package/dist/types/module-federation-css/collector.d.ts +25 -0
  106. package/dist/types/module-federation-css/index.d.ts +8 -0
  107. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  108. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  109. package/dist/types/module-federation-css/remote.d.ts +20 -0
  110. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  111. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  112. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  113. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  114. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  115. package/dist/types/telemetry/canary.d.ts +85 -0
  116. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  117. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  118. package/dist/types/telemetry/envelope.d.ts +55 -0
  119. package/dist/types/telemetry/exporters.d.ts +12 -0
  120. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  121. package/dist/types/telemetry/metrics.d.ts +3 -0
  122. package/dist/types/telemetry/plugin.d.ts +12 -0
  123. package/dist/types/telemetry/registry.d.ts +69 -0
  124. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  125. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  126. package/dist/types/telemetry.d.ts +1 -12
  127. package/dist/types/telemetryCore.d.ts +6 -257
  128. package/package.json +11 -13
  129. package/src/contract-gate-snapshot-normalization.ts +155 -0
  130. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  131. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  132. package/src/contract-gate-snapshot-store/index.ts +20 -0
  133. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  134. package/src/contract-gate-snapshot-store/types.ts +64 -0
  135. package/src/contractGateAutopilot.ts +39 -131
  136. package/src/index.ts +1 -17
  137. package/src/mfCache.ts +3 -1
  138. package/src/module-federation-css/collector.ts +82 -0
  139. package/src/module-federation-css/index.ts +14 -0
  140. package/src/module-federation-css/manifest.ts +163 -0
  141. package/src/module-federation-css/plugin.ts +86 -0
  142. package/src/module-federation-css/remote.ts +165 -0
  143. package/src/runtime-fallback-signal/index.ts +34 -0
  144. package/src/runtime-fallback-signal/model.ts +230 -0
  145. package/src/runtime-fallback-signal/resolver.ts +304 -0
  146. package/src/runtime-fallback-signal/store.ts +78 -0
  147. package/src/runtimeFallbackSignal.ts +1 -584
  148. package/src/telemetry/canary.ts +291 -0
  149. package/src/telemetry/canaryEvaluation.ts +83 -0
  150. package/src/telemetry/canarySetup.ts +160 -0
  151. package/src/telemetry/envelope.ts +277 -0
  152. package/src/telemetry/exporters.ts +165 -0
  153. package/src/telemetry/lifecycle.ts +138 -0
  154. package/src/telemetry/metrics.ts +141 -0
  155. package/src/telemetry/plugin.ts +197 -0
  156. package/src/telemetry/registry.ts +424 -0
  157. package/src/telemetry/registryTypes.ts +63 -0
  158. package/src/telemetry/runtimeEndpoints.ts +172 -0
  159. package/src/telemetry.ts +1 -554
  160. package/src/telemetryCore.ts +34 -1332
  161. package/tests/contractGateAutopilot.test.ts +205 -0
  162. package/tests/contractGateSnapshotStore.test.ts +54 -1
  163. package/tests/helpers.ts +1 -0
  164. package/tests/moduleFederationCss.test.ts +1 -1
  165. package/tests/registration.test.ts +1 -1
  166. package/tests/telemetry.test.ts +51 -0
  167. package/tests/telemetryAutopilot.test.ts +141 -0
  168. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  169. package/tests/telemetryLifecycle.test.ts +253 -2
  170. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  171. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  172. package/dist/cjs/moduleFederationCss.js +0 -285
  173. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  174. package/dist/esm/moduleFederationCss.mjs +0 -225
  175. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  176. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  177. package/dist/types/moduleFederationCss.d.ts +0 -87
  178. package/src/contractGateSnapshotStore.ts +0 -420
  179. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,142 @@
1
+ import { evaluateCanaryHealth } from "./canaryEvaluation.mjs";
2
+ import { clamp } from "./envelope.mjs";
3
+ class TelemetryCanaryOrchestrator {
4
+ setRequiredContractGates(gates) {
5
+ this.requiredContractGates = Array.from(new Set(gates.map((item)=>item.trim()).filter(Boolean)));
6
+ }
7
+ addRequiredContractGate(name) {
8
+ const normalizedName = name.trim();
9
+ if (!normalizedName) return;
10
+ if (!this.requiredContractGates.includes(normalizedName)) this.requiredContractGates.push(normalizedName);
11
+ }
12
+ setContractGate(name, passed, reason) {
13
+ this.contractGates.set(name, {
14
+ name,
15
+ passed,
16
+ reason,
17
+ updatedAt: Date.now()
18
+ });
19
+ }
20
+ setContractGates(gates) {
21
+ for (const [name, value] of Object.entries(gates)){
22
+ if ('boolean' == typeof value) {
23
+ this.setContractGate(name, value);
24
+ continue;
25
+ }
26
+ this.setContractGate(name, value.passed, value.reason);
27
+ }
28
+ }
29
+ resetToCanary() {
30
+ this.state = 'canary';
31
+ this.consecutiveHealthy = 0;
32
+ this.consecutiveFailures = 0;
33
+ }
34
+ collectFailures() {
35
+ const queueStats = this.registry.getQueueStats();
36
+ const unhealthyExporterCount = this.registry.getExporterHealth().filter((item)=>!item.healthy).length;
37
+ return evaluateCanaryHealth({
38
+ queueStats,
39
+ unhealthyExporterCount,
40
+ requiredContractGates: this.requiredContractGates,
41
+ contractGates: this.contractGates
42
+ }, {
43
+ maxQueueUtilization: this.maxQueueUtilization,
44
+ maxTotalDropped: this.maxTotalDropped,
45
+ maxUnhealthyExporters: this.maxUnhealthyExporters
46
+ });
47
+ }
48
+ evaluate() {
49
+ const now = Date.now();
50
+ const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
51
+ let action = 'hold';
52
+ if (failures.length > 0) {
53
+ this.consecutiveHealthy = 0;
54
+ this.consecutiveFailures += 1;
55
+ if ('rolled_back' !== this.state && this.consecutiveFailures >= this.rollbackConsecutiveFailures) {
56
+ this.state = 'rolled_back';
57
+ action = 'rollback';
58
+ }
59
+ } else {
60
+ this.consecutiveFailures = 0;
61
+ this.consecutiveHealthy += 1;
62
+ if ('canary' === this.state && this.consecutiveHealthy >= this.minConsecutiveHealthyEvaluations) {
63
+ this.state = 'promoted';
64
+ action = 'promote';
65
+ }
66
+ }
67
+ const decision = {
68
+ timestamp: now,
69
+ action,
70
+ state: this.state,
71
+ consecutiveHealthy: this.consecutiveHealthy,
72
+ consecutiveFailures: this.consecutiveFailures,
73
+ failures,
74
+ queueStats,
75
+ unhealthyExporterCount,
76
+ contractGates: Array.from(this.contractGates.values()).map((item)=>({
77
+ ...item
78
+ }))
79
+ };
80
+ try {
81
+ this.onEvaluate?.(decision);
82
+ } catch (_error) {}
83
+ if ('promote' === action) try {
84
+ this.onPromote?.(decision);
85
+ } catch (_error) {}
86
+ if ('rollback' === action) try {
87
+ this.onRollback?.(decision);
88
+ } catch (_error) {}
89
+ return decision;
90
+ }
91
+ getStatusSnapshot() {
92
+ const now = Date.now();
93
+ const { failures, queueStats, unhealthyExporterCount } = this.collectFailures();
94
+ return {
95
+ timestamp: now,
96
+ state: this.state,
97
+ consecutiveHealthy: this.consecutiveHealthy,
98
+ consecutiveFailures: this.consecutiveFailures,
99
+ queueStats,
100
+ unhealthyExporterCount,
101
+ requiredContractGates: [
102
+ ...this.requiredContractGates
103
+ ],
104
+ contractGates: Array.from(this.contractGates.values()).map((item)=>({
105
+ ...item
106
+ })),
107
+ failurePreview: failures
108
+ };
109
+ }
110
+ start() {
111
+ if (this.evaluationTimer) return;
112
+ this.evaluationTimer = setInterval(()=>{
113
+ this.evaluate();
114
+ }, this.evaluationIntervalMs);
115
+ if ('function' == typeof this.evaluationTimer.unref) this.evaluationTimer.unref();
116
+ }
117
+ stop() {
118
+ if (this.evaluationTimer) {
119
+ clearInterval(this.evaluationTimer);
120
+ this.evaluationTimer = void 0;
121
+ }
122
+ }
123
+ constructor(options){
124
+ this.requiredContractGates = [];
125
+ this.contractGates = new Map();
126
+ this.state = 'canary';
127
+ this.consecutiveHealthy = 0;
128
+ this.consecutiveFailures = 0;
129
+ this.registry = options.registry;
130
+ this.evaluationIntervalMs = Math.max(250, options.evaluationIntervalMs ?? 15000);
131
+ this.minConsecutiveHealthyEvaluations = Math.max(1, options.minConsecutiveHealthyEvaluations ?? 3);
132
+ this.rollbackConsecutiveFailures = Math.max(1, options.rollbackConsecutiveFailures ?? 2);
133
+ this.maxQueueUtilization = clamp(options.maxQueueUtilization ?? 0.8, 0, 1);
134
+ this.maxTotalDropped = Math.max(0, options.maxTotalDropped ?? 0);
135
+ this.maxUnhealthyExporters = Math.max(0, options.maxUnhealthyExporters ?? 0);
136
+ this.setRequiredContractGates(options.requiredContractGates || []);
137
+ this.onEvaluate = options.onEvaluate;
138
+ this.onPromote = options.onPromote;
139
+ this.onRollback = options.onRollback;
140
+ }
141
+ }
142
+ export { TelemetryCanaryOrchestrator };
@@ -0,0 +1,41 @@
1
+ const evaluateCanaryHealth = (metrics, thresholds)=>{
2
+ const failures = [];
3
+ const { queueStats, unhealthyExporterCount } = metrics;
4
+ if (queueStats.utilization > thresholds.maxQueueUtilization) failures.push({
5
+ reason: 'queue_utilization',
6
+ threshold: thresholds.maxQueueUtilization,
7
+ value: queueStats.utilization
8
+ });
9
+ if (queueStats.totalDropped > thresholds.maxTotalDropped) failures.push({
10
+ reason: 'queue_dropped',
11
+ threshold: thresholds.maxTotalDropped,
12
+ value: queueStats.totalDropped
13
+ });
14
+ if (unhealthyExporterCount > thresholds.maxUnhealthyExporters) failures.push({
15
+ reason: 'unhealthy_exporter',
16
+ threshold: thresholds.maxUnhealthyExporters,
17
+ value: unhealthyExporterCount
18
+ });
19
+ for (const gateName of metrics.requiredContractGates){
20
+ const gate = metrics.contractGates.get(gateName);
21
+ if (!gate) {
22
+ failures.push({
23
+ reason: 'contract_gate_missing',
24
+ gate: gateName,
25
+ message: `Contract gate "${gateName}" is missing`
26
+ });
27
+ continue;
28
+ }
29
+ if (!gate.passed) failures.push({
30
+ reason: 'contract_gate_failed',
31
+ gate: gateName,
32
+ message: gate.reason || `Contract gate "${gateName}" is not passing`
33
+ });
34
+ }
35
+ return {
36
+ failures,
37
+ queueStats,
38
+ unhealthyExporterCount
39
+ };
40
+ };
41
+ export { evaluateCanaryHealth };
@@ -0,0 +1,69 @@
1
+ import { DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "../contract-gate-snapshot-store/index.mjs";
2
+ import { DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, createRuntimeFallbackSignalRuntimeState, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, resolveRuntimeFallbackSignalEndpoint } from "../runtimeFallbackSignal.mjs";
3
+ import { TelemetryCanaryOrchestrator } from "../telemetryCore.mjs";
4
+ function emitCanaryDecisionMetric(registry, decision, action) {
5
+ try {
6
+ registry.enqueueMetric({
7
+ name: `telemetry.canary.${action}`,
8
+ value: 1,
9
+ unit: 'count',
10
+ tags: {
11
+ action,
12
+ state: decision.state,
13
+ failures: String(decision.failures.length)
14
+ }
15
+ });
16
+ } catch (_error) {}
17
+ }
18
+ const setupTelemetryCanary = ({ registry, appDirectory, canaryConfig })=>{
19
+ if (!canaryConfig?.enabled) return {};
20
+ const contractGates = canaryConfig.contractGates;
21
+ const canaryOrchestrator = new TelemetryCanaryOrchestrator({
22
+ registry,
23
+ evaluationIntervalMs: canaryConfig.evaluationIntervalMs,
24
+ minConsecutiveHealthyEvaluations: canaryConfig.minConsecutiveHealthyEvaluations,
25
+ rollbackConsecutiveFailures: canaryConfig.rollbackConsecutiveFailures,
26
+ maxQueueUtilization: canaryConfig.maxQueueUtilization,
27
+ maxTotalDropped: canaryConfig.maxTotalDropped,
28
+ maxUnhealthyExporters: canaryConfig.maxUnhealthyExporters,
29
+ requiredContractGates: Object.keys(contractGates || {}),
30
+ onPromote: (decision)=>{
31
+ emitCanaryDecisionMetric(registry, decision, 'promote');
32
+ },
33
+ onRollback: (decision)=>{
34
+ emitCanaryDecisionMetric(registry, decision, 'rollback');
35
+ }
36
+ });
37
+ if (contractGates) canaryOrchestrator.setContractGates(contractGates);
38
+ let gateSnapshotStorePromise;
39
+ let runtimeFallbackSignalConfig;
40
+ const autopilotEnabled = canaryConfig.autopilot?.enabled ?? true;
41
+ if (autopilotEnabled) {
42
+ const gateSnapshotPath = resolveContractGateSnapshotPath(appDirectory, canaryConfig.autopilot?.gateSnapshotPath);
43
+ gateSnapshotStorePromise = resolveContractGateSnapshotStore({
44
+ appDirectory,
45
+ gateSnapshotPath: gateSnapshotPath || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
46
+ stateStore: canaryConfig.autopilot?.stateStore
47
+ });
48
+ const runtimeSignalConfig = canaryConfig.autopilot?.runtimeFallbackSignal;
49
+ const runtimeSignalEnabled = runtimeSignalConfig?.enabled === true;
50
+ if (runtimeSignalEnabled && gateSnapshotStorePromise) runtimeFallbackSignalConfig = {
51
+ endpoint: resolveRuntimeFallbackSignalEndpoint(runtimeSignalConfig?.endpoint),
52
+ gateName: runtimeSignalConfig?.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
53
+ gateSnapshotStore: gateSnapshotStorePromise,
54
+ failureHoldMs: Math.max(1000, runtimeSignalConfig?.failureHoldMs ?? DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS),
55
+ maxBodyBytes: Math.max(512, runtimeSignalConfig?.maxBodyBytes ?? DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES),
56
+ auth: normalizeRequiredRuntimeFallbackSignalAuthConfig(runtimeSignalConfig?.auth),
57
+ trustPolicy: normalizeRuntimeFallbackTrustPolicy(runtimeSignalConfig?.trustPolicy),
58
+ runtimeState: createRuntimeFallbackSignalRuntimeState()
59
+ };
60
+ }
61
+ const runtimeStatusAuthConfig = runtimeFallbackSignalConfig?.auth ?? normalizeRuntimeFallbackSignalAuthConfig(canaryConfig.autopilot?.runtimeFallbackSignal?.auth);
62
+ return {
63
+ canaryOrchestrator,
64
+ gateSnapshotStorePromise,
65
+ runtimeFallbackSignalConfig,
66
+ runtimeStatusAuthConfig
67
+ };
68
+ };
69
+ export { setupTelemetryCanary };
@@ -0,0 +1,164 @@
1
+ function buildDroppedEnvelope(context, droppedCount) {
2
+ return {
3
+ timestamp: Date.now(),
4
+ service: context.service,
5
+ module: context.module,
6
+ environment: context.environment,
7
+ signalType: 'metric',
8
+ name: 'telemetry.queue.dropped',
9
+ value: droppedCount,
10
+ unit: 'count',
11
+ tags: {
12
+ reason: 'queue_backpressure'
13
+ }
14
+ };
15
+ }
16
+ function buildQueueDepthEnvelope(context, queueDepth) {
17
+ return {
18
+ timestamp: Date.now(),
19
+ service: context.service,
20
+ module: context.module,
21
+ environment: context.environment,
22
+ signalType: 'metric',
23
+ name: 'telemetry.queue.depth',
24
+ value: queueDepth,
25
+ unit: 'count',
26
+ tags: {
27
+ capacity: String(context.maxQueueSize)
28
+ }
29
+ };
30
+ }
31
+ function buildQueueUtilizationEnvelope(context, queueDepth) {
32
+ return {
33
+ timestamp: Date.now(),
34
+ service: context.service,
35
+ module: context.module,
36
+ environment: context.environment,
37
+ signalType: 'metric',
38
+ name: 'telemetry.queue.utilization',
39
+ value: queueDepth / context.maxQueueSize,
40
+ unit: 'ratio',
41
+ tags: {
42
+ capacity: String(context.maxQueueSize)
43
+ }
44
+ };
45
+ }
46
+ function buildStartupProbeEnvelope(context) {
47
+ return {
48
+ timestamp: Date.now(),
49
+ service: context.service,
50
+ module: context.module,
51
+ environment: context.environment,
52
+ signalType: 'log',
53
+ name: 'telemetry.exporter.startup_probe',
54
+ level: 'info',
55
+ tags: {
56
+ phase: 'startup'
57
+ },
58
+ attributes: {
59
+ source: 'TelemetryRegistry'
60
+ }
61
+ };
62
+ }
63
+ function clamp(value, min, max) {
64
+ if (Number.isNaN(value)) return max;
65
+ return Math.max(min, Math.min(max, value));
66
+ }
67
+ function isRecord(value) {
68
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
69
+ }
70
+ function redactObject(value, redactionKeys) {
71
+ if (!isRecord(value)) return;
72
+ const output = {};
73
+ for (const [key, nested] of Object.entries(value)){
74
+ if (redactionKeys.has(key)) {
75
+ output[key] = '[REDACTED]';
76
+ continue;
77
+ }
78
+ if (Array.isArray(nested)) {
79
+ output[key] = nested.map((item)=>{
80
+ if (isRecord(item)) return redactObject(item, redactionKeys);
81
+ return item;
82
+ });
83
+ continue;
84
+ }
85
+ if (isRecord(nested)) {
86
+ output[key] = redactObject(nested, redactionKeys);
87
+ continue;
88
+ }
89
+ output[key] = nested;
90
+ }
91
+ return output;
92
+ }
93
+ function normalizeLabels(labels) {
94
+ if (!labels) return;
95
+ const normalized = {};
96
+ for (const [key, value] of Object.entries(labels))if (null != value) normalized[key] = String(value);
97
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
98
+ }
99
+ function extractError(args) {
100
+ for (const arg of args)if (arg instanceof Error) return {
101
+ name: arg.name,
102
+ message: arg.message,
103
+ stack: arg.stack
104
+ };
105
+ }
106
+ function toTelemetryEnvelope(event, input) {
107
+ const base = {
108
+ timestamp: Date.now(),
109
+ service: input.service,
110
+ module: input.module,
111
+ environment: input.environment,
112
+ ...input.traceId ? {
113
+ traceId: input.traceId
114
+ } : {},
115
+ ...input.spanId ? {
116
+ spanId: input.spanId
117
+ } : {},
118
+ ...input.attributes ? {
119
+ attributes: input.attributes
120
+ } : {}
121
+ };
122
+ if ('log' === event.type) {
123
+ const payload = event.payload;
124
+ const args = payload.args || [];
125
+ const signalType = 'trace' === payload.level ? 'trace' : 'log';
126
+ return {
127
+ ...base,
128
+ signalType,
129
+ name: payload.message,
130
+ level: payload.level,
131
+ attributes: {
132
+ ...base.attributes || {},
133
+ args
134
+ },
135
+ error: extractError(args)
136
+ };
137
+ }
138
+ if ('timing' === event.type) return {
139
+ ...base,
140
+ signalType: 'metric',
141
+ name: event.payload.name,
142
+ value: event.payload.dur,
143
+ unit: 'ms',
144
+ tags: normalizeLabels(event.payload.tags),
145
+ attributes: {
146
+ ...base.attributes || {},
147
+ desc: event.payload.desc,
148
+ args: event.payload.args
149
+ }
150
+ };
151
+ return {
152
+ ...base,
153
+ signalType: 'metric',
154
+ name: event.payload.name,
155
+ value: 1,
156
+ unit: 'count',
157
+ tags: normalizeLabels(event.payload.tags),
158
+ attributes: {
159
+ ...base.attributes || {},
160
+ args: event.payload.args
161
+ }
162
+ };
163
+ }
164
+ export { buildDroppedEnvelope, buildQueueDepthEnvelope, buildQueueUtilizationEnvelope, buildStartupProbeEnvelope, clamp, isRecord, redactObject, toTelemetryEnvelope };
@@ -0,0 +1,104 @@
1
+ const DEFAULT_OTLP_ENDPOINT = 'http://127.0.0.1:4318/v1/logs';
2
+ const DEFAULT_VM_ENDPOINT = 'http://127.0.0.1:8428/api/v1/import/prometheus';
3
+ const DEFAULT_TIMEOUT_MS = 5000;
4
+ async function postWithTimeout(options) {
5
+ const controller = new AbortController();
6
+ const timer = setTimeout(()=>controller.abort(), options.timeoutMs);
7
+ if ('function' == typeof timer.unref) timer.unref();
8
+ try {
9
+ const response = await fetch(options.endpoint, {
10
+ method: 'POST',
11
+ body: options.body,
12
+ headers: options.headers,
13
+ signal: controller.signal
14
+ });
15
+ if (!response.ok) throw new Error(`Telemetry exporter request failed: ${response.status} ${response.statusText}`);
16
+ } finally{
17
+ clearTimeout(timer);
18
+ }
19
+ }
20
+ function sanitizeMetricName(value) {
21
+ return value.replace(/[^a-zA-Z0-9_:]/g, '_').replace(/_+/g, '_');
22
+ }
23
+ function escapeLabelValue(value) {
24
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
25
+ }
26
+ function toPrometheusLine(envelope, metricPrefix) {
27
+ const metricName = sanitizeMetricName(`${metricPrefix}_${envelope.signalType}_${envelope.name}`);
28
+ const labels = {
29
+ service: envelope.service,
30
+ module: envelope.module,
31
+ environment: envelope.environment,
32
+ ...envelope.level ? {
33
+ level: envelope.level
34
+ } : {},
35
+ ...envelope.traceId ? {
36
+ trace_id: envelope.traceId
37
+ } : {},
38
+ ...envelope.spanId ? {
39
+ span_id: envelope.spanId
40
+ } : {},
41
+ ...envelope.tags || {}
42
+ };
43
+ const labelPairs = Object.entries(labels).sort(([a], [b])=>a.localeCompare(b)).map(([key, value])=>`${sanitizeMetricName(key)}="${escapeLabelValue(value)}"`);
44
+ const labelText = labelPairs.length > 0 ? `{${labelPairs.join(',')}}` : '';
45
+ const value = 'number' == typeof envelope.value && Number.isFinite(envelope.value) ? envelope.value : 1;
46
+ const timestampMs = envelope.timestamp;
47
+ return `${metricName}${labelText} ${value} ${timestampMs}`;
48
+ }
49
+ function createOtlpTelemetryExporter(options = {}) {
50
+ const endpoint = options.endpoint || DEFAULT_OTLP_ENDPOINT;
51
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
52
+ const headers = {
53
+ 'content-type': 'application/json',
54
+ ...options.headers || {}
55
+ };
56
+ return {
57
+ name: 'otlp',
58
+ async emit (batch) {
59
+ if (0 === batch.length) return;
60
+ const body = JSON.stringify({
61
+ resource: {
62
+ service: batch[0]?.service,
63
+ module: batch[0]?.module,
64
+ environment: batch[0]?.environment
65
+ },
66
+ emittedAt: Date.now(),
67
+ events: batch
68
+ });
69
+ await postWithTimeout({
70
+ endpoint,
71
+ body,
72
+ headers,
73
+ timeoutMs
74
+ });
75
+ }
76
+ };
77
+ }
78
+ function createVictoriaMetricsTelemetryExporter(options = {}) {
79
+ const endpoint = options.endpoint || DEFAULT_VM_ENDPOINT;
80
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
81
+ const metricPrefix = sanitizeMetricName(options.metricPrefix || 'modernjs');
82
+ const headers = {
83
+ 'content-type': 'text/plain; version=0.0.4',
84
+ ...options.headers || {}
85
+ };
86
+ return {
87
+ name: 'victoria-metrics',
88
+ async emit (batch) {
89
+ if (0 === batch.length) return;
90
+ const lines = batch.map((item)=>toPrometheusLine(item, metricPrefix));
91
+ await postWithTimeout({
92
+ endpoint,
93
+ body: `${lines.join('\n')}\n`,
94
+ headers,
95
+ timeoutMs
96
+ });
97
+ }
98
+ };
99
+ }
100
+ function maybeWarnLegacyOtlpEndpoint(endpoint) {
101
+ if (!endpoint || !endpoint.includes('/v1/metrics')) return;
102
+ console.warn(`[telemetry] OTLP endpoint "${endpoint}" looks like a metrics path. UltraModern telemetry exporter expects log-style envelopes (default: ${DEFAULT_OTLP_ENDPOINT}).`);
103
+ }
104
+ export { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint };
@@ -0,0 +1,60 @@
1
+ import { resolveContractGateSnapshotPath } from "../contract-gate-snapshot-store/index.mjs";
2
+ import { ContractGateAutopilot } from "../contractGateAutopilot.mjs";
3
+ import { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint } from "../telemetryCore.mjs";
4
+ const activeTelemetryLaneClosers = new Set();
5
+ let telemetryBeforeExitHookInstalled = false;
6
+ const ensureTelemetryBeforeExitHook = ()=>{
7
+ if (telemetryBeforeExitHookInstalled) return;
8
+ telemetryBeforeExitHookInstalled = true;
9
+ process.on('beforeExit', ()=>{
10
+ for (const close of [
11
+ ...activeTelemetryLaneClosers
12
+ ])close();
13
+ });
14
+ };
15
+ const registerTelemetryLifecycle = ({ api, registry, telemetryConfig, canaryConfig, canaryOrchestrator, gateSnapshotStorePromise, appDirectory })=>{
16
+ let contractGateAutopilot;
17
+ let telemetryLaneClosed = false;
18
+ const closeTelemetryLane = async ()=>{
19
+ if (telemetryLaneClosed) return;
20
+ telemetryLaneClosed = true;
21
+ activeTelemetryLaneClosers.delete(closeTelemetryLane);
22
+ contractGateAutopilot?.stop();
23
+ canaryOrchestrator?.stop();
24
+ await registry.shutdown();
25
+ };
26
+ let prepared = false;
27
+ api.onPrepare(async ()=>{
28
+ if (prepared) return;
29
+ prepared = true;
30
+ const { nodeServer } = api.getServerContext();
31
+ if (nodeServer && 'function' == typeof nodeServer.once) nodeServer.once('close', ()=>{
32
+ closeTelemetryLane();
33
+ });
34
+ activeTelemetryLaneClosers.add(closeTelemetryLane);
35
+ ensureTelemetryBeforeExitHook();
36
+ if (telemetryConfig.exporters?.otlp?.enabled) {
37
+ maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
38
+ await registry.register(createOtlpTelemetryExporter(telemetryConfig.exporters.otlp));
39
+ }
40
+ if (telemetryConfig.exporters?.victoriaMetrics?.enabled) await registry.register(createVictoriaMetricsTelemetryExporter(telemetryConfig.exporters.victoriaMetrics));
41
+ await registry.startupHealthCheck({
42
+ failLoud: telemetryConfig.failLoudStartup ?? true
43
+ });
44
+ if (!canaryOrchestrator) return;
45
+ canaryOrchestrator.start();
46
+ if (gateSnapshotStorePromise) {
47
+ const gateSnapshotStore = await gateSnapshotStorePromise;
48
+ contractGateAutopilot = new ContractGateAutopilot({
49
+ orchestrator: canaryOrchestrator,
50
+ gateSnapshotPath: resolveContractGateSnapshotPath(appDirectory, canaryConfig?.autopilot?.gateSnapshotPath),
51
+ gateSnapshotStore,
52
+ pollIntervalMs: canaryConfig?.autopilot?.pollIntervalMs,
53
+ gateStaleAfterMs: canaryConfig?.autopilot?.gateStaleAfterMs
54
+ });
55
+ }
56
+ if (contractGateAutopilot) await contractGateAutopilot.start();
57
+ canaryOrchestrator.evaluate();
58
+ });
59
+ };
60
+ export { registerTelemetryLifecycle };
@@ -0,0 +1,77 @@
1
+ import { isRecord } from "./envelope.mjs";
2
+ function normalizeMetricsInput(prefixOrTags, tags) {
3
+ if ('string' == typeof prefixOrTags) return {
4
+ prefix: prefixOrTags,
5
+ tags: tags || {}
6
+ };
7
+ if (isRecord(prefixOrTags)) return {
8
+ prefix: void 0,
9
+ tags: prefixOrTags
10
+ };
11
+ return {
12
+ prefix: void 0,
13
+ tags: tags || {}
14
+ };
15
+ }
16
+ function normalizeMetricName(name, prefix) {
17
+ return prefix && prefix.length > 0 ? `${prefix}.${name}` : name;
18
+ }
19
+ function toTelemetryMetricTags(tags) {
20
+ const output = {};
21
+ for (const [key, value] of Object.entries(tags))if (null != value) output[key] = String(value);
22
+ return output;
23
+ }
24
+ function getTraceContext(tags) {
25
+ const traceId = 'string' == typeof tags.trace_id ? tags.trace_id : 'string' == typeof tags.traceId ? tags.traceId : void 0;
26
+ const spanId = 'string' == typeof tags.span_id ? tags.span_id : 'string' == typeof tags.spanId ? tags.spanId : void 0;
27
+ const parentSpanId = 'string' == typeof tags.parent_span_id ? tags.parent_span_id : 'string' == typeof tags.parentSpanId ? tags.parentSpanId : void 0;
28
+ return {
29
+ traceId,
30
+ spanId,
31
+ parentSpanId
32
+ };
33
+ }
34
+ const createTelemetryAwareMetrics = (baseMetrics, registry)=>{
35
+ const emitCounter = (name, value, prefixOrTags, tags)=>{
36
+ const normalized = normalizeMetricsInput(prefixOrTags, tags);
37
+ baseMetrics.emitCounter(name, value, normalized.prefix, normalized.tags);
38
+ try {
39
+ const metricName = normalizeMetricName(name, normalized.prefix);
40
+ const traceContext = getTraceContext(normalized.tags);
41
+ registry.enqueueMetric({
42
+ name: metricName,
43
+ value,
44
+ unit: 'count',
45
+ traceId: traceContext.traceId,
46
+ spanId: traceContext.spanId,
47
+ parentSpanId: traceContext.parentSpanId,
48
+ tags: toTelemetryMetricTags(normalized.tags),
49
+ attributes: normalized.tags
50
+ });
51
+ } catch (_error) {}
52
+ };
53
+ const emitTimer = (name, value, prefixOrTags, tags)=>{
54
+ const normalized = normalizeMetricsInput(prefixOrTags, tags);
55
+ baseMetrics.emitTimer(name, value, normalized.prefix, normalized.tags);
56
+ try {
57
+ const metricName = normalizeMetricName(name, normalized.prefix);
58
+ const traceContext = getTraceContext(normalized.tags);
59
+ registry.enqueueMetric({
60
+ name: metricName,
61
+ value,
62
+ unit: 'ms',
63
+ traceId: traceContext.traceId,
64
+ spanId: traceContext.spanId,
65
+ parentSpanId: traceContext.parentSpanId,
66
+ tags: toTelemetryMetricTags(normalized.tags),
67
+ attributes: normalized.tags
68
+ });
69
+ } catch (_error) {}
70
+ };
71
+ return {
72
+ ...baseMetrics,
73
+ emitCounter,
74
+ emitTimer
75
+ };
76
+ };
77
+ export { createTelemetryAwareMetrics };