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

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,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 };
@@ -0,0 +1,165 @@
1
+ import "node:module";
2
+ function buildDroppedEnvelope(context, droppedCount) {
3
+ return {
4
+ timestamp: Date.now(),
5
+ service: context.service,
6
+ module: context.module,
7
+ environment: context.environment,
8
+ signalType: 'metric',
9
+ name: 'telemetry.queue.dropped',
10
+ value: droppedCount,
11
+ unit: 'count',
12
+ tags: {
13
+ reason: 'queue_backpressure'
14
+ }
15
+ };
16
+ }
17
+ function buildQueueDepthEnvelope(context, queueDepth) {
18
+ return {
19
+ timestamp: Date.now(),
20
+ service: context.service,
21
+ module: context.module,
22
+ environment: context.environment,
23
+ signalType: 'metric',
24
+ name: 'telemetry.queue.depth',
25
+ value: queueDepth,
26
+ unit: 'count',
27
+ tags: {
28
+ capacity: String(context.maxQueueSize)
29
+ }
30
+ };
31
+ }
32
+ function buildQueueUtilizationEnvelope(context, queueDepth) {
33
+ return {
34
+ timestamp: Date.now(),
35
+ service: context.service,
36
+ module: context.module,
37
+ environment: context.environment,
38
+ signalType: 'metric',
39
+ name: 'telemetry.queue.utilization',
40
+ value: queueDepth / context.maxQueueSize,
41
+ unit: 'ratio',
42
+ tags: {
43
+ capacity: String(context.maxQueueSize)
44
+ }
45
+ };
46
+ }
47
+ function buildStartupProbeEnvelope(context) {
48
+ return {
49
+ timestamp: Date.now(),
50
+ service: context.service,
51
+ module: context.module,
52
+ environment: context.environment,
53
+ signalType: 'log',
54
+ name: 'telemetry.exporter.startup_probe',
55
+ level: 'info',
56
+ tags: {
57
+ phase: 'startup'
58
+ },
59
+ attributes: {
60
+ source: 'TelemetryRegistry'
61
+ }
62
+ };
63
+ }
64
+ function clamp(value, min, max) {
65
+ if (Number.isNaN(value)) return max;
66
+ return Math.max(min, Math.min(max, value));
67
+ }
68
+ function isRecord(value) {
69
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
70
+ }
71
+ function redactObject(value, redactionKeys) {
72
+ if (!isRecord(value)) return;
73
+ const output = {};
74
+ for (const [key, nested] of Object.entries(value)){
75
+ if (redactionKeys.has(key)) {
76
+ output[key] = '[REDACTED]';
77
+ continue;
78
+ }
79
+ if (Array.isArray(nested)) {
80
+ output[key] = nested.map((item)=>{
81
+ if (isRecord(item)) return redactObject(item, redactionKeys);
82
+ return item;
83
+ });
84
+ continue;
85
+ }
86
+ if (isRecord(nested)) {
87
+ output[key] = redactObject(nested, redactionKeys);
88
+ continue;
89
+ }
90
+ output[key] = nested;
91
+ }
92
+ return output;
93
+ }
94
+ function normalizeLabels(labels) {
95
+ if (!labels) return;
96
+ const normalized = {};
97
+ for (const [key, value] of Object.entries(labels))if (null != value) normalized[key] = String(value);
98
+ return Object.keys(normalized).length > 0 ? normalized : void 0;
99
+ }
100
+ function extractError(args) {
101
+ for (const arg of args)if (arg instanceof Error) return {
102
+ name: arg.name,
103
+ message: arg.message,
104
+ stack: arg.stack
105
+ };
106
+ }
107
+ function toTelemetryEnvelope(event, input) {
108
+ const base = {
109
+ timestamp: Date.now(),
110
+ service: input.service,
111
+ module: input.module,
112
+ environment: input.environment,
113
+ ...input.traceId ? {
114
+ traceId: input.traceId
115
+ } : {},
116
+ ...input.spanId ? {
117
+ spanId: input.spanId
118
+ } : {},
119
+ ...input.attributes ? {
120
+ attributes: input.attributes
121
+ } : {}
122
+ };
123
+ if ('log' === event.type) {
124
+ const payload = event.payload;
125
+ const args = payload.args || [];
126
+ const signalType = 'trace' === payload.level ? 'trace' : 'log';
127
+ return {
128
+ ...base,
129
+ signalType,
130
+ name: payload.message,
131
+ level: payload.level,
132
+ attributes: {
133
+ ...base.attributes || {},
134
+ args
135
+ },
136
+ error: extractError(args)
137
+ };
138
+ }
139
+ if ('timing' === event.type) return {
140
+ ...base,
141
+ signalType: 'metric',
142
+ name: event.payload.name,
143
+ value: event.payload.dur,
144
+ unit: 'ms',
145
+ tags: normalizeLabels(event.payload.tags),
146
+ attributes: {
147
+ ...base.attributes || {},
148
+ desc: event.payload.desc,
149
+ args: event.payload.args
150
+ }
151
+ };
152
+ return {
153
+ ...base,
154
+ signalType: 'metric',
155
+ name: event.payload.name,
156
+ value: 1,
157
+ unit: 'count',
158
+ tags: normalizeLabels(event.payload.tags),
159
+ attributes: {
160
+ ...base.attributes || {},
161
+ args: event.payload.args
162
+ }
163
+ };
164
+ }
165
+ export { buildDroppedEnvelope, buildQueueDepthEnvelope, buildQueueUtilizationEnvelope, buildStartupProbeEnvelope, clamp, isRecord, redactObject, toTelemetryEnvelope };
@@ -0,0 +1,105 @@
1
+ import "node:module";
2
+ const DEFAULT_OTLP_ENDPOINT = 'http://127.0.0.1:4318/v1/logs';
3
+ const DEFAULT_VM_ENDPOINT = 'http://127.0.0.1:8428/api/v1/import/prometheus';
4
+ const DEFAULT_TIMEOUT_MS = 5000;
5
+ async function postWithTimeout(options) {
6
+ const controller = new AbortController();
7
+ const timer = setTimeout(()=>controller.abort(), options.timeoutMs);
8
+ if ('function' == typeof timer.unref) timer.unref();
9
+ try {
10
+ const response = await fetch(options.endpoint, {
11
+ method: 'POST',
12
+ body: options.body,
13
+ headers: options.headers,
14
+ signal: controller.signal
15
+ });
16
+ if (!response.ok) throw new Error(`Telemetry exporter request failed: ${response.status} ${response.statusText}`);
17
+ } finally{
18
+ clearTimeout(timer);
19
+ }
20
+ }
21
+ function sanitizeMetricName(value) {
22
+ return value.replace(/[^a-zA-Z0-9_:]/g, '_').replace(/_+/g, '_');
23
+ }
24
+ function escapeLabelValue(value) {
25
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
26
+ }
27
+ function toPrometheusLine(envelope, metricPrefix) {
28
+ const metricName = sanitizeMetricName(`${metricPrefix}_${envelope.signalType}_${envelope.name}`);
29
+ const labels = {
30
+ service: envelope.service,
31
+ module: envelope.module,
32
+ environment: envelope.environment,
33
+ ...envelope.level ? {
34
+ level: envelope.level
35
+ } : {},
36
+ ...envelope.traceId ? {
37
+ trace_id: envelope.traceId
38
+ } : {},
39
+ ...envelope.spanId ? {
40
+ span_id: envelope.spanId
41
+ } : {},
42
+ ...envelope.tags || {}
43
+ };
44
+ const labelPairs = Object.entries(labels).sort(([a], [b])=>a.localeCompare(b)).map(([key, value])=>`${sanitizeMetricName(key)}="${escapeLabelValue(value)}"`);
45
+ const labelText = labelPairs.length > 0 ? `{${labelPairs.join(',')}}` : '';
46
+ const value = 'number' == typeof envelope.value && Number.isFinite(envelope.value) ? envelope.value : 1;
47
+ const timestampMs = envelope.timestamp;
48
+ return `${metricName}${labelText} ${value} ${timestampMs}`;
49
+ }
50
+ function createOtlpTelemetryExporter(options = {}) {
51
+ const endpoint = options.endpoint || DEFAULT_OTLP_ENDPOINT;
52
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
53
+ const headers = {
54
+ 'content-type': 'application/json',
55
+ ...options.headers || {}
56
+ };
57
+ return {
58
+ name: 'otlp',
59
+ async emit (batch) {
60
+ if (0 === batch.length) return;
61
+ const body = JSON.stringify({
62
+ resource: {
63
+ service: batch[0]?.service,
64
+ module: batch[0]?.module,
65
+ environment: batch[0]?.environment
66
+ },
67
+ emittedAt: Date.now(),
68
+ events: batch
69
+ });
70
+ await postWithTimeout({
71
+ endpoint,
72
+ body,
73
+ headers,
74
+ timeoutMs
75
+ });
76
+ }
77
+ };
78
+ }
79
+ function createVictoriaMetricsTelemetryExporter(options = {}) {
80
+ const endpoint = options.endpoint || DEFAULT_VM_ENDPOINT;
81
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
82
+ const metricPrefix = sanitizeMetricName(options.metricPrefix || 'modernjs');
83
+ const headers = {
84
+ 'content-type': 'text/plain; version=0.0.4',
85
+ ...options.headers || {}
86
+ };
87
+ return {
88
+ name: 'victoria-metrics',
89
+ async emit (batch) {
90
+ if (0 === batch.length) return;
91
+ const lines = batch.map((item)=>toPrometheusLine(item, metricPrefix));
92
+ await postWithTimeout({
93
+ endpoint,
94
+ body: `${lines.join('\n')}\n`,
95
+ headers,
96
+ timeoutMs
97
+ });
98
+ }
99
+ };
100
+ }
101
+ function maybeWarnLegacyOtlpEndpoint(endpoint) {
102
+ if (!endpoint || !endpoint.includes('/v1/metrics')) return;
103
+ console.warn(`[telemetry] OTLP endpoint "${endpoint}" looks like a metrics path. UltraModern telemetry exporter expects log-style envelopes (default: ${DEFAULT_OTLP_ENDPOINT}).`);
104
+ }
105
+ export { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint };
@@ -0,0 +1,61 @@
1
+ import "node:module";
2
+ import { resolveContractGateSnapshotPath } from "../contract-gate-snapshot-store/index.mjs";
3
+ import { ContractGateAutopilot } from "../contractGateAutopilot.mjs";
4
+ import { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint } from "../telemetryCore.mjs";
5
+ const activeTelemetryLaneClosers = new Set();
6
+ let telemetryBeforeExitHookInstalled = false;
7
+ const ensureTelemetryBeforeExitHook = ()=>{
8
+ if (telemetryBeforeExitHookInstalled) return;
9
+ telemetryBeforeExitHookInstalled = true;
10
+ process.on('beforeExit', ()=>{
11
+ for (const close of [
12
+ ...activeTelemetryLaneClosers
13
+ ])close();
14
+ });
15
+ };
16
+ const registerTelemetryLifecycle = ({ api, registry, telemetryConfig, canaryConfig, canaryOrchestrator, gateSnapshotStorePromise, appDirectory })=>{
17
+ let contractGateAutopilot;
18
+ let telemetryLaneClosed = false;
19
+ const closeTelemetryLane = async ()=>{
20
+ if (telemetryLaneClosed) return;
21
+ telemetryLaneClosed = true;
22
+ activeTelemetryLaneClosers.delete(closeTelemetryLane);
23
+ contractGateAutopilot?.stop();
24
+ canaryOrchestrator?.stop();
25
+ await registry.shutdown();
26
+ };
27
+ let prepared = false;
28
+ api.onPrepare(async ()=>{
29
+ if (prepared) return;
30
+ prepared = true;
31
+ const { nodeServer } = api.getServerContext();
32
+ if (nodeServer && 'function' == typeof nodeServer.once) nodeServer.once('close', ()=>{
33
+ closeTelemetryLane();
34
+ });
35
+ activeTelemetryLaneClosers.add(closeTelemetryLane);
36
+ ensureTelemetryBeforeExitHook();
37
+ if (telemetryConfig.exporters?.otlp?.enabled) {
38
+ maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
39
+ await registry.register(createOtlpTelemetryExporter(telemetryConfig.exporters.otlp));
40
+ }
41
+ if (telemetryConfig.exporters?.victoriaMetrics?.enabled) await registry.register(createVictoriaMetricsTelemetryExporter(telemetryConfig.exporters.victoriaMetrics));
42
+ await registry.startupHealthCheck({
43
+ failLoud: telemetryConfig.failLoudStartup ?? true
44
+ });
45
+ if (!canaryOrchestrator) return;
46
+ canaryOrchestrator.start();
47
+ if (gateSnapshotStorePromise) {
48
+ const gateSnapshotStore = await gateSnapshotStorePromise;
49
+ contractGateAutopilot = new ContractGateAutopilot({
50
+ orchestrator: canaryOrchestrator,
51
+ gateSnapshotPath: resolveContractGateSnapshotPath(appDirectory, canaryConfig?.autopilot?.gateSnapshotPath),
52
+ gateSnapshotStore,
53
+ pollIntervalMs: canaryConfig?.autopilot?.pollIntervalMs,
54
+ gateStaleAfterMs: canaryConfig?.autopilot?.gateStaleAfterMs
55
+ });
56
+ }
57
+ if (contractGateAutopilot) await contractGateAutopilot.start();
58
+ canaryOrchestrator.evaluate();
59
+ });
60
+ };
61
+ export { registerTelemetryLifecycle };
@@ -0,0 +1,78 @@
1
+ import "node:module";
2
+ import { isRecord } from "./envelope.mjs";
3
+ function normalizeMetricsInput(prefixOrTags, tags) {
4
+ if ('string' == typeof prefixOrTags) return {
5
+ prefix: prefixOrTags,
6
+ tags: tags || {}
7
+ };
8
+ if (isRecord(prefixOrTags)) return {
9
+ prefix: void 0,
10
+ tags: prefixOrTags
11
+ };
12
+ return {
13
+ prefix: void 0,
14
+ tags: tags || {}
15
+ };
16
+ }
17
+ function normalizeMetricName(name, prefix) {
18
+ return prefix && prefix.length > 0 ? `${prefix}.${name}` : name;
19
+ }
20
+ function toTelemetryMetricTags(tags) {
21
+ const output = {};
22
+ for (const [key, value] of Object.entries(tags))if (null != value) output[key] = String(value);
23
+ return output;
24
+ }
25
+ function getTraceContext(tags) {
26
+ const traceId = 'string' == typeof tags.trace_id ? tags.trace_id : 'string' == typeof tags.traceId ? tags.traceId : void 0;
27
+ const spanId = 'string' == typeof tags.span_id ? tags.span_id : 'string' == typeof tags.spanId ? tags.spanId : void 0;
28
+ const parentSpanId = 'string' == typeof tags.parent_span_id ? tags.parent_span_id : 'string' == typeof tags.parentSpanId ? tags.parentSpanId : void 0;
29
+ return {
30
+ traceId,
31
+ spanId,
32
+ parentSpanId
33
+ };
34
+ }
35
+ const createTelemetryAwareMetrics = (baseMetrics, registry)=>{
36
+ const emitCounter = (name, value, prefixOrTags, tags)=>{
37
+ const normalized = normalizeMetricsInput(prefixOrTags, tags);
38
+ baseMetrics.emitCounter(name, value, normalized.prefix, normalized.tags);
39
+ try {
40
+ const metricName = normalizeMetricName(name, normalized.prefix);
41
+ const traceContext = getTraceContext(normalized.tags);
42
+ registry.enqueueMetric({
43
+ name: metricName,
44
+ value,
45
+ unit: 'count',
46
+ traceId: traceContext.traceId,
47
+ spanId: traceContext.spanId,
48
+ parentSpanId: traceContext.parentSpanId,
49
+ tags: toTelemetryMetricTags(normalized.tags),
50
+ attributes: normalized.tags
51
+ });
52
+ } catch (_error) {}
53
+ };
54
+ const emitTimer = (name, value, prefixOrTags, tags)=>{
55
+ const normalized = normalizeMetricsInput(prefixOrTags, tags);
56
+ baseMetrics.emitTimer(name, value, normalized.prefix, normalized.tags);
57
+ try {
58
+ const metricName = normalizeMetricName(name, normalized.prefix);
59
+ const traceContext = getTraceContext(normalized.tags);
60
+ registry.enqueueMetric({
61
+ name: metricName,
62
+ value,
63
+ unit: 'ms',
64
+ traceId: traceContext.traceId,
65
+ spanId: traceContext.spanId,
66
+ parentSpanId: traceContext.parentSpanId,
67
+ tags: toTelemetryMetricTags(normalized.tags),
68
+ attributes: normalized.tags
69
+ });
70
+ } catch (_error) {}
71
+ };
72
+ return {
73
+ ...baseMetrics,
74
+ emitCounter,
75
+ emitTimer
76
+ };
77
+ };
78
+ export { createTelemetryAwareMetrics };