@bleedingdev/modern-js-server-runtime-extensions 3.9.0-ultramodern.1 → 3.9.0-ultramodern.10

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/README.md +5 -5
  2. package/dist/cjs/bff-policy/crossProjectPolicy.js +299 -0
  3. package/dist/cjs/bff-policy/index.js +62 -0
  4. package/dist/cjs/bff-policy/node.js +69 -0
  5. package/dist/cjs/bff-policy/operationContracts.js +182 -0
  6. package/dist/cjs/bff-policy/resolveCrossProjectPolicy.js +65 -0
  7. package/dist/cjs/contract-gate-snapshot-store/http-store.js +1 -8
  8. package/dist/cjs/errorResponsePlugin.js +57 -0
  9. package/dist/cjs/localisedLoaderPlugin.js +62 -0
  10. package/dist/cjs/mfCache.js +6 -0
  11. package/dist/cjs/module-federation-css/plugin.js +6 -0
  12. package/dist/cjs/serverConfig.js +18 -0
  13. package/dist/cjs/serverPlugin.js +74 -0
  14. package/dist/cjs/static-serving/plugin.js +57 -0
  15. package/dist/cjs/static-serving/responders.js +158 -0
  16. package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
  17. package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
  18. package/dist/cjs/telemetry/exporters.js +4 -4
  19. package/dist/cjs/telemetry/healthSetup.js +14 -14
  20. package/dist/cjs/telemetry/lifecycle.js +20 -21
  21. package/dist/cjs/telemetry/plugin.js +10 -4
  22. package/dist/cjs/telemetry/runtimeEndpoints.js +3 -2
  23. package/dist/cjs/telemetryCore.js +5 -5
  24. package/dist/esm/bff-policy/crossProjectPolicy.mjs +249 -0
  25. package/dist/esm/bff-policy/index.mjs +1 -0
  26. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -8
  27. package/dist/esm/errorResponsePlugin.mjs +19 -0
  28. package/dist/esm/localisedLoaderPlugin.mjs +24 -0
  29. package/dist/esm/mfCache.mjs +6 -0
  30. package/dist/esm/module-federation-css/plugin.mjs +6 -0
  31. package/dist/esm/serverConfig.mjs +0 -0
  32. package/dist/esm/serverPlugin.mjs +34 -0
  33. package/dist/esm/telemetry/exporters.mjs +2 -2
  34. package/dist/esm/telemetry/healthSetup.mjs +14 -14
  35. package/dist/esm/telemetry/lifecycle.mjs +21 -22
  36. package/dist/esm/telemetry/plugin.mjs +9 -3
  37. package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -2
  38. package/dist/esm/telemetryCore.mjs +1 -1
  39. package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +250 -0
  40. package/dist/esm-node/bff-policy/index.mjs +2 -0
  41. package/dist/esm-node/bff-policy/node.mjs +3 -0
  42. package/dist/esm-node/bff-policy/operationContracts.mjs +129 -0
  43. package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
  44. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -8
  45. package/dist/esm-node/errorResponsePlugin.mjs +20 -0
  46. package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
  47. package/dist/esm-node/mfCache.mjs +6 -0
  48. package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
  49. package/dist/esm-node/serverConfig.mjs +1 -0
  50. package/dist/esm-node/serverPlugin.mjs +35 -0
  51. package/dist/esm-node/static-serving/plugin.mjs +18 -0
  52. package/dist/esm-node/static-serving/responders.mjs +111 -0
  53. package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
  54. package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
  55. package/dist/esm-node/telemetry/exporters.mjs +2 -2
  56. package/dist/esm-node/telemetry/healthSetup.mjs +14 -14
  57. package/dist/esm-node/telemetry/lifecycle.mjs +21 -22
  58. package/dist/esm-node/telemetry/plugin.mjs +9 -3
  59. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -2
  60. package/dist/esm-node/telemetryCore.mjs +1 -1
  61. package/dist/types/bff-policy/crossProjectPolicy.d.ts +101 -0
  62. package/dist/types/bff-policy/index.d.ts +1 -0
  63. package/dist/types/bff-policy/node.d.ts +2 -0
  64. package/dist/types/bff-policy/operationContracts.d.ts +85 -0
  65. package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
  66. package/dist/types/errorResponsePlugin.d.ts +3 -0
  67. package/dist/types/index.d.ts +1 -0
  68. package/dist/types/localisedLoaderPlugin.d.ts +2 -0
  69. package/dist/types/mfCache.d.ts +2 -3
  70. package/dist/types/module-federation-css/plugin.d.ts +2 -3
  71. package/dist/types/serverConfig.d.ts +17 -0
  72. package/dist/types/serverPlugin.d.ts +5 -0
  73. package/dist/types/static-serving/plugin.d.ts +3 -0
  74. package/dist/types/static-serving/responders.d.ts +2 -0
  75. package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
  76. package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
  77. package/dist/types/telemetry/exporters.d.ts +1 -1
  78. package/dist/types/telemetry/healthSetup.d.ts +3 -3
  79. package/dist/types/telemetry/lifecycle.d.ts +4 -4
  80. package/dist/types/telemetry/plugin.d.ts +2 -1
  81. package/dist/types/telemetryCore.d.ts +1 -1
  82. package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
  83. package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
  84. package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +101 -0
  85. package/dist/types-esm/bff-policy/index.d.mts +1 -0
  86. package/dist/types-esm/bff-policy/node.d.mts +2 -0
  87. package/dist/types-esm/bff-policy/operationContracts.d.mts +85 -0
  88. package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
  89. package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
  90. package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
  91. package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
  92. package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
  93. package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
  94. package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
  95. package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
  96. package/dist/types-esm/env.d.mts +40 -0
  97. package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
  98. package/dist/types-esm/index.d.mts +8 -0
  99. package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
  100. package/dist/types-esm/mfCache.d.mts +26 -0
  101. package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
  102. package/dist/types-esm/module-federation-css/index.d.mts +8 -0
  103. package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
  104. package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
  105. package/dist/types-esm/module-federation-css/remote.d.mts +20 -0
  106. package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
  107. package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
  108. package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
  109. package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
  110. package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
  111. package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
  112. package/dist/types-esm/serverConfig.d.mts +17 -0
  113. package/dist/types-esm/serverPlugin.d.mts +5 -0
  114. package/dist/types-esm/static-serving/plugin.d.mts +3 -0
  115. package/dist/types-esm/static-serving/responders.d.mts +2 -0
  116. package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
  117. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
  118. package/dist/types-esm/telemetry/envelope.d.mts +55 -0
  119. package/dist/types-esm/telemetry/exporters.d.mts +12 -0
  120. package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
  121. package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
  122. package/dist/types-esm/telemetry/healthSetup.d.mts +17 -0
  123. package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
  124. package/dist/types-esm/telemetry/metrics.d.mts +3 -0
  125. package/dist/types-esm/telemetry/plugin.d.mts +13 -0
  126. package/dist/types-esm/telemetry/registry.d.mts +69 -0
  127. package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
  128. package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +35 -0
  129. package/dist/types-esm/telemetry.d.mts +1 -0
  130. package/dist/types-esm/telemetryCore.d.mts +6 -0
  131. package/package.json +159 -27
  132. package/rslib.config.mts +36 -2
  133. package/rstest.config.mts +11 -0
  134. package/src/bff-policy/crossProjectPolicy.ts +754 -0
  135. package/src/bff-policy/index.ts +1 -0
  136. package/src/bff-policy/node.ts +2 -0
  137. package/src/bff-policy/operationContracts.ts +298 -0
  138. package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
  139. package/src/contract-gate-snapshot-store/http-store.ts +1 -11
  140. package/src/errorResponsePlugin.ts +21 -0
  141. package/src/index.ts +4 -0
  142. package/src/localisedLoaderPlugin.ts +34 -0
  143. package/src/mfCache.ts +4 -3
  144. package/src/module-federation-css/plugin.ts +4 -3
  145. package/src/serverConfig.ts +32 -0
  146. package/src/serverPlugin.ts +38 -0
  147. package/src/static-serving/plugin.ts +16 -0
  148. package/src/static-serving/responders.ts +208 -0
  149. package/src/static-serving/staticModuleFederation.ts +255 -0
  150. package/src/static-serving/staticPrecompressed.ts +193 -0
  151. package/src/telemetry/exporters.ts +1 -1
  152. package/src/telemetry/healthSetup.ts +17 -20
  153. package/src/telemetry/lifecycle.ts +27 -39
  154. package/src/telemetry/plugin.ts +6 -4
  155. package/src/telemetry/runtimeEndpoints.ts +3 -2
  156. package/src/telemetryCore.ts +1 -1
  157. package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +450 -0
  158. package/tests/bff-policy/crossProjectPolicy.test.ts +197 -0
  159. package/tests/bff-policy/operationContracts.test.ts +221 -0
  160. package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
  161. package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +76 -0
  162. package/tests/contractGateSnapshotObserver.test.ts +0 -58
  163. package/tests/contractGateSnapshotStore.test.ts +0 -51
  164. package/tests/env.test.ts +45 -64
  165. package/tests/localisedLoader.test.ts +120 -0
  166. package/tests/mfCache.test.ts +1 -88
  167. package/tests/moduleFederationCss.test.ts +4 -48
  168. package/tests/nativeErrorResponse.test.ts +118 -0
  169. package/tests/nativeServerAssembly.test.ts +385 -0
  170. package/tests/runtimeLifecycle.test.ts +69 -17
  171. package/tests/static-serving/ordering.test.ts +214 -0
  172. package/tests/static-serving/static.test.ts +411 -0
  173. package/tests/telemetry.test.ts +35 -198
  174. package/tests/telemetryHealthMonitor.test.ts +0 -4
  175. package/tests/telemetryHealthObservation.test.ts +302 -0
  176. package/tests/telemetryLifecycle.test.ts +7 -303
  177. package/tests/telemetryRegistryQueueMatrix.test.ts +14 -111
  178. package/tests/registration.test.ts +0 -112
  179. package/tests/telemetryAutopilot.test.ts +0 -1134
