@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,277 @@
1
+ import type { LogEvent, MonitorEvent } from '@modern-js/types';
2
+
3
+ export type TelemetrySignalType = 'log' | 'metric' | 'trace';
4
+
5
+ export interface TelemetryEnvelope {
6
+ timestamp: number;
7
+ service: string;
8
+ module: string;
9
+ environment: string;
10
+ signalType: TelemetrySignalType;
11
+ name: string;
12
+ level?: string;
13
+ value?: number;
14
+ unit?: string;
15
+ traceId?: string;
16
+ spanId?: string;
17
+ parentSpanId?: string;
18
+ tags?: Record<string, string>;
19
+ attributes?: Record<string, unknown>;
20
+ error?: {
21
+ name?: string;
22
+ message: string;
23
+ stack?: string;
24
+ };
25
+ }
26
+
27
+ export interface TelemetryExporter {
28
+ name: string;
29
+ init?: (context: {
30
+ service: string;
31
+ module: string;
32
+ environment: string;
33
+ }) => void | Promise<void>;
34
+ emit: (batch: TelemetryEnvelope[]) => void | Promise<void>;
35
+ flush?: () => void | Promise<void>;
36
+ shutdown?: () => void | Promise<void>;
37
+ }
38
+
39
+ export type TelemetryEnvelopeBuilderContext = {
40
+ service: string;
41
+ module: string;
42
+ environment: string;
43
+ maxQueueSize: number;
44
+ };
45
+
46
+ export function buildDroppedEnvelope(
47
+ context: TelemetryEnvelopeBuilderContext,
48
+ droppedCount: number,
49
+ ): TelemetryEnvelope {
50
+ return {
51
+ timestamp: Date.now(),
52
+ service: context.service,
53
+ module: context.module,
54
+ environment: context.environment,
55
+ signalType: 'metric',
56
+ name: 'telemetry.queue.dropped',
57
+ value: droppedCount,
58
+ unit: 'count',
59
+ tags: {
60
+ reason: 'queue_backpressure',
61
+ },
62
+ };
63
+ }
64
+
65
+ export function buildQueueDepthEnvelope(
66
+ context: TelemetryEnvelopeBuilderContext,
67
+ queueDepth: number,
68
+ ): TelemetryEnvelope {
69
+ return {
70
+ timestamp: Date.now(),
71
+ service: context.service,
72
+ module: context.module,
73
+ environment: context.environment,
74
+ signalType: 'metric',
75
+ name: 'telemetry.queue.depth',
76
+ value: queueDepth,
77
+ unit: 'count',
78
+ tags: {
79
+ capacity: String(context.maxQueueSize),
80
+ },
81
+ };
82
+ }
83
+
84
+ export function buildQueueUtilizationEnvelope(
85
+ context: TelemetryEnvelopeBuilderContext,
86
+ queueDepth: number,
87
+ ): TelemetryEnvelope {
88
+ return {
89
+ timestamp: Date.now(),
90
+ service: context.service,
91
+ module: context.module,
92
+ environment: context.environment,
93
+ signalType: 'metric',
94
+ name: 'telemetry.queue.utilization',
95
+ value: queueDepth / context.maxQueueSize,
96
+ unit: 'ratio',
97
+ tags: {
98
+ capacity: String(context.maxQueueSize),
99
+ },
100
+ };
101
+ }
102
+
103
+ export function buildStartupProbeEnvelope(
104
+ context: TelemetryEnvelopeBuilderContext,
105
+ ): TelemetryEnvelope {
106
+ return {
107
+ timestamp: Date.now(),
108
+ service: context.service,
109
+ module: context.module,
110
+ environment: context.environment,
111
+ signalType: 'log',
112
+ name: 'telemetry.exporter.startup_probe',
113
+ level: 'info',
114
+ tags: {
115
+ phase: 'startup',
116
+ },
117
+ attributes: {
118
+ source: 'TelemetryRegistry',
119
+ },
120
+ };
121
+ }
122
+
123
+ export function clamp(value: number, min: number, max: number) {
124
+ if (Number.isNaN(value)) {
125
+ return max;
126
+ }
127
+
128
+ return Math.max(min, Math.min(max, value));
129
+ }
130
+
131
+ export function isRecord(value: unknown): value is Record<string, unknown> {
132
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
133
+ }
134
+
135
+ export function redactObject(
136
+ value: unknown,
137
+ redactionKeys: Set<string>,
138
+ ): Record<string, unknown> | undefined {
139
+ if (!isRecord(value)) {
140
+ return undefined;
141
+ }
142
+
143
+ const output: Record<string, unknown> = {};
144
+ for (const [key, nested] of Object.entries(value)) {
145
+ if (redactionKeys.has(key)) {
146
+ output[key] = '[REDACTED]';
147
+ continue;
148
+ }
149
+
150
+ if (Array.isArray(nested)) {
151
+ output[key] = nested.map(item => {
152
+ if (isRecord(item)) {
153
+ return redactObject(item, redactionKeys);
154
+ }
155
+ return item;
156
+ });
157
+ continue;
158
+ }
159
+
160
+ if (isRecord(nested)) {
161
+ output[key] = redactObject(nested, redactionKeys);
162
+ continue;
163
+ }
164
+
165
+ output[key] = nested;
166
+ }
167
+
168
+ return output;
169
+ }
170
+
171
+ function normalizeLabels(labels: Record<string, unknown> | undefined) {
172
+ if (!labels) {
173
+ return undefined;
174
+ }
175
+
176
+ const normalized: Record<string, string> = {};
177
+ for (const [key, value] of Object.entries(labels)) {
178
+ if (value === undefined || value === null) {
179
+ continue;
180
+ }
181
+ normalized[key] = String(value);
182
+ }
183
+
184
+ return Object.keys(normalized).length > 0 ? normalized : undefined;
185
+ }
186
+
187
+ function extractError(args: unknown[]): TelemetryEnvelope['error'] | undefined {
188
+ for (const arg of args) {
189
+ if (arg instanceof Error) {
190
+ return {
191
+ name: arg.name,
192
+ message: arg.message,
193
+ stack: arg.stack,
194
+ };
195
+ }
196
+ }
197
+
198
+ return undefined;
199
+ }
200
+
201
+ export function toTelemetryEnvelope(
202
+ event: MonitorEvent,
203
+ input: {
204
+ service: string;
205
+ module: string;
206
+ environment: string;
207
+ traceId?: string;
208
+ spanId?: string;
209
+ attributes?: Record<string, unknown>;
210
+ },
211
+ ): TelemetryEnvelope {
212
+ const base: Pick<
213
+ TelemetryEnvelope,
214
+ | 'timestamp'
215
+ | 'service'
216
+ | 'module'
217
+ | 'environment'
218
+ | 'traceId'
219
+ | 'spanId'
220
+ | 'attributes'
221
+ > = {
222
+ timestamp: Date.now(),
223
+ service: input.service,
224
+ module: input.module,
225
+ environment: input.environment,
226
+ ...(input.traceId ? { traceId: input.traceId } : {}),
227
+ ...(input.spanId ? { spanId: input.spanId } : {}),
228
+ ...(input.attributes ? { attributes: input.attributes } : {}),
229
+ };
230
+
231
+ if (event.type === 'log') {
232
+ const payload = event.payload as LogEvent['payload'];
233
+ const args = payload.args || [];
234
+ const signalType: TelemetrySignalType =
235
+ payload.level === 'trace' ? 'trace' : 'log';
236
+ return {
237
+ ...base,
238
+ signalType,
239
+ name: payload.message,
240
+ level: payload.level,
241
+ attributes: {
242
+ ...(base.attributes || {}),
243
+ args,
244
+ },
245
+ error: extractError(args),
246
+ };
247
+ }
248
+
249
+ if (event.type === 'timing') {
250
+ return {
251
+ ...base,
252
+ signalType: 'metric',
253
+ name: event.payload.name,
254
+ value: event.payload.dur,
255
+ unit: 'ms',
256
+ tags: normalizeLabels(event.payload.tags),
257
+ attributes: {
258
+ ...(base.attributes || {}),
259
+ desc: event.payload.desc,
260
+ args: event.payload.args,
261
+ },
262
+ };
263
+ }
264
+
265
+ return {
266
+ ...base,
267
+ signalType: 'metric',
268
+ name: event.payload.name,
269
+ value: 1,
270
+ unit: 'count',
271
+ tags: normalizeLabels(event.payload.tags),
272
+ attributes: {
273
+ ...(base.attributes || {}),
274
+ args: event.payload.args,
275
+ },
276
+ };
277
+ }
@@ -0,0 +1,165 @@
1
+ import type { TelemetryEnvelope, TelemetryExporter } from './envelope';
2
+
3
+ export interface OtlpExporterOptions {
4
+ endpoint?: string;
5
+ headers?: Record<string, string>;
6
+ timeoutMs?: number;
7
+ }
8
+
9
+ export interface VictoriaMetricsExporterOptions extends OtlpExporterOptions {
10
+ metricPrefix?: string;
11
+ }
12
+
13
+ const DEFAULT_OTLP_ENDPOINT = 'http://127.0.0.1:4318/v1/logs';
14
+ const DEFAULT_VM_ENDPOINT = 'http://127.0.0.1:8428/api/v1/import/prometheus';
15
+ const DEFAULT_TIMEOUT_MS = 5_000;
16
+
17
+ async function postWithTimeout(options: {
18
+ endpoint: string;
19
+ body: string;
20
+ headers: Record<string, string>;
21
+ timeoutMs: number;
22
+ }) {
23
+ const controller = new AbortController();
24
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs);
25
+ if (typeof (timer as NodeJS.Timeout).unref === 'function') {
26
+ (timer as NodeJS.Timeout).unref();
27
+ }
28
+
29
+ try {
30
+ const response = await fetch(options.endpoint, {
31
+ method: 'POST',
32
+ body: options.body,
33
+ headers: options.headers,
34
+ signal: controller.signal,
35
+ });
36
+
37
+ if (!response.ok) {
38
+ throw new Error(
39
+ `Telemetry exporter request failed: ${response.status} ${response.statusText}`,
40
+ );
41
+ }
42
+ } finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+
47
+ function sanitizeMetricName(value: string) {
48
+ return value.replace(/[^a-zA-Z0-9_:]/g, '_').replace(/_+/g, '_');
49
+ }
50
+
51
+ function escapeLabelValue(value: string) {
52
+ return value
53
+ .replace(/\\/g, '\\\\')
54
+ .replace(/"/g, '\\"')
55
+ .replace(/\n/g, '\\n');
56
+ }
57
+
58
+ function toPrometheusLine(
59
+ envelope: TelemetryEnvelope,
60
+ metricPrefix: string,
61
+ ): string {
62
+ const metricName = sanitizeMetricName(
63
+ `${metricPrefix}_${envelope.signalType}_${envelope.name}`,
64
+ );
65
+ const labels: Record<string, string> = {
66
+ service: envelope.service,
67
+ module: envelope.module,
68
+ environment: envelope.environment,
69
+ ...(envelope.level ? { level: envelope.level } : {}),
70
+ ...(envelope.traceId ? { trace_id: envelope.traceId } : {}),
71
+ ...(envelope.spanId ? { span_id: envelope.spanId } : {}),
72
+ ...(envelope.tags || {}),
73
+ };
74
+
75
+ const labelPairs = Object.entries(labels)
76
+ .sort(([a], [b]) => a.localeCompare(b))
77
+ .map(
78
+ ([key, value]) =>
79
+ `${sanitizeMetricName(key)}="${escapeLabelValue(value)}"`,
80
+ );
81
+ const labelText = labelPairs.length > 0 ? `{${labelPairs.join(',')}}` : '';
82
+ const value =
83
+ typeof envelope.value === 'number' && Number.isFinite(envelope.value)
84
+ ? envelope.value
85
+ : 1;
86
+ const timestampMs = envelope.timestamp;
87
+ return `${metricName}${labelText} ${value} ${timestampMs}`;
88
+ }
89
+
90
+ export function createOtlpTelemetryExporter(
91
+ options: OtlpExporterOptions = {},
92
+ ): TelemetryExporter {
93
+ const endpoint = options.endpoint || DEFAULT_OTLP_ENDPOINT;
94
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
95
+ const headers = {
96
+ 'content-type': 'application/json',
97
+ ...(options.headers || {}),
98
+ };
99
+
100
+ return {
101
+ name: 'otlp',
102
+ async emit(batch) {
103
+ if (batch.length === 0) {
104
+ return;
105
+ }
106
+
107
+ const body = JSON.stringify({
108
+ resource: {
109
+ service: batch[0]?.service,
110
+ module: batch[0]?.module,
111
+ environment: batch[0]?.environment,
112
+ },
113
+ emittedAt: Date.now(),
114
+ events: batch,
115
+ });
116
+
117
+ await postWithTimeout({
118
+ endpoint,
119
+ body,
120
+ headers,
121
+ timeoutMs,
122
+ });
123
+ },
124
+ };
125
+ }
126
+
127
+ export function createVictoriaMetricsTelemetryExporter(
128
+ options: VictoriaMetricsExporterOptions = {},
129
+ ): TelemetryExporter {
130
+ const endpoint = options.endpoint || DEFAULT_VM_ENDPOINT;
131
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
132
+ const metricPrefix = sanitizeMetricName(options.metricPrefix || 'modernjs');
133
+ const headers = {
134
+ 'content-type': 'text/plain; version=0.0.4',
135
+ ...(options.headers || {}),
136
+ };
137
+
138
+ return {
139
+ name: 'victoria-metrics',
140
+ async emit(batch) {
141
+ if (batch.length === 0) {
142
+ return;
143
+ }
144
+
145
+ const lines = batch.map(item => toPrometheusLine(item, metricPrefix));
146
+ await postWithTimeout({
147
+ endpoint,
148
+ body: `${lines.join('\n')}\n`,
149
+ headers,
150
+ timeoutMs,
151
+ });
152
+ },
153
+ };
154
+ }
155
+
156
+ export function maybeWarnLegacyOtlpEndpoint(endpoint: string | undefined) {
157
+ if (!endpoint || !endpoint.includes('/v1/metrics')) {
158
+ return;
159
+ }
160
+ // Keep this warning lightweight and runtime-safe.
161
+ // eslint-disable-next-line no-console
162
+ console.warn(
163
+ `[telemetry] OTLP endpoint "${endpoint}" looks like a metrics path. UltraModern telemetry exporter expects log-style envelopes (default: ${DEFAULT_OTLP_ENDPOINT}).`,
164
+ );
165
+ }
@@ -0,0 +1,138 @@
1
+ import type { ServerTelemetryUserConfig } from '@modern-js/server-core';
2
+ import {
3
+ type ContractGateSnapshotStore,
4
+ resolveContractGateSnapshotPath,
5
+ } from '../contract-gate-snapshot-store';
6
+ import { ContractGateAutopilot } from '../contractGateAutopilot';
7
+ import {
8
+ createOtlpTelemetryExporter,
9
+ createVictoriaMetricsTelemetryExporter,
10
+ maybeWarnLegacyOtlpEndpoint,
11
+ TelemetryCanaryOrchestrator,
12
+ TelemetryRegistry,
13
+ } from '../telemetryCore';
14
+
15
+ type TelemetryLifecycleApi = {
16
+ getServerContext: () => unknown;
17
+ onPrepare: (prepare: () => Promise<void>) => void;
18
+ };
19
+
20
+ type RegisterTelemetryLifecycleOptions = {
21
+ api: TelemetryLifecycleApi;
22
+ registry: TelemetryRegistry;
23
+ telemetryConfig: ServerTelemetryUserConfig;
24
+ canaryConfig: ServerTelemetryUserConfig['canary'] | undefined;
25
+ canaryOrchestrator?: TelemetryCanaryOrchestrator;
26
+ gateSnapshotStorePromise?: Promise<ContractGateSnapshotStore>;
27
+ appDirectory: string;
28
+ };
29
+
30
+ /**
31
+ * Active telemetry lane disposers, flushed by a single shared process
32
+ * `beforeExit` hook (a per-lane listener would accumulate listeners across
33
+ * dev-server restarts and embedded multi-server setups).
34
+ */
35
+ const activeTelemetryLaneClosers = new Set<() => Promise<void>>();
36
+ let telemetryBeforeExitHookInstalled = false;
37
+ const ensureTelemetryBeforeExitHook = () => {
38
+ if (telemetryBeforeExitHookInstalled) {
39
+ return;
40
+ }
41
+ telemetryBeforeExitHookInstalled = true;
42
+ process.on('beforeExit', () => {
43
+ for (const close of [...activeTelemetryLaneClosers]) {
44
+ void close();
45
+ }
46
+ });
47
+ };
48
+
49
+ export const registerTelemetryLifecycle = ({
50
+ api,
51
+ registry,
52
+ telemetryConfig,
53
+ canaryConfig,
54
+ canaryOrchestrator,
55
+ gateSnapshotStorePromise,
56
+ appDirectory,
57
+ }: RegisterTelemetryLifecycleOptions) => {
58
+ let contractGateAutopilot: ContractGateAutopilot | undefined;
59
+ let telemetryLaneClosed = false;
60
+ const closeTelemetryLane = async () => {
61
+ if (telemetryLaneClosed) {
62
+ return;
63
+ }
64
+ telemetryLaneClosed = true;
65
+ activeTelemetryLaneClosers.delete(closeTelemetryLane);
66
+ contractGateAutopilot?.stop();
67
+ canaryOrchestrator?.stop();
68
+ await registry.shutdown();
69
+ };
70
+
71
+ let prepared = false;
72
+ api.onPrepare(async () => {
73
+ if (prepared) {
74
+ return;
75
+ }
76
+ prepared = true;
77
+
78
+ // Shutdown path for the telemetry lane: flush pending envelopes and
79
+ // stop canary/autopilot pollers when the node server closes (this also
80
+ // covers dev-server restarts, which close the previous node server
81
+ // before assembling a new one), with process beforeExit as the
82
+ // final-flush floor when no node server handle exists.
83
+ const { nodeServer } = api.getServerContext() as {
84
+ nodeServer?: {
85
+ once?: (event: string, listener: () => void) => unknown;
86
+ };
87
+ };
88
+ if (nodeServer && typeof nodeServer.once === 'function') {
89
+ nodeServer.once('close', () => {
90
+ void closeTelemetryLane();
91
+ });
92
+ }
93
+ activeTelemetryLaneClosers.add(closeTelemetryLane);
94
+ ensureTelemetryBeforeExitHook();
95
+
96
+ if (telemetryConfig.exporters?.otlp?.enabled) {
97
+ maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
98
+ await registry.register(
99
+ createOtlpTelemetryExporter(telemetryConfig.exporters.otlp),
100
+ );
101
+ }
102
+
103
+ if (telemetryConfig.exporters?.victoriaMetrics?.enabled) {
104
+ await registry.register(
105
+ createVictoriaMetricsTelemetryExporter(
106
+ telemetryConfig.exporters.victoriaMetrics,
107
+ ),
108
+ );
109
+ }
110
+
111
+ await registry.startupHealthCheck({
112
+ failLoud: telemetryConfig.failLoudStartup ?? true,
113
+ });
114
+
115
+ if (!canaryOrchestrator) {
116
+ return;
117
+ }
118
+
119
+ canaryOrchestrator.start();
120
+ if (gateSnapshotStorePromise) {
121
+ const gateSnapshotStore = await gateSnapshotStorePromise;
122
+ contractGateAutopilot = new ContractGateAutopilot({
123
+ orchestrator: canaryOrchestrator,
124
+ gateSnapshotPath: resolveContractGateSnapshotPath(
125
+ appDirectory,
126
+ canaryConfig?.autopilot?.gateSnapshotPath,
127
+ ),
128
+ gateSnapshotStore,
129
+ pollIntervalMs: canaryConfig?.autopilot?.pollIntervalMs,
130
+ gateStaleAfterMs: canaryConfig?.autopilot?.gateStaleAfterMs,
131
+ });
132
+ }
133
+ if (contractGateAutopilot) {
134
+ await contractGateAutopilot.start();
135
+ }
136
+ canaryOrchestrator.evaluate();
137
+ });
138
+ };
@@ -0,0 +1,141 @@
1
+ import type { Metrics } from '@modern-js/types';
2
+
3
+ import { isRecord } from './envelope';
4
+ import type { TelemetryRegistry } from './registry';
5
+
6
+ type TelemetryMetricsTags = Record<string, unknown>;
7
+ type TelemetryMetricsPrefixOrTags = string | TelemetryMetricsTags;
8
+
9
+ function normalizeMetricsInput(
10
+ prefixOrTags?: TelemetryMetricsPrefixOrTags,
11
+ tags?: TelemetryMetricsTags,
12
+ ) {
13
+ if (typeof prefixOrTags === 'string') {
14
+ return {
15
+ prefix: prefixOrTags,
16
+ tags: tags || {},
17
+ };
18
+ }
19
+
20
+ if (isRecord(prefixOrTags)) {
21
+ return {
22
+ prefix: undefined,
23
+ tags: prefixOrTags,
24
+ };
25
+ }
26
+
27
+ return {
28
+ prefix: undefined,
29
+ tags: tags || {},
30
+ };
31
+ }
32
+
33
+ function normalizeMetricName(name: string, prefix: string | undefined) {
34
+ return prefix && prefix.length > 0 ? `${prefix}.${name}` : name;
35
+ }
36
+
37
+ function toTelemetryMetricTags(tags: TelemetryMetricsTags) {
38
+ const output: Record<string, string> = {};
39
+ for (const [key, value] of Object.entries(tags)) {
40
+ if (value === undefined || value === null) {
41
+ continue;
42
+ }
43
+ output[key] = String(value);
44
+ }
45
+ return output;
46
+ }
47
+
48
+ function getTraceContext(tags: TelemetryMetricsTags) {
49
+ const traceId =
50
+ typeof tags.trace_id === 'string'
51
+ ? tags.trace_id
52
+ : typeof tags.traceId === 'string'
53
+ ? tags.traceId
54
+ : undefined;
55
+
56
+ const spanId =
57
+ typeof tags.span_id === 'string'
58
+ ? tags.span_id
59
+ : typeof tags.spanId === 'string'
60
+ ? tags.spanId
61
+ : undefined;
62
+
63
+ const parentSpanId =
64
+ typeof tags.parent_span_id === 'string'
65
+ ? tags.parent_span_id
66
+ : typeof tags.parentSpanId === 'string'
67
+ ? tags.parentSpanId
68
+ : undefined;
69
+
70
+ return {
71
+ traceId,
72
+ spanId,
73
+ parentSpanId,
74
+ };
75
+ }
76
+
77
+ export const createTelemetryAwareMetrics = <T extends Metrics>(
78
+ baseMetrics: T,
79
+ registry: TelemetryRegistry,
80
+ ): T => {
81
+ const emitCounter: Metrics['emitCounter'] = (
82
+ name,
83
+ value,
84
+ prefixOrTags,
85
+ tags,
86
+ ) => {
87
+ const normalized = normalizeMetricsInput(
88
+ prefixOrTags as TelemetryMetricsPrefixOrTags | undefined,
89
+ tags,
90
+ );
91
+ baseMetrics.emitCounter(name, value, normalized.prefix, normalized.tags);
92
+
93
+ try {
94
+ const metricName = normalizeMetricName(name, normalized.prefix);
95
+ const traceContext = getTraceContext(normalized.tags);
96
+ registry.enqueueMetric({
97
+ name: metricName,
98
+ value,
99
+ unit: 'count',
100
+ traceId: traceContext.traceId,
101
+ spanId: traceContext.spanId,
102
+ parentSpanId: traceContext.parentSpanId,
103
+ tags: toTelemetryMetricTags(normalized.tags),
104
+ attributes: normalized.tags,
105
+ });
106
+ } catch (_error) {
107
+ // telemetry wrapping must never break request metrics.
108
+ }
109
+ };
110
+
111
+ const emitTimer: Metrics['emitTimer'] = (name, value, prefixOrTags, tags) => {
112
+ const normalized = normalizeMetricsInput(
113
+ prefixOrTags as TelemetryMetricsPrefixOrTags | undefined,
114
+ tags,
115
+ );
116
+ baseMetrics.emitTimer(name, value, normalized.prefix, normalized.tags);
117
+
118
+ try {
119
+ const metricName = normalizeMetricName(name, normalized.prefix);
120
+ const traceContext = getTraceContext(normalized.tags);
121
+ registry.enqueueMetric({
122
+ name: metricName,
123
+ value,
124
+ unit: 'ms',
125
+ traceId: traceContext.traceId,
126
+ spanId: traceContext.spanId,
127
+ parentSpanId: traceContext.parentSpanId,
128
+ tags: toTelemetryMetricTags(normalized.tags),
129
+ attributes: normalized.tags,
130
+ });
131
+ } catch (_error) {
132
+ // telemetry wrapping must never break request metrics.
133
+ }
134
+ };
135
+
136
+ return {
137
+ ...baseMetrics,
138
+ emitCounter,
139
+ emitTimer,
140
+ };
141
+ };