@omen.foundation/node-microservice-runtime 0.1.0

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 (145) hide show
  1. package/.env +13 -0
  2. package/dist/auth.cjs +97 -0
  3. package/dist/auth.d.ts +14 -0
  4. package/dist/auth.d.ts.map +1 -0
  5. package/dist/auth.js +93 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/cli/index.d.ts +3 -0
  8. package/dist/cli/index.d.ts.map +1 -0
  9. package/dist/cli/index.js +588 -0
  10. package/dist/cli/index.js.map +1 -0
  11. package/dist/decorators.cjs +181 -0
  12. package/dist/decorators.d.ts +23 -0
  13. package/dist/decorators.d.ts.map +1 -0
  14. package/dist/decorators.js +155 -0
  15. package/dist/decorators.js.map +1 -0
  16. package/dist/dependency.cjs +165 -0
  17. package/dist/dependency.d.ts +56 -0
  18. package/dist/dependency.d.ts.map +1 -0
  19. package/dist/dependency.js +162 -0
  20. package/dist/dependency.js.map +1 -0
  21. package/dist/dev.cjs +34 -0
  22. package/dist/dev.d.ts +9 -0
  23. package/dist/dev.d.ts.map +1 -0
  24. package/dist/dev.js +32 -0
  25. package/dist/dev.js.map +1 -0
  26. package/dist/discovery.cjs +79 -0
  27. package/dist/discovery.d.ts +20 -0
  28. package/dist/discovery.d.ts.map +1 -0
  29. package/dist/discovery.js +75 -0
  30. package/dist/discovery.js.map +1 -0
  31. package/dist/docs.cjs +206 -0
  32. package/dist/docs.d.ts +30 -0
  33. package/dist/docs.d.ts.map +1 -0
  34. package/dist/docs.js +209 -0
  35. package/dist/docs.js.map +1 -0
  36. package/dist/env.cjs +106 -0
  37. package/dist/env.d.ts +4 -0
  38. package/dist/env.d.ts.map +1 -0
  39. package/dist/env.js +108 -0
  40. package/dist/env.js.map +1 -0
  41. package/dist/errors.cjs +58 -0
  42. package/dist/errors.d.ts +26 -0
  43. package/dist/errors.d.ts.map +1 -0
  44. package/dist/errors.js +48 -0
  45. package/dist/errors.js.map +1 -0
  46. package/dist/federation.cjs +356 -0
  47. package/dist/federation.d.ts +108 -0
  48. package/dist/federation.d.ts.map +1 -0
  49. package/dist/federation.js +341 -0
  50. package/dist/federation.js.map +1 -0
  51. package/dist/index.cjs +42 -0
  52. package/dist/index.d.ts +13 -0
  53. package/dist/index.d.ts.map +1 -0
  54. package/dist/index.js +10 -0
  55. package/dist/index.js.map +1 -0
  56. package/dist/inventory.cjs +361 -0
  57. package/dist/inventory.d.ts +116 -0
  58. package/dist/inventory.d.ts.map +1 -0
  59. package/dist/inventory.js +351 -0
  60. package/dist/inventory.js.map +1 -0
  61. package/dist/logger.cjs +62 -0
  62. package/dist/logger.d.ts +9 -0
  63. package/dist/logger.d.ts.map +1 -0
  64. package/dist/logger.js +29 -0
  65. package/dist/logger.js.map +1 -0
  66. package/dist/message.cjs +19 -0
  67. package/dist/message.d.ts +5 -0
  68. package/dist/message.d.ts.map +1 -0
  69. package/dist/message.js +15 -0
  70. package/dist/message.js.map +1 -0
  71. package/dist/requester.cjs +100 -0
  72. package/dist/requester.d.ts +20 -0
  73. package/dist/requester.d.ts.map +1 -0
  74. package/dist/requester.js +99 -0
  75. package/dist/requester.js.map +1 -0
  76. package/dist/routing.cjs +39 -0
  77. package/dist/routing.d.ts +2 -0
  78. package/dist/routing.d.ts.map +1 -0
  79. package/dist/routing.js +36 -0
  80. package/dist/routing.js.map +1 -0
  81. package/dist/runtime.cjs +735 -0
  82. package/dist/runtime.d.ts +40 -0
  83. package/dist/runtime.d.ts.map +1 -0
  84. package/dist/runtime.js +825 -0
  85. package/dist/runtime.js.map +1 -0
  86. package/dist/services.cjs +346 -0
  87. package/dist/services.d.ts +46 -0
  88. package/dist/services.d.ts.map +1 -0
  89. package/dist/services.js +343 -0
  90. package/dist/services.js.map +1 -0
  91. package/dist/storage.cjs +147 -0
  92. package/dist/storage.d.ts +46 -0
  93. package/dist/storage.d.ts.map +1 -0
  94. package/dist/storage.js +144 -0
  95. package/dist/storage.js.map +1 -0
  96. package/dist/types.cjs +2 -0
  97. package/dist/types.d.ts +108 -0
  98. package/dist/types.d.ts.map +1 -0
  99. package/dist/types.js +2 -0
  100. package/dist/types.js.map +1 -0
  101. package/dist/utils/urls.cjs +55 -0
  102. package/dist/utils/urls.d.ts +5 -0
  103. package/dist/utils/urls.d.ts.map +1 -0
  104. package/dist/utils/urls.js +50 -0
  105. package/dist/utils/urls.js.map +1 -0
  106. package/dist/websocket.cjs +142 -0
  107. package/dist/websocket.d.ts +33 -0
  108. package/dist/websocket.d.ts.map +1 -0
  109. package/dist/websocket.js +139 -0
  110. package/dist/websocket.js.map +1 -0
  111. package/env.sample +13 -0
  112. package/package.json +49 -0
  113. package/scripts/generate-openapi.mjs +114 -0
  114. package/scripts/lib/cli-utils.mjs +58 -0
  115. package/scripts/prepare-cjs.mjs +44 -0
  116. package/scripts/publish-service.mjs +1126 -0
  117. package/scripts/validate-service.mjs +103 -0
  118. package/scripts/ws-test.mjs +25 -0
  119. package/src/auth.ts +117 -0
  120. package/src/cli/index.ts +699 -0
  121. package/src/decorators.ts +207 -0
  122. package/src/dependency.ts +211 -0
  123. package/src/dev.ts +17 -0
  124. package/src/discovery.ts +88 -0
  125. package/src/docs.ts +262 -0
  126. package/src/env.ts +125 -0
  127. package/src/errors.ts +55 -0
  128. package/src/federation.ts +559 -0
  129. package/src/index.ts +51 -0
  130. package/src/inventory.ts +491 -0
  131. package/src/logger.ts +38 -0
  132. package/src/message.ts +19 -0
  133. package/src/requester.ts +126 -0
  134. package/src/routing.ts +42 -0
  135. package/src/runtime.ts +967 -0
  136. package/src/services.ts +459 -0
  137. package/src/storage.ts +206 -0
  138. package/src/types/beamable-sdk-api.d.ts +5 -0
  139. package/src/types.ts +117 -0
  140. package/src/utils/urls.ts +53 -0
  141. package/src/websocket.ts +170 -0
  142. package/tsconfig.base.json +31 -0
  143. package/tsconfig.build.json +10 -0
  144. package/tsconfig.cjs.json +16 -0
  145. package/tsconfig.dev.json +14 -0
