@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.10 → 3.5.0-ultramodern.100

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 +10 -12
  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,87 @@
1
+ import { parseTraceparent } from "@modern-js/create-request/server";
2
+ import { logger } from "@modern-js/utils";
3
+ import { parseServerRuntimeExtensionsEnv } from "../env.mjs";
4
+ import { TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, toTelemetryEnvelope } from "../telemetryCore.mjs";
5
+ import { setupTelemetryCanary } from "./canarySetup.mjs";
6
+ import { registerTelemetryLifecycle } from "./lifecycle.mjs";
7
+ import { createRuntimeFallbackSignalMiddleware, createRuntimeStatusMiddleware } from "./runtimeEndpoints.mjs";
8
+ const hasEnabledTelemetryExporters = (config)=>Boolean(config?.exporters?.otlp?.enabled || config?.exporters?.victoriaMetrics?.enabled);
9
+ const resolveTelemetrySloOptions = (sloConfig, warnSink = (message)=>logger.warn(message))=>({
10
+ queueUtilizationWarnThreshold: sloConfig?.queueUtilizationWarnThreshold,
11
+ queueDroppedWarnThreshold: sloConfig?.queueDroppedWarnThreshold,
12
+ alertCooldownMs: sloConfig?.alertCooldownMs,
13
+ onAlert: (alert)=>{
14
+ warnSink(`[telemetry.slo] ${alert.type} threshold=${alert.threshold} value=${alert.value} depth=${alert.queueDepth}/${alert.queueCapacity} dropped=${alert.totalDropped}`);
15
+ }
16
+ });
17
+ const injectTelemetryPlugin = ()=>({
18
+ name: '@modern-js/inject-telemetry',
19
+ setup (api) {
20
+ const serverConfig = api.getServerConfig();
21
+ const telemetryConfig = serverConfig?.server?.telemetry;
22
+ if (!telemetryConfig) return;
23
+ if (true !== telemetryConfig.enabled && !hasEnabledTelemetryExporters(telemetryConfig)) return;
24
+ const { middlewares, metaName, appDirectory } = api.getServerContext();
25
+ const serviceName = telemetryConfig.service || metaName || 'modern-js';
26
+ const moduleName = telemetryConfig.module || 'server';
27
+ const environmentName = telemetryConfig.environment || parseServerRuntimeExtensionsEnv().environmentName;
28
+ const registry = new TelemetryRegistry({
29
+ service: serviceName,
30
+ module: moduleName,
31
+ environment: environmentName,
32
+ samplingRate: telemetryConfig.samplingRate,
33
+ flushIntervalMs: telemetryConfig.flushIntervalMs,
34
+ maxBatchSize: telemetryConfig.maxBatchSize,
35
+ maxQueueSize: telemetryConfig.maxQueueSize,
36
+ redactionKeys: telemetryConfig.redactionKeys,
37
+ slo: resolveTelemetrySloOptions(telemetryConfig.slo)
38
+ });
39
+ const { canaryOrchestrator, gateSnapshotStorePromise, runtimeFallbackSignalConfig, runtimeStatusAuthConfig } = setupTelemetryCanary({
40
+ registry,
41
+ appDirectory,
42
+ canaryConfig: telemetryConfig.canary
43
+ });
44
+ if (runtimeFallbackSignalConfig) middlewares.push(createRuntimeFallbackSignalMiddleware(runtimeFallbackSignalConfig));
45
+ middlewares.push(createRuntimeStatusMiddleware({
46
+ registry,
47
+ canaryOrchestrator,
48
+ runtimeFallbackSignalConfig,
49
+ runtimeStatusAuthConfig
50
+ }));
51
+ middlewares.push({
52
+ name: 'inject-telemetry',
53
+ handler: async (c, next)=>{
54
+ const monitors = c.get('monitors');
55
+ if (monitors) {
56
+ const traceContext = parseTraceparent(c.req.header('traceparent'));
57
+ const monitor = (event)=>{
58
+ registry.enqueue(toTelemetryEnvelope(event, {
59
+ service: serviceName,
60
+ module: moduleName,
61
+ environment: environmentName,
62
+ traceId: traceContext?.traceId,
63
+ spanId: traceContext?.spanId,
64
+ attributes: {
65
+ requestMethod: c.req.method,
66
+ requestPath: c.req.path
67
+ }
68
+ }));
69
+ };
70
+ monitors.push(monitor);
71
+ }
72
+ await next();
73
+ }
74
+ });
75
+ registerTelemetryLifecycle({
76
+ api,
77
+ registry,
78
+ telemetryConfig,
79
+ canaryConfig: telemetryConfig.canary,
80
+ canaryOrchestrator,
81
+ gateSnapshotStorePromise,
82
+ appDirectory
83
+ });
84
+ }
85
+ });
86
+ export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayloadFromRawBody, resolveRuntimeFallbackSignalEndpoint } from "../runtimeFallbackSignal.mjs";
87
+ export { TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, hasEnabledTelemetryExporters, injectTelemetryPlugin, resolveTelemetrySloOptions };
@@ -0,0 +1,258 @@
1
+ import { buildDroppedEnvelope, buildQueueDepthEnvelope, buildQueueUtilizationEnvelope, buildStartupProbeEnvelope, clamp, redactObject } from "./envelope.mjs";
2
+ import { TelemetryStartupHealthError } from "./registryTypes.mjs";
3
+ class TelemetryRegistry {
4
+ async register(exporter) {
5
+ this.exporters.push(exporter);
6
+ this.exporterHealth.set(exporter.name, {
7
+ name: exporter.name,
8
+ healthy: true,
9
+ failures: 0
10
+ });
11
+ if (exporter.init) try {
12
+ await exporter.init({
13
+ service: this.service,
14
+ module: this.module,
15
+ environment: this.environment
16
+ });
17
+ this.markExporterHealthy(exporter.name);
18
+ } catch (error) {
19
+ this.markExporterFailure(exporter.name, error);
20
+ throw error;
21
+ }
22
+ else this.markExporterHealthy(exporter.name);
23
+ }
24
+ getOrCreateExporterHealth(name) {
25
+ const existing = this.exporterHealth.get(name);
26
+ if (existing) return existing;
27
+ const next = {
28
+ name,
29
+ healthy: true,
30
+ failures: 0
31
+ };
32
+ this.exporterHealth.set(name, next);
33
+ return next;
34
+ }
35
+ markExporterHealthy(name) {
36
+ const status = this.getOrCreateExporterHealth(name);
37
+ status.healthy = true;
38
+ status.lastSuccessAt = Date.now();
39
+ status.lastError = void 0;
40
+ }
41
+ markExporterFailure(name, error) {
42
+ const status = this.getOrCreateExporterHealth(name);
43
+ status.healthy = false;
44
+ status.failures += 1;
45
+ status.lastFailureAt = Date.now();
46
+ status.lastError = error instanceof Error ? error.message : String(error);
47
+ }
48
+ maybeEmitSloAlert(type, value, threshold) {
49
+ if (!this.onSloAlert || value < threshold) return;
50
+ const now = Date.now();
51
+ const lastTimestamp = this.lastSloAlertAt.get(type) ?? 0;
52
+ if (now - lastTimestamp < this.alertCooldownMs) return;
53
+ this.lastSloAlertAt.set(type, now);
54
+ const queueDepth = this.queue.length;
55
+ try {
56
+ this.onSloAlert({
57
+ timestamp: now,
58
+ service: this.service,
59
+ module: this.module,
60
+ environment: this.environment,
61
+ type,
62
+ value,
63
+ threshold,
64
+ queueDepth,
65
+ queueCapacity: this.maxQueueSize,
66
+ queueUtilization: queueDepth / this.maxQueueSize,
67
+ totalDropped: this.totalDroppedCount
68
+ });
69
+ } catch (_error) {}
70
+ }
71
+ enqueue(envelope) {
72
+ if (this.samplingRate < 1 && Math.random() > this.samplingRate) return;
73
+ const redactedEnvelope = this.redactionKeys.size > 0 ? {
74
+ ...envelope,
75
+ attributes: redactObject(envelope.attributes, this.redactionKeys)
76
+ } : envelope;
77
+ if (this.queue.length >= this.maxQueueSize) {
78
+ this.queue.shift();
79
+ this.droppedCount += 1;
80
+ this.totalDroppedCount += 1;
81
+ this.maybeEmitSloAlert('queue.drop', this.droppedCount, this.queueDroppedWarnThreshold);
82
+ }
83
+ this.queue.push(redactedEnvelope);
84
+ this.maybeEmitSloAlert('queue.utilization', this.queue.length / this.maxQueueSize, this.queueUtilizationWarnThreshold);
85
+ if (this.queue.length >= this.maxBatchSize) this.flush();
86
+ }
87
+ enqueueMetric(input) {
88
+ this.enqueue({
89
+ ...this.baseEnvelope(),
90
+ signalType: 'metric',
91
+ name: input.name,
92
+ value: input.value,
93
+ unit: input.unit || 'count',
94
+ traceId: input.traceId,
95
+ spanId: input.spanId,
96
+ parentSpanId: input.parentSpanId,
97
+ tags: input.tags,
98
+ attributes: input.attributes
99
+ });
100
+ }
101
+ enqueueLog(input) {
102
+ this.enqueue({
103
+ ...this.baseEnvelope(),
104
+ signalType: 'log',
105
+ name: input.name,
106
+ level: input.level,
107
+ traceId: input.traceId,
108
+ spanId: input.spanId,
109
+ parentSpanId: input.parentSpanId,
110
+ tags: input.tags,
111
+ attributes: input.attributes,
112
+ error: input.error
113
+ });
114
+ }
115
+ enqueueTrace(input) {
116
+ this.enqueue({
117
+ ...this.baseEnvelope(),
118
+ signalType: 'trace',
119
+ name: input.name,
120
+ traceId: input.traceId,
121
+ spanId: input.spanId,
122
+ parentSpanId: input.parentSpanId,
123
+ tags: input.tags,
124
+ attributes: input.attributes
125
+ });
126
+ }
127
+ baseEnvelope() {
128
+ return {
129
+ timestamp: Date.now(),
130
+ service: this.service,
131
+ module: this.module,
132
+ environment: this.environment
133
+ };
134
+ }
135
+ async emitBatch(batch) {
136
+ const results = await Promise.allSettled(this.exporters.map(async (exporter)=>{
137
+ await exporter.emit(batch);
138
+ return exporter.name;
139
+ }));
140
+ for (const [index, result] of results.entries()){
141
+ const exporterName = this.exporters[index]?.name || `exporter-${index}`;
142
+ if ('rejected' === result.status) {
143
+ this.markExporterFailure(exporterName, result.reason);
144
+ continue;
145
+ }
146
+ this.markExporterHealthy(exporterName);
147
+ }
148
+ }
149
+ async startupHealthCheck(options) {
150
+ if (0 === this.exporters.length) return;
151
+ const probeBatch = [
152
+ buildStartupProbeEnvelope({
153
+ service: this.service,
154
+ module: this.module,
155
+ environment: this.environment,
156
+ maxQueueSize: this.maxQueueSize
157
+ })
158
+ ];
159
+ const failedExporters = [];
160
+ await Promise.all(this.exporters.map(async (exporter)=>{
161
+ try {
162
+ await exporter.emit(probeBatch);
163
+ this.markExporterHealthy(exporter.name);
164
+ } catch (error) {
165
+ this.markExporterFailure(exporter.name, error);
166
+ const status = this.exporterHealth.get(exporter.name);
167
+ if (status) failedExporters.push({
168
+ ...status
169
+ });
170
+ }
171
+ }));
172
+ if ((options?.failLoud ?? true) && failedExporters.length > 0) throw new TelemetryStartupHealthError(failedExporters);
173
+ }
174
+ getExporterHealth() {
175
+ return Array.from(this.exporterHealth.values()).map((item)=>({
176
+ ...item
177
+ }));
178
+ }
179
+ getQueueStats() {
180
+ return {
181
+ depth: this.queue.length,
182
+ capacity: this.maxQueueSize,
183
+ utilization: this.queue.length / this.maxQueueSize,
184
+ pendingDropped: this.droppedCount,
185
+ totalDropped: this.totalDroppedCount
186
+ };
187
+ }
188
+ async flushInternal() {
189
+ const queueDepthBeforeFlush = this.queue.length;
190
+ const envelopeContext = {
191
+ service: this.service,
192
+ module: this.module,
193
+ environment: this.environment,
194
+ maxQueueSize: this.maxQueueSize
195
+ };
196
+ if (queueDepthBeforeFlush > 0) {
197
+ this.queue.unshift(buildQueueUtilizationEnvelope(envelopeContext, queueDepthBeforeFlush));
198
+ this.queue.unshift(buildQueueDepthEnvelope(envelopeContext, queueDepthBeforeFlush));
199
+ }
200
+ if (this.droppedCount > 0) {
201
+ const droppedCount = this.droppedCount;
202
+ this.droppedCount = 0;
203
+ this.queue.unshift(buildDroppedEnvelope(envelopeContext, droppedCount));
204
+ }
205
+ if (0 === this.queue.length) return;
206
+ if (0 === this.exporters.length) {
207
+ this.queue.length = 0;
208
+ return;
209
+ }
210
+ while(this.queue.length > 0){
211
+ const batch = this.queue.splice(0, this.maxBatchSize);
212
+ await this.emitBatch(batch);
213
+ }
214
+ await Promise.allSettled(this.exporters.map(async (exporter)=>{
215
+ if (exporter.flush) await exporter.flush();
216
+ }));
217
+ }
218
+ flush() {
219
+ if (this.flushing) return this.flushing;
220
+ this.flushing = this.flushInternal().finally(()=>{
221
+ this.flushing = null;
222
+ });
223
+ return this.flushing;
224
+ }
225
+ async shutdown() {
226
+ if (this.flushTimer) clearInterval(this.flushTimer);
227
+ await this.flush();
228
+ await Promise.allSettled(this.exporters.map(async (exporter)=>{
229
+ if (exporter.shutdown) await exporter.shutdown();
230
+ }));
231
+ }
232
+ constructor(options){
233
+ this.exporters = [];
234
+ this.queue = [];
235
+ this.droppedCount = 0;
236
+ this.totalDroppedCount = 0;
237
+ this.flushing = null;
238
+ this.exporterHealth = new Map();
239
+ this.lastSloAlertAt = new Map();
240
+ this.service = options.service;
241
+ this.module = options.module;
242
+ this.environment = options.environment;
243
+ this.samplingRate = clamp(options.samplingRate ?? 1, 0, 1);
244
+ this.maxBatchSize = Math.max(1, options.maxBatchSize ?? 50);
245
+ this.maxQueueSize = Math.max(1, options.maxQueueSize ?? 1000);
246
+ this.flushIntervalMs = Math.max(50, options.flushIntervalMs ?? 1000);
247
+ this.redactionKeys = new Set(options.redactionKeys || []);
248
+ this.queueUtilizationWarnThreshold = clamp(options.slo?.queueUtilizationWarnThreshold ?? 0.8, 0, 1);
249
+ this.queueDroppedWarnThreshold = Math.max(1, options.slo?.queueDroppedWarnThreshold ?? 1);
250
+ this.alertCooldownMs = Math.max(0, options.slo?.alertCooldownMs ?? 60000);
251
+ this.onSloAlert = options.slo?.onAlert;
252
+ this.flushTimer = setInterval(()=>{
253
+ this.flush();
254
+ }, this.flushIntervalMs);
255
+ if ('function' == typeof this.flushTimer.unref) this.flushTimer.unref();
256
+ }
257
+ }
258
+ export { TelemetryRegistry };
@@ -0,0 +1,8 @@
1
+ class TelemetryStartupHealthError extends Error {
2
+ constructor(failedExporters){
3
+ super(`Telemetry startup health check failed for exporters: ${failedExporters.map((item)=>item.name).join(', ')}`), this.code = 'TELEMETRY_EXPORTER_STARTUP_HEALTH_FAILED';
4
+ this.name = 'TelemetryStartupHealthError';
5
+ this.failedExporters = failedExporters;
6
+ }
7
+ }
8
+ export { TelemetryStartupHealthError };
@@ -0,0 +1,94 @@
1
+ import { DEFAULT_RUNTIME_STATUS_ENDPOINT, enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, parseRuntimeFallbackSignalPayload, persistRuntimeFallbackContractGate } from "../runtimeFallbackSignal.mjs";
2
+ const getRequestRemoteAddress = (c)=>{
3
+ const env = c.env;
4
+ const remoteAddress = env?.node?.req?.socket?.remoteAddress;
5
+ return 'string' == typeof remoteAddress && remoteAddress.trim().length > 0 ? remoteAddress.trim() : void 0;
6
+ };
7
+ const createRuntimeFallbackSignalMiddleware = (signalConfig)=>({
8
+ name: 'telemetry-runtime-fallback-signal',
9
+ path: signalConfig.endpoint,
10
+ method: 'post',
11
+ order: 'pre',
12
+ handler: async (c)=>{
13
+ try {
14
+ enforceRuntimeFallbackSignalAuth(c, signalConfig);
15
+ const { payload } = await parseRuntimeFallbackSignalPayload(c, signalConfig.maxBodyBytes);
16
+ const trustResult = enforceRuntimeFallbackSignalTrustPolicy(payload, signalConfig, {
17
+ remoteAddress: getRequestRemoteAddress(c)
18
+ });
19
+ if (trustResult.deduped) return c.json({
20
+ ok: true,
21
+ deduped: true
22
+ }, 202);
23
+ await persistRuntimeFallbackContractGate(payload, signalConfig);
24
+ return c.json({
25
+ ok: true
26
+ }, 202);
27
+ } catch (error) {
28
+ const signalError = error;
29
+ const status = getRuntimeSignalErrorStatusCode(signalError);
30
+ return c.json({
31
+ ok: false,
32
+ error: signalError instanceof Error ? signalError.message : String(signalError)
33
+ }, status);
34
+ }
35
+ }
36
+ });
37
+ const createRuntimeStatusMiddleware = ({ registry, canaryOrchestrator, runtimeFallbackSignalConfig, runtimeStatusAuthConfig })=>({
38
+ name: 'telemetry-runtime-status',
39
+ path: DEFAULT_RUNTIME_STATUS_ENDPOINT,
40
+ method: 'get',
41
+ order: 'pre',
42
+ handler: async (c)=>{
43
+ try {
44
+ if (!runtimeStatusAuthConfig?.enabled) return c.json({
45
+ ok: true,
46
+ timestamp: Date.now()
47
+ });
48
+ enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeStatusAuthConfig.headerName), runtimeStatusAuthConfig);
49
+ return c.json({
50
+ ok: true,
51
+ timestamp: Date.now(),
52
+ telemetry: {
53
+ queueStats: registry.getQueueStats(),
54
+ exporterHealth: registry.getExporterHealth()
55
+ },
56
+ canary: canaryOrchestrator ? {
57
+ enabled: true,
58
+ ...canaryOrchestrator.getStatusSnapshot()
59
+ } : {
60
+ enabled: false
61
+ },
62
+ runtimeFallbackSignal: runtimeFallbackSignalConfig ? {
63
+ enabled: true,
64
+ endpoint: runtimeFallbackSignalConfig.endpoint,
65
+ gateName: runtimeFallbackSignalConfig.gateName,
66
+ failureHoldMs: runtimeFallbackSignalConfig.failureHoldMs,
67
+ maxBodyBytes: runtimeFallbackSignalConfig.maxBodyBytes,
68
+ auth: {
69
+ enabled: runtimeFallbackSignalConfig.auth.enabled,
70
+ headerName: runtimeFallbackSignalConfig.auth.headerName
71
+ },
72
+ trustPolicy: {
73
+ allowedApps: runtimeFallbackSignalConfig.trustPolicy.allowedApps,
74
+ allowedEntryOrigins: runtimeFallbackSignalConfig.trustPolicy.allowedEntryOrigins,
75
+ enforceRuntimeDigest: runtimeFallbackSignalConfig.trustPolicy.enforceRuntimeDigest,
76
+ expectedRuntimeDigestsCount: Object.keys(runtimeFallbackSignalConfig.trustPolicy.expectedRuntimeDigests).length,
77
+ maxSignalsPerWindow: runtimeFallbackSignalConfig.trustPolicy.maxSignalsPerWindow,
78
+ windowMs: runtimeFallbackSignalConfig.trustPolicy.windowMs,
79
+ dedupeWindowMs: runtimeFallbackSignalConfig.trustPolicy.dedupeWindowMs
80
+ }
81
+ } : {
82
+ enabled: false
83
+ }
84
+ });
85
+ } catch (error) {
86
+ const signalError = error;
87
+ return c.json({
88
+ ok: false,
89
+ error: signalError instanceof Error ? signalError.message : String(signalError)
90
+ }, getRuntimeSignalErrorStatusCode(signalError));
91
+ }
92
+ }
93
+ });
94
+ export { createRuntimeFallbackSignalMiddleware, createRuntimeStatusMiddleware };