@omen.foundation/node-microservice-runtime 0.1.65 → 0.1.68

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.
package/src/runtime.ts DELETED
@@ -1,1071 +0,0 @@
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 { startCollectorAndWaitForReady } from './collector-manager.js';
8
- import pino from 'pino';
9
- // Removed deasync - using non-blocking async pattern instead
10
- import { listRegisteredServices, getServiceOptions, getConfigureServicesHandlers, getInitializeServicesHandlers } from './decorators.js';
11
- import { generateOpenApiDocument } from './docs.js';
12
- import { VERSION } from './index.js';
13
- import { DiscoveryBroadcaster } from './discovery.js';
14
- import { BeamableRuntimeError, MissingScopesError, UnauthorizedUserError, UnknownRouteError } from './errors.js';
15
- import type {
16
- EnvironmentConfig,
17
- RequestContext,
18
- ServiceDefinition,
19
- ServiceCallableMetadata,
20
- GatewayResponse,
21
- WebsocketEventEnvelope,
22
- ServiceAccess,
23
- } from './types.js';
24
- import type { Logger } from 'pino';
25
- import { BeamableServiceManager } from './services.js';
26
- import {
27
- DependencyBuilder,
28
- LOGGER_TOKEN,
29
- ENVIRONMENT_CONFIG_TOKEN,
30
- REQUEST_CONTEXT_TOKEN,
31
- BEAMABLE_SERVICES_TOKEN,
32
- ServiceProvider,
33
- MutableDependencyScope,
34
- } from './dependency.js';
35
- import { hostToHttpUrl, hostToPortalUrl } from './utils/urls.js';
36
- import { FederationRegistry, getFederationComponents, getFederatedInventoryMetadata } from './federation.js';
37
- import type { FederatedRequestContext } from './federation.js';
38
- import { createServer, type Server } from 'node:http';
39
-
40
- interface ServiceInstance {
41
- definition: ServiceDefinition;
42
- instance: Record<string, unknown>;
43
- configureHandlers: ReturnType<typeof getConfigureServicesHandlers>;
44
- initializeHandlers: ReturnType<typeof getInitializeServicesHandlers>;
45
- provider?: ServiceProvider;
46
- logger: Logger;
47
- federationRegistry: FederationRegistry;
48
- }
49
-
50
- export class MicroserviceRuntime {
51
- private readonly env: EnvironmentConfig;
52
- private logger: Logger; // Mutable to allow upgrading from console logger to structured logger when collector is ready
53
- private readonly services: ServiceInstance[];
54
- private readonly webSocket: BeamableWebSocket;
55
- private readonly requester: GatewayRequester;
56
- private readonly authManager: AuthManager;
57
- private readonly discovery?: DiscoveryBroadcaster;
58
- private readonly microServiceId = randomUUID();
59
- private readonly serviceManager: BeamableServiceManager;
60
- private healthCheckServer?: Server;
61
- private isReady: boolean = false;
62
-
63
- constructor(env?: EnvironmentConfig) {
64
- this.env = env ?? loadEnvironmentConfig();
65
-
66
- // STEP 1: Create minimal console logger for startup messages (before collector setup)
67
- // This ensures we have logging available immediately, even before collector is ready
68
- const startupLogger = pino({
69
- name: 'beamable-runtime-startup',
70
- level: 'info',
71
- }, process.stdout);
72
- // Display runtime version at startup (VERSION is imported synchronously at top of file)
73
- startupLogger.info(`Starting Beamable Node microservice runtime (version: ${VERSION}).`);
74
-
75
- // STEP 2: Get registered services to extract service name
76
- const registered = listRegisteredServices();
77
- if (registered.length === 0) {
78
- throw new Error('No microservices registered. Use the @Microservice decorator to register at least one class.');
79
- }
80
-
81
- // Use the first service's name for the main logger (for CloudWatch filtering and ClickHouse compatibility)
82
- const primaryService = registered[0];
83
- const qualifiedServiceName = `micro_${primaryService.qualifiedName}`;
84
-
85
- // STEP 3: Create logger immediately (non-blocking pattern, matching C#)
86
- // Start with minimal console logger, upgrade to structured logger when collector is ready
87
- // This allows the service to start immediately without blocking
88
- startupLogger.info('Setting up OpenTelemetry collector in background (non-blocking)...');
89
-
90
- // Create logger immediately with console output (no OTLP yet)
91
- // This ensures we have logging available right away
92
- this.logger = createLogger(this.env, {
93
- name: 'beamable-node-microservice',
94
- serviceName: primaryService.name,
95
- qualifiedServiceName: qualifiedServiceName,
96
- // No otlpEndpoint - will use console logger initially
97
- });
98
-
99
- // STEP 4: Start collector setup in background (non-blocking)
100
- // When collector is ready, upgrade logger to structured logger with OTLP
101
- // This matches C# pattern: collector starts in background, service starts immediately
102
- startCollectorAndWaitForReady(this.env)
103
- .then((endpoint) => {
104
- if (endpoint) {
105
- // Collector is ready - upgrade to structured logger with OTLP support
106
- this.logger.info(`Collector ready at ${endpoint}, upgrading to structured logger for Portal logs...`);
107
- this.logger = createLogger(this.env, {
108
- name: 'beamable-node-microservice',
109
- serviceName: primaryService.name,
110
- qualifiedServiceName: qualifiedServiceName,
111
- otlpEndpoint: endpoint, // Collector is ready, Portal logs will now work
112
- });
113
- this.logger.info('Portal logs enabled - structured logs will now appear in Beamable Portal');
114
- } else {
115
- this.logger.warn('Collector setup completed but no endpoint was returned. Continuing with console logs. Portal logs will not be available.');
116
- }
117
- })
118
- .catch((error) => {
119
- const errorMsg = error instanceof Error ? error.message : String(error);
120
- this.logger.error(`Failed to setup collector: ${errorMsg}. Continuing with console logs. Portal logs will not be available.`);
121
- // Service continues to work with console logger - graceful degradation
122
- });
123
-
124
- // Continue immediately - don't wait for collector!
125
- // Service can start accepting requests right away
126
- // Collector setup happens in background, logger upgrades automatically when ready
127
- this.serviceManager = new BeamableServiceManager(this.env, this.logger);
128
-
129
- this.services = registered.map((definition) => {
130
- const instance = new definition.ctor() as Record<string, unknown>;
131
- const configureHandlers = getConfigureServicesHandlers(definition.ctor);
132
- const initializeHandlers = getInitializeServicesHandlers(definition.ctor);
133
- const logger = this.logger.child({ service: definition.name });
134
- const federationRegistry = new FederationRegistry(logger);
135
- const decoratedFederations = getFederationComponents(definition.ctor);
136
- for (const component of decoratedFederations) {
137
- federationRegistry.register(component);
138
- }
139
- const inventoryMetadata = getFederatedInventoryMetadata(definition.ctor);
140
- if (inventoryMetadata.length > 0) {
141
- federationRegistry.registerInventoryHandlers(instance, inventoryMetadata);
142
- }
143
- this.serviceManager.registerFederationRegistry(definition.name, federationRegistry);
144
- return { definition, instance, configureHandlers, initializeHandlers, logger, federationRegistry };
145
- });
146
-
147
- const socketUrl = this.env.host.endsWith('/socket') ? this.env.host : `${this.env.host}/socket`;
148
- this.webSocket = new BeamableWebSocket({ url: socketUrl, logger: this.logger });
149
- this.webSocket.on('message', (payload) => {
150
- this.logger.debug({ payload }, 'Runtime observed websocket frame.');
151
- });
152
- this.requester = new GatewayRequester(this.webSocket, this.logger);
153
- this.authManager = new AuthManager(this.env, this.requester);
154
- this.requester.on('event', (envelope) => this.handleEvent(envelope));
155
-
156
- // Discovery broadcaster only runs in local development (not in containers)
157
- // This allows the portal to detect that the service is running locally
158
- if (!isRunningInContainer() && this.services.length > 0) {
159
- this.discovery = new DiscoveryBroadcaster({
160
- env: this.env,
161
- serviceName: this.services[0].definition.name,
162
- routingKey: this.env.routingKey,
163
- logger: this.logger.child({ component: 'DiscoveryBroadcaster' }),
164
- });
165
- }
166
- }
167
-
168
- async start(): Promise<void> {
169
- // Immediate console output for container logs (before logger is ready)
170
- debugLog('[BEAMABLE-NODE] MicroserviceRuntime.start() called');
171
- debugLog(`[BEAMABLE-NODE] Service count: ${this.services.length}`);
172
-
173
- this.printHelpfulUrls(this.services[0]);
174
- this.logger.info('Starting Beamable Node microservice runtime.');
175
-
176
- // Start health check server FIRST - this is critical for container health checks
177
- // Even if startup fails, the health check server must be running so we can debug
178
- debugLog('[BEAMABLE-NODE] Starting health check server...');
179
- await this.startHealthCheckServer();
180
- debugLog('[BEAMABLE-NODE] Health check server started');
181
-
182
- try {
183
- this.logger.info('Connecting to Beamable gateway...');
184
- await this.webSocket.connect();
185
- await new Promise((resolve) => setTimeout(resolve, 250));
186
-
187
- this.logger.info('Authenticating with Beamable...');
188
- await this.authManager.authenticate();
189
-
190
- this.logger.info('Initializing Beamable SDK services...');
191
- await this.serviceManager.initialize();
192
-
193
- this.logger.info('Initializing dependency providers...');
194
- await this.initializeDependencyProviders();
195
-
196
- this.logger.info('Registering service with gateway...');
197
- await this.registerService();
198
-
199
- this.logger.info('Starting discovery broadcaster...');
200
- await this.discovery?.start();
201
-
202
- // Mark as ready only after service is fully registered and discovery is started
203
- this.isReady = true;
204
- this.logger.info('Beamable microservice runtime is ready to accept traffic.');
205
- } catch (error) {
206
- // Log the error with full context but don't crash - health check server is running
207
- // This allows the container to stay alive so we can debug the issue
208
- // Debug output for local development only (in containers, logger handles this)
209
- debugLog('[BEAMABLE-NODE] FATAL ERROR during startup:');
210
- debugLog(`[BEAMABLE-NODE] Error message: ${error instanceof Error ? error.message : String(error)}`);
211
- debugLog(`[BEAMABLE-NODE] Error stack: ${error instanceof Error ? error.stack : 'No stack trace'}`);
212
- debugLog(`[BEAMABLE-NODE] isReady: ${this.isReady}`);
213
-
214
- this.logger.error(
215
- {
216
- err: error,
217
- errorMessage: error instanceof Error ? error.message : String(error),
218
- errorStack: error instanceof Error ? error.stack : undefined,
219
- isReady: this.isReady,
220
- },
221
- 'Failed to fully initialize microservice runtime. Health check will continue to return 503 until initialization completes.'
222
- );
223
- // DON'T re-throw - keep process alive so health check can show 503
224
- // This allows us to see the error in logs
225
- this.isReady = false;
226
- }
227
- }
228
-
229
- async shutdown(): Promise<void> {
230
- this.logger.info('Shutting down microservice runtime.');
231
- this.isReady = false; // Mark as not ready during shutdown
232
- this.discovery?.stop();
233
- await this.stopHealthCheckServer();
234
- this.requester.dispose();
235
- await this.webSocket.close();
236
- }
237
-
238
- private async startHealthCheckServer(): Promise<void> {
239
- // For deployed services, always start health check server (required for container health checks)
240
- // For local development, only start if healthPort is explicitly set
241
- // IMPORTANT: Always default to 6565 if HEALTH_PORT env var is not set, as this is the standard port
242
- const healthPort = this.env.healthPort || 6565;
243
-
244
- // Always start health check server if we have a valid port
245
- // The container orchestrator expects this endpoint to be available
246
- if (!healthPort || healthPort === 0) {
247
- // Health check server not needed (local development without explicit port)
248
- this.logger.debug('Health check server skipped (no healthPort set)');
249
- return;
250
- }
251
-
252
- this.healthCheckServer = createServer((req, res) => {
253
- if (req.url === '/health' && req.method === 'GET') {
254
- // Only return success if service is fully ready (registered and accepting traffic)
255
- if (this.isReady) {
256
- res.writeHead(200, { 'Content-Type': 'text/plain' });
257
- res.end('responsive');
258
- } else {
259
- // Service is still starting up
260
- res.writeHead(503, { 'Content-Type': 'text/plain' });
261
- res.end('Service Unavailable');
262
- }
263
- } else {
264
- res.writeHead(404, { 'Content-Type': 'text/plain' });
265
- res.end('Not Found');
266
- }
267
- });
268
-
269
- return new Promise((resolve, reject) => {
270
- this.healthCheckServer!.listen(healthPort, '0.0.0.0', () => {
271
- this.logger.info({ port: healthPort }, 'Health check server started on port');
272
- resolve();
273
- });
274
- this.healthCheckServer!.on('error', (err) => {
275
- this.logger.error({ err, port: healthPort }, 'Failed to start health check server');
276
- reject(err);
277
- });
278
- });
279
- }
280
-
281
- private async stopHealthCheckServer(): Promise<void> {
282
- if (!this.healthCheckServer) {
283
- return;
284
- }
285
-
286
- return new Promise((resolve) => {
287
- this.healthCheckServer!.close(() => {
288
- this.logger.info('Health check server stopped');
289
- resolve();
290
- });
291
- });
292
- }
293
-
294
- private async registerService(): Promise<void> {
295
- const primary = this.services[0]?.definition;
296
- if (!primary) {
297
- throw new Error('Unexpected missing service definition during registration.');
298
- }
299
- const options = getServiceOptions(primary.ctor) ?? {};
300
- // Match C# exactly: use qualifiedName (preserves case) for name field.
301
- // The gateway lowercases service names when creating bindings, but uses the original case
302
- // from the registration request when constructing routing key lookups.
303
- // This ensures the routing key format matches what the gateway expects.
304
- // The gateway's binding lookup behavior:
305
- // - Gateway error shows: "No binding found for service ...micro_examplenodeservice.basic"
306
- // - This means the gateway lowercases the service name for binding storage/lookup
307
- // - Portal sends requests with mixed case in URL and routing key header
308
- // - The gateway lowercases the URL path for binding lookup, which should work
309
- // - But we need to register with the format the gateway expects for the binding key
310
- // - The gateway constructs binding key as: {cid}.{pid}.{lowercaseServiceName}.{type}
311
- // - So we register with lowercase to match what the gateway stores in the binding
312
- // - The portal will still send mixed case, and the gateway will lowercase it for lookup
313
- // Register with mixed-case qualifiedName to match C# behavior
314
- // The gateway will lowercase the service name when creating the binding key,
315
- // but the registration request should use the original case (as C# does)
316
- // This ensures the service name in the registration matches what the portal expects
317
- // Register with mixed-case qualifiedName to match C# behavior
318
- // The gateway's ServiceIdentity.fullNameNoType lowercases the service name when creating bindings,
319
- // but the registration request should use the original case (as C# does)
320
- // This ensures the service name in the registration matches what the portal expects
321
- const isDeployed = isRunningInContainer();
322
-
323
- // For deployed services, routingKey should be null/undefined (None in Scala)
324
- // For local dev, routingKey should be the actual routing key string
325
- // The backend expects Option[String] = None for deployed services
326
- // Note: microServiceId is not part of SocketSessionProviderRegisterRequest, so we don't include it
327
- // All fields except 'type' are Option[T] in Scala, so undefined fields will be omitted from JSON
328
- // This matches C# behavior where null/None fields are not serialized
329
- const request: Record<string, unknown> = {
330
- type: 'basic',
331
- name: primary.qualifiedName, // Use mixed-case as C# does - gateway handles lowercasing for binding storage
332
- beamoName: primary.name,
333
- };
334
-
335
- // Only include routingKey and startedById if they have values (for local dev)
336
- // For deployed services, these should be omitted (undefined) to match None in Scala
337
- if (!isDeployed && this.env.routingKey) {
338
- request.routingKey = this.env.routingKey;
339
- }
340
- if (!isDeployed && this.env.accountId) {
341
- request.startedById = this.env.accountId;
342
- }
343
-
344
- // Log registration request to match C# behavior exactly
345
- // Also log the actual JSON that will be sent (undefined fields will be omitted)
346
- const serializedRequest = JSON.stringify(request);
347
- this.logger.debug(
348
- {
349
- request: {
350
- type: request.type,
351
- name: request.name,
352
- beamoName: request.beamoName,
353
- routingKey: request.routingKey,
354
- startedById: request.startedById,
355
- },
356
- serializedJson: serializedRequest,
357
- isDeployed,
358
- },
359
- 'Registering service provider with gateway.',
360
- );
361
-
362
- try {
363
- await this.requester.request('post', 'gateway/provider', request);
364
- this.logger.info({ serviceName: primary.qualifiedName }, 'Service provider registered successfully.');
365
-
366
- // After registration, the gateway's BasicServiceProvider.start() is called asynchronously
367
- // This triggers afterRabbitInit() -> setupDirectServiceCommunication() -> scheduleServiceBindingCheck()
368
- // The first updateBindings() call happens immediately (0.millisecond delay)
369
- // We wait a bit to allow the gateway to set up the HTTP binding and call updateBindings()
370
- // This is especially important for deployed services where the gateway needs to establish
371
- // the external host binding before bindings can be created
372
- if (isDeployed) {
373
- this.logger.debug('Waiting for gateway to establish bindings after registration...');
374
- await new Promise((resolve) => setTimeout(resolve, 2000)); // 2 second wait for deployed services
375
- this.logger.debug('Wait complete, gateway should have established bindings by now.');
376
- }
377
- } catch (error) {
378
- this.logger.error(
379
- {
380
- err: error,
381
- request,
382
- serviceName: primary.qualifiedName,
383
- errorMessage: error instanceof Error ? error.message : String(error),
384
- },
385
- 'Failed to register service provider with gateway. This will prevent the service from receiving requests.'
386
- );
387
- throw error; // Re-throw so startup fails and we can see the error
388
- }
389
-
390
- if (options.disableAllBeamableEvents) {
391
- this.logger.info('Beamable events disabled by configuration.');
392
- } else {
393
- const eventRequest = {
394
- type: 'event',
395
- evtWhitelist: ['content.manifest', 'realm.config', 'logging.context'],
396
- };
397
- try {
398
- await this.requester.request('post', 'gateway/provider', eventRequest);
399
- } catch (error) {
400
- this.logger.warn({ err: error }, 'Failed to register event provider. Continuing without events.');
401
- }
402
- }
403
- }
404
-
405
- private async handleEvent(envelope: WebsocketEventEnvelope): Promise<void> {
406
- try {
407
- if (!envelope.path) {
408
- this.logger.debug({ envelope }, 'Ignoring websocket event without path.');
409
- return;
410
- }
411
-
412
- if (envelope.path.startsWith('event/')) {
413
- await this.requester.acknowledge(envelope.id);
414
- return;
415
- }
416
-
417
- const context = this.toRequestContext(envelope);
418
- await this.dispatch(context);
419
- } catch (error) {
420
- const err = error instanceof Error ? error : new Error(String(error));
421
- this.logger.error({ err, envelope }, 'Failed to handle websocket event.');
422
- const status = this.resolveErrorStatus(err);
423
- const response: GatewayResponse = {
424
- id: envelope.id,
425
- status,
426
- body: {
427
- error: err.name,
428
- message: err.message,
429
- },
430
- };
431
- await this.requester.sendResponse(response);
432
- }
433
- }
434
-
435
- private toRequestContext(envelope: WebsocketEventEnvelope): RequestContext {
436
- const path = envelope.path ?? '';
437
- const method = envelope.method ?? 'post';
438
- const userId = typeof envelope.from === 'number' ? envelope.from : 0;
439
- const headers = envelope.headers ?? {};
440
-
441
- // Extract scopes from envelope.scopes array
442
- // Note: X-DE-SCOPE header contains CID.PID, not scope values
443
- // The gateway sends scopes in envelope.scopes array
444
- // For admin endpoints, the gateway may not send scopes in the envelope,
445
- // so we infer admin scope from the path if it's an admin route
446
- const envelopeScopes = envelope.scopes ?? [];
447
- let scopes = normalizeScopes(envelopeScopes);
448
-
449
- // If this is an admin endpoint and no scopes are provided, infer admin scope
450
- // The gateway may not always send scopes for admin routes
451
- const pathLower = path.toLowerCase();
452
- if (pathLower.includes('/admin/') && scopes.size === 0) {
453
- scopes = normalizeScopes(['admin']);
454
- }
455
-
456
- let body: Record<string, unknown> | undefined;
457
- if (envelope.body && typeof envelope.body === 'string') {
458
- try {
459
- body = JSON.parse(envelope.body) as Record<string, unknown>;
460
- } catch (error) {
461
- this.logger.warn({ err: error, raw: envelope.body }, 'Failed to parse body string.');
462
- }
463
- } else if (envelope.body && typeof envelope.body === 'object') {
464
- body = envelope.body as Record<string, unknown>;
465
- }
466
-
467
- let payload: unknown;
468
- if (body && typeof body === 'object' && 'payload' in body) {
469
- const rawPayload = (body as Record<string, unknown>).payload;
470
- if (typeof rawPayload === 'string') {
471
- try {
472
- payload = JSON.parse(rawPayload) as unknown[];
473
- } catch (error) {
474
- this.logger.warn({ err: error }, 'Failed to parse payload JSON.');
475
- payload = rawPayload;
476
- }
477
- } else {
478
- payload = rawPayload;
479
- }
480
- }
481
-
482
- const targetService = this.findServiceForPath(path);
483
- const services = this.serviceManager.createFacade(userId, scopes, targetService?.definition.name);
484
- const provider = this.createRequestScope(path, targetService);
485
-
486
- const context: RequestContext = {
487
- id: envelope.id,
488
- path,
489
- method,
490
- status: envelope.status ?? 0,
491
- userId,
492
- payload,
493
- body,
494
- scopes,
495
- headers,
496
- cid: this.env.cid,
497
- pid: this.env.pid,
498
- services,
499
- throwIfCancelled: () => {},
500
- isCancelled: () => false,
501
- hasScopes: (...requiredScopes: string[]) => requiredScopes.every((scope) => scopeSetHas(scopes, scope)),
502
- requireScopes: (...requiredScopes: string[]) => {
503
- const missingScopes = requiredScopes.filter((scope) => !scopeSetHas(scopes, scope));
504
- if (missingScopes.length > 0) {
505
- throw new MissingScopesError(missingScopes);
506
- }
507
- },
508
- provider,
509
- };
510
-
511
- provider.setInstance(REQUEST_CONTEXT_TOKEN, context);
512
- provider.setInstance(BEAMABLE_SERVICES_TOKEN, services);
513
-
514
- return context;
515
- }
516
-
517
- private findServiceForPath(path: string): ServiceInstance | undefined {
518
- // Gateway sends paths with lowercase service names, so we need case-insensitive matching
519
- // Match by comparing lowercase versions to handle gateway's lowercase path format
520
- const pathLower = path.toLowerCase();
521
- return this.services.find((service) => {
522
- const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();
523
- return pathLower.startsWith(`${qualifiedNameLower}/`);
524
- });
525
- }
526
-
527
- private async dispatch(ctx: RequestContext): Promise<void> {
528
- const service = this.findServiceForPath(ctx.path);
529
- if (!service) {
530
- throw new UnknownRouteError(ctx.path);
531
- }
532
-
533
- if (await this.tryHandleFederationRoute(ctx, service)) {
534
- return;
535
- }
536
-
537
- if (await this.tryHandleAdminRoute(ctx, service)) {
538
- return;
539
- }
540
-
541
- // Extract route from path - handle case-insensitive path matching
542
- const pathLower = ctx.path.toLowerCase();
543
- const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();
544
- const route = pathLower.substring(qualifiedNameLower.length + 1);
545
- const metadata = service.definition.callables.get(route);
546
- if (!metadata) {
547
- throw new UnknownRouteError(ctx.path);
548
- }
549
-
550
- // For server and admin access, allow userId: 0 if the appropriate scope is present
551
- // For client access, always require userId > 0
552
- if (metadata.requireAuth && ctx.userId <= 0) {
553
- if (metadata.access === 'server' && scopeSetHas(ctx.scopes, 'server')) {
554
- // Server callables with server scope don't need a user ID
555
- } else if (metadata.access === 'admin' && scopeSetHas(ctx.scopes, 'admin')) {
556
- // Admin callables with admin scope don't need a user ID
557
- } else {
558
- throw new UnauthorizedUserError(route);
559
- }
560
- }
561
-
562
- enforceAccess(metadata.access, ctx);
563
-
564
- if (metadata.requiredScopes.length > 0) {
565
- const missing = metadata.requiredScopes.filter((scope) => !scopeSetHas(ctx.scopes, scope));
566
- if (missing.length > 0) {
567
- throw new MissingScopesError(missing);
568
- }
569
- }
570
-
571
- const handler = service.instance[metadata.displayName];
572
- if (typeof handler !== 'function') {
573
- throw new Error(`Callable ${metadata.displayName} is not a function on service ${service.definition.name}.`);
574
- }
575
-
576
- const args = this.buildInvocationArguments(handler as (...args: unknown[]) => unknown, ctx);
577
- const result = await Promise.resolve((handler as (...args: unknown[]) => unknown).apply(service.instance, args));
578
- await this.sendSuccessResponse(ctx, metadata, result);
579
- }
580
-
581
- private buildInvocationArguments(
582
- handler: (...args: unknown[]) => unknown,
583
- ctx: RequestContext,
584
- ): unknown[] {
585
- const payload = Array.isArray(ctx.payload)
586
- ? ctx.payload
587
- : typeof ctx.payload === 'string'
588
- ? [ctx.payload]
589
- : ctx.payload === undefined
590
- ? []
591
- : [ctx.payload];
592
-
593
- const expectedParams = handler.length;
594
- if (expectedParams === payload.length + 1) {
595
- return [ctx, ...payload];
596
- }
597
- return payload;
598
- }
599
-
600
- private async sendSuccessResponse(ctx: RequestContext, metadata: ServiceCallableMetadata, result: unknown): Promise<void> {
601
- let body: unknown;
602
- if (metadata.useLegacySerialization) {
603
- const serialized = typeof result === 'string' ? result : JSON.stringify(result ?? null);
604
- body = { payload: serialized };
605
- } else {
606
- body = result ?? null;
607
- }
608
-
609
- const response: GatewayResponse = {
610
- id: ctx.id,
611
- status: 200,
612
- body,
613
- };
614
- await this.requester.sendResponse(response);
615
- }
616
-
617
- private async sendFederationResponse(ctx: RequestContext, result: unknown): Promise<void> {
618
- const response: GatewayResponse = {
619
- id: ctx.id,
620
- status: 200,
621
- body: result ?? null,
622
- };
623
- await this.requester.sendResponse(response);
624
- }
625
-
626
- private async tryHandleFederationRoute(ctx: RequestContext, service: ServiceInstance): Promise<boolean> {
627
- // Gateway sends paths with lowercase service names, so we need case-insensitive matching
628
- const pathLower = ctx.path.toLowerCase();
629
- const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();
630
- const prefixLower = `${qualifiedNameLower}/`;
631
- if (!pathLower.startsWith(prefixLower)) {
632
- return false;
633
- }
634
- // Extract relative path - use lowercase length since gateway sends lowercase paths
635
- const relativePath = ctx.path.substring(qualifiedNameLower.length + 1);
636
- const handler = service.federationRegistry.resolve(relativePath);
637
- if (!handler) {
638
- return false;
639
- }
640
-
641
- const result = await handler.invoke(ctx as FederatedRequestContext);
642
- await this.sendFederationResponse(ctx, result);
643
- return true;
644
- }
645
-
646
- private async tryHandleAdminRoute(ctx: RequestContext, service: ServiceInstance): Promise<boolean> {
647
- // Gateway sends paths with lowercase service names, so we need case-insensitive matching
648
- // Check if path starts with the admin prefix (case-insensitive)
649
- const pathLower = ctx.path.toLowerCase();
650
- const adminPrefixLower = `${service.definition.qualifiedName.toLowerCase()}/admin/`;
651
- if (!pathLower.startsWith(adminPrefixLower)) {
652
- return false;
653
- }
654
-
655
- const options = getServiceOptions(service.definition.ctor) ?? {};
656
-
657
- const action = pathLower.substring(adminPrefixLower.length);
658
- const requiresAdmin = action === 'metadata' || action === 'docs';
659
- if (requiresAdmin && !scopeSetHas(ctx.scopes, 'admin')) {
660
- // For portal requests to admin endpoints, the gateway may not send scopes
661
- // The X-DE-SCOPE header contains CID.PID, not scope values
662
- // If this is a portal request (has X-DE-SCOPE header), grant admin scope
663
- const hasPortalHeader = ctx.headers['X-DE-SCOPE'] || ctx.headers['x-de-scope'];
664
- if (hasPortalHeader) {
665
- // Grant admin scope for portal requests to admin endpoints
666
- ctx.scopes.add('admin');
667
- } else {
668
- throw new MissingScopesError(['admin']);
669
- }
670
- }
671
-
672
- switch (action) {
673
- case 'health':
674
- case 'healthcheck':
675
- await this.requester.sendResponse({ id: ctx.id, status: 200, body: 'responsive' });
676
- return true;
677
- case 'metadata':
678
- case 'docs':
679
- break;
680
- default:
681
- if (!scopeSetHas(ctx.scopes, 'admin')) {
682
- throw new MissingScopesError(['admin']);
683
- }
684
- throw new UnknownRouteError(ctx.path);
685
- }
686
-
687
- if (action === 'metadata') {
688
- const federatedComponents = service.federationRegistry
689
- .list()
690
- .map((component) => ({
691
- federationNamespace: component.federationNamespace,
692
- federationType: component.federationType,
693
- }));
694
-
695
- await this.requester.sendResponse({
696
- id: ctx.id,
697
- status: 200,
698
- body: {
699
- serviceName: service.definition.name,
700
- sdkVersion: this.env.sdkVersionExecution,
701
- sdkBaseBuildVersion: this.env.sdkVersionExecution,
702
- sdkExecutionVersion: this.env.sdkVersionExecution,
703
- useLegacySerialization: Boolean(options.useLegacySerialization),
704
- disableAllBeamableEvents: Boolean(options.disableAllBeamableEvents),
705
- enableEagerContentLoading: false,
706
- instanceId: this.microServiceId,
707
- routingKey: this.env.routingKey ?? '',
708
- federatedComponents,
709
- },
710
- });
711
- return true;
712
- }
713
-
714
- if (action === 'docs') {
715
- try {
716
- const document = generateOpenApiDocument(
717
- {
718
- qualifiedName: service.definition.qualifiedName,
719
- name: service.definition.name,
720
- callables: Array.from(service.definition.callables.values()).map((callable) => ({
721
- name: callable.displayName,
722
- route: callable.route,
723
- metadata: callable,
724
- handler: typeof service.instance[callable.displayName] === 'function'
725
- ? (service.instance[callable.displayName] as (...args: unknown[]) => unknown)
726
- : undefined,
727
- })),
728
- },
729
- this.env,
730
- VERSION,
731
- );
732
-
733
- // Ensure document is valid (not empty)
734
- if (!document || Object.keys(document).length === 0) {
735
- this.logger.warn({ serviceName: service.definition.name }, 'Generated OpenAPI document is empty');
736
- }
737
-
738
- await this.requester.sendResponse({
739
- id: ctx.id,
740
- status: 200,
741
- body: document,
742
- });
743
- return true;
744
- } catch (error) {
745
- this.logger.error({ err: error, serviceName: service.definition.name }, 'Failed to generate or send docs');
746
- throw error;
747
- }
748
- }
749
-
750
- return false;
751
- }
752
-
753
- private resolveErrorStatus(error: Error): number {
754
- if (error instanceof UnauthorizedUserError) {
755
- return 401;
756
- }
757
- if (error instanceof MissingScopesError) {
758
- return 403;
759
- }
760
- if (error instanceof UnknownRouteError) {
761
- return 404;
762
- }
763
- if (error instanceof BeamableRuntimeError) {
764
- return 500;
765
- }
766
- return 500;
767
- }
768
-
769
- private printHelpfulUrls(service?: ServiceInstance): void {
770
- if (!service) {
771
- return;
772
- }
773
-
774
- // Only print helpful URLs when IS_LOCAL=1 is set
775
- // In deployed containers, we want only JSON logs for proper log collection
776
- if (process.env.IS_LOCAL !== '1' && process.env.IS_LOCAL !== 'true') {
777
- return;
778
- }
779
-
780
- const docsUrl = buildDocsPortalUrl(this.env, service.definition);
781
- const endpointBase = buildPostmanBaseUrl(this.env, service.definition);
782
-
783
- const green = (text: string) => `\x1b[32m${text}\x1b[0m`;
784
- const yellow = (text: string) => `\x1b[33m${text}\x1b[0m`;
785
-
786
- const bannerLines = [
787
- '',
788
- yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),
789
- ` ${green('Beamable Node microservice ready:')} ${green(service.definition.name)}`,
790
- yellow(' Quick shortcuts'),
791
- ` ${yellow('Docs:')} ${docsUrl}`,
792
- ` ${yellow('Endpoint:')} ${endpointBase}`,
793
- yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),
794
- '',
795
- ];
796
-
797
- process.stdout.write(`${bannerLines.join('\n')}`);
798
- }
799
-
800
- private async initializeDependencyProviders(): Promise<void> {
801
- for (const service of this.services) {
802
- const builder = new DependencyBuilder();
803
- builder.tryAddSingletonInstance(LOGGER_TOKEN, service.logger);
804
- builder.tryAddSingletonInstance(ENVIRONMENT_CONFIG_TOKEN, this.env);
805
- builder.tryAddSingletonInstance(BeamableServiceManager, this.serviceManager);
806
- builder.tryAddSingletonInstance(service.definition.ctor, service.instance);
807
- builder.tryAddSingletonInstance(FederationRegistry, service.federationRegistry);
808
-
809
- for (const handler of service.configureHandlers) {
810
- await handler(builder);
811
- }
812
-
813
- const provider = builder.build();
814
- service.provider = provider;
815
-
816
- for (const handler of service.initializeHandlers) {
817
- await handler(provider);
818
- }
819
-
820
- Object.defineProperty(service.instance, 'provider', {
821
- value: provider,
822
- enumerable: false,
823
- configurable: false,
824
- writable: false,
825
- });
826
- }
827
- }
828
-
829
- private createRequestScope(path: string, service?: ServiceInstance): MutableDependencyScope {
830
- const targetService = service ?? this.findServiceForPath(path);
831
- const provider = targetService?.provider ?? new DependencyBuilder().build();
832
- return provider.createScope();
833
- }
834
- }
835
-
836
- function enforceAccess(access: ServiceAccess, ctx: RequestContext): void {
837
- switch (access) {
838
- case 'client':
839
- if (ctx.userId <= 0) {
840
- throw new UnauthorizedUserError(ctx.path);
841
- }
842
- break;
843
- case 'server':
844
- if (!scopeSetHas(ctx.scopes, 'server')) {
845
- throw new MissingScopesError(['server']);
846
- }
847
- break;
848
- case 'admin':
849
- if (!scopeSetHas(ctx.scopes, 'admin')) {
850
- throw new MissingScopesError(['admin']);
851
- }
852
- break;
853
- default:
854
- break;
855
- }
856
- }
857
-
858
- /**
859
- * Conditionally output to console.error only when running locally (not in container).
860
- * In containers, we want only Pino JSON logs to stdout for proper log collection.
861
- */
862
- function debugLog(...args: unknown[]): void {
863
- // Only output debug logs when IS_LOCAL=1 is set
864
- if (process.env.IS_LOCAL === '1' || process.env.IS_LOCAL === 'true') {
865
- console.error(...args);
866
- }
867
- }
868
-
869
- /**
870
- * Determines if we're running in a deployed container.
871
- * Used for service registration logic (routing key handling, discovery broadcaster, etc.)
872
- *
873
- * Note: For log formatting, use IS_LOCAL env var instead.
874
- */
875
- function isRunningInContainer(): boolean {
876
- // Check for Docker container
877
- try {
878
- const fs = require('fs');
879
- if (fs.existsSync('/.dockerenv')) {
880
- return true;
881
- }
882
- } catch {
883
- // fs might not be available
884
- }
885
-
886
- // Check for Docker container hostname pattern (12 hex chars)
887
- const hostname = process.env.HOSTNAME || '';
888
- if (hostname && /^[a-f0-9]{12}$/i.test(hostname)) {
889
- return true;
890
- }
891
-
892
- // Explicit container indicators
893
- if (
894
- process.env.DOTNET_RUNNING_IN_CONTAINER === 'true' ||
895
- process.env.CONTAINER === 'beamable' ||
896
- !!process.env.ECS_CONTAINER_METADATA_URI ||
897
- !!process.env.KUBERNETES_SERVICE_HOST
898
- ) {
899
- return true;
900
- }
901
-
902
- // Default: assume local development
903
- return false;
904
- }
905
-
906
- function normalizeScopes(scopes: Array<unknown>): Set<string> {
907
- const normalized = new Set<string>();
908
- for (const scope of scopes) {
909
- if (typeof scope !== 'string' || scope.trim().length === 0) {
910
- continue;
911
- }
912
- normalized.add(scope.trim().toLowerCase());
913
- }
914
- return normalized;
915
- }
916
-
917
- function scopeSetHas(scopes: Set<string>, scope: string): boolean {
918
- const normalized = scope.trim().toLowerCase();
919
- if (normalized.length === 0) {
920
- return false;
921
- }
922
- return scopes.has('*') || scopes.has(normalized);
923
- }
924
-
925
- function buildPostmanBaseUrl(env: EnvironmentConfig, service: ServiceDefinition): string {
926
- const httpHost = hostToHttpUrl(env.host);
927
- const routingKeyPart = env.routingKey ? env.routingKey : '';
928
- return `${httpHost}/basic/${env.cid}.${env.pid}.${routingKeyPart}${service.qualifiedName}/`;
929
- }
930
-
931
- function buildDocsPortalUrl(env: EnvironmentConfig, service: ServiceDefinition): string {
932
- const portalHost = hostToPortalUrl(hostToHttpUrl(env.host));
933
- const queryParams: Record<string, string> = { srcTool: 'node-runtime' };
934
- if (env.routingKey) {
935
- queryParams.routingKey = env.routingKey;
936
- }
937
- const query = new URLSearchParams(queryParams);
938
- if (env.refreshToken) {
939
- query.set('refresh_token', env.refreshToken);
940
- }
941
- const beamoId = service.name;
942
- return `${portalHost}/${env.cid}/games/${env.pid}/realms/${env.pid}/microservices/micro_${beamoId}/docs?${query.toString()}`;
943
- }
944
-
945
- export async function runMicroservice(): Promise<void> {
946
- // Immediate console output to verify process is starting (local dev only)
947
- // In containers, we rely on Pino logger for all output
948
- debugLog('[BEAMABLE-NODE] Starting microservice...');
949
- debugLog(`[BEAMABLE-NODE] Node version: ${process.version}`);
950
- debugLog(`[BEAMABLE-NODE] Working directory: ${process.cwd()}`);
951
- debugLog(`[BEAMABLE-NODE] Environment: ${JSON.stringify({
952
- NODE_ENV: process.env.NODE_ENV,
953
- CID: process.env.CID ? 'SET' : 'NOT SET',
954
- PID: process.env.PID ? 'SET' : 'NOT SET',
955
- HOST: process.env.HOST ? 'SET' : 'NOT SET',
956
- SECRET: process.env.SECRET ? 'SET' : 'NOT SET',
957
- })}`);
958
- if (process.env.BEAMABLE_SKIP_RUNTIME === 'true') {
959
- return;
960
- }
961
- const runtime = new MicroserviceRuntime();
962
-
963
- // Handle uncaught errors - log them but don't crash immediately
964
- // This allows the health check server to keep running so we can debug
965
- // In containers, errors will be logged by the logger in the runtime
966
- // Locally, use console.error for visibility
967
- process.on('uncaughtException', (error) => {
968
- // In containers, the logger will handle this; locally, show in console
969
- debugLog('Uncaught Exception:', error);
970
- // Don't exit - let the health check server keep running
971
- });
972
-
973
- process.on('unhandledRejection', (reason, promise) => {
974
- // In containers, the logger will handle this; locally, show in console
975
- debugLog('Unhandled Rejection at:', promise, 'reason:', reason);
976
- // Don't exit - let the health check server keep running
977
- });
978
-
979
- try {
980
- await runtime.start();
981
- } catch (error) {
982
- // Log the error but don't exit - health check server is running
983
- // This allows the container to stay alive so we can see what went wrong
984
- // In containers, the logger already logged it in start(); locally, also use console.error
985
- debugLog('Failed to start microservice runtime:', error);
986
- // Keep the process alive so health check can continue
987
- // The health check will return 503 until isReady is true
988
- }
989
-
990
- const shutdownSignals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];
991
- shutdownSignals.forEach((signal) => {
992
- process.once(signal, async () => {
993
- await runtime.shutdown();
994
- process.exit(0);
995
- });
996
- });
997
- }
998
-
999
- interface GenerateOpenApiOptions {
1000
- serviceName?: string;
1001
- }
1002
-
1003
- export function generateOpenApiDocumentForRegisteredServices(
1004
- overrides: Partial<EnvironmentConfig> = {},
1005
- options: GenerateOpenApiOptions = {},
1006
- ): unknown {
1007
- const services = listRegisteredServices();
1008
- if (services.length === 0) {
1009
- throw new Error('No microservices registered. Import your service module before generating documentation.');
1010
- }
1011
-
1012
- const baseEnv = buildEnvironmentConfig(overrides);
1013
- const primary = options.serviceName
1014
- ? services.find((svc) => svc.name === options.serviceName || svc.qualifiedName === options.serviceName)
1015
- : services[0];
1016
-
1017
- if (!primary) {
1018
- throw new Error(`No registered microservice matched '${options.serviceName}'.`);
1019
- }
1020
-
1021
- return generateOpenApiDocument(
1022
- {
1023
- qualifiedName: primary.qualifiedName,
1024
- name: primary.name,
1025
- callables: Array.from(primary.callables.entries()).map(([displayName, metadata]) => ({
1026
- name: displayName,
1027
- route: metadata.route,
1028
- metadata,
1029
- handler: undefined,
1030
- })),
1031
- },
1032
- baseEnv,
1033
- VERSION,
1034
- );
1035
- }
1036
-
1037
- function buildEnvironmentConfig(overrides: Partial<EnvironmentConfig>): EnvironmentConfig {
1038
- const merged: Partial<EnvironmentConfig> = { ...overrides };
1039
-
1040
- const ensure = (key: keyof EnvironmentConfig, fallbackEnv?: string) => {
1041
- if (merged[key] !== undefined) {
1042
- return;
1043
- }
1044
- if (fallbackEnv && process.env[fallbackEnv]) {
1045
- merged[key] = process.env[fallbackEnv] as never;
1046
- }
1047
- };
1048
-
1049
- ensure('cid', 'CID');
1050
- ensure('pid', 'PID');
1051
- ensure('host', 'HOST');
1052
- ensure('secret', 'SECRET');
1053
- ensure('refreshToken', 'REFRESH_TOKEN');
1054
- // Routing key is optional for deployed services (in containers)
1055
- // It will be resolved to empty string if not provided and running in container
1056
- if (!merged.routingKey && !isRunningInContainer()) {
1057
- ensure('routingKey', 'NAME_PREFIX');
1058
- }
1059
-
1060
- if (!merged.cid || !merged.pid || !merged.host) {
1061
- throw new Error('CID, PID, and HOST are required to generate documentation.');
1062
- }
1063
-
1064
- const base = loadEnvironmentConfig();
1065
-
1066
- return {
1067
- ...base,
1068
- ...merged,
1069
- routingKey: merged.routingKey ?? base.routingKey,
1070
- };
1071
- }