@@ -0,0 +1,825 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { BeamableWebSocket } from './websocket.js';
3
+ import { GatewayRequester } from './requester.js';
4
+ import { AuthManager } from './auth.js';
5
+ import { createLogger } from './logger.js';
6
+ import { loadEnvironmentConfig } from './env.js';
7
+ import { listRegisteredServices, getServiceOptions, getConfigureServicesHandlers, getInitializeServicesHandlers } from './decorators.js';
8
+ import { generateOpenApiDocument } from './docs.js';
9
+ import { DiscoveryBroadcaster } from './discovery.js';
10
+ import { BeamableRuntimeError, MissingScopesError, UnauthorizedUserError, UnknownRouteError } from './errors.js';
11
+ import { BeamableServiceManager } from './services.js';
12
+ import { DependencyBuilder, LOGGER_TOKEN, ENVIRONMENT_CONFIG_TOKEN, REQUEST_CONTEXT_TOKEN, BEAMABLE_SERVICES_TOKEN, } from './dependency.js';
13
+ import { hostToHttpUrl, hostToPortalUrl } from './utils/urls.js';
14
+ import { FederationRegistry, getFederationComponents, getFederatedInventoryMetadata } from './federation.js';
15
+ import { createServer } from 'node:http';
16
+ export class MicroserviceRuntime {
17
+ env;
18
+ logger;
19
+ services;
20
+ webSocket;
21
+ requester;
22
+ authManager;
23
+ discovery;
24
+ microServiceId = randomUUID();
25
+ serviceManager;
26
+ healthCheckServer;
27
+ isReady = false;
28
+ constructor(env) {
29
+ this.env = env ?? loadEnvironmentConfig();
30
+ this.logger = createLogger(this.env, { name: 'beamable-node-microservice' });
31
+ this.serviceManager = new BeamableServiceManager(this.env, this.logger);
32
+ const registered = listRegisteredServices();
33
+ if (registered.length === 0) {
34
+ throw new Error('No microservices registered. Use the @Microservice decorator to register at least one class.');
35
+ }
36
+ this.services = registered.map((definition) => {
37
+ const instance = new definition.ctor();
38
+ const configureHandlers = getConfigureServicesHandlers(definition.ctor);
39
+ const initializeHandlers = getInitializeServicesHandlers(definition.ctor);
40
+ const logger = this.logger.child({ service: definition.name });
41
+ const federationRegistry = new FederationRegistry(logger);
42
+ const decoratedFederations = getFederationComponents(definition.ctor);
43
+ for (const component of decoratedFederations) {
44
+ federationRegistry.register(component);
45
+ }
46
+ const inventoryMetadata = getFederatedInventoryMetadata(definition.ctor);
47
+ if (inventoryMetadata.length > 0) {
48
+ federationRegistry.registerInventoryHandlers(instance, inventoryMetadata);
49
+ }
50
+ this.serviceManager.registerFederationRegistry(definition.name, federationRegistry);
51
+ return { definition, instance, configureHandlers, initializeHandlers, logger, federationRegistry };
52
+ });
53
+ const socketUrl = this.env.host.endsWith('/socket') ? this.env.host : `${this.env.host}/socket`;
54
+ this.webSocket = new BeamableWebSocket({ url: socketUrl, logger: this.logger });
55
+ this.webSocket.on('message', (payload) => {
56
+ this.logger.debug({ payload }, 'Runtime observed websocket frame.');
57
+ });
58
+ this.requester = new GatewayRequester(this.webSocket, this.logger);
59
+ this.authManager = new AuthManager(this.env, this.requester);
60
+ this.requester.on('event', (envelope) => this.handleEvent(envelope));
61
+ if (!isRunningInContainer() && this.services.length > 0) {
62
+ this.discovery = new DiscoveryBroadcaster({
63
+ env: this.env,
64
+ serviceName: this.services[0].definition.name,
65
+ routingKey: this.env.routingKey,
66
+ logger: this.logger.child({ component: 'DiscoveryBroadcaster' }),
67
+ });
68
+ }
69
+ }
70
+ async start() {
71
+ // Immediate console output for container logs (before logger is ready)
72
+ console.error('[BEAMABLE-NODE] MicroserviceRuntime.start() called');
73
+ console.error(`[BEAMABLE-NODE] Service count: ${this.services.length}`);
74
+ this.printHelpfulUrls(this.services[0]);
75
+ this.logger.info('Starting Beamable Node microservice runtime.');
76
+ // Start health check server FIRST - this is critical for container health checks
77
+ // Even if startup fails, the health check server must be running so we can debug
78
+ console.error('[BEAMABLE-NODE] Starting health check server...');
79
+ await this.startHealthCheckServer();
80
+ console.error('[BEAMABLE-NODE] Health check server started');
81
+ try {
82
+ this.logger.info('Connecting to Beamable gateway...');
83
+ await this.webSocket.connect();
84
+ await new Promise((resolve) => setTimeout(resolve, 250));
85
+ this.logger.info('Authenticating with Beamable...');
86
+ await this.authManager.authenticate();
87
+ this.logger.info('Initializing Beamable SDK services...');
88
+ await this.serviceManager.initialize();
89
+ this.logger.info('Initializing dependency providers...');
90
+ await this.initializeDependencyProviders();
91
+ this.logger.info('Registering service with gateway...');
92
+ await this.registerService();
93
+ this.logger.info('Starting discovery broadcaster...');
94
+ await this.discovery?.start();
95
+ // Mark as ready only after service is fully registered and discovery is started
96
+ this.isReady = true;
97
+ this.logger.info('Beamable microservice runtime is ready to accept traffic.');
98
+ }
99
+ catch (error) {
100
+ // Log the error with full context but don't crash - health check server is running
101
+ // This allows the container to stay alive so we can debug the issue
102
+ // Immediate console output for container logs (logger might not be working)
103
+ console.error('[BEAMABLE-NODE] FATAL ERROR during startup:');
104
+ console.error(`[BEAMABLE-NODE] Error message: ${error instanceof Error ? error.message : String(error)}`);
105
+ console.error(`[BEAMABLE-NODE] Error stack: ${error instanceof Error ? error.stack : 'No stack trace'}`);
106
+ console.error(`[BEAMABLE-NODE] isReady: ${this.isReady}`);
107
+ this.logger.error({
108
+ err: error,
109
+ errorMessage: error instanceof Error ? error.message : String(error),
110
+ errorStack: error instanceof Error ? error.stack : undefined,
111
+ isReady: this.isReady,
112
+ }, 'Failed to fully initialize microservice runtime. Health check will continue to return 503 until initialization completes.');
113
+ // DON'T re-throw - keep process alive so health check can show 503
114
+ // This allows us to see the error in logs
115
+ this.isReady = false;
116
+ }
117
+ }
118
+ async shutdown() {
119
+ this.logger.info('Shutting down microservice runtime.');
120
+ this.isReady = false; // Mark as not ready during shutdown
121
+ this.discovery?.stop();
122
+ await this.stopHealthCheckServer();
123
+ this.requester.dispose();
124
+ await this.webSocket.close();
125
+ }
126
+ async startHealthCheckServer() {
127
+ // For deployed services, always start health check server (required for container health checks)
128
+ // For local development, only start if healthPort is explicitly set
129
+ // IMPORTANT: Always default to 6565 if HEALTH_PORT env var is not set, as this is the standard port
130
+ const healthPort = this.env.healthPort || 6565;
131
+ // Always start health check server if we have a valid port
132
+ // The container orchestrator expects this endpoint to be available
133
+ if (!healthPort || healthPort === 0) {
134
+ // Health check server not needed (local development without explicit port)
135
+ this.logger.debug('Health check server skipped (no healthPort set)');
136
+ return;
137
+ }
138
+ this.healthCheckServer = createServer((req, res) => {
139
+ if (req.url === '/health' && req.method === 'GET') {
140
+ // Only return success if service is fully ready (registered and accepting traffic)
141
+ if (this.isReady) {
142
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
143
+ res.end('responsive');
144
+ }
145
+ else {
146
+ // Service is still starting up
147
+ res.writeHead(503, { 'Content-Type': 'text/plain' });
148
+ res.end('Service Unavailable');
149
+ }
150
+ }
151
+ else {
152
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
153
+ res.end('Not Found');
154
+ }
155
+ });
156
+ return new Promise((resolve, reject) => {
157
+ this.healthCheckServer.listen(healthPort, '0.0.0.0', () => {
158
+ this.logger.info({ port: healthPort }, 'Health check server started on port');
159
+ resolve();
160
+ });
161
+ this.healthCheckServer.on('error', (err) => {
162
+ this.logger.error({ err, port: healthPort }, 'Failed to start health check server');
163
+ reject(err);
164
+ });
165
+ });
166
+ }
167
+ async stopHealthCheckServer() {
168
+ if (!this.healthCheckServer) {
169
+ return;
170
+ }
171
+ return new Promise((resolve) => {
172
+ this.healthCheckServer.close(() => {
173
+ this.logger.info('Health check server stopped');
174
+ resolve();
175
+ });
176
+ });
177
+ }
178
+ async registerService() {
179
+ const primary = this.services[0]?.definition;
180
+ if (!primary) {
181
+ throw new Error('Unexpected missing service definition during registration.');
182
+ }
183
+ const options = getServiceOptions(primary.ctor) ?? {};
184
+ // Match C# exactly: use qualifiedName (preserves case) for name field.
185
+ // The gateway lowercases service names when creating bindings, but uses the original case
186
+ // from the registration request when constructing routing key lookups.
187
+ // This ensures the routing key format matches what the gateway expects.
188
+ // The gateway's binding lookup behavior:
189
+ // - Gateway error shows: "No binding found for service ...micro_examplenodeservice.basic"
190
+ // - This means the gateway lowercases the service name for binding storage/lookup
191
+ // - Portal sends requests with mixed case in URL and routing key header
192
+ // - The gateway lowercases the URL path for binding lookup, which should work
193
+ // - But we need to register with the format the gateway expects for the binding key
194
+ // - The gateway constructs binding key as: {cid}.{pid}.{lowercaseServiceName}.{type}
195
+ // - So we register with lowercase to match what the gateway stores in the binding
196
+ // - The portal will still send mixed case, and the gateway will lowercase it for lookup
197
+ // Register with mixed-case qualifiedName to match C# behavior
198
+ // The gateway will lowercase the service name when creating the binding key,
199
+ // but the registration request should use the original case (as C# does)
200
+ // This ensures the service name in the registration matches what the portal expects
201
+ // Register with mixed-case qualifiedName to match C# behavior
202
+ // The gateway's ServiceIdentity.fullNameNoType lowercases the service name when creating bindings,
203
+ // but the registration request should use the original case (as C# does)
204
+ // This ensures the service name in the registration matches what the portal expects
205
+ const isDeployed = isRunningInContainer();
206
+ // For deployed services, routingKey should be null/undefined (None in Scala)
207
+ // For local dev, routingKey should be the actual routing key string
208
+ // The backend expects Option[String] = None for deployed services
209
+ // Note: microServiceId is not part of SocketSessionProviderRegisterRequest, so we don't include it
210
+ // All fields except 'type' are Option[T] in Scala, so undefined fields will be omitted from JSON
211
+ // This matches C# behavior where null/None fields are not serialized
212
+ const request = {
213
+ type: 'basic',
214
+ name: primary.qualifiedName, // Use mixed-case as C# does - gateway handles lowercasing for binding storage
215
+ beamoName: primary.name,
216
+ };
217
+ // Only include routingKey and startedById if they have values (for local dev)
218
+ // For deployed services, these should be omitted (undefined) to match None in Scala
219
+ if (!isDeployed && this.env.routingKey) {
220
+ request.routingKey = this.env.routingKey;
221
+ }
222
+ if (!isDeployed && this.env.accountId) {
223
+ request.startedById = this.env.accountId;
224
+ }
225
+ // Log registration request to match C# behavior exactly
226
+ // Also log the actual JSON that will be sent (undefined fields will be omitted)
227
+ const serializedRequest = JSON.stringify(request);
228
+ this.logger.debug({
229
+ request: {
230
+ type: request.type,
231
+ name: request.name,
232
+ beamoName: request.beamoName,
233
+ routingKey: request.routingKey,
234
+ startedById: request.startedById,
235
+ },
236
+ serializedJson: serializedRequest,
237
+ isDeployed,
238
+ }, 'Registering service provider with gateway.');
239
+ try {
240
+ await this.requester.request('post', 'gateway/provider', request);
241
+ this.logger.info({ serviceName: primary.qualifiedName }, 'Service provider registered successfully.');
242
+ // After registration, the gateway's BasicServiceProvider.start() is called asynchronously
243
+ // This triggers afterRabbitInit() -> setupDirectServiceCommunication() -> scheduleServiceBindingCheck()
244
+ // The first updateBindings() call happens immediately (0.millisecond delay)
245
+ // We wait a bit to allow the gateway to set up the HTTP binding and call updateBindings()
246
+ // This is especially important for deployed services where the gateway needs to establish
247
+ // the external host binding before bindings can be created
248
+ if (isDeployed) {
249
+ this.logger.debug('Waiting for gateway to establish bindings after registration...');
250
+ await new Promise((resolve) => setTimeout(resolve, 2000)); // 2 second wait for deployed services
251
+ this.logger.debug('Wait complete, gateway should have established bindings by now.');
252
+ }
253
+ }
254
+ catch (error) {
255
+ this.logger.error({
256
+ err: error,
257
+ request,
258
+ serviceName: primary.qualifiedName,
259
+ errorMessage: error instanceof Error ? error.message : String(error),
260
+ }, 'Failed to register service provider with gateway. This will prevent the service from receiving requests.');
261
+ throw error; // Re-throw so startup fails and we can see the error
262
+ }
263
+ if (options.disableAllBeamableEvents) {
264
+ this.logger.info('Beamable events disabled by configuration.');
265
+ }
266
+ else {
267
+ const eventRequest = {
268
+ type: 'event',
269
+ evtWhitelist: ['content.manifest', 'realm.config', 'logging.context'],
270
+ };
271
+ try {
272
+ await this.requester.request('post', 'gateway/provider', eventRequest);
273
+ }
274
+ catch (error) {
275
+ this.logger.warn({ err: error }, 'Failed to register event provider. Continuing without events.');
276
+ }
277
+ }
278
+ }
279
+ async handleEvent(envelope) {
280
+ try {
281
+ if (!envelope.path) {
282
+ this.logger.debug({ envelope }, 'Ignoring websocket event without path.');
283
+ return;
284
+ }
285
+ if (envelope.path.startsWith('event/')) {
286
+ await this.requester.acknowledge(envelope.id);
287
+ return;
288
+ }
289
+ const context = this.toRequestContext(envelope);
290
+ await this.dispatch(context);
291
+ }
292
+ catch (error) {
293
+ const err = error instanceof Error ? error : new Error(String(error));
294
+ this.logger.error({ err, envelope }, 'Failed to handle websocket event.');
295
+ const status = this.resolveErrorStatus(err);
296
+ const response = {
297
+ id: envelope.id,
298
+ status,
299
+ body: {
300
+ error: err.name,
301
+ message: err.message,
302
+ },
303
+ };
304
+ await this.requester.sendResponse(response);
305
+ }
306
+ }
307
+ toRequestContext(envelope) {
308
+ const path = envelope.path ?? '';
309
+ const method = envelope.method ?? 'post';
310
+ const userId = typeof envelope.from === 'number' ? envelope.from : 0;
311
+ const headers = envelope.headers ?? {};
312
+ // Extract scopes from envelope.scopes array
313
+ // Note: X-DE-SCOPE header contains CID.PID, not scope values
314
+ // The gateway sends scopes in envelope.scopes array
315
+ // For admin endpoints, the gateway may not send scopes in the envelope,
316
+ // so we infer admin scope from the path if it's an admin route
317
+ const envelopeScopes = envelope.scopes ?? [];
318
+ let scopes = normalizeScopes(envelopeScopes);
319
+ // If this is an admin endpoint and no scopes are provided, infer admin scope
320
+ // The gateway may not always send scopes for admin routes
321
+ const pathLower = path.toLowerCase();
322
+ if (pathLower.includes('/admin/') && scopes.size === 0) {
323
+ scopes = normalizeScopes(['admin']);
324
+ }
325
+ let body;
326
+ if (envelope.body && typeof envelope.body === 'string') {
327
+ try {
328
+ body = JSON.parse(envelope.body);
329
+ }
330
+ catch (error) {
331
+ this.logger.warn({ err: error, raw: envelope.body }, 'Failed to parse body string.');
332
+ }
333
+ }
334
+ else if (envelope.body && typeof envelope.body === 'object') {
335
+ body = envelope.body;
336
+ }
337
+ let payload;
338
+ if (body && typeof body === 'object' && 'payload' in body) {
339
+ const rawPayload = body.payload;
340
+ if (typeof rawPayload === 'string') {
341
+ try {
342
+ payload = JSON.parse(rawPayload);
343
+ }
344
+ catch (error) {
345
+ this.logger.warn({ err: error }, 'Failed to parse payload JSON.');
346
+ payload = rawPayload;
347
+ }
348
+ }
349
+ else {
350
+ payload = rawPayload;
351
+ }
352
+ }
353
+ const targetService = this.findServiceForPath(path);
354
+ const services = this.serviceManager.createFacade(userId, scopes, targetService?.definition.name);
355
+ const provider = this.createRequestScope(path, targetService);
356
+ const context = {
357
+ id: envelope.id,
358
+ path,
359
+ method,
360
+ status: envelope.status ?? 0,
361
+ userId,
362
+ payload,
363
+ body,
364
+ scopes,
365
+ headers,
366
+ cid: this.env.cid,
367
+ pid: this.env.pid,
368
+ services,
369
+ throwIfCancelled: () => { },
370
+ isCancelled: () => false,
371
+ hasScopes: (...requiredScopes) => requiredScopes.every((scope) => scopeSetHas(scopes, scope)),
372
+ requireScopes: (...requiredScopes) => {
373
+ const missingScopes = requiredScopes.filter((scope) => !scopeSetHas(scopes, scope));
374
+ if (missingScopes.length > 0) {
375
+ throw new MissingScopesError(missingScopes);
376
+ }
377
+ },
378
+ provider,
379
+ };
380
+ provider.setInstance(REQUEST_CONTEXT_TOKEN, context);
381
+ provider.setInstance(BEAMABLE_SERVICES_TOKEN, services);
382
+ return context;
383
+ }
384
+ findServiceForPath(path) {
385
+ // Gateway sends paths with lowercase service names, so we need case-insensitive matching
386
+ // Match by comparing lowercase versions to handle gateway's lowercase path format
387
+ const pathLower = path.toLowerCase();
388
+ return this.services.find((service) => {
389
+ const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();
390
+ return pathLower.startsWith(`${qualifiedNameLower}/`);
391
+ });
392
+ }
393
+ async dispatch(ctx) {
394
+ const service = this.findServiceForPath(ctx.path);
395
+ if (!service) {
396
+ throw new UnknownRouteError(ctx.path);
397
+ }
398
+ if (await this.tryHandleFederationRoute(ctx, service)) {
399
+ return;
400
+ }
401
+ if (await this.tryHandleAdminRoute(ctx, service)) {
402
+ return;
403
+ }
404
+ // Extract route from path - handle case-insensitive path matching
405
+ const pathLower = ctx.path.toLowerCase();
406
+ const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();
407
+ const route = pathLower.substring(qualifiedNameLower.length + 1);
408
+ const metadata = service.definition.callables.get(route);
409
+ if (!metadata) {
410
+ throw new UnknownRouteError(ctx.path);
411
+ }
412
+ // For server and admin access, allow userId: 0 if the appropriate scope is present
413
+ // For client access, always require userId > 0
414
+ if (metadata.requireAuth && ctx.userId <= 0) {
415
+ if (metadata.access === 'server' && scopeSetHas(ctx.scopes, 'server')) {
416
+ // Server callables with server scope don't need a user ID
417
+ }
418
+ else if (metadata.access === 'admin' && scopeSetHas(ctx.scopes, 'admin')) {
419
+ // Admin callables with admin scope don't need a user ID
420
+ }
421
+ else {
422
+ throw new UnauthorizedUserError(route);
423
+ }
424
+ }
425
+ enforceAccess(metadata.access, ctx);
426
+ if (metadata.requiredScopes.length > 0) {
427
+ const missing = metadata.requiredScopes.filter((scope) => !scopeSetHas(ctx.scopes, scope));
428
+ if (missing.length > 0) {
429
+ throw new MissingScopesError(missing);
430
+ }
431
+ }
432
+ const handler = service.instance[metadata.displayName];
433
+ if (typeof handler !== 'function') {
434
+ throw new Error(`Callable ${metadata.displayName} is not a function on service ${service.definition.name}.`);
435
+ }
436
+ const args = this.buildInvocationArguments(handler, ctx);
437
+ const result = await Promise.resolve(handler.apply(service.instance, args));
438
+ await this.sendSuccessResponse(ctx, metadata, result);
439
+ }
440
+ buildInvocationArguments(handler, ctx) {
441
+ const payload = Array.isArray(ctx.payload)
442
+ ? ctx.payload
443
+ : typeof ctx.payload === 'string'
444
+ ? [ctx.payload]
445
+ : ctx.payload === undefined
446
+ ? []
447
+ : [ctx.payload];
448
+ const expectedParams = handler.length;
449
+ if (expectedParams === payload.length + 1) {
450
+ return [ctx, ...payload];
451
+ }
452
+ return payload;
453
+ }
454
+ async sendSuccessResponse(ctx, metadata, result) {
455
+ let body;
456
+ if (metadata.useLegacySerialization) {
457
+ const serialized = typeof result === 'string' ? result : JSON.stringify(result ?? null);
458
+ body = { payload: serialized };
459
+ }
460
+ else {
461
+ body = result ?? null;
462
+ }
463
+ const response = {
464
+ id: ctx.id,
465
+ status: 200,
466
+ body,
467
+ };
468
+ await this.requester.sendResponse(response);
469
+ }
470
+ async sendFederationResponse(ctx, result) {
471
+ const response = {
472
+ id: ctx.id,
473
+ status: 200,
474
+ body: result ?? null,
475
+ };
476
+ await this.requester.sendResponse(response);
477
+ }
478
+ async tryHandleFederationRoute(ctx, service) {
479
+ // Gateway sends paths with lowercase service names, so we need case-insensitive matching
480
+ const pathLower = ctx.path.toLowerCase();
481
+ const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();
482
+ const prefixLower = `${qualifiedNameLower}/`;
483
+ if (!pathLower.startsWith(prefixLower)) {
484
+ return false;
485
+ }
486
+ // Extract relative path - use lowercase length since gateway sends lowercase paths
487
+ const relativePath = ctx.path.substring(qualifiedNameLower.length + 1);
488
+ const handler = service.federationRegistry.resolve(relativePath);
489
+ if (!handler) {
490
+ return false;
491
+ }
492
+ const result = await handler.invoke(ctx);
493
+ await this.sendFederationResponse(ctx, result);
494
+ return true;
495
+ }
496
+ async tryHandleAdminRoute(ctx, service) {
497
+ // Gateway sends paths with lowercase service names, so we need case-insensitive matching
498
+ // Check if path starts with the admin prefix (case-insensitive)
499
+ const pathLower = ctx.path.toLowerCase();
500
+ const adminPrefixLower = `${service.definition.qualifiedName.toLowerCase()}/admin/`;
501
+ if (!pathLower.startsWith(adminPrefixLower)) {
502
+ return false;
503
+ }
504
+ const options = getServiceOptions(service.definition.ctor) ?? {};
505
+ const action = pathLower.substring(adminPrefixLower.length);
506
+ const requiresAdmin = action === 'metadata' || action === 'docs';
507
+ if (requiresAdmin && !scopeSetHas(ctx.scopes, 'admin')) {
508
+ // For portal requests to admin endpoints, the gateway may not send scopes
509
+ // The X-DE-SCOPE header contains CID.PID, not scope values
510
+ // If this is a portal request (has X-DE-SCOPE header), grant admin scope
511
+ const hasPortalHeader = ctx.headers['X-DE-SCOPE'] || ctx.headers['x-de-scope'];
512
+ if (hasPortalHeader) {
513
+ // Grant admin scope for portal requests to admin endpoints
514
+ ctx.scopes.add('admin');
515
+ }
516
+ else {
517
+ throw new MissingScopesError(['admin']);
518
+ }
519
+ }
520
+ switch (action) {
521
+ case 'health':
522
+ case 'healthcheck':
523
+ await this.requester.sendResponse({ id: ctx.id, status: 200, body: 'responsive' });
524
+ return true;
525
+ case 'metadata':
526
+ case 'docs':
527
+ break;
528
+ default:
529
+ if (!scopeSetHas(ctx.scopes, 'admin')) {
530
+ throw new MissingScopesError(['admin']);
531
+ }
532
+ throw new UnknownRouteError(ctx.path);
533
+ }
534
+ if (action === 'metadata') {
535
+ const federatedComponents = service.federationRegistry
536
+ .list()
537
+ .map((component) => ({
538
+ federationNamespace: component.federationNamespace,
539
+ federationType: component.federationType,
540
+ }));
541
+ await this.requester.sendResponse({
542
+ id: ctx.id,
543
+ status: 200,
544
+ body: {
545
+ serviceName: service.definition.name,
546
+ sdkVersion: this.env.sdkVersionExecution,
547
+ sdkBaseBuildVersion: this.env.sdkVersionExecution,
548
+ sdkExecutionVersion: this.env.sdkVersionExecution,
549
+ useLegacySerialization: Boolean(options.useLegacySerialization),
550
+ disableAllBeamableEvents: Boolean(options.disableAllBeamableEvents),
551
+ enableEagerContentLoading: false,
552
+ instanceId: this.microServiceId,
553
+ routingKey: this.env.routingKey ?? '',
554
+ federatedComponents,
555
+ },
556
+ });
557
+ return true;
558
+ }
559
+ if (action === 'docs') {
560
+ try {
561
+ const document = generateOpenApiDocument({
562
+ qualifiedName: service.definition.qualifiedName,
563
+ name: service.definition.name,
564
+ callables: Array.from(service.definition.callables.values()).map((callable) => ({
565
+ name: callable.displayName,
566
+ route: callable.route,
567
+ metadata: callable,
568
+ handler: typeof service.instance[callable.displayName] === 'function'
569
+ ? service.instance[callable.displayName]
570
+ : undefined,
571
+ })),
572
+ }, this.env);
573
+ // Ensure document is valid (not empty)
574
+ if (!document || Object.keys(document).length === 0) {
575
+ this.logger.warn({ serviceName: service.definition.name }, 'Generated OpenAPI document is empty');
576
+ }
577
+ await this.requester.sendResponse({
578
+ id: ctx.id,
579
+ status: 200,
580
+ body: document,
581
+ });
582
+ return true;
583
+ }
584
+ catch (error) {
585
+ this.logger.error({ err: error, serviceName: service.definition.name }, 'Failed to generate or send docs');
586
+ throw error;
587
+ }
588
+ }
589
+ return false;
590
+ }
591
+ resolveErrorStatus(error) {
592
+ if (error instanceof UnauthorizedUserError) {
593
+ return 401;
594
+ }
595
+ if (error instanceof MissingScopesError) {
596
+ return 403;
597
+ }
598
+ if (error instanceof UnknownRouteError) {
599
+ return 404;
600
+ }
601
+ if (error instanceof BeamableRuntimeError) {
602
+ return 500;
603
+ }
604
+ return 500;
605
+ }
606
+ printHelpfulUrls(service) {
607
+ if (!service) {
608
+ return;
609
+ }
610
+ const docsUrl = buildDocsPortalUrl(this.env, service.definition);
611
+ const endpointBase = buildPostmanBaseUrl(this.env, service.definition);
612
+ const green = (text) => `\x1b[32m${text}\x1b[0m`;
613
+ const yellow = (text) => `\x1b[33m${text}\x1b[0m`;
614
+ const bannerLines = [
615
+ '',
616
+ yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),
617
+ ` ${green('Beamable Node microservice ready:')} ${green(service.definition.name)}`,
618
+ yellow(' Quick shortcuts'),
619
+ ` ${yellow('Docs:')} ${docsUrl}`,
620
+ ` ${yellow('Endpoint:')} ${endpointBase}`,
621
+ yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),
622
+ '',
623
+ ];
624
+ process.stdout.write(`${bannerLines.join('\n')}`);
625
+ }
626
+ async initializeDependencyProviders() {
627
+ for (const service of this.services) {
628
+ const builder = new DependencyBuilder();
629
+ builder.tryAddSingletonInstance(LOGGER_TOKEN, service.logger);
630
+ builder.tryAddSingletonInstance(ENVIRONMENT_CONFIG_TOKEN, this.env);
631
+ builder.tryAddSingletonInstance(BeamableServiceManager, this.serviceManager);
632
+ builder.tryAddSingletonInstance(service.definition.ctor, service.instance);
633
+ builder.tryAddSingletonInstance(FederationRegistry, service.federationRegistry);
634
+ for (const handler of service.configureHandlers) {
635
+ await handler(builder);
636
+ }
637
+ const provider = builder.build();
638
+ service.provider = provider;
639
+ for (const handler of service.initializeHandlers) {
640
+ await handler(provider);
641
+ }
642
+ Object.defineProperty(service.instance, 'provider', {
643
+ value: provider,
644
+ enumerable: false,
645
+ configurable: false,
646
+ writable: false,
647
+ });
648
+ }
649
+ }
650
+ createRequestScope(path, service) {
651
+ const targetService = service ?? this.findServiceForPath(path);
652
+ const provider = targetService?.provider ?? new DependencyBuilder().build();
653
+ return provider.createScope();
654
+ }
655
+ }
656
+ function enforceAccess(access, ctx) {
657
+ switch (access) {
658
+ case 'client':
659
+ if (ctx.userId <= 0) {
660
+ throw new UnauthorizedUserError(ctx.path);
661
+ }
662
+ break;
663
+ case 'server':
664
+ if (!scopeSetHas(ctx.scopes, 'server')) {
665
+ throw new MissingScopesError(['server']);
666
+ }
667
+ break;
668
+ case 'admin':
669
+ if (!scopeSetHas(ctx.scopes, 'admin')) {
670
+ throw new MissingScopesError(['admin']);
671
+ }
672
+ break;
673
+ default:
674
+ break;
675
+ }
676
+ }
677
+ function isRunningInContainer() {
678
+ // Beamable sets CID, PID, HOST, SECRET in deployed containers
679
+ // If we have these required env vars but NO routing key, we're in a deployed container
680
+ // This is more reliable than checking for DOTNET_RUNNING_IN_CONTAINER (which is C#-specific)
681
+ const hasBeamableEnvVars = !!(process.env.CID && process.env.PID && process.env.HOST && process.env.SECRET);
682
+ const hasNoRoutingKey = !process.env.NAME_PREFIX && !process.env.ROUTING_KEY;
683
+ if (hasBeamableEnvVars && hasNoRoutingKey) {
684
+ return true; // Deployed container
685
+ }
686
+ // Fallback checks for other container indicators
687
+ return (process.env.DOTNET_RUNNING_IN_CONTAINER === 'true' ||
688
+ process.env.CONTAINER === 'beamable' ||
689
+ !!process.env.ECS_CONTAINER_METADATA_URI ||
690
+ !!process.env.KUBERNETES_SERVICE_HOST);
691
+ }
692
+ function normalizeScopes(scopes) {
693
+ const normalized = new Set();
694
+ for (const scope of scopes) {
695
+ if (typeof scope !== 'string' || scope.trim().length === 0) {
696
+ continue;
697
+ }
698
+ normalized.add(scope.trim().toLowerCase());
699
+ }
700
+ return normalized;
701
+ }
702
+ function scopeSetHas(scopes, scope) {
703
+ const normalized = scope.trim().toLowerCase();
704
+ if (normalized.length === 0) {
705
+ return false;
706
+ }
707
+ return scopes.has('*') || scopes.has(normalized);
708
+ }
709
+ function buildPostmanBaseUrl(env, service) {
710
+ const httpHost = hostToHttpUrl(env.host);
711
+ const routingKeyPart = env.routingKey ? env.routingKey : '';
712
+ return `${httpHost}/basic/${env.cid}.${env.pid}.${routingKeyPart}${service.qualifiedName}/`;
713
+ }
714
+ function buildDocsPortalUrl(env, service) {
715
+ const portalHost = hostToPortalUrl(hostToHttpUrl(env.host));
716
+ const queryParams = { srcTool: 'node-runtime' };
717
+ if (env.routingKey) {
718
+ queryParams.routingKey = env.routingKey;
719
+ }
720
+ const query = new URLSearchParams(queryParams);
721
+ if (env.refreshToken) {
722
+ query.set('refresh_token', env.refreshToken);
723
+ }
724
+ const beamoId = service.name;
725
+ return `${portalHost}/${env.cid}/games/${env.pid}/realms/${env.pid}/microservices/micro_${beamoId}/docs?${query.toString()}`;
726
+ }
727
+ export async function runMicroservice() {
728
+ // Immediate console output to verify process is starting
729
+ // This goes to stdout and should be visible in container logs
730
+ console.error('[BEAMABLE-NODE] Starting microservice...');
731
+ console.error(`[BEAMABLE-NODE] Node version: ${process.version}`);
732
+ console.error(`[BEAMABLE-NODE] Working directory: ${process.cwd()}`);
733
+ console.error(`[BEAMABLE-NODE] Environment: ${JSON.stringify({
734
+ NODE_ENV: process.env.NODE_ENV,
735
+ CID: process.env.CID ? 'SET' : 'NOT SET',
736
+ PID: process.env.PID ? 'SET' : 'NOT SET',
737
+ HOST: process.env.HOST ? 'SET' : 'NOT SET',
738
+ SECRET: process.env.SECRET ? 'SET' : 'NOT SET',
739
+ })}`);
740
+ if (process.env.BEAMABLE_SKIP_RUNTIME === 'true') {
741
+ return;
742
+ }
743
+ const runtime = new MicroserviceRuntime();
744
+ // Handle uncaught errors - log them but don't crash immediately
745
+ // This allows the health check server to keep running so we can debug
746
+ process.on('uncaughtException', (error) => {
747
+ console.error('Uncaught Exception:', error);
748
+ // Don't exit - let the health check server keep running
749
+ });
750
+ process.on('unhandledRejection', (reason, promise) => {
751
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
752
+ // Don't exit - let the health check server keep running
753
+ });
754
+ try {
755
+ await runtime.start();
756
+ }
757
+ catch (error) {
758
+ // Log the error but don't exit - health check server is running
759
+ // This allows the container to stay alive so we can see what went wrong
760
+ console.error('Failed to start microservice runtime:', error);
761
+ // Keep the process alive so health check can continue
762
+ // The health check will return 503 until isReady is true
763
+ }
764
+ const shutdownSignals = ['SIGTERM', 'SIGINT'];
765
+ shutdownSignals.forEach((signal) => {
766
+ process.once(signal, async () => {
767
+ await runtime.shutdown();
768
+ process.exit(0);
769
+ });
770
+ });
771
+ }
772
+ export function generateOpenApiDocumentForRegisteredServices(overrides = {}, options = {}) {
773
+ const services = listRegisteredServices();
774
+ if (services.length === 0) {
775
+ throw new Error('No microservices registered. Import your service module before generating documentation.');
776
+ }
777
+ const baseEnv = buildEnvironmentConfig(overrides);
778
+ const primary = options.serviceName
779
+ ? services.find((svc) => svc.name === options.serviceName || svc.qualifiedName === options.serviceName)
780
+ : services[0];
781
+ if (!primary) {
782
+ throw new Error(`No registered microservice matched '${options.serviceName}'.`);
783
+ }
784
+ return generateOpenApiDocument({
785
+ qualifiedName: primary.qualifiedName,
786
+ name: primary.name,
787
+ callables: Array.from(primary.callables.entries()).map(([displayName, metadata]) => ({
788
+ name: displayName,
789
+ route: metadata.route,
790
+ metadata,
791
+ handler: undefined,
792
+ })),
793
+ }, baseEnv);
794
+ }
795
+ function buildEnvironmentConfig(overrides) {
796
+ const merged = { ...overrides };
797
+ const ensure = (key, fallbackEnv) => {
798
+ if (merged[key] !== undefined) {
799
+ return;
800
+ }
801
+ if (fallbackEnv && process.env[fallbackEnv]) {
802
+ merged[key] = process.env[fallbackEnv];
803
+ }
804
+ };
805
+ ensure('cid', 'CID');
806
+ ensure('pid', 'PID');
807
+ ensure('host', 'HOST');
808
+ ensure('secret', 'SECRET');
809
+ ensure('refreshToken', 'REFRESH_TOKEN');
810
+ // Routing key is optional for deployed services (in containers)
811
+ // It will be resolved to empty string if not provided and running in container
812
+ if (!merged.routingKey && !isRunningInContainer()) {
813
+ ensure('routingKey', 'NAME_PREFIX');
814
+ }
815
+ if (!merged.cid || !merged.pid || !merged.host) {
816
+ throw new Error('CID, PID, and HOST are required to generate documentation.');
817
+ }
818
+ const base = loadEnvironmentConfig();
819
+ return {
820
+ ...base,
821
+ ...merged,
822
+ routingKey: merged.routingKey ?? base.routingKey,
823
+ };
824
+ }
825
+ //# sourceMappingURL=runtime.js.map