@@ -0,0 +1,302 @@
1
+ import { createDefaultPlugins, createServerBase } from '@modern-js/server-core';
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
5
+ import { injectTelemetryPlugin } from '../src/telemetry';
6
+ import { getDefaultAppContext, getDefaultConfig } from './helpers';
7
+
8
+ type ServerBase = ReturnType<typeof createServerBase>;
9
+
10
+ const SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
11
+ const TOKEN_HEADER = 'x-modernjs-runtime-signal-token';
12
+
13
+ /**
14
+ * Boots a real server with the telemetry plugin and the given snapshot-
15
+ * observation
16
+ * config, then tears the temp workspace down. `server.init()` is left to the
17
+ * caller so fail-closed init can be asserted.
18
+ */
19
+ const withHealthObservation = async (
20
+ snapshotObservation: Record<string, unknown>,
21
+ run: (server: ServerBase, snapshotPath: string) => Promise<void>,
22
+ ) => {
23
+ const tempDir = fs.mkdtempSync(
24
+ path.join(os.tmpdir(), 'modern-telemetry-health-observation-'),
25
+ );
26
+ const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
27
+ try {
28
+ const config = getDefaultConfig();
29
+ config.server = {
30
+ telemetry: {
31
+ enabled: true,
32
+ health: {
33
+ enabled: true,
34
+ minConsecutiveFailedEvaluations: 1,
35
+ snapshotObservation: {
36
+ enabled: true,
37
+ gateSnapshotPath: snapshotPath,
38
+ ...snapshotObservation,
39
+ },
40
+ },
41
+ },
42
+ } as any;
43
+
44
+ const server = createServerBase({
45
+ config,
46
+ pwd: tempDir,
47
+ appContext: getDefaultAppContext(),
48
+ });
49
+ server.addPlugins([
50
+ ...createDefaultPlugins({ logger: false }),
51
+ injectTelemetryPlugin(),
52
+ ]);
53
+
54
+ await run(server, snapshotPath);
55
+ } finally {
56
+ fs.rmSync(tempDir, { recursive: true, force: true });
57
+ }
58
+ };
59
+
60
+ const postSignal = (server: ServerBase, token: string | null, body: unknown) =>
61
+ server.request(
62
+ SIGNAL_ENDPOINT,
63
+ {
64
+ method: 'POST',
65
+ headers: new Headers({
66
+ 'content-type': 'application/json',
67
+ ...(token ? { [TOKEN_HEADER]: token } : {}),
68
+ }),
69
+ body: JSON.stringify(body),
70
+ },
71
+ {},
72
+ );
73
+
74
+ describe('telemetry health observation runtime signal', () => {
75
+ test('rejects oversized runtime fallback signal payload', async () => {
76
+ await withHealthObservation(
77
+ {
78
+ runtimeFallbackSignal: {
79
+ enabled: true,
80
+ endpoint: SIGNAL_ENDPOINT,
81
+ maxBodyBytes: 16,
82
+ auth: { expectedValue: 'oversize-signal-token' },
83
+ },
84
+ },
85
+ async server => {
86
+ await server.init();
87
+ const response = await postSignal(server, 'oversize-signal-token', {
88
+ reason: 'x'.repeat(2_048),
89
+ });
90
+ expect(response.status).toBe(413);
91
+ const payload = (await response.json()) as { error?: string };
92
+ expect(String(payload.error)).toContain('payload too large');
93
+ },
94
+ );
95
+ });
96
+
97
+ test('requires runtime fallback auth token when configured', async () => {
98
+ await withHealthObservation(
99
+ {
100
+ runtimeFallbackSignal: {
101
+ enabled: true,
102
+ endpoint: SIGNAL_ENDPOINT,
103
+ auth: {
104
+ enabled: true,
105
+ headerName: TOKEN_HEADER,
106
+ expectedValue: 'top-secret-token',
107
+ },
108
+ },
109
+ },
110
+ async (server, snapshotPath) => {
111
+ await server.init();
112
+ const signal = {
113
+ reason: 'remote_load_failed',
114
+ phase: 'load',
115
+ appName: 'crm',
116
+ };
117
+
118
+ const rejected = await postSignal(server, null, signal);
119
+ expect(rejected.status).toBe(401);
120
+ expect(fs.existsSync(snapshotPath)).toBe(false);
121
+
122
+ const accepted = await postSignal(server, 'top-secret-token', signal);
123
+ expect(accepted.status).toBe(202);
124
+ expect(fs.existsSync(snapshotPath)).toBe(true);
125
+ },
126
+ );
127
+ });
128
+
129
+ test('enforces runtime fallback trust policy before mutating gate snapshots', async () => {
130
+ await withHealthObservation(
131
+ {
132
+ runtimeFallbackSignal: {
133
+ enabled: true,
134
+ endpoint: SIGNAL_ENDPOINT,
135
+ auth: { expectedValue: 'trust-policy-token' },
136
+ trustPolicy: {
137
+ allowedApps: ['crm-shell'],
138
+ allowedEntryOrigins: ['https://erp.example.com'],
139
+ expectedRuntimeDigests: { 'crm-shell': 'digest-crm-v1' },
140
+ enforceRuntimeDigest: true,
141
+ },
142
+ },
143
+ },
144
+ async (server, snapshotPath) => {
145
+ await server.init();
146
+ const base = {
147
+ reason: 'remote_load_failed',
148
+ phase: 'load',
149
+ appName: 'crm-shell',
150
+ entry: 'https://erp.example.com/remoteEntry.js',
151
+ runtimeDigest: 'digest-crm-v1',
152
+ };
153
+
154
+ const untrustedApp = await postSignal(server, 'trust-policy-token', {
155
+ ...base,
156
+ appName: 'unknown-app',
157
+ });
158
+ expect(untrustedApp.status).toBe(403);
159
+
160
+ const digestMismatch = await postSignal(server, 'trust-policy-token', {
161
+ ...base,
162
+ runtimeDigest: 'digest-wrong',
163
+ });
164
+ expect(digestMismatch.status).toBe(403);
165
+
166
+ const trusted = await postSignal(server, 'trust-policy-token', {
167
+ ...base,
168
+ metadata: {
169
+ compatibility: { '@tanstack/react-router': '1.170.15' },
170
+ },
171
+ });
172
+ expect(trusted.status).toBe(202);
173
+
174
+ const snapshot = JSON.parse(fs.readFileSync(snapshotPath, 'utf8')) as {
175
+ gates?: Record<string, any>;
176
+ };
177
+ const gate = snapshot.gates?.['runtime-mf-fallback-health'];
178
+ expect(gate?.passed).toBe(false);
179
+ expect(
180
+ gate?.metadata?.metadata?.compatibility?.['@tanstack/react-router'],
181
+ ).toBe('1.170.15');
182
+ },
183
+ );
184
+ });
185
+
186
+ test('dedupes repeated fallback events and rate limits rotated identities', async () => {
187
+ await withHealthObservation(
188
+ {
189
+ runtimeFallbackSignal: {
190
+ enabled: true,
191
+ endpoint: SIGNAL_ENDPOINT,
192
+ auth: { expectedValue: 'rate-limit-token' },
193
+ trustPolicy: {
194
+ dedupeWindowMs: 60_000,
195
+ maxSignalsPerWindow: 1,
196
+ windowMs: 60_000,
197
+ },
198
+ },
199
+ },
200
+ async server => {
201
+ await server.init();
202
+ const sendSignal = (appName: string) =>
203
+ postSignal(server, 'rate-limit-token', {
204
+ reason: 'remote_mount_failed',
205
+ phase: 'mount',
206
+ appName,
207
+ entry: `https://${appName}.example.com/remoteEntry.js`,
208
+ });
209
+
210
+ expect((await sendSignal('app-a')).status).toBe(202);
211
+
212
+ const duplicate = await sendSignal('app-a');
213
+ expect(duplicate.status).toBe(202);
214
+ expect(((await duplicate.json()) as any).deduped).toBe(true);
215
+
216
+ // A rotated appName/entry pair used to mint a fresh rate-limit bucket;
217
+ // the limiter is now keyed on connection identity instead.
218
+ expect((await sendSignal('app-b')).status).toBe(429);
219
+ },
220
+ );
221
+ });
222
+
223
+ test('keeps the runtime fallback signal endpoint disabled unless explicitly enabled', async () => {
224
+ // no runtimeFallbackSignal config: the health kill switch must stay OFF.
225
+ await withHealthObservation({}, async (server, snapshotPath) => {
226
+ await server.init();
227
+ const response = await postSignal(server, null, {
228
+ reason: 'remote_load_failed',
229
+ phase: 'load',
230
+ appName: 'dashboard',
231
+ });
232
+ expect(response.status).toBe(404);
233
+ expect(fs.existsSync(snapshotPath)).toBe(false);
234
+ });
235
+ });
236
+
237
+ test('refuses to enable the runtime fallback signal endpoint without an auth token', async () => {
238
+ await withHealthObservation(
239
+ // enabled with no auth token configured: init must fail closed.
240
+ { runtimeFallbackSignal: { enabled: true } },
241
+ async server => {
242
+ await expect(server.init()).rejects.toThrow(
243
+ /requires an auth token|auth\.expectedValue/,
244
+ );
245
+ },
246
+ );
247
+ });
248
+
249
+ test('runtime status endpoint stays a bare health probe without configured auth', async () => {
250
+ await withHealthObservation({}, async server => {
251
+ await server.init();
252
+ const response = await server.request('/_modern/runtime/status', {}, {});
253
+ expect(response.status).toBe(200);
254
+ const payload = (await response.json()) as Record<string, unknown>;
255
+ expect(payload.ok).toBe(true);
256
+ // No telemetry/health/trust internals are disclosed without auth.
257
+ expect(payload.telemetry).toBeUndefined();
258
+ expect(payload.health).toBeUndefined();
259
+ expect(payload.runtimeFallbackSignal).toBeUndefined();
260
+ });
261
+ });
262
+
263
+ test('runtime status auth works even when the signal endpoint stays disabled', async () => {
264
+ await withHealthObservation(
265
+ {
266
+ runtimeFallbackSignal: {
267
+ // endpoint stays disabled, but its auth config still guards the
268
+ // status endpoint detail view.
269
+ auth: { enabled: true, expectedValue: 'status-only-token' },
270
+ },
271
+ },
272
+ async server => {
273
+ await server.init();
274
+
275
+ const signalResponse = await postSignal(server, 'status-only-token', {
276
+ appName: 'dashboard',
277
+ });
278
+ expect(signalResponse.status).toBe(404);
279
+
280
+ const unauthorized = await server.request(
281
+ '/_modern/runtime/status',
282
+ {},
283
+ {},
284
+ );
285
+ expect(unauthorized.status).toBe(401);
286
+
287
+ const authorized = await server.request(
288
+ '/_modern/runtime/status',
289
+ {
290
+ method: 'GET',
291
+ headers: new Headers({ [TOKEN_HEADER]: 'status-only-token' }),
292
+ },
293
+ {},
294
+ );
295
+ expect(authorized.status).toBe(200);
296
+ const payload = (await authorized.json()) as Record<string, any>;
297
+ expect(payload.health?.enabled).toBe(true);
298
+ expect(payload.runtimeFallbackSignal?.enabled).toBe(false);
299
+ },
300
+ );
301
+ });
302
+ });
@@ -4,10 +4,6 @@ import {
4
4
  createServerBase,
5
5
  type ServerPlugin,
6
6
  } from '@modern-js/server-core';
7
- import { logger } from '@modern-js/utils';
8
- import fs from 'fs';
9
- import os from 'os';
10
- import path from 'path';
11
7
  import { injectTelemetryPlugin } from '../src/telemetry';
12
8
  import { getDefaultAppContext, getDefaultConfig } from './helpers';
13
9
 
@@ -49,302 +45,7 @@ const waitFor = async (
49
45
  };
50
46
 
51
47
  describe('telemetry plugin lifecycle', () => {
52
- test('wires server.telemetry.slo through to alert emission', async () => {
53
- const warnSpy = rs.spyOn(logger, 'warn').mockImplementation(() => {});
54
-
55
- try {
56
- const config = getDefaultConfig();
57
- config.server = {
58
- telemetry: {
59
- enabled: true,
60
- maxQueueSize: 2,
61
- maxBatchSize: 500,
62
- flushIntervalMs: 60_000,
63
- slo: {
64
- queueUtilizationWarnThreshold: 0.5,
65
- queueDroppedWarnThreshold: 1,
66
- alertCooldownMs: 0,
67
- },
68
- },
69
- } as any;
70
-
71
- const server = createServerBase({
72
- config,
73
- pwd: process.cwd(),
74
- appContext: getDefaultAppContext(),
75
- });
76
- server.addPlugins([
77
- ...createDefaultPlugins({ logger: false }),
78
- injectTelemetryPlugin(),
79
- emitMonitorEventsPlugin({
80
- path: '/emit',
81
- message: 'slo-probe',
82
- count: 6,
83
- }),
84
- ]);
85
- await server.init();
86
-
87
- const response = await server.request('/emit', {}, {});
88
- expect(response.status).toBe(200);
89
-
90
- const sloWarnings = warnSpy.mock.calls.filter(call =>
91
- String(call[0]).includes('[telemetry.slo]'),
92
- );
93
- expect(sloWarnings.length).toBeGreaterThan(0);
94
- expect(
95
- sloWarnings.some(call => String(call[0]).includes('queue.drop')),
96
- ).toBe(true);
97
- } finally {
98
- warnSpy.mockRestore();
99
- }
100
- });
101
-
102
- test('boots canary autopilot lane and exports rollback telemetry', async () => {
103
- const tempDir = fs.mkdtempSync(
104
- path.join(os.tmpdir(), 'modern-telemetry-lifecycle-'),
105
- );
106
- const gateName = 'runtime-mf-fallback-health';
107
- const signalToken = 'canary-lifecycle-token';
108
- const snapshotPath = path.join(tempDir, '.modern/contract-gates.json');
109
- const otlpEndpoint = 'http://127.0.0.1:4318/v1/logs';
110
- const fetchCalls: Array<{
111
- url: string;
112
- body: string;
113
- headers: HeadersInit | undefined;
114
- }> = [];
115
- const fetchMock = rs.fn(async (url: any, init?: RequestInit) => {
116
- fetchCalls.push({
117
- url: String(url),
118
- body: String(init?.body ?? ''),
119
- headers: init?.headers,
120
- });
121
- return new Response('{}', { status: 200 });
122
- });
123
- const warnSpy = rs.spyOn(logger, 'warn').mockImplementation(() => {});
124
- const originalFetch = globalThis.fetch;
125
- globalThis.fetch = fetchMock as typeof fetch;
126
-
127
- const nodeServerStub = new EventEmitter();
128
- const stubNodeServerPlugin: ServerPlugin = {
129
- name: 'stub-node-server',
130
- setup(api) {
131
- api.updateServerContext({ nodeServer: nodeServerStub } as any);
132
- },
133
- };
134
-
135
- try {
136
- fs.mkdirSync(path.dirname(snapshotPath), { recursive: true });
137
- fs.writeFileSync(
138
- snapshotPath,
139
- JSON.stringify({
140
- schemaVersion: 1,
141
- updatedAt: Date.now(),
142
- gates: {
143
- [gateName]: {
144
- passed: true,
145
- updatedAt: Date.now(),
146
- },
147
- },
148
- }),
149
- 'utf8',
150
- );
151
-
152
- const config = getDefaultConfig();
153
- config.server = {
154
- telemetry: {
155
- enabled: true,
156
- service: 'runtime-extensions-test',
157
- module: 'telemetry-lifecycle',
158
- environment: 'test',
159
- maxQueueSize: 64,
160
- maxBatchSize: 100,
161
- flushIntervalMs: 60_000,
162
- slo: {
163
- queueUtilizationWarnThreshold: 0.01,
164
- alertCooldownMs: 0,
165
- },
166
- exporters: {
167
- otlp: {
168
- enabled: true,
169
- endpoint: otlpEndpoint,
170
- headers: {
171
- 'x-modernjs-test': 'canary-autopilot',
172
- },
173
- timeoutMs: 200,
174
- },
175
- },
176
- canary: {
177
- enabled: true,
178
- evaluationIntervalMs: 250,
179
- minConsecutiveHealthyEvaluations: 1,
180
- rollbackConsecutiveFailures: 1,
181
- maxQueueUtilization: 1,
182
- maxTotalDropped: 0,
183
- maxUnhealthyExporters: 0,
184
- contractGates: {
185
- [gateName]: true,
186
- },
187
- autopilot: {
188
- enabled: true,
189
- gateSnapshotPath: snapshotPath,
190
- pollIntervalMs: 250,
191
- gateStaleAfterMs: 60_000,
192
- runtimeFallbackSignal: {
193
- enabled: true,
194
- endpoint: '/_modern/contract-gates/runtime-fallback',
195
- gateName,
196
- failureHoldMs: 5_000,
197
- maxBodyBytes: 4_096,
198
- auth: {
199
- expectedValue: signalToken,
200
- },
201
- },
202
- },
203
- },
204
- },
205
- } as any;
206
-
207
- const server = createServerBase({
208
- config,
209
- pwd: tempDir,
210
- appContext: getDefaultAppContext(),
211
- });
212
- server.addPlugins([
213
- ...createDefaultPlugins({ logger: false }),
214
- stubNodeServerPlugin,
215
- injectTelemetryPlugin(),
216
- emitMonitorEventsPlugin({
217
- path: '/emit',
218
- message: 'canary-request',
219
- count: 2,
220
- }),
221
- ]);
222
- await server.init();
223
-
224
- const statusHeaders = new Headers({
225
- 'x-modernjs-runtime-signal-token': signalToken,
226
- });
227
- let statusPayload: any;
228
-
229
- await waitFor(async () => {
230
- const status = await server.request(
231
- '/_modern/runtime/status',
232
- {
233
- method: 'GET',
234
- headers: statusHeaders,
235
- },
236
- {},
237
- );
238
- expect(status.status).toBe(200);
239
- statusPayload = await status.json();
240
- return (
241
- statusPayload.canary?.state === 'promoted' &&
242
- statusPayload.canary?.contractGates?.some(
243
- (gate: any) => gate.name === gateName && gate.passed === true,
244
- )
245
- );
246
- });
247
-
248
- const emitResponse = await server.request('/emit', {}, {});
249
- expect(emitResponse.status).toBe(200);
250
-
251
- const signalResponse = await server.request(
252
- '/_modern/contract-gates/runtime-fallback',
253
- {
254
- method: 'POST',
255
- headers: new Headers({
256
- 'content-type': 'application/json',
257
- 'x-modernjs-runtime-signal-token': signalToken,
258
- }),
259
- body: JSON.stringify({
260
- reason: 'remote_load_failed',
261
- phase: 'load',
262
- appName: 'crm',
263
- entry: 'https://remote.example.com/remoteEntry.js',
264
- }),
265
- },
266
- {},
267
- );
268
- expect(signalResponse.status).toBe(202);
269
-
270
- const persistedSnapshot = JSON.parse(
271
- fs.readFileSync(snapshotPath, 'utf8'),
272
- ) as {
273
- gates?: Record<
274
- string,
275
- {
276
- expiresAt?: number;
277
- passed?: boolean;
278
- reason?: string;
279
- }
280
- >;
281
- };
282
- expect(persistedSnapshot.gates?.[gateName]?.passed).toBe(false);
283
- expect(persistedSnapshot.gates?.[gateName]?.expiresAt).toBeGreaterThan(
284
- Date.now(),
285
- );
286
-
287
- await waitFor(async () => {
288
- const status = await server.request(
289
- '/_modern/runtime/status',
290
- {
291
- method: 'GET',
292
- headers: statusHeaders,
293
- },
294
- {},
295
- );
296
- expect(status.status).toBe(200);
297
- statusPayload = await status.json();
298
- return (
299
- statusPayload.canary?.state === 'rolled_back' &&
300
- statusPayload.canary?.contractGates?.some(
301
- (gate: any) =>
302
- gate.name === gateName &&
303
- gate.passed === false &&
304
- String(gate.reason).includes('remote_load_failed'),
305
- )
306
- );
307
- }, 4_000);
308
-
309
- expect(statusPayload.telemetry?.exporterHealth).toContainEqual(
310
- expect.objectContaining({
311
- name: 'otlp',
312
- healthy: true,
313
- }),
314
- );
315
- expect(
316
- fetchCalls.some(
317
- call =>
318
- call.url === otlpEndpoint &&
319
- (call.headers as Record<string, string>)['x-modernjs-test'] ===
320
- 'canary-autopilot',
321
- ),
322
- ).toBe(true);
323
- expect(
324
- warnSpy.mock.calls.some(call =>
325
- String(call[0]).includes('[telemetry.slo] queue.utilization'),
326
- ),
327
- ).toBe(true);
328
-
329
- nodeServerStub.emit('close');
330
-
331
- await waitFor(() =>
332
- fetchCalls.some(call =>
333
- call.body.includes('telemetry.canary.rollback'),
334
- ),
335
- );
336
- const exportedBodies = fetchCalls.map(call => call.body).join('\n');
337
- expect(exportedBodies).toContain('telemetry.canary.rollback');
338
- expect(exportedBodies).toContain('canary-request-0');
339
- } finally {
340
- nodeServerStub.emit('close');
341
- globalThis.fetch = originalFetch;
342
- warnSpy.mockRestore();
343
- fs.rmSync(tempDir, { recursive: true, force: true });
344
- }
345
- });
346
-
347
- test('flushes pending envelopes when the node server closes', async () => {
48
+ test('flushes pending envelopes when the native runtime is disposed', async () => {
348
49
  const fetchCalls: Array<{ url: string; body: string }> = [];
349
50
  const fetchMock = rs.fn(async (url: any, init?: any) => {
350
51
  fetchCalls.push({ url: String(url), body: String(init?.body ?? '') });
@@ -361,12 +62,14 @@ describe('telemetry plugin lifecycle', () => {
361
62
  },
362
63
  };
363
64
 
65
+ let server: ReturnType<typeof createServerBase> | undefined;
66
+
364
67
  try {
365
68
  const config = getDefaultConfig();
366
69
  config.server = {
367
70
  telemetry: {
368
71
  enabled: true,
369
- // make sure nothing flushes before the close event:
72
+ // make sure nothing flushes before native disposal:
370
73
  flushIntervalMs: 60_000,
371
74
  maxBatchSize: 500,
372
75
  exporters: {
@@ -378,7 +81,7 @@ describe('telemetry plugin lifecycle', () => {
378
81
  },
379
82
  } as any;
380
83
 
381
- const server = createServerBase({
84
+ server = createServerBase({
382
85
  config,
383
86
  pwd: process.cwd(),
384
87
  appContext: getDefaultAppContext(),
@@ -407,12 +110,13 @@ describe('telemetry plugin lifecycle', () => {
407
110
  fetchCalls.some(call => call.body.includes('close-flush-probe')),
408
111
  ).toBe(false);
409
112
 
410
- nodeServerStub.emit('close');
113
+ await server?.dispose();
411
114
 
412
115
  await waitFor(() =>
413
116
  fetchCalls.some(call => call.body.includes('close-flush-probe')),
414
117
  );
415
118
  } finally {
119
+ await server?.dispose();
416
120
  globalThis.fetch = originalFetch;
417
121
  }
418
122
  });