@omen.foundation/node-microservice-runtime 0.1.113 → 0.1.114
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/dist/runtime.cjs +4 -3
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +3 -1
- package/dist/runtime.js.map +1 -1
- package/dist/services.cjs +12 -3
- package/dist/services.d.ts +1 -1
- package/dist/services.d.ts.map +1 -1
- package/dist/services.js +17 -10
- package/dist/services.js.map +1 -1
- package/package.json +1 -1
package/dist/runtime.cjs
CHANGED
|
@@ -116,7 +116,7 @@ class MicroserviceRuntime {
|
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
118
|
async start() {
|
|
119
|
-
var _a;
|
|
119
|
+
var _a, _b;
|
|
120
120
|
debugLog('[BEAMABLE-NODE] MicroserviceRuntime.start() called');
|
|
121
121
|
debugLog(`[BEAMABLE-NODE] Service count: ${this.services.length}`);
|
|
122
122
|
this.printHelpfulUrls(this.services[0]);
|
|
@@ -131,13 +131,14 @@ class MicroserviceRuntime {
|
|
|
131
131
|
this.logger.info('Authenticating with Beamable...');
|
|
132
132
|
await this.authManager.authenticate();
|
|
133
133
|
this.logger.info('Initializing Beamable SDK services...');
|
|
134
|
-
|
|
134
|
+
const primaryServiceName = (_a = this.services[0]) === null || _a === void 0 ? void 0 : _a.definition.name;
|
|
135
|
+
await this.serviceManager.initialize(primaryServiceName);
|
|
135
136
|
this.logger.info('Initializing dependency providers...');
|
|
136
137
|
await this.initializeDependencyProviders();
|
|
137
138
|
this.logger.info('Registering service with gateway...');
|
|
138
139
|
await this.registerService();
|
|
139
140
|
this.logger.info('Starting discovery broadcaster...');
|
|
140
|
-
await ((
|
|
141
|
+
await ((_b = this.discovery) === null || _b === void 0 ? void 0 : _b.start());
|
|
141
142
|
this.isReady = true;
|
|
142
143
|
this.logger.info('Beamable microservice runtime is ready to accept traffic.');
|
|
143
144
|
}
|
package/dist/runtime.d.ts.map
CHANGED
|
@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;IAC/C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAyB;IACxD,OAAO,CAAC,iBAAiB,CAAC,CAAS;IACnC,OAAO,CAAC,OAAO,CAAkB;gBAErB,GAAG,CAAC,EAAE,iBAAiB;IA2H7B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA+DtB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;YASjB,sBAAsB;YA2CtB,qBAAqB;YAarB,eAAe;YA+Gf,WAAW;IA8BzB,OAAO,CAAC,gBAAgB;IAuFxB,OAAO,CAAC,kBAAkB;IAW1B;;;;;OAKG;IACH,OAAO,CAAC,gBAAgB;YA+BV,QAAQ;IAwDtB,OAAO,CAAC,wBAAwB;YA8BlB,mBAAmB;YAiBnB,sBAAsB;YAStB,wBAAwB;YAsBxB,mBAAmB;IA6GjC,OAAO,CAAC,kBAAkB;IAgB1B,OAAO,CAAC,gBAAgB;YA+BV,6BAA6B;IAiC3C,OAAO,CAAC,kBAAkB;IAO1B;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;CAI5B;AA+GD,wBAAsB,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC,CAoDrD;AAED,UAAU,sBAAsB;IAC9B,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,wBAAgB,4CAA4C,CAC1D,SAAS,GAAE,OAAO,CAAC,iBAAiB,CAAM,EAC1C,OAAO,GAAE,sBAA2B,GACnC,OAAO,CA6BT"}
|
package/dist/runtime.js
CHANGED
|
@@ -161,7 +161,9 @@ export class MicroserviceRuntime {
|
|
|
161
161
|
this.logger.info('Authenticating with Beamable...');
|
|
162
162
|
await this.authManager.authenticate();
|
|
163
163
|
this.logger.info('Initializing Beamable SDK services...');
|
|
164
|
-
|
|
164
|
+
// Pass service name to initialize so routing key can be configured for service-level requests
|
|
165
|
+
const primaryServiceName = this.services[0]?.definition.name;
|
|
166
|
+
await this.serviceManager.initialize(primaryServiceName);
|
|
165
167
|
this.logger.info('Initializing dependency providers...');
|
|
166
168
|
await this.initializeDependencyProviders();
|
|
167
169
|
this.logger.info('Registering service with gateway...');
|
package/dist/runtime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC9F,OAAO,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,6DAA6D;AAC7D,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,4BAA4B,EAAE,6BAA6B,EAAE,MAAM,iBAAiB,CAAC;AACzI,OAAO,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAWjH,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,wBAAwB,EACxB,qBAAqB,EACrB,uBAAuB,GAGxB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,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OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAC5C,MAAM,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAU,CAAC;QAClD,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACrB,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACrB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvB,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC3B,MAAM,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC;IACxC,gEAAgE;IAChE,+EAA+E;IAC/E,IAAI,CAAC,MAAM,CAAC,UAAU,IAAI,CAAC,oBAAoB,EAAE,EAAE,CAAC;QAClD,MAAM,CAAC,YAAY,EAAE,aAAa,CAAC,CAAC;IACtC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC;IAChF,CAAC;IAED,MAAM,IAAI,GAAG,qBAAqB,EAAE,CAAC;IAErC,OAAO;QACL,GAAG,IAAI;QACP,GAAG,MAAM;QACT,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,IAAI,CAAC,UAAU;KACjD,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { BeamableWebSocket } from './websocket.js';\nimport { GatewayRequester } from './requester.js';\nimport { AuthManager } from './auth.js';\nimport { createLogger } from './logger.js';\nimport { loadEnvironmentConfig } from './env.js';\nimport { loadAndInjectEnvironmentVariables, loadDeveloperEnvVarsSync } from './env-loader.js';\nimport { startCollectorAndWaitForReady } from './collector-manager.js';\nimport pino from 'pino';\n// Removed deasync - using non-blocking async pattern instead\nimport { listRegisteredServices, getServiceOptions, getConfigureServicesHandlers, getInitializeServicesHandlers } from './decorators.js';\nimport { generateOpenApiDocument } from './docs.js';\nimport { VERSION } from './index.js';\nimport { DiscoveryBroadcaster } from './discovery.js';\nimport { BeamableRuntimeError, MissingScopesError, UnauthorizedUserError, UnknownRouteError } from './errors.js';\nimport type {\n EnvironmentConfig,\n RequestContext,\n ServiceDefinition,\n ServiceCallableMetadata,\n GatewayResponse,\n WebsocketEventEnvelope,\n ServiceAccess,\n} from './types.js';\nimport type { Logger } from 'pino';\nimport { BeamableServiceManager } from './services.js';\nimport { StorageService } from './storage.js';\nimport {\n DependencyBuilder,\n LOGGER_TOKEN,\n ENVIRONMENT_CONFIG_TOKEN,\n REQUEST_CONTEXT_TOKEN,\n BEAMABLE_SERVICES_TOKEN,\n ServiceProvider,\n MutableDependencyScope,\n} from './dependency.js';\nimport { hostToHttpUrl, hostToPortalUrl } from './utils/urls.js';\nimport { FederationRegistry, getFederationComponents, getFederatedInventoryMetadata } from './federation.js';\nimport type { FederatedRequestContext } from './federation.js';\nimport { createServer, type Server } from 'node:http';\n\ninterface ServiceInstance {\n definition: ServiceDefinition;\n instance: Record<string, unknown>;\n configureHandlers: ReturnType<typeof getConfigureServicesHandlers>;\n initializeHandlers: ReturnType<typeof getInitializeServicesHandlers>;\n provider?: ServiceProvider;\n logger: Logger;\n federationRegistry: FederationRegistry;\n}\n\nexport class MicroserviceRuntime {\n private readonly env: EnvironmentConfig;\n private logger: Logger; // Mutable to allow upgrading from console logger to structured logger when collector is ready\n private readonly services: ServiceInstance[];\n private readonly webSocket: BeamableWebSocket;\n private readonly requester: GatewayRequester;\n private readonly authManager: AuthManager;\n private readonly discovery?: DiscoveryBroadcaster;\n private readonly microServiceId = randomUUID();\n private readonly serviceManager: BeamableServiceManager;\n private healthCheckServer?: Server;\n private isReady: boolean = false;\n\n constructor(env?: EnvironmentConfig) {\n this.env = env ?? loadEnvironmentConfig();\n const envConfig = this.env; // Capture for async IIFE to satisfy TypeScript\n \n // STEP 1: Load developer-defined environment variables SYNCHRONOUSLY before logger creation\n // This ensures BetterStack and other env vars are available when the logger initializes\n loadDeveloperEnvVarsSync();\n \n // STEP 2: Create minimal console logger for startup messages (before collector setup)\n // This ensures we have logging available immediately, even before collector is ready\n const startupLogger = pino({\n name: 'beamable-runtime-startup',\n level: 'info',\n }, process.stdout);\n // Display runtime version at startup (VERSION is imported synchronously at top of file)\n startupLogger.info(`Starting Beamable Node microservice runtime (version: ${VERSION}).`);\n \n // STEP 2.5: Load Beamable Config asynchronously (in background, non-blocking)\n // Developer-defined vars are already loaded synchronously above\n // Beamable Config is fetched via API with a 2-second timeout\n (async () => {\n try {\n startupLogger.info('Loading Beamable Config environment variables...');\n await loadAndInjectEnvironmentVariables(envConfig, undefined, true, 2000);\n startupLogger.info('Beamable Config loading completed');\n } catch (error) {\n startupLogger.warn(`Beamable Config loading completed with warnings: ${error instanceof Error ? error.message : String(error)}`);\n }\n })();\n \n // STEP 2: Get registered services to extract service name\n const registered = listRegisteredServices();\n if (registered.length === 0) {\n throw new Error('No microservices registered. Use the @Microservice decorator to register at least one class.');\n }\n \n // Use the first service's name for the main logger (for CloudWatch filtering and ClickHouse compatibility)\n const primaryService = registered[0];\n const qualifiedServiceName = `micro_${primaryService.qualifiedName}`;\n \n // STEP 3: Create logger immediately (non-blocking pattern, matching C#)\n // Start with minimal console logger, upgrade to structured logger when collector is ready\n // This allows the service to start immediately without blocking\n startupLogger.info('Setting up OpenTelemetry collector in background (non-blocking)...');\n \n // Create logger immediately with console output (no OTLP yet)\n // This ensures we have logging available right away\n this.logger = createLogger(this.env, {\n name: 'beamable-node-microservice',\n serviceName: primaryService.name,\n qualifiedServiceName: qualifiedServiceName,\n // No otlpEndpoint - will use console logger initially\n });\n \n // STEP 4: Start collector setup in background (non-blocking)\n // When collector is ready, upgrade logger to structured logger with OTLP\n // This matches C# pattern: collector starts in background, service starts immediately\n startCollectorAndWaitForReady(this.env)\n .then((endpoint) => {\n if (endpoint) {\n // Collector is ready - upgrade to structured logger with OTLP support\n this.logger.info(`Collector ready at ${endpoint}, upgrading to structured logger for Portal logs...`);\n this.logger = createLogger(this.env, {\n name: 'beamable-node-microservice',\n serviceName: primaryService.name,\n qualifiedServiceName: qualifiedServiceName,\n otlpEndpoint: endpoint, // Collector is ready, Portal logs will now work\n });\n this.logger.info('Portal logs enabled - structured logs will now appear in Beamable Portal');\n } else {\n this.logger.warn('Collector setup completed but no endpoint was returned. Continuing with console logs. Portal logs will not be available.');\n }\n })\n .catch((error) => {\n const errorMsg = error instanceof Error ? error.message : String(error);\n this.logger.error(`Failed to setup collector: ${errorMsg}. Continuing with console logs. Portal logs will not be available.`);\n // Service continues to work with console logger - graceful degradation\n });\n \n // Continue immediately - don't wait for collector!\n // Service can start accepting requests right away\n // Collector setup happens in background, logger upgrades automatically when ready\n this.serviceManager = new BeamableServiceManager(this.env, this.logger);\n\n this.services = registered.map((definition) => {\n const instance = new definition.ctor() as Record<string, unknown>;\n const configureHandlers = getConfigureServicesHandlers(definition.ctor);\n const initializeHandlers = getInitializeServicesHandlers(definition.ctor);\n const logger = this.logger.child({ service: definition.name });\n const federationRegistry = new FederationRegistry(logger);\n const decoratedFederations = getFederationComponents(definition.ctor);\n for (const component of decoratedFederations) {\n federationRegistry.register(component);\n }\n const inventoryMetadata = getFederatedInventoryMetadata(definition.ctor);\n if (inventoryMetadata.length > 0) {\n federationRegistry.registerInventoryHandlers(instance, inventoryMetadata);\n }\n this.serviceManager.registerFederationRegistry(definition.name, federationRegistry);\n return { definition, instance, configureHandlers, initializeHandlers, logger, federationRegistry };\n });\n\n const socketUrl = this.env.host.endsWith('/socket') ? this.env.host : `${this.env.host}/socket`;\n this.webSocket = new BeamableWebSocket({ url: socketUrl, logger: this.logger });\n this.webSocket.on('message', (payload) => {\n this.logger.debug({ payload }, 'Runtime observed websocket frame.');\n });\n this.requester = new GatewayRequester(this.webSocket, this.logger);\n this.authManager = new AuthManager(this.env, this.requester);\n this.requester.on('event', (envelope) => this.handleEvent(envelope));\n\n // Discovery broadcaster only runs in local development (not in containers)\n // This allows the portal to detect that the service is running locally\n if (!isRunningInContainer() && this.services.length > 0) {\n this.discovery = new DiscoveryBroadcaster({\n env: this.env,\n serviceName: this.services[0].definition.name,\n routingKey: this.env.routingKey,\n logger: this.logger.child({ component: 'DiscoveryBroadcaster' }),\n });\n }\n }\n\n async start(): Promise<void> {\n // Immediate console output for container logs (before logger is ready)\n debugLog('[BEAMABLE-NODE] MicroserviceRuntime.start() called');\n debugLog(`[BEAMABLE-NODE] Service count: ${this.services.length}`);\n \n this.printHelpfulUrls(this.services[0]);\n this.logger.info('Starting Beamable Node microservice runtime.');\n \n // Start health check server FIRST - this is critical for container health checks\n // Even if startup fails, the health check server must be running so we can debug\n debugLog('[BEAMABLE-NODE] Starting health check server...');\n await this.startHealthCheckServer();\n debugLog('[BEAMABLE-NODE] Health check server started');\n \n try {\n this.logger.info('Connecting to Beamable gateway...');\n await this.webSocket.connect();\n await new Promise((resolve) => setTimeout(resolve, 250));\n \n this.logger.info('Authenticating with Beamable...');\n await this.authManager.authenticate();\n \n this.logger.info('Initializing Beamable SDK services...');\n await this.serviceManager.initialize();\n \n this.logger.info('Initializing dependency providers...');\n await this.initializeDependencyProviders();\n \n this.logger.info('Registering service with gateway...');\n await this.registerService();\n \n this.logger.info('Starting discovery broadcaster...');\n await this.discovery?.start();\n \n // Mark as ready only after service is fully registered and discovery is started\n this.isReady = true;\n this.logger.info('Beamable microservice runtime is ready to accept traffic.');\n } catch (error) {\n // Log the error with full context but don't crash - health check server is running\n // This allows the container to stay alive so we can debug the issue\n // Debug output for local development only (in containers, logger handles this)\n debugLog('[BEAMABLE-NODE] FATAL ERROR during startup:');\n debugLog(`[BEAMABLE-NODE] Error message: ${error instanceof Error ? error.message : String(error)}`);\n debugLog(`[BEAMABLE-NODE] Error stack: ${error instanceof Error ? error.stack : 'No stack trace'}`);\n debugLog(`[BEAMABLE-NODE] isReady: ${this.isReady}`);\n \n this.logger.error(\n { \n err: error,\n errorMessage: error instanceof Error ? error.message : String(error),\n errorStack: error instanceof Error ? error.stack : undefined,\n isReady: this.isReady,\n },\n 'Failed to fully initialize microservice runtime. Health check will continue to return 503 until initialization completes.'\n );\n // DON'T re-throw - keep process alive so health check can show 503\n // This allows us to see the error in logs\n this.isReady = false;\n }\n }\n\n async shutdown(): Promise<void> {\n this.logger.info('Shutting down microservice runtime.');\n this.isReady = false; // Mark as not ready during shutdown\n this.discovery?.stop();\n await this.stopHealthCheckServer();\n this.requester.dispose();\n await this.webSocket.close();\n }\n\n private async startHealthCheckServer(): Promise<void> {\n // For deployed services, always start health check server (required for container health checks)\n // For local development, only start if healthPort is explicitly set\n // IMPORTANT: Always default to 6565 if HEALTH_PORT env var is not set, as this is the standard port\n const healthPort = this.env.healthPort || 6565;\n \n // Always start health check server if we have a valid port\n // The container orchestrator expects this endpoint to be available\n if (!healthPort || healthPort === 0) {\n // Health check server not needed (local development without explicit port)\n this.logger.debug('Health check server skipped (no healthPort set)');\n return;\n }\n\n this.healthCheckServer = createServer((req, res) => {\n if (req.url === '/health' && req.method === 'GET') {\n // Only return success if service is fully ready (registered and accepting traffic)\n if (this.isReady) {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('responsive');\n } else {\n // Service is still starting up\n res.writeHead(503, { 'Content-Type': 'text/plain' });\n res.end('Service Unavailable');\n }\n } else {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n });\n\n return new Promise((resolve, reject) => {\n this.healthCheckServer!.listen(healthPort, '0.0.0.0', () => {\n this.logger.info({ port: healthPort }, 'Health check server started on port');\n resolve();\n });\n this.healthCheckServer!.on('error', (err) => {\n this.logger.error({ err, port: healthPort }, 'Failed to start health check server');\n reject(err);\n });\n });\n }\n\n private async stopHealthCheckServer(): Promise<void> {\n if (!this.healthCheckServer) {\n return;\n }\n\n return new Promise((resolve) => {\n this.healthCheckServer!.close(() => {\n this.logger.info('Health check server stopped');\n resolve();\n });\n });\n }\n\n private async registerService(): Promise<void> {\n const primary = this.services[0]?.definition;\n if (!primary) {\n throw new Error('Unexpected missing service definition during registration.');\n }\n const options = getServiceOptions(primary.ctor) ?? {};\n // Match C# exactly: use qualifiedName (preserves case) for name field.\n // The gateway lowercases service names when creating bindings, but uses the original case\n // from the registration request when constructing routing key lookups.\n // This ensures the routing key format matches what the gateway expects.\n // The gateway's binding lookup behavior:\n // - Gateway error shows: \"No binding found for service ...micro_examplenodeservice.basic\"\n // - This means the gateway lowercases the service name for binding storage/lookup\n // - Portal sends requests with mixed case in URL and routing key header\n // - The gateway lowercases the URL path for binding lookup, which should work\n // - But we need to register with the format the gateway expects for the binding key\n // - The gateway constructs binding key as: {cid}.{pid}.{lowercaseServiceName}.{type}\n // - So we register with lowercase to match what the gateway stores in the binding\n // - The portal will still send mixed case, and the gateway will lowercase it for lookup\n // Register with mixed-case qualifiedName to match C# behavior\n // The gateway will lowercase the service name when creating the binding key,\n // but the registration request should use the original case (as C# does)\n // This ensures the service name in the registration matches what the portal expects\n // Register with mixed-case qualifiedName to match C# behavior\n // The gateway's ServiceIdentity.fullNameNoType lowercases the service name when creating bindings,\n // but the registration request should use the original case (as C# does)\n // This ensures the service name in the registration matches what the portal expects\n const isDeployed = isRunningInContainer();\n \n // For deployed services, routingKey should be null/undefined (None in Scala)\n // For local dev, routingKey should be the actual routing key string\n // The backend expects Option[String] = None for deployed services\n // Note: microServiceId is not part of SocketSessionProviderRegisterRequest, so we don't include it\n // All fields except 'type' are Option[T] in Scala, so undefined fields will be omitted from JSON\n // This matches C# behavior where null/None fields are not serialized\n const request: Record<string, unknown> = {\n type: 'basic',\n name: primary.qualifiedName, // Use mixed-case as C# does - gateway handles lowercasing for binding storage\n beamoName: primary.name,\n };\n \n // Only include routingKey and startedById if they have values (for local dev)\n // For deployed services, these should be omitted (undefined) to match None in Scala\n if (!isDeployed && this.env.routingKey) {\n request.routingKey = this.env.routingKey;\n }\n if (!isDeployed && this.env.accountId) {\n request.startedById = this.env.accountId;\n }\n\n // Log registration request to match C# behavior exactly\n // Also log the actual JSON that will be sent (undefined fields will be omitted)\n const serializedRequest = JSON.stringify(request);\n this.logger.debug(\n {\n request: {\n type: request.type,\n name: request.name,\n beamoName: request.beamoName,\n routingKey: request.routingKey,\n startedById: request.startedById,\n },\n serializedJson: serializedRequest,\n isDeployed,\n },\n 'Registering service provider with gateway.',\n );\n\n try {\n await this.requester.request('post', 'gateway/provider', request);\n this.logger.info({ serviceName: primary.qualifiedName }, 'Service provider registered successfully.');\n \n // After registration, the gateway's BasicServiceProvider.start() is called asynchronously\n // This triggers afterRabbitInit() -> setupDirectServiceCommunication() -> scheduleServiceBindingCheck()\n // The first updateBindings() call happens immediately (0.millisecond delay)\n // We wait a bit to allow the gateway to set up the HTTP binding and call updateBindings()\n // This is especially important for deployed services where the gateway needs to establish\n // the external host binding before bindings can be created\n if (isDeployed) {\n this.logger.debug('Waiting for gateway to establish bindings after registration...');\n await new Promise((resolve) => setTimeout(resolve, 2000)); // 2 second wait for deployed services\n this.logger.debug('Wait complete, gateway should have established bindings by now.');\n }\n } catch (error) {\n this.logger.error(\n {\n err: error,\n request,\n serviceName: primary.qualifiedName,\n errorMessage: error instanceof Error ? error.message : String(error),\n },\n 'Failed to register service provider with gateway. This will prevent the service from receiving requests.'\n );\n throw error; // Re-throw so startup fails and we can see the error\n }\n\n if (options.disableAllBeamableEvents) {\n this.logger.info('Beamable events disabled by configuration.');\n } else {\n const eventRequest = {\n type: 'event',\n evtWhitelist: ['content.manifest', 'realm.config', 'logging.context'],\n };\n try {\n await this.requester.request('post', 'gateway/provider', eventRequest);\n } catch (error) {\n this.logger.warn({ err: error }, 'Failed to register event provider. Continuing without events.');\n }\n }\n }\n\n private async handleEvent(envelope: WebsocketEventEnvelope): Promise<void> {\n try {\n if (!envelope.path) {\n this.logger.debug({ envelope }, 'Ignoring websocket event without path.');\n return;\n }\n\n if (envelope.path.startsWith('event/')) {\n await this.requester.acknowledge(envelope.id);\n return;\n }\n\n const context = this.toRequestContext(envelope);\n await this.dispatch(context);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.logger.error({ err, envelope }, 'Failed to handle websocket event.');\n const status = this.resolveErrorStatus(err);\n const response: GatewayResponse = {\n id: envelope.id,\n status,\n body: {\n error: err.name,\n message: err.message,\n },\n };\n await this.requester.sendResponse(response);\n }\n }\n\n private toRequestContext(envelope: WebsocketEventEnvelope): RequestContext {\n const path = envelope.path ?? '';\n const method = envelope.method ?? 'post';\n const userId = typeof envelope.from === 'number' ? envelope.from : 0;\n const headers = envelope.headers ?? {};\n \n // Parse query parameters from path (e.g., /service/route?param1=value1¶m2=value2)\n const [pathWithoutQuery, queryString] = path.split('?', 2);\n const query = this.parseQueryString(queryString ?? '');\n \n // Extract scopes from envelope.scopes array\n // Note: X-DE-SCOPE header contains CID.PID, not scope values\n // The gateway sends scopes in envelope.scopes array\n // For admin endpoints, the gateway may not send scopes in the envelope,\n // so we infer admin scope from the path if it's an admin route\n const envelopeScopes = envelope.scopes ?? [];\n let scopes = normalizeScopes(envelopeScopes);\n \n // If this is an admin endpoint and no scopes are provided, infer admin scope\n // The gateway may not always send scopes for admin routes\n const pathLower = pathWithoutQuery.toLowerCase();\n if (pathLower.includes('/admin/') && scopes.size === 0) {\n scopes = normalizeScopes(['admin']);\n }\n\n let body: Record<string, unknown> | undefined;\n if (envelope.body && typeof envelope.body === 'string') {\n try {\n body = JSON.parse(envelope.body) as Record<string, unknown>;\n } catch (error) {\n this.logger.warn({ err: error, raw: envelope.body }, 'Failed to parse body string.');\n }\n } else if (envelope.body && typeof envelope.body === 'object') {\n body = envelope.body as Record<string, unknown>;\n }\n\n let payload: unknown;\n if (body && typeof body === 'object' && 'payload' in body) {\n const rawPayload = (body as Record<string, unknown>).payload;\n if (typeof rawPayload === 'string') {\n try {\n payload = JSON.parse(rawPayload) as unknown[];\n } catch (error) {\n this.logger.warn({ err: error }, 'Failed to parse payload JSON.');\n payload = rawPayload;\n }\n } else {\n payload = rawPayload;\n }\n }\n\n const targetService = this.findServiceForPath(pathWithoutQuery);\n const services = this.serviceManager.createFacade(userId, scopes, targetService?.definition.name);\n const provider = this.createRequestScope(pathWithoutQuery, targetService);\n\n const context: RequestContext = {\n id: envelope.id,\n path,\n method,\n status: envelope.status ?? 0,\n userId,\n payload,\n body,\n query,\n scopes,\n headers,\n cid: this.env.cid,\n pid: this.env.pid,\n services,\n throwIfCancelled: () => {},\n isCancelled: () => false,\n hasScopes: (...requiredScopes: string[]) => requiredScopes.every((scope) => scopeSetHas(scopes, scope)),\n requireScopes: (...requiredScopes: string[]) => {\n const missingScopes = requiredScopes.filter((scope) => !scopeSetHas(scopes, scope));\n if (missingScopes.length > 0) {\n throw new MissingScopesError(missingScopes);\n }\n },\n provider,\n };\n\n provider.setInstance(REQUEST_CONTEXT_TOKEN, context);\n provider.setInstance(BEAMABLE_SERVICES_TOKEN, services);\n\n return context;\n }\n\n private findServiceForPath(path: string): ServiceInstance | undefined {\n // Gateway sends paths with lowercase service names, so we need case-insensitive matching\n // Match by comparing lowercase versions to handle gateway's lowercase path format\n // Note: path should already have query string stripped before calling this method\n const pathLower = path.toLowerCase();\n return this.services.find((service) => {\n const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();\n return pathLower.startsWith(`${qualifiedNameLower}/`);\n });\n }\n\n /**\n * Parses a query string into a record of parameter names to values.\n * Handles multiple values for the same parameter name by storing them as an array.\n * @param queryString The query string (without the leading '?')\n * @returns A record mapping parameter names to their values (single string or array of strings)\n */\n private parseQueryString(queryString: string): Record<string, string | string[]> {\n if (!queryString || queryString.trim().length === 0) {\n return {};\n }\n\n const params: Record<string, string | string[]> = {};\n const pairs = queryString.split('&');\n\n for (const pair of pairs) {\n const [key, value = ''] = pair.split('=', 2);\n if (key) {\n const decodedKey = decodeURIComponent(key);\n const decodedValue = decodeURIComponent(value);\n\n // If the key already exists, convert to array or append to existing array\n if (decodedKey in params) {\n const existing = params[decodedKey];\n if (Array.isArray(existing)) {\n existing.push(decodedValue);\n } else {\n params[decodedKey] = [existing, decodedValue];\n }\n } else {\n params[decodedKey] = decodedValue;\n }\n }\n }\n\n return params;\n }\n\n private async dispatch(ctx: RequestContext): Promise<void> {\n // Extract path without query string for routing\n const pathWithoutQuery = this.getPathWithoutQuery(ctx.path);\n const service = this.findServiceForPath(pathWithoutQuery);\n if (!service) {\n throw new UnknownRouteError(ctx.path);\n }\n\n if (await this.tryHandleFederationRoute(ctx, service)) {\n return;\n }\n\n if (await this.tryHandleAdminRoute(ctx, service)) {\n return;\n }\n\n // Extract route from path - handle case-insensitive path matching\n const pathLower = pathWithoutQuery.toLowerCase();\n const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();\n const route = pathLower.substring(qualifiedNameLower.length + 1);\n const metadata = service.definition.callables.get(route);\n if (!metadata) {\n throw new UnknownRouteError(ctx.path);\n }\n\n // For server and admin access, allow userId: 0 if the appropriate scope is present\n // For client access, always require userId > 0\n if (metadata.requireAuth && ctx.userId <= 0) {\n if (metadata.access === 'server' && scopeSetHas(ctx.scopes, 'server')) {\n // Server callables with server scope don't need a user ID\n } else if (metadata.access === 'admin' && scopeSetHas(ctx.scopes, 'admin')) {\n // Admin callables with admin scope don't need a user ID\n } else {\n throw new UnauthorizedUserError(route);\n }\n }\n\n enforceAccess(metadata.access, ctx);\n\n if (metadata.requiredScopes.length > 0) {\n const missing = metadata.requiredScopes.filter((scope) => !scopeSetHas(ctx.scopes, scope));\n if (missing.length > 0) {\n throw new MissingScopesError(missing);\n }\n }\n\n const handler = service.instance[metadata.displayName];\n if (typeof handler !== 'function') {\n throw new Error(`Callable ${metadata.displayName} is not a function on service ${service.definition.name}.`);\n }\n\n const args = this.buildInvocationArguments(handler as (...args: unknown[]) => unknown, ctx);\n const result = await Promise.resolve((handler as (...args: unknown[]) => unknown).apply(service.instance, args));\n await this.sendSuccessResponse(ctx, metadata, result);\n }\n\n private buildInvocationArguments(\n handler: (...args: unknown[]) => unknown,\n ctx: RequestContext,\n ): unknown[] {\n const payload = Array.isArray(ctx.payload)\n ? ctx.payload\n : typeof ctx.payload === 'string'\n ? [ctx.payload]\n : ctx.payload === undefined\n ? []\n : [ctx.payload];\n\n const expectedParams = handler.length;\n\n // Determine if RequestContext should be passed as the first argument\n // Strategy: If handler expects more parameters than payload provides,\n // assume the first parameter is RequestContext\n // This covers common cases:\n // - handler(ctx: RequestContext) with empty payload -> expectedParams=1, payload.length=0 -> include ctx\n // - handler(ctx: RequestContext, param: string) with payload=['value'] -> expectedParams=2, payload.length=1 -> include ctx\n // - handler(param: string) with payload=['value'] -> expectedParams=1, payload.length=1 -> don't include ctx\n if (expectedParams > payload.length) {\n return [ctx, ...payload];\n }\n\n // If handler expects exactly the same number of parameters as payload,\n // don't include ctx (handler doesn't expect it)\n return payload;\n }\n\n private async sendSuccessResponse(ctx: RequestContext, metadata: ServiceCallableMetadata, result: unknown): Promise<void> {\n let body: unknown;\n if (metadata.useLegacySerialization) {\n const serialized = typeof result === 'string' ? result : JSON.stringify(result ?? null);\n body = { payload: serialized };\n } else {\n body = result ?? null;\n }\n\n const response: GatewayResponse = {\n id: ctx.id,\n status: 200,\n body,\n };\n await this.requester.sendResponse(response);\n }\n\n private async sendFederationResponse(ctx: RequestContext, result: unknown): Promise<void> {\n const response: GatewayResponse = {\n id: ctx.id,\n status: 200,\n body: result ?? null,\n };\n await this.requester.sendResponse(response);\n }\n\n private async tryHandleFederationRoute(ctx: RequestContext, service: ServiceInstance): Promise<boolean> {\n // Gateway sends paths with lowercase service names, so we need case-insensitive matching\n // Extract path without query string for routing\n const pathWithoutQuery = this.getPathWithoutQuery(ctx.path);\n const pathLower = pathWithoutQuery.toLowerCase();\n const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();\n const prefixLower = `${qualifiedNameLower}/`;\n if (!pathLower.startsWith(prefixLower)) {\n return false;\n }\n // Extract relative path - use lowercase length since gateway sends lowercase paths\n const relativePath = pathWithoutQuery.substring(qualifiedNameLower.length + 1);\n const handler = service.federationRegistry.resolve(relativePath);\n if (!handler) {\n return false;\n }\n\n const result = await handler.invoke(ctx as FederatedRequestContext);\n await this.sendFederationResponse(ctx, result);\n return true;\n }\n\n private async tryHandleAdminRoute(ctx: RequestContext, service: ServiceInstance): Promise<boolean> {\n // Gateway sends paths with lowercase service names, so we need case-insensitive matching\n // Check if path starts with the admin prefix (case-insensitive)\n // Extract path without query string for routing\n const pathWithoutQuery = this.getPathWithoutQuery(ctx.path);\n const pathLower = pathWithoutQuery.toLowerCase();\n const adminPrefixLower = `${service.definition.qualifiedName.toLowerCase()}/admin/`;\n if (!pathLower.startsWith(adminPrefixLower)) {\n return false;\n }\n\n const options = getServiceOptions(service.definition.ctor) ?? {};\n\n const action = pathLower.substring(adminPrefixLower.length);\n const requiresAdmin = action === 'metadata' || action === 'docs';\n if (requiresAdmin && !scopeSetHas(ctx.scopes, 'admin')) {\n // For portal requests to admin endpoints, the gateway may not send scopes\n // The X-DE-SCOPE header contains CID.PID, not scope values\n // If this is a portal request (has X-DE-SCOPE header), grant admin scope\n const hasPortalHeader = ctx.headers['X-DE-SCOPE'] || ctx.headers['x-de-scope'];\n if (hasPortalHeader) {\n // Grant admin scope for portal requests to admin endpoints\n ctx.scopes.add('admin');\n } else {\n throw new MissingScopesError(['admin']);\n }\n }\n\n switch (action) {\n case 'health':\n case 'healthcheck':\n await this.requester.sendResponse({ id: ctx.id, status: 200, body: 'responsive' });\n return true;\n case 'metadata':\n case 'docs':\n break;\n default:\n if (!scopeSetHas(ctx.scopes, 'admin')) {\n throw new MissingScopesError(['admin']);\n }\n throw new UnknownRouteError(ctx.path);\n }\n\n if (action === 'metadata') {\n const federatedComponents = service.federationRegistry\n .list()\n .map((component) => ({\n federationNamespace: component.federationNamespace,\n federationType: component.federationType,\n }));\n\n await this.requester.sendResponse({\n id: ctx.id,\n status: 200,\n body: {\n serviceName: service.definition.name,\n sdkVersion: this.env.sdkVersionExecution,\n sdkBaseBuildVersion: this.env.sdkVersionExecution,\n sdkExecutionVersion: this.env.sdkVersionExecution,\n useLegacySerialization: Boolean(options.useLegacySerialization),\n disableAllBeamableEvents: Boolean(options.disableAllBeamableEvents),\n enableEagerContentLoading: false,\n instanceId: this.microServiceId,\n routingKey: this.env.routingKey ?? '',\n federatedComponents,\n },\n });\n return true;\n }\n\n if (action === 'docs') {\n try {\n const document = generateOpenApiDocument(\n {\n qualifiedName: service.definition.qualifiedName,\n name: service.definition.name,\n callables: Array.from(service.definition.callables.values()).map((callable) => ({\n name: callable.displayName,\n route: callable.route,\n metadata: callable,\n handler: typeof service.instance[callable.displayName] === 'function'\n ? (service.instance[callable.displayName] as (...args: unknown[]) => unknown)\n : undefined,\n })),\n },\n this.env,\n VERSION,\n );\n\n // Ensure document is valid (not empty)\n if (!document || Object.keys(document).length === 0) {\n this.logger.warn({ serviceName: service.definition.name }, 'Generated OpenAPI document is empty');\n }\n\n await this.requester.sendResponse({\n id: ctx.id,\n status: 200,\n body: document,\n });\n return true;\n } catch (error) {\n this.logger.error({ err: error, serviceName: service.definition.name }, 'Failed to generate or send docs');\n throw error;\n }\n }\n\n return false;\n }\n\n private resolveErrorStatus(error: Error): number {\n if (error instanceof UnauthorizedUserError) {\n return 401;\n }\n if (error instanceof MissingScopesError) {\n return 403;\n }\n if (error instanceof UnknownRouteError) {\n return 404;\n }\n if (error instanceof BeamableRuntimeError) {\n return 500;\n }\n return 500;\n }\n\n private printHelpfulUrls(service?: ServiceInstance): void {\n if (!service) {\n return;\n }\n\n // Only print helpful URLs when IS_LOCAL=1 is set\n // In deployed containers, we want only JSON logs for proper log collection\n if (process.env.IS_LOCAL !== '1' && process.env.IS_LOCAL !== 'true') {\n return;\n }\n\n const docsUrl = buildDocsPortalUrl(this.env, service.definition);\n const endpointBase = buildPostmanBaseUrl(this.env, service.definition);\n\n const green = (text: string) => `\\x1b[32m${text}\\x1b[0m`;\n const yellow = (text: string) => `\\x1b[33m${text}\\x1b[0m`;\n\n const bannerLines = [\n '',\n yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),\n ` ${green('Beamable Node microservice ready:')} ${green(service.definition.name)}`,\n yellow(' Quick shortcuts'),\n ` ${yellow('Docs:')} ${docsUrl}`,\n ` ${yellow('Endpoint:')} ${endpointBase}`,\n yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),\n '',\n ];\n\n process.stdout.write(`${bannerLines.join('\\n')}`);\n }\n\n private async initializeDependencyProviders(): Promise<void> {\n // Get StorageService from service manager (it's initialized during serviceManager.initialize())\n const storageService = this.serviceManager.getStorageService();\n \n for (const service of this.services) {\n const builder = new DependencyBuilder();\n builder.tryAddSingletonInstance(LOGGER_TOKEN, service.logger);\n builder.tryAddSingletonInstance(ENVIRONMENT_CONFIG_TOKEN, this.env);\n builder.tryAddSingletonInstance(BeamableServiceManager, this.serviceManager);\n builder.tryAddSingletonInstance(StorageService, storageService);\n builder.tryAddSingletonInstance(service.definition.ctor, service.instance);\n builder.tryAddSingletonInstance(FederationRegistry, service.federationRegistry);\n\n for (const handler of service.configureHandlers) {\n await handler(builder);\n }\n\n const provider = builder.build();\n service.provider = provider;\n\n for (const handler of service.initializeHandlers) {\n await handler(provider);\n }\n\n Object.defineProperty(service.instance, 'provider', {\n value: provider,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n }\n }\n\n private createRequestScope(path: string, service?: ServiceInstance): MutableDependencyScope {\n // Path should already have query string stripped before calling this method\n const targetService = service ?? this.findServiceForPath(path);\n const provider = targetService?.provider ?? new DependencyBuilder().build();\n return provider.createScope();\n }\n\n /**\n * Extracts the path portion without the query string.\n * @param path The full path potentially containing a query string\n * @returns The path without the query string\n */\n private getPathWithoutQuery(path: string): string {\n const [pathWithoutQuery] = path.split('?', 2);\n return pathWithoutQuery;\n }\n}\n\nfunction enforceAccess(access: ServiceAccess, ctx: RequestContext): void {\n switch (access) {\n case 'client':\n if (ctx.userId <= 0) {\n throw new UnauthorizedUserError(ctx.path);\n }\n break;\n case 'server':\n if (!scopeSetHas(ctx.scopes, 'server')) {\n throw new MissingScopesError(['server']);\n }\n break;\n case 'admin':\n if (!scopeSetHas(ctx.scopes, 'admin')) {\n throw new MissingScopesError(['admin']);\n }\n break;\n default:\n break;\n }\n}\n\n/**\n * Conditionally output to console.error only when running locally (not in container).\n * In containers, we want only Pino JSON logs to stdout for proper log collection.\n */\nfunction debugLog(...args: unknown[]): void {\n // Only output debug logs when IS_LOCAL=1 is set\n if (process.env.IS_LOCAL === '1' || process.env.IS_LOCAL === 'true') {\n console.error(...args);\n }\n}\n\n/**\n * Determines if we're running in a deployed container.\n * Used for service registration logic (routing key handling, discovery broadcaster, etc.)\n * \n * Note: For log formatting, use IS_LOCAL env var instead.\n */\nfunction isRunningInContainer(): boolean {\n // Check for Docker container\n try {\n const fs = require('fs');\n if (fs.existsSync('/.dockerenv')) {\n return true;\n }\n } catch {\n // fs might not be available\n }\n \n // Check for Docker container hostname pattern (12 hex chars)\n const hostname = process.env.HOSTNAME || '';\n if (hostname && /^[a-f0-9]{12}$/i.test(hostname)) {\n return true;\n }\n \n // Explicit container indicators\n if (\n process.env.DOTNET_RUNNING_IN_CONTAINER === 'true' ||\n process.env.CONTAINER === 'beamable' ||\n !!process.env.ECS_CONTAINER_METADATA_URI ||\n !!process.env.KUBERNETES_SERVICE_HOST\n ) {\n return true;\n }\n \n // Default: assume local development\n return false;\n}\n\nfunction normalizeScopes(scopes: Array<unknown>): Set<string> {\n const normalized = new Set<string>();\n for (const scope of scopes) {\n if (typeof scope !== 'string' || scope.trim().length === 0) {\n continue;\n }\n normalized.add(scope.trim().toLowerCase());\n }\n return normalized;\n}\n\nfunction scopeSetHas(scopes: Set<string>, scope: string): boolean {\n const normalized = scope.trim().toLowerCase();\n if (normalized.length === 0) {\n return false;\n }\n return scopes.has('*') || scopes.has(normalized);\n}\n\nfunction buildPostmanBaseUrl(env: EnvironmentConfig, service: ServiceDefinition): string {\n const httpHost = hostToHttpUrl(env.host);\n const routingKeyPart = env.routingKey ? env.routingKey : '';\n return `${httpHost}/basic/${env.cid}.${env.pid}.${routingKeyPart}${service.qualifiedName}/`;\n}\n\nfunction buildDocsPortalUrl(env: EnvironmentConfig, service: ServiceDefinition): string {\n const portalHost = hostToPortalUrl(hostToHttpUrl(env.host));\n const queryParams: Record<string, string> = { srcTool: 'node-runtime' };\n if (env.routingKey) {\n queryParams.routingKey = env.routingKey;\n }\n const query = new URLSearchParams(queryParams);\n if (env.refreshToken) {\n query.set('refresh_token', env.refreshToken);\n }\n const beamoId = service.name;\n return `${portalHost}/${env.cid}/games/${env.pid}/realms/${env.pid}/microservices/micro_${beamoId}/docs?${query.toString()}`;\n}\n\nexport async function runMicroservice(): Promise<void> {\n // Immediate console output to verify process is starting (local dev only)\n // In containers, we rely on Pino logger for all output\n debugLog('[BEAMABLE-NODE] Starting microservice...');\n debugLog(`[BEAMABLE-NODE] Node version: ${process.version}`);\n debugLog(`[BEAMABLE-NODE] Working directory: ${process.cwd()}`);\n debugLog(`[BEAMABLE-NODE] Environment: ${JSON.stringify({\n NODE_ENV: process.env.NODE_ENV,\n CID: process.env.CID ? 'SET' : 'NOT SET',\n PID: process.env.PID ? 'SET' : 'NOT SET',\n HOST: process.env.HOST ? 'SET' : 'NOT SET',\n SECRET: process.env.SECRET ? 'SET' : 'NOT SET',\n })}`);\n if (process.env.BEAMABLE_SKIP_RUNTIME === 'true') {\n return;\n }\n const runtime = new MicroserviceRuntime();\n \n // Handle uncaught errors - log them but don't crash immediately\n // This allows the health check server to keep running so we can debug\n // In containers, errors will be logged by the logger in the runtime\n // Locally, use console.error for visibility\n process.on('uncaughtException', (error) => {\n // In containers, the logger will handle this; locally, show in console\n debugLog('Uncaught Exception:', error);\n // Don't exit - let the health check server keep running\n });\n \n process.on('unhandledRejection', (reason, promise) => {\n // In containers, the logger will handle this; locally, show in console\n debugLog('Unhandled Rejection at:', promise, 'reason:', reason);\n // Don't exit - let the health check server keep running\n });\n \n try {\n await runtime.start();\n } catch (error) {\n // Log the error but don't exit - health check server is running\n // This allows the container to stay alive so we can see what went wrong\n // In containers, the logger already logged it in start(); locally, also use console.error\n debugLog('Failed to start microservice runtime:', error);\n // Keep the process alive so health check can continue\n // The health check will return 503 until isReady is true\n }\n \n const shutdownSignals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\n shutdownSignals.forEach((signal) => {\n process.once(signal, async () => {\n await runtime.shutdown();\n process.exit(0);\n });\n });\n}\n\ninterface GenerateOpenApiOptions {\n serviceName?: string;\n}\n\nexport function generateOpenApiDocumentForRegisteredServices(\n overrides: Partial<EnvironmentConfig> = {},\n options: GenerateOpenApiOptions = {},\n): unknown {\n const services = listRegisteredServices();\n if (services.length === 0) {\n throw new Error('No microservices registered. Import your service module before generating documentation.');\n }\n\n const baseEnv = buildEnvironmentConfig(overrides);\n const primary = options.serviceName\n ? services.find((svc) => svc.name === options.serviceName || svc.qualifiedName === options.serviceName)\n : services[0];\n\n if (!primary) {\n throw new Error(`No registered microservice matched '${options.serviceName}'.`);\n }\n\n return generateOpenApiDocument(\n {\n qualifiedName: primary.qualifiedName,\n name: primary.name,\n callables: Array.from(primary.callables.entries()).map(([displayName, metadata]) => ({\n name: displayName,\n route: metadata.route,\n metadata,\n handler: undefined,\n })),\n },\n baseEnv,\n VERSION,\n );\n}\n\nfunction buildEnvironmentConfig(overrides: Partial<EnvironmentConfig>): EnvironmentConfig {\n const merged: Partial<EnvironmentConfig> = { ...overrides };\n\n const ensure = (key: keyof EnvironmentConfig, fallbackEnv?: string) => {\n if (merged[key] !== undefined) {\n return;\n }\n if (fallbackEnv && process.env[fallbackEnv]) {\n merged[key] = process.env[fallbackEnv] as never;\n }\n };\n\n ensure('cid', 'CID');\n ensure('pid', 'PID');\n ensure('host', 'HOST');\n ensure('secret', 'SECRET');\n ensure('refreshToken', 'REFRESH_TOKEN');\n // Routing key is optional for deployed services (in containers)\n // It will be resolved to empty string if not provided and running in container\n if (!merged.routingKey && !isRunningInContainer()) {\n ensure('routingKey', 'NAME_PREFIX');\n }\n\n if (!merged.cid || !merged.pid || !merged.host) {\n throw new Error('CID, PID, and HOST are required to generate documentation.');\n }\n\n const base = loadEnvironmentConfig();\n\n return {\n ...base,\n ...merged,\n routingKey: merged.routingKey ?? base.routingKey,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../src/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,qBAAqB,EAAE,MAAM,UAAU,CAAC;AACjD,OAAO,EAAE,iCAAiC,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC9F,OAAO,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,6DAA6D;AAC7D,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,4BAA4B,EAAE,6BAA6B,EAAE,MAAM,iBAAiB,CAAC;AACzI,OAAO,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAWjH,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,EACL,iBAAiB,EACjB,YAAY,E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AAM,MAAM,GAA+B,EAAE,GAAG,SAAS,EAAE,CAAC;IAE5D,MAAM,MAAM,GAAG,CAAC,GAA4B,EAAE,WAAoB,EAAE,EAAE;QACpE,IAAI,MAAM,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE,CAAC;YAC9B,OAAO;QACT,CAAC;QACD,IAAI,WAAW,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAC5C,MAAM,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,WAAW,CAAU,CAAC;QAClD,CAAC;IACH,CAAC,CAAC;IAEF,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACrB,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACrB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvB,MAAM,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC3B,MAAM,CAAC,cAAc,EAAE,eAAe,CAAC,CAAC;IACxC,gEAAgE;IAChE,+EAA+E;IAC/E,IAAI,CAAC,MAAM,CAAC,UAAU,IAAI,CAAC,oBAAoB,EAAE,EAAE,CAAC;QAClD,MAAM,CAAC,YAAY,EAAE,aAAa,CAAC,CAAC;IACtC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC;IAChF,CAAC;IAED,MAAM,IAAI,GAAG,qBAAqB,EAAE,CAAC;IAErC,OAAO;QACL,GAAG,IAAI;QACP,GAAG,MAAM;QACT,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,IAAI,CAAC,UAAU;KACjD,CAAC;AACJ,CAAC","sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { BeamableWebSocket } from './websocket.js';\nimport { GatewayRequester } from './requester.js';\nimport { AuthManager } from './auth.js';\nimport { createLogger } from './logger.js';\nimport { loadEnvironmentConfig } from './env.js';\nimport { loadAndInjectEnvironmentVariables, loadDeveloperEnvVarsSync } from './env-loader.js';\nimport { startCollectorAndWaitForReady } from './collector-manager.js';\nimport pino from 'pino';\n// Removed deasync - using non-blocking async pattern instead\nimport { listRegisteredServices, getServiceOptions, getConfigureServicesHandlers, getInitializeServicesHandlers } from './decorators.js';\nimport { generateOpenApiDocument } from './docs.js';\nimport { VERSION } from './index.js';\nimport { DiscoveryBroadcaster } from './discovery.js';\nimport { BeamableRuntimeError, MissingScopesError, UnauthorizedUserError, UnknownRouteError } from './errors.js';\nimport type {\n EnvironmentConfig,\n RequestContext,\n ServiceDefinition,\n ServiceCallableMetadata,\n GatewayResponse,\n WebsocketEventEnvelope,\n ServiceAccess,\n} from './types.js';\nimport type { Logger } from 'pino';\nimport { BeamableServiceManager } from './services.js';\nimport { StorageService } from './storage.js';\nimport {\n DependencyBuilder,\n LOGGER_TOKEN,\n ENVIRONMENT_CONFIG_TOKEN,\n REQUEST_CONTEXT_TOKEN,\n BEAMABLE_SERVICES_TOKEN,\n ServiceProvider,\n MutableDependencyScope,\n} from './dependency.js';\nimport { hostToHttpUrl, hostToPortalUrl } from './utils/urls.js';\nimport { FederationRegistry, getFederationComponents, getFederatedInventoryMetadata } from './federation.js';\nimport type { FederatedRequestContext } from './federation.js';\nimport { createServer, type Server } from 'node:http';\n\ninterface ServiceInstance {\n definition: ServiceDefinition;\n instance: Record<string, unknown>;\n configureHandlers: ReturnType<typeof getConfigureServicesHandlers>;\n initializeHandlers: ReturnType<typeof getInitializeServicesHandlers>;\n provider?: ServiceProvider;\n logger: Logger;\n federationRegistry: FederationRegistry;\n}\n\nexport class MicroserviceRuntime {\n private readonly env: EnvironmentConfig;\n private logger: Logger; // Mutable to allow upgrading from console logger to structured logger when collector is ready\n private readonly services: ServiceInstance[];\n private readonly webSocket: BeamableWebSocket;\n private readonly requester: GatewayRequester;\n private readonly authManager: AuthManager;\n private readonly discovery?: DiscoveryBroadcaster;\n private readonly microServiceId = randomUUID();\n private readonly serviceManager: BeamableServiceManager;\n private healthCheckServer?: Server;\n private isReady: boolean = false;\n\n constructor(env?: EnvironmentConfig) {\n this.env = env ?? loadEnvironmentConfig();\n const envConfig = this.env; // Capture for async IIFE to satisfy TypeScript\n \n // STEP 1: Load developer-defined environment variables SYNCHRONOUSLY before logger creation\n // This ensures BetterStack and other env vars are available when the logger initializes\n loadDeveloperEnvVarsSync();\n \n // STEP 2: Create minimal console logger for startup messages (before collector setup)\n // This ensures we have logging available immediately, even before collector is ready\n const startupLogger = pino({\n name: 'beamable-runtime-startup',\n level: 'info',\n }, process.stdout);\n // Display runtime version at startup (VERSION is imported synchronously at top of file)\n startupLogger.info(`Starting Beamable Node microservice runtime (version: ${VERSION}).`);\n \n // STEP 2.5: Load Beamable Config asynchronously (in background, non-blocking)\n // Developer-defined vars are already loaded synchronously above\n // Beamable Config is fetched via API with a 2-second timeout\n (async () => {\n try {\n startupLogger.info('Loading Beamable Config environment variables...');\n await loadAndInjectEnvironmentVariables(envConfig, undefined, true, 2000);\n startupLogger.info('Beamable Config loading completed');\n } catch (error) {\n startupLogger.warn(`Beamable Config loading completed with warnings: ${error instanceof Error ? error.message : String(error)}`);\n }\n })();\n \n // STEP 2: Get registered services to extract service name\n const registered = listRegisteredServices();\n if (registered.length === 0) {\n throw new Error('No microservices registered. Use the @Microservice decorator to register at least one class.');\n }\n \n // Use the first service's name for the main logger (for CloudWatch filtering and ClickHouse compatibility)\n const primaryService = registered[0];\n const qualifiedServiceName = `micro_${primaryService.qualifiedName}`;\n \n // STEP 3: Create logger immediately (non-blocking pattern, matching C#)\n // Start with minimal console logger, upgrade to structured logger when collector is ready\n // This allows the service to start immediately without blocking\n startupLogger.info('Setting up OpenTelemetry collector in background (non-blocking)...');\n \n // Create logger immediately with console output (no OTLP yet)\n // This ensures we have logging available right away\n this.logger = createLogger(this.env, {\n name: 'beamable-node-microservice',\n serviceName: primaryService.name,\n qualifiedServiceName: qualifiedServiceName,\n // No otlpEndpoint - will use console logger initially\n });\n \n // STEP 4: Start collector setup in background (non-blocking)\n // When collector is ready, upgrade logger to structured logger with OTLP\n // This matches C# pattern: collector starts in background, service starts immediately\n startCollectorAndWaitForReady(this.env)\n .then((endpoint) => {\n if (endpoint) {\n // Collector is ready - upgrade to structured logger with OTLP support\n this.logger.info(`Collector ready at ${endpoint}, upgrading to structured logger for Portal logs...`);\n this.logger = createLogger(this.env, {\n name: 'beamable-node-microservice',\n serviceName: primaryService.name,\n qualifiedServiceName: qualifiedServiceName,\n otlpEndpoint: endpoint, // Collector is ready, Portal logs will now work\n });\n this.logger.info('Portal logs enabled - structured logs will now appear in Beamable Portal');\n } else {\n this.logger.warn('Collector setup completed but no endpoint was returned. Continuing with console logs. Portal logs will not be available.');\n }\n })\n .catch((error) => {\n const errorMsg = error instanceof Error ? error.message : String(error);\n this.logger.error(`Failed to setup collector: ${errorMsg}. Continuing with console logs. Portal logs will not be available.`);\n // Service continues to work with console logger - graceful degradation\n });\n \n // Continue immediately - don't wait for collector!\n // Service can start accepting requests right away\n // Collector setup happens in background, logger upgrades automatically when ready\n this.serviceManager = new BeamableServiceManager(this.env, this.logger);\n\n this.services = registered.map((definition) => {\n const instance = new definition.ctor() as Record<string, unknown>;\n const configureHandlers = getConfigureServicesHandlers(definition.ctor);\n const initializeHandlers = getInitializeServicesHandlers(definition.ctor);\n const logger = this.logger.child({ service: definition.name });\n const federationRegistry = new FederationRegistry(logger);\n const decoratedFederations = getFederationComponents(definition.ctor);\n for (const component of decoratedFederations) {\n federationRegistry.register(component);\n }\n const inventoryMetadata = getFederatedInventoryMetadata(definition.ctor);\n if (inventoryMetadata.length > 0) {\n federationRegistry.registerInventoryHandlers(instance, inventoryMetadata);\n }\n this.serviceManager.registerFederationRegistry(definition.name, federationRegistry);\n return { definition, instance, configureHandlers, initializeHandlers, logger, federationRegistry };\n });\n\n const socketUrl = this.env.host.endsWith('/socket') ? this.env.host : `${this.env.host}/socket`;\n this.webSocket = new BeamableWebSocket({ url: socketUrl, logger: this.logger });\n this.webSocket.on('message', (payload) => {\n this.logger.debug({ payload }, 'Runtime observed websocket frame.');\n });\n this.requester = new GatewayRequester(this.webSocket, this.logger);\n this.authManager = new AuthManager(this.env, this.requester);\n this.requester.on('event', (envelope) => this.handleEvent(envelope));\n\n // Discovery broadcaster only runs in local development (not in containers)\n // This allows the portal to detect that the service is running locally\n if (!isRunningInContainer() && this.services.length > 0) {\n this.discovery = new DiscoveryBroadcaster({\n env: this.env,\n serviceName: this.services[0].definition.name,\n routingKey: this.env.routingKey,\n logger: this.logger.child({ component: 'DiscoveryBroadcaster' }),\n });\n }\n }\n\n async start(): Promise<void> {\n // Immediate console output for container logs (before logger is ready)\n debugLog('[BEAMABLE-NODE] MicroserviceRuntime.start() called');\n debugLog(`[BEAMABLE-NODE] Service count: ${this.services.length}`);\n \n this.printHelpfulUrls(this.services[0]);\n this.logger.info('Starting Beamable Node microservice runtime.');\n \n // Start health check server FIRST - this is critical for container health checks\n // Even if startup fails, the health check server must be running so we can debug\n debugLog('[BEAMABLE-NODE] Starting health check server...');\n await this.startHealthCheckServer();\n debugLog('[BEAMABLE-NODE] Health check server started');\n \n try {\n this.logger.info('Connecting to Beamable gateway...');\n await this.webSocket.connect();\n await new Promise((resolve) => setTimeout(resolve, 250));\n \n this.logger.info('Authenticating with Beamable...');\n await this.authManager.authenticate();\n \n this.logger.info('Initializing Beamable SDK services...');\n // Pass service name to initialize so routing key can be configured for service-level requests\n const primaryServiceName = this.services[0]?.definition.name;\n await this.serviceManager.initialize(primaryServiceName);\n \n this.logger.info('Initializing dependency providers...');\n await this.initializeDependencyProviders();\n \n this.logger.info('Registering service with gateway...');\n await this.registerService();\n \n this.logger.info('Starting discovery broadcaster...');\n await this.discovery?.start();\n \n // Mark as ready only after service is fully registered and discovery is started\n this.isReady = true;\n this.logger.info('Beamable microservice runtime is ready to accept traffic.');\n } catch (error) {\n // Log the error with full context but don't crash - health check server is running\n // This allows the container to stay alive so we can debug the issue\n // Debug output for local development only (in containers, logger handles this)\n debugLog('[BEAMABLE-NODE] FATAL ERROR during startup:');\n debugLog(`[BEAMABLE-NODE] Error message: ${error instanceof Error ? error.message : String(error)}`);\n debugLog(`[BEAMABLE-NODE] Error stack: ${error instanceof Error ? error.stack : 'No stack trace'}`);\n debugLog(`[BEAMABLE-NODE] isReady: ${this.isReady}`);\n \n this.logger.error(\n { \n err: error,\n errorMessage: error instanceof Error ? error.message : String(error),\n errorStack: error instanceof Error ? error.stack : undefined,\n isReady: this.isReady,\n },\n 'Failed to fully initialize microservice runtime. Health check will continue to return 503 until initialization completes.'\n );\n // DON'T re-throw - keep process alive so health check can show 503\n // This allows us to see the error in logs\n this.isReady = false;\n }\n }\n\n async shutdown(): Promise<void> {\n this.logger.info('Shutting down microservice runtime.');\n this.isReady = false; // Mark as not ready during shutdown\n this.discovery?.stop();\n await this.stopHealthCheckServer();\n this.requester.dispose();\n await this.webSocket.close();\n }\n\n private async startHealthCheckServer(): Promise<void> {\n // For deployed services, always start health check server (required for container health checks)\n // For local development, only start if healthPort is explicitly set\n // IMPORTANT: Always default to 6565 if HEALTH_PORT env var is not set, as this is the standard port\n const healthPort = this.env.healthPort || 6565;\n \n // Always start health check server if we have a valid port\n // The container orchestrator expects this endpoint to be available\n if (!healthPort || healthPort === 0) {\n // Health check server not needed (local development without explicit port)\n this.logger.debug('Health check server skipped (no healthPort set)');\n return;\n }\n\n this.healthCheckServer = createServer((req, res) => {\n if (req.url === '/health' && req.method === 'GET') {\n // Only return success if service is fully ready (registered and accepting traffic)\n if (this.isReady) {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('responsive');\n } else {\n // Service is still starting up\n res.writeHead(503, { 'Content-Type': 'text/plain' });\n res.end('Service Unavailable');\n }\n } else {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n }\n });\n\n return new Promise((resolve, reject) => {\n this.healthCheckServer!.listen(healthPort, '0.0.0.0', () => {\n this.logger.info({ port: healthPort }, 'Health check server started on port');\n resolve();\n });\n this.healthCheckServer!.on('error', (err) => {\n this.logger.error({ err, port: healthPort }, 'Failed to start health check server');\n reject(err);\n });\n });\n }\n\n private async stopHealthCheckServer(): Promise<void> {\n if (!this.healthCheckServer) {\n return;\n }\n\n return new Promise((resolve) => {\n this.healthCheckServer!.close(() => {\n this.logger.info('Health check server stopped');\n resolve();\n });\n });\n }\n\n private async registerService(): Promise<void> {\n const primary = this.services[0]?.definition;\n if (!primary) {\n throw new Error('Unexpected missing service definition during registration.');\n }\n const options = getServiceOptions(primary.ctor) ?? {};\n // Match C# exactly: use qualifiedName (preserves case) for name field.\n // The gateway lowercases service names when creating bindings, but uses the original case\n // from the registration request when constructing routing key lookups.\n // This ensures the routing key format matches what the gateway expects.\n // The gateway's binding lookup behavior:\n // - Gateway error shows: \"No binding found for service ...micro_examplenodeservice.basic\"\n // - This means the gateway lowercases the service name for binding storage/lookup\n // - Portal sends requests with mixed case in URL and routing key header\n // - The gateway lowercases the URL path for binding lookup, which should work\n // - But we need to register with the format the gateway expects for the binding key\n // - The gateway constructs binding key as: {cid}.{pid}.{lowercaseServiceName}.{type}\n // - So we register with lowercase to match what the gateway stores in the binding\n // - The portal will still send mixed case, and the gateway will lowercase it for lookup\n // Register with mixed-case qualifiedName to match C# behavior\n // The gateway will lowercase the service name when creating the binding key,\n // but the registration request should use the original case (as C# does)\n // This ensures the service name in the registration matches what the portal expects\n // Register with mixed-case qualifiedName to match C# behavior\n // The gateway's ServiceIdentity.fullNameNoType lowercases the service name when creating bindings,\n // but the registration request should use the original case (as C# does)\n // This ensures the service name in the registration matches what the portal expects\n const isDeployed = isRunningInContainer();\n \n // For deployed services, routingKey should be null/undefined (None in Scala)\n // For local dev, routingKey should be the actual routing key string\n // The backend expects Option[String] = None for deployed services\n // Note: microServiceId is not part of SocketSessionProviderRegisterRequest, so we don't include it\n // All fields except 'type' are Option[T] in Scala, so undefined fields will be omitted from JSON\n // This matches C# behavior where null/None fields are not serialized\n const request: Record<string, unknown> = {\n type: 'basic',\n name: primary.qualifiedName, // Use mixed-case as C# does - gateway handles lowercasing for binding storage\n beamoName: primary.name,\n };\n \n // Only include routingKey and startedById if they have values (for local dev)\n // For deployed services, these should be omitted (undefined) to match None in Scala\n if (!isDeployed && this.env.routingKey) {\n request.routingKey = this.env.routingKey;\n }\n if (!isDeployed && this.env.accountId) {\n request.startedById = this.env.accountId;\n }\n\n // Log registration request to match C# behavior exactly\n // Also log the actual JSON that will be sent (undefined fields will be omitted)\n const serializedRequest = JSON.stringify(request);\n this.logger.debug(\n {\n request: {\n type: request.type,\n name: request.name,\n beamoName: request.beamoName,\n routingKey: request.routingKey,\n startedById: request.startedById,\n },\n serializedJson: serializedRequest,\n isDeployed,\n },\n 'Registering service provider with gateway.',\n );\n\n try {\n await this.requester.request('post', 'gateway/provider', request);\n this.logger.info({ serviceName: primary.qualifiedName }, 'Service provider registered successfully.');\n \n // After registration, the gateway's BasicServiceProvider.start() is called asynchronously\n // This triggers afterRabbitInit() -> setupDirectServiceCommunication() -> scheduleServiceBindingCheck()\n // The first updateBindings() call happens immediately (0.millisecond delay)\n // We wait a bit to allow the gateway to set up the HTTP binding and call updateBindings()\n // This is especially important for deployed services where the gateway needs to establish\n // the external host binding before bindings can be created\n if (isDeployed) {\n this.logger.debug('Waiting for gateway to establish bindings after registration...');\n await new Promise((resolve) => setTimeout(resolve, 2000)); // 2 second wait for deployed services\n this.logger.debug('Wait complete, gateway should have established bindings by now.');\n }\n } catch (error) {\n this.logger.error(\n {\n err: error,\n request,\n serviceName: primary.qualifiedName,\n errorMessage: error instanceof Error ? error.message : String(error),\n },\n 'Failed to register service provider with gateway. This will prevent the service from receiving requests.'\n );\n throw error; // Re-throw so startup fails and we can see the error\n }\n\n if (options.disableAllBeamableEvents) {\n this.logger.info('Beamable events disabled by configuration.');\n } else {\n const eventRequest = {\n type: 'event',\n evtWhitelist: ['content.manifest', 'realm.config', 'logging.context'],\n };\n try {\n await this.requester.request('post', 'gateway/provider', eventRequest);\n } catch (error) {\n this.logger.warn({ err: error }, 'Failed to register event provider. Continuing without events.');\n }\n }\n }\n\n private async handleEvent(envelope: WebsocketEventEnvelope): Promise<void> {\n try {\n if (!envelope.path) {\n this.logger.debug({ envelope }, 'Ignoring websocket event without path.');\n return;\n }\n\n if (envelope.path.startsWith('event/')) {\n await this.requester.acknowledge(envelope.id);\n return;\n }\n\n const context = this.toRequestContext(envelope);\n await this.dispatch(context);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.logger.error({ err, envelope }, 'Failed to handle websocket event.');\n const status = this.resolveErrorStatus(err);\n const response: GatewayResponse = {\n id: envelope.id,\n status,\n body: {\n error: err.name,\n message: err.message,\n },\n };\n await this.requester.sendResponse(response);\n }\n }\n\n private toRequestContext(envelope: WebsocketEventEnvelope): RequestContext {\n const path = envelope.path ?? '';\n const method = envelope.method ?? 'post';\n const userId = typeof envelope.from === 'number' ? envelope.from : 0;\n const headers = envelope.headers ?? {};\n \n // Parse query parameters from path (e.g., /service/route?param1=value1¶m2=value2)\n const [pathWithoutQuery, queryString] = path.split('?', 2);\n const query = this.parseQueryString(queryString ?? '');\n \n // Extract scopes from envelope.scopes array\n // Note: X-DE-SCOPE header contains CID.PID, not scope values\n // The gateway sends scopes in envelope.scopes array\n // For admin endpoints, the gateway may not send scopes in the envelope,\n // so we infer admin scope from the path if it's an admin route\n const envelopeScopes = envelope.scopes ?? [];\n let scopes = normalizeScopes(envelopeScopes);\n \n // If this is an admin endpoint and no scopes are provided, infer admin scope\n // The gateway may not always send scopes for admin routes\n const pathLower = pathWithoutQuery.toLowerCase();\n if (pathLower.includes('/admin/') && scopes.size === 0) {\n scopes = normalizeScopes(['admin']);\n }\n\n let body: Record<string, unknown> | undefined;\n if (envelope.body && typeof envelope.body === 'string') {\n try {\n body = JSON.parse(envelope.body) as Record<string, unknown>;\n } catch (error) {\n this.logger.warn({ err: error, raw: envelope.body }, 'Failed to parse body string.');\n }\n } else if (envelope.body && typeof envelope.body === 'object') {\n body = envelope.body as Record<string, unknown>;\n }\n\n let payload: unknown;\n if (body && typeof body === 'object' && 'payload' in body) {\n const rawPayload = (body as Record<string, unknown>).payload;\n if (typeof rawPayload === 'string') {\n try {\n payload = JSON.parse(rawPayload) as unknown[];\n } catch (error) {\n this.logger.warn({ err: error }, 'Failed to parse payload JSON.');\n payload = rawPayload;\n }\n } else {\n payload = rawPayload;\n }\n }\n\n const targetService = this.findServiceForPath(pathWithoutQuery);\n const services = this.serviceManager.createFacade(userId, scopes, targetService?.definition.name);\n const provider = this.createRequestScope(pathWithoutQuery, targetService);\n\n const context: RequestContext = {\n id: envelope.id,\n path,\n method,\n status: envelope.status ?? 0,\n userId,\n payload,\n body,\n query,\n scopes,\n headers,\n cid: this.env.cid,\n pid: this.env.pid,\n services,\n throwIfCancelled: () => {},\n isCancelled: () => false,\n hasScopes: (...requiredScopes: string[]) => requiredScopes.every((scope) => scopeSetHas(scopes, scope)),\n requireScopes: (...requiredScopes: string[]) => {\n const missingScopes = requiredScopes.filter((scope) => !scopeSetHas(scopes, scope));\n if (missingScopes.length > 0) {\n throw new MissingScopesError(missingScopes);\n }\n },\n provider,\n };\n\n provider.setInstance(REQUEST_CONTEXT_TOKEN, context);\n provider.setInstance(BEAMABLE_SERVICES_TOKEN, services);\n\n return context;\n }\n\n private findServiceForPath(path: string): ServiceInstance | undefined {\n // Gateway sends paths with lowercase service names, so we need case-insensitive matching\n // Match by comparing lowercase versions to handle gateway's lowercase path format\n // Note: path should already have query string stripped before calling this method\n const pathLower = path.toLowerCase();\n return this.services.find((service) => {\n const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();\n return pathLower.startsWith(`${qualifiedNameLower}/`);\n });\n }\n\n /**\n * Parses a query string into a record of parameter names to values.\n * Handles multiple values for the same parameter name by storing them as an array.\n * @param queryString The query string (without the leading '?')\n * @returns A record mapping parameter names to their values (single string or array of strings)\n */\n private parseQueryString(queryString: string): Record<string, string | string[]> {\n if (!queryString || queryString.trim().length === 0) {\n return {};\n }\n\n const params: Record<string, string | string[]> = {};\n const pairs = queryString.split('&');\n\n for (const pair of pairs) {\n const [key, value = ''] = pair.split('=', 2);\n if (key) {\n const decodedKey = decodeURIComponent(key);\n const decodedValue = decodeURIComponent(value);\n\n // If the key already exists, convert to array or append to existing array\n if (decodedKey in params) {\n const existing = params[decodedKey];\n if (Array.isArray(existing)) {\n existing.push(decodedValue);\n } else {\n params[decodedKey] = [existing, decodedValue];\n }\n } else {\n params[decodedKey] = decodedValue;\n }\n }\n }\n\n return params;\n }\n\n private async dispatch(ctx: RequestContext): Promise<void> {\n // Extract path without query string for routing\n const pathWithoutQuery = this.getPathWithoutQuery(ctx.path);\n const service = this.findServiceForPath(pathWithoutQuery);\n if (!service) {\n throw new UnknownRouteError(ctx.path);\n }\n\n if (await this.tryHandleFederationRoute(ctx, service)) {\n return;\n }\n\n if (await this.tryHandleAdminRoute(ctx, service)) {\n return;\n }\n\n // Extract route from path - handle case-insensitive path matching\n const pathLower = pathWithoutQuery.toLowerCase();\n const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();\n const route = pathLower.substring(qualifiedNameLower.length + 1);\n const metadata = service.definition.callables.get(route);\n if (!metadata) {\n throw new UnknownRouteError(ctx.path);\n }\n\n // For server and admin access, allow userId: 0 if the appropriate scope is present\n // For client access, always require userId > 0\n if (metadata.requireAuth && ctx.userId <= 0) {\n if (metadata.access === 'server' && scopeSetHas(ctx.scopes, 'server')) {\n // Server callables with server scope don't need a user ID\n } else if (metadata.access === 'admin' && scopeSetHas(ctx.scopes, 'admin')) {\n // Admin callables with admin scope don't need a user ID\n } else {\n throw new UnauthorizedUserError(route);\n }\n }\n\n enforceAccess(metadata.access, ctx);\n\n if (metadata.requiredScopes.length > 0) {\n const missing = metadata.requiredScopes.filter((scope) => !scopeSetHas(ctx.scopes, scope));\n if (missing.length > 0) {\n throw new MissingScopesError(missing);\n }\n }\n\n const handler = service.instance[metadata.displayName];\n if (typeof handler !== 'function') {\n throw new Error(`Callable ${metadata.displayName} is not a function on service ${service.definition.name}.`);\n }\n\n const args = this.buildInvocationArguments(handler as (...args: unknown[]) => unknown, ctx);\n const result = await Promise.resolve((handler as (...args: unknown[]) => unknown).apply(service.instance, args));\n await this.sendSuccessResponse(ctx, metadata, result);\n }\n\n private buildInvocationArguments(\n handler: (...args: unknown[]) => unknown,\n ctx: RequestContext,\n ): unknown[] {\n const payload = Array.isArray(ctx.payload)\n ? ctx.payload\n : typeof ctx.payload === 'string'\n ? [ctx.payload]\n : ctx.payload === undefined\n ? []\n : [ctx.payload];\n\n const expectedParams = handler.length;\n\n // Determine if RequestContext should be passed as the first argument\n // Strategy: If handler expects more parameters than payload provides,\n // assume the first parameter is RequestContext\n // This covers common cases:\n // - handler(ctx: RequestContext) with empty payload -> expectedParams=1, payload.length=0 -> include ctx\n // - handler(ctx: RequestContext, param: string) with payload=['value'] -> expectedParams=2, payload.length=1 -> include ctx\n // - handler(param: string) with payload=['value'] -> expectedParams=1, payload.length=1 -> don't include ctx\n if (expectedParams > payload.length) {\n return [ctx, ...payload];\n }\n\n // If handler expects exactly the same number of parameters as payload,\n // don't include ctx (handler doesn't expect it)\n return payload;\n }\n\n private async sendSuccessResponse(ctx: RequestContext, metadata: ServiceCallableMetadata, result: unknown): Promise<void> {\n let body: unknown;\n if (metadata.useLegacySerialization) {\n const serialized = typeof result === 'string' ? result : JSON.stringify(result ?? null);\n body = { payload: serialized };\n } else {\n body = result ?? null;\n }\n\n const response: GatewayResponse = {\n id: ctx.id,\n status: 200,\n body,\n };\n await this.requester.sendResponse(response);\n }\n\n private async sendFederationResponse(ctx: RequestContext, result: unknown): Promise<void> {\n const response: GatewayResponse = {\n id: ctx.id,\n status: 200,\n body: result ?? null,\n };\n await this.requester.sendResponse(response);\n }\n\n private async tryHandleFederationRoute(ctx: RequestContext, service: ServiceInstance): Promise<boolean> {\n // Gateway sends paths with lowercase service names, so we need case-insensitive matching\n // Extract path without query string for routing\n const pathWithoutQuery = this.getPathWithoutQuery(ctx.path);\n const pathLower = pathWithoutQuery.toLowerCase();\n const qualifiedNameLower = service.definition.qualifiedName.toLowerCase();\n const prefixLower = `${qualifiedNameLower}/`;\n if (!pathLower.startsWith(prefixLower)) {\n return false;\n }\n // Extract relative path - use lowercase length since gateway sends lowercase paths\n const relativePath = pathWithoutQuery.substring(qualifiedNameLower.length + 1);\n const handler = service.federationRegistry.resolve(relativePath);\n if (!handler) {\n return false;\n }\n\n const result = await handler.invoke(ctx as FederatedRequestContext);\n await this.sendFederationResponse(ctx, result);\n return true;\n }\n\n private async tryHandleAdminRoute(ctx: RequestContext, service: ServiceInstance): Promise<boolean> {\n // Gateway sends paths with lowercase service names, so we need case-insensitive matching\n // Check if path starts with the admin prefix (case-insensitive)\n // Extract path without query string for routing\n const pathWithoutQuery = this.getPathWithoutQuery(ctx.path);\n const pathLower = pathWithoutQuery.toLowerCase();\n const adminPrefixLower = `${service.definition.qualifiedName.toLowerCase()}/admin/`;\n if (!pathLower.startsWith(adminPrefixLower)) {\n return false;\n }\n\n const options = getServiceOptions(service.definition.ctor) ?? {};\n\n const action = pathLower.substring(adminPrefixLower.length);\n const requiresAdmin = action === 'metadata' || action === 'docs';\n if (requiresAdmin && !scopeSetHas(ctx.scopes, 'admin')) {\n // For portal requests to admin endpoints, the gateway may not send scopes\n // The X-DE-SCOPE header contains CID.PID, not scope values\n // If this is a portal request (has X-DE-SCOPE header), grant admin scope\n const hasPortalHeader = ctx.headers['X-DE-SCOPE'] || ctx.headers['x-de-scope'];\n if (hasPortalHeader) {\n // Grant admin scope for portal requests to admin endpoints\n ctx.scopes.add('admin');\n } else {\n throw new MissingScopesError(['admin']);\n }\n }\n\n switch (action) {\n case 'health':\n case 'healthcheck':\n await this.requester.sendResponse({ id: ctx.id, status: 200, body: 'responsive' });\n return true;\n case 'metadata':\n case 'docs':\n break;\n default:\n if (!scopeSetHas(ctx.scopes, 'admin')) {\n throw new MissingScopesError(['admin']);\n }\n throw new UnknownRouteError(ctx.path);\n }\n\n if (action === 'metadata') {\n const federatedComponents = service.federationRegistry\n .list()\n .map((component) => ({\n federationNamespace: component.federationNamespace,\n federationType: component.federationType,\n }));\n\n await this.requester.sendResponse({\n id: ctx.id,\n status: 200,\n body: {\n serviceName: service.definition.name,\n sdkVersion: this.env.sdkVersionExecution,\n sdkBaseBuildVersion: this.env.sdkVersionExecution,\n sdkExecutionVersion: this.env.sdkVersionExecution,\n useLegacySerialization: Boolean(options.useLegacySerialization),\n disableAllBeamableEvents: Boolean(options.disableAllBeamableEvents),\n enableEagerContentLoading: false,\n instanceId: this.microServiceId,\n routingKey: this.env.routingKey ?? '',\n federatedComponents,\n },\n });\n return true;\n }\n\n if (action === 'docs') {\n try {\n const document = generateOpenApiDocument(\n {\n qualifiedName: service.definition.qualifiedName,\n name: service.definition.name,\n callables: Array.from(service.definition.callables.values()).map((callable) => ({\n name: callable.displayName,\n route: callable.route,\n metadata: callable,\n handler: typeof service.instance[callable.displayName] === 'function'\n ? (service.instance[callable.displayName] as (...args: unknown[]) => unknown)\n : undefined,\n })),\n },\n this.env,\n VERSION,\n );\n\n // Ensure document is valid (not empty)\n if (!document || Object.keys(document).length === 0) {\n this.logger.warn({ serviceName: service.definition.name }, 'Generated OpenAPI document is empty');\n }\n\n await this.requester.sendResponse({\n id: ctx.id,\n status: 200,\n body: document,\n });\n return true;\n } catch (error) {\n this.logger.error({ err: error, serviceName: service.definition.name }, 'Failed to generate or send docs');\n throw error;\n }\n }\n\n return false;\n }\n\n private resolveErrorStatus(error: Error): number {\n if (error instanceof UnauthorizedUserError) {\n return 401;\n }\n if (error instanceof MissingScopesError) {\n return 403;\n }\n if (error instanceof UnknownRouteError) {\n return 404;\n }\n if (error instanceof BeamableRuntimeError) {\n return 500;\n }\n return 500;\n }\n\n private printHelpfulUrls(service?: ServiceInstance): void {\n if (!service) {\n return;\n }\n\n // Only print helpful URLs when IS_LOCAL=1 is set\n // In deployed containers, we want only JSON logs for proper log collection\n if (process.env.IS_LOCAL !== '1' && process.env.IS_LOCAL !== 'true') {\n return;\n }\n\n const docsUrl = buildDocsPortalUrl(this.env, service.definition);\n const endpointBase = buildPostmanBaseUrl(this.env, service.definition);\n\n const green = (text: string) => `\\x1b[32m${text}\\x1b[0m`;\n const yellow = (text: string) => `\\x1b[33m${text}\\x1b[0m`;\n\n const bannerLines = [\n '',\n yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),\n ` ${green('Beamable Node microservice ready:')} ${green(service.definition.name)}`,\n yellow(' Quick shortcuts'),\n ` ${yellow('Docs:')} ${docsUrl}`,\n ` ${yellow('Endpoint:')} ${endpointBase}`,\n yellow('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━'),\n '',\n ];\n\n process.stdout.write(`${bannerLines.join('\\n')}`);\n }\n\n private async initializeDependencyProviders(): Promise<void> {\n // Get StorageService from service manager (it's initialized during serviceManager.initialize())\n const storageService = this.serviceManager.getStorageService();\n \n for (const service of this.services) {\n const builder = new DependencyBuilder();\n builder.tryAddSingletonInstance(LOGGER_TOKEN, service.logger);\n builder.tryAddSingletonInstance(ENVIRONMENT_CONFIG_TOKEN, this.env);\n builder.tryAddSingletonInstance(BeamableServiceManager, this.serviceManager);\n builder.tryAddSingletonInstance(StorageService, storageService);\n builder.tryAddSingletonInstance(service.definition.ctor, service.instance);\n builder.tryAddSingletonInstance(FederationRegistry, service.federationRegistry);\n\n for (const handler of service.configureHandlers) {\n await handler(builder);\n }\n\n const provider = builder.build();\n service.provider = provider;\n\n for (const handler of service.initializeHandlers) {\n await handler(provider);\n }\n\n Object.defineProperty(service.instance, 'provider', {\n value: provider,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n }\n }\n\n private createRequestScope(path: string, service?: ServiceInstance): MutableDependencyScope {\n // Path should already have query string stripped before calling this method\n const targetService = service ?? this.findServiceForPath(path);\n const provider = targetService?.provider ?? new DependencyBuilder().build();\n return provider.createScope();\n }\n\n /**\n * Extracts the path portion without the query string.\n * @param path The full path potentially containing a query string\n * @returns The path without the query string\n */\n private getPathWithoutQuery(path: string): string {\n const [pathWithoutQuery] = path.split('?', 2);\n return pathWithoutQuery;\n }\n}\n\nfunction enforceAccess(access: ServiceAccess, ctx: RequestContext): void {\n switch (access) {\n case 'client':\n if (ctx.userId <= 0) {\n throw new UnauthorizedUserError(ctx.path);\n }\n break;\n case 'server':\n if (!scopeSetHas(ctx.scopes, 'server')) {\n throw new MissingScopesError(['server']);\n }\n break;\n case 'admin':\n if (!scopeSetHas(ctx.scopes, 'admin')) {\n throw new MissingScopesError(['admin']);\n }\n break;\n default:\n break;\n }\n}\n\n/**\n * Conditionally output to console.error only when running locally (not in container).\n * In containers, we want only Pino JSON logs to stdout for proper log collection.\n */\nfunction debugLog(...args: unknown[]): void {\n // Only output debug logs when IS_LOCAL=1 is set\n if (process.env.IS_LOCAL === '1' || process.env.IS_LOCAL === 'true') {\n console.error(...args);\n }\n}\n\n/**\n * Determines if we're running in a deployed container.\n * Used for service registration logic (routing key handling, discovery broadcaster, etc.)\n * \n * Note: For log formatting, use IS_LOCAL env var instead.\n */\nfunction isRunningInContainer(): boolean {\n // Check for Docker container\n try {\n const fs = require('fs');\n if (fs.existsSync('/.dockerenv')) {\n return true;\n }\n } catch {\n // fs might not be available\n }\n \n // Check for Docker container hostname pattern (12 hex chars)\n const hostname = process.env.HOSTNAME || '';\n if (hostname && /^[a-f0-9]{12}$/i.test(hostname)) {\n return true;\n }\n \n // Explicit container indicators\n if (\n process.env.DOTNET_RUNNING_IN_CONTAINER === 'true' ||\n process.env.CONTAINER === 'beamable' ||\n !!process.env.ECS_CONTAINER_METADATA_URI ||\n !!process.env.KUBERNETES_SERVICE_HOST\n ) {\n return true;\n }\n \n // Default: assume local development\n return false;\n}\n\nfunction normalizeScopes(scopes: Array<unknown>): Set<string> {\n const normalized = new Set<string>();\n for (const scope of scopes) {\n if (typeof scope !== 'string' || scope.trim().length === 0) {\n continue;\n }\n normalized.add(scope.trim().toLowerCase());\n }\n return normalized;\n}\n\nfunction scopeSetHas(scopes: Set<string>, scope: string): boolean {\n const normalized = scope.trim().toLowerCase();\n if (normalized.length === 0) {\n return false;\n }\n return scopes.has('*') || scopes.has(normalized);\n}\n\nfunction buildPostmanBaseUrl(env: EnvironmentConfig, service: ServiceDefinition): string {\n const httpHost = hostToHttpUrl(env.host);\n const routingKeyPart = env.routingKey ? env.routingKey : '';\n return `${httpHost}/basic/${env.cid}.${env.pid}.${routingKeyPart}${service.qualifiedName}/`;\n}\n\nfunction buildDocsPortalUrl(env: EnvironmentConfig, service: ServiceDefinition): string {\n const portalHost = hostToPortalUrl(hostToHttpUrl(env.host));\n const queryParams: Record<string, string> = { srcTool: 'node-runtime' };\n if (env.routingKey) {\n queryParams.routingKey = env.routingKey;\n }\n const query = new URLSearchParams(queryParams);\n if (env.refreshToken) {\n query.set('refresh_token', env.refreshToken);\n }\n const beamoId = service.name;\n return `${portalHost}/${env.cid}/games/${env.pid}/realms/${env.pid}/microservices/micro_${beamoId}/docs?${query.toString()}`;\n}\n\nexport async function runMicroservice(): Promise<void> {\n // Immediate console output to verify process is starting (local dev only)\n // In containers, we rely on Pino logger for all output\n debugLog('[BEAMABLE-NODE] Starting microservice...');\n debugLog(`[BEAMABLE-NODE] Node version: ${process.version}`);\n debugLog(`[BEAMABLE-NODE] Working directory: ${process.cwd()}`);\n debugLog(`[BEAMABLE-NODE] Environment: ${JSON.stringify({\n NODE_ENV: process.env.NODE_ENV,\n CID: process.env.CID ? 'SET' : 'NOT SET',\n PID: process.env.PID ? 'SET' : 'NOT SET',\n HOST: process.env.HOST ? 'SET' : 'NOT SET',\n SECRET: process.env.SECRET ? 'SET' : 'NOT SET',\n })}`);\n if (process.env.BEAMABLE_SKIP_RUNTIME === 'true') {\n return;\n }\n const runtime = new MicroserviceRuntime();\n \n // Handle uncaught errors - log them but don't crash immediately\n // This allows the health check server to keep running so we can debug\n // In containers, errors will be logged by the logger in the runtime\n // Locally, use console.error for visibility\n process.on('uncaughtException', (error) => {\n // In containers, the logger will handle this; locally, show in console\n debugLog('Uncaught Exception:', error);\n // Don't exit - let the health check server keep running\n });\n \n process.on('unhandledRejection', (reason, promise) => {\n // In containers, the logger will handle this; locally, show in console\n debugLog('Unhandled Rejection at:', promise, 'reason:', reason);\n // Don't exit - let the health check server keep running\n });\n \n try {\n await runtime.start();\n } catch (error) {\n // Log the error but don't exit - health check server is running\n // This allows the container to stay alive so we can see what went wrong\n // In containers, the logger already logged it in start(); locally, also use console.error\n debugLog('Failed to start microservice runtime:', error);\n // Keep the process alive so health check can continue\n // The health check will return 503 until isReady is true\n }\n \n const shutdownSignals: NodeJS.Signals[] = ['SIGTERM', 'SIGINT'];\n shutdownSignals.forEach((signal) => {\n process.once(signal, async () => {\n await runtime.shutdown();\n process.exit(0);\n });\n });\n}\n\ninterface GenerateOpenApiOptions {\n serviceName?: string;\n}\n\nexport function generateOpenApiDocumentForRegisteredServices(\n overrides: Partial<EnvironmentConfig> = {},\n options: GenerateOpenApiOptions = {},\n): unknown {\n const services = listRegisteredServices();\n if (services.length === 0) {\n throw new Error('No microservices registered. Import your service module before generating documentation.');\n }\n\n const baseEnv = buildEnvironmentConfig(overrides);\n const primary = options.serviceName\n ? services.find((svc) => svc.name === options.serviceName || svc.qualifiedName === options.serviceName)\n : services[0];\n\n if (!primary) {\n throw new Error(`No registered microservice matched '${options.serviceName}'.`);\n }\n\n return generateOpenApiDocument(\n {\n qualifiedName: primary.qualifiedName,\n name: primary.name,\n callables: Array.from(primary.callables.entries()).map(([displayName, metadata]) => ({\n name: displayName,\n route: metadata.route,\n metadata,\n handler: undefined,\n })),\n },\n baseEnv,\n VERSION,\n );\n}\n\nfunction buildEnvironmentConfig(overrides: Partial<EnvironmentConfig>): EnvironmentConfig {\n const merged: Partial<EnvironmentConfig> = { ...overrides };\n\n const ensure = (key: keyof EnvironmentConfig, fallbackEnv?: string) => {\n if (merged[key] !== undefined) {\n return;\n }\n if (fallbackEnv && process.env[fallbackEnv]) {\n merged[key] = process.env[fallbackEnv] as never;\n }\n };\n\n ensure('cid', 'CID');\n ensure('pid', 'PID');\n ensure('host', 'HOST');\n ensure('secret', 'SECRET');\n ensure('refreshToken', 'REFRESH_TOKEN');\n // Routing key is optional for deployed services (in containers)\n // It will be resolved to empty string if not provided and running in container\n if (!merged.routingKey && !isRunningInContainer()) {\n ensure('routingKey', 'NAME_PREFIX');\n }\n\n if (!merged.cid || !merged.pid || !merged.host) {\n throw new Error('CID, PID, and HOST are required to generate documentation.');\n }\n\n const base = loadEnvironmentConfig();\n\n return {\n ...base,\n ...merged,\n routingKey: merged.routingKey ?? base.routingKey,\n };\n}\n"]}
|
package/dist/services.cjs
CHANGED
|
@@ -234,7 +234,7 @@ class BeamableServiceManager {
|
|
|
234
234
|
this.logger = logger.child({ component: 'BeamableServiceManager' });
|
|
235
235
|
this.tokenStorage = (0, beamable_sdk_1.defaultTokenStorage)({ pid: env.pid, tag: (_a = env.routingKey) !== null && _a !== void 0 ? _a : RUNTIME_ENVIRONMENT_NAME });
|
|
236
236
|
}
|
|
237
|
-
async initialize() {
|
|
237
|
+
async initialize(serviceName) {
|
|
238
238
|
if (this.initialized) {
|
|
239
239
|
return;
|
|
240
240
|
}
|
|
@@ -264,6 +264,16 @@ class BeamableServiceManager {
|
|
|
264
264
|
return;
|
|
265
265
|
}
|
|
266
266
|
this.boundApi = await bindBeamApi(this.beamServer.requester);
|
|
267
|
+
if (serviceName && this.beamServer.requester && this.env.routingKey) {
|
|
268
|
+
const fullRoutingKey = `micro_${serviceName}:${this.env.routingKey}`;
|
|
269
|
+
beamable_sdk_1.BeamServer.env.BEAM_ROUTING_KEY = fullRoutingKey;
|
|
270
|
+
const scopeHeader = `${this.env.cid}.${this.env.pid}`;
|
|
271
|
+
this.beamServer.requester.defaultHeaders = {
|
|
272
|
+
...this.beamServer.requester.defaultHeaders,
|
|
273
|
+
'X-BEAM-SCOPE': scopeHeader,
|
|
274
|
+
'X-BEAM-SERVICE-ROUTING-KEY': fullRoutingKey,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
267
277
|
this.storageService = new storage_js_1.StorageService({
|
|
268
278
|
requester: this.beamServer.requester,
|
|
269
279
|
api: this.boundApi,
|
|
@@ -335,11 +345,10 @@ class BeamableServiceManager {
|
|
|
335
345
|
}
|
|
336
346
|
}
|
|
337
347
|
configureSharedEnvironment() {
|
|
338
|
-
var _a;
|
|
339
348
|
if (this.env.secret) {
|
|
340
349
|
beamable_sdk_1.BeamServer.env.BEAM_REALM_SECRET = this.env.secret;
|
|
341
350
|
}
|
|
342
|
-
beamable_sdk_1.BeamServer.env.BEAM_ROUTING_KEY =
|
|
351
|
+
beamable_sdk_1.BeamServer.env.BEAM_ROUTING_KEY = '';
|
|
343
352
|
}
|
|
344
353
|
registerDefaultServices() {
|
|
345
354
|
if (!this.beamServer) {
|
package/dist/services.d.ts
CHANGED
|
@@ -32,7 +32,7 @@ export declare class BeamableServiceManager {
|
|
|
32
32
|
private initialized;
|
|
33
33
|
private readonly federationRegistries;
|
|
34
34
|
constructor(env: EnvironmentConfig, logger: Logger);
|
|
35
|
-
initialize(): Promise<void>;
|
|
35
|
+
initialize(serviceName?: string): Promise<void>;
|
|
36
36
|
createFacade(userId: string | number, scopes: Set<string>, serviceName?: string): BeamableMicroserviceServices;
|
|
37
37
|
getRequester(): HttpRequester;
|
|
38
38
|
getBoundApi(): BoundBeamApi;
|
package/dist/services.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.d.ts","sourceRoot":"","sources":["../src/services.ts"],"names":[],"mappings":"AAAA,OAAa,EAAE,KAAK,MAAM,EAAE,MAAM,MAAM,CAAC;AACzC,OAAO,EAIL,KAAK,aAAa,EAClB,cAAc,EACd,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,mBAAmB,EACnB,YAAY,EACb,MAAM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E,MAAM,GAAG,kBAAkB,GAAG,SAAS;IAI1E,OAAO,CAAC,mBAAmB;IAkB3B,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,uBAAuB;CAWhC"}
|
package/dist/services.js
CHANGED
|
@@ -218,7 +218,7 @@ export class BeamableServiceManager {
|
|
|
218
218
|
this.logger = logger.child({ component: 'BeamableServiceManager' });
|
|
219
219
|
this.tokenStorage = defaultTokenStorage({ pid: env.pid, tag: env.routingKey ?? RUNTIME_ENVIRONMENT_NAME });
|
|
220
220
|
}
|
|
221
|
-
async initialize() {
|
|
221
|
+
async initialize(serviceName) {
|
|
222
222
|
if (this.initialized) {
|
|
223
223
|
return;
|
|
224
224
|
}
|
|
@@ -248,9 +248,19 @@ export class BeamableServiceManager {
|
|
|
248
248
|
return;
|
|
249
249
|
}
|
|
250
250
|
this.boundApi = await bindBeamApi(this.beamServer.requester);
|
|
251
|
-
// Configure the
|
|
252
|
-
// The routing key format is: serviceName
|
|
253
|
-
//
|
|
251
|
+
// Configure the routing key for service-level requests (used by StorageService)
|
|
252
|
+
// The routing key format is: micro_<serviceName>:<routingKey>
|
|
253
|
+
// This is needed when StorageService is used outside of request context
|
|
254
|
+
if (serviceName && this.beamServer.requester && this.env.routingKey) {
|
|
255
|
+
const fullRoutingKey = `micro_${serviceName}:${this.env.routingKey}`;
|
|
256
|
+
BeamServer.env.BEAM_ROUTING_KEY = fullRoutingKey;
|
|
257
|
+
const scopeHeader = `${this.env.cid}.${this.env.pid}`;
|
|
258
|
+
this.beamServer.requester.defaultHeaders = {
|
|
259
|
+
...this.beamServer.requester.defaultHeaders,
|
|
260
|
+
'X-BEAM-SCOPE': scopeHeader,
|
|
261
|
+
'X-BEAM-SERVICE-ROUTING-KEY': fullRoutingKey,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
254
264
|
this.storageService = new StorageService({
|
|
255
265
|
requester: this.beamServer.requester,
|
|
256
266
|
api: this.boundApi,
|
|
@@ -330,12 +340,9 @@ export class BeamableServiceManager {
|
|
|
330
340
|
if (this.env.secret) {
|
|
331
341
|
BeamServer.env.BEAM_REALM_SECRET = this.env.secret;
|
|
332
342
|
}
|
|
333
|
-
// BEAM_ROUTING_KEY
|
|
334
|
-
//
|
|
335
|
-
|
|
336
|
-
// For deployed services, routingKey is undefined, so we set it to empty string
|
|
337
|
-
// The SDK will handle this appropriately
|
|
338
|
-
BeamServer.env.BEAM_ROUTING_KEY = this.env.routingKey ?? '';
|
|
343
|
+
// BEAM_ROUTING_KEY will be set in initialize() after we have the service name
|
|
344
|
+
// For now, just set it to empty string - it will be updated with the full format
|
|
345
|
+
BeamServer.env.BEAM_ROUTING_KEY = '';
|
|
339
346
|
}
|
|
340
347
|
registerDefaultServices() {
|
|
341
348
|
if (!this.beamServer) {
|
package/dist/services.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"services.js","sourceRoot":"","sources":["../src/services.ts"],"names":[],"mappings":"AAAA,OAAO,IAAqB,MAAM,MAAM,CAAC;AACzC,OAAO,EACL,UAAU,EACV,eAAe,EACf,mBAAmB,EAEnB,cAAc,EACd,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,mBAAmB,EACnB,YAAY,GACb,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,6BAA6B,EAAE,MAAM,iBAAiB,CAAC;AAClH,OAAO,EAAE,sBAAsB,EAAyB,MAAM,gBAAgB,CAAC;AAC/E,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEjD,MAAM,wBAAwB,GAAG,cAAc,CAAC;AAIhD,IAAI,mBAAmB,GAAmC,IAAI,CAAC;AAE/D,KAAK,UAAU,oBAAoB;IACjC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QACzB,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,kBAAkB,CAAC,CAAC;QACl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B,EAAE;gBACjD,MAAM;gBACN,SAAS;gBACT,mBAAmB,EAAE,UAAU;gBAC/B,iBAAiB,EAAE,GAAG,WAAW,MAAM;aACxC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,8EAA8E,CAAC,CAAC;QACpH,CAAC;IACH,CAAC;IAEO,0BAA0B;QAChC,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;YACpB,UAAU,CAAC,GAAG,CAAC,iBAAiB,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC;QACrD,CAAC;QACD,yFAAyF;QACzF,6FAA6F;QAC7F,yFAAyF;QACzF,+EAA+E;QAC/E,yCAAyC;QACzC,UAAU,CAAC,GAAG,CAAC,gBAAgB,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,IAAI,EAAE,CAAC;IAC9D,CAAC;IAEO,uBAAuB;QAC7B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;QAC1C,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACjC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACzC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;IACpC,CAAC;CACF","sourcesContent":["import pino, { type Logger } from 'pino';\r\nimport {\r\n BeamServer,\r\n BeamEnvironment,\r\n defaultTokenStorage,\r\n type HttpRequester,\r\n AccountService,\r\n AnnouncementsService,\r\n AuthService,\r\n ContentService,\r\n LeaderboardsService,\r\n StatsService,\r\n} from 'beamable-sdk';\r\nimport type { EnvironmentConfig } from './types.js';\r\nimport { hostToHttpUrl, hostToPortalUrl, hostToStorageUrl, hostToMicroserviceRegistryUrl } from './utils/urls.js';\r\nimport { createInventoryService, type InventoryService } from './inventory.js';\r\nimport { StorageService } from './storage.js';\r\nimport type { FederationRegistry } from './federation.js';\r\nimport { MissingScopesError } from './errors.js';\r\n\r\nconst RUNTIME_ENVIRONMENT_NAME = 'node-runtime';\r\n\r\nexport type BoundBeamApi = Record<string, (...args: unknown[]) => unknown>;\r\n\r\nlet cachedBeamApiModule: Record<string, unknown> | null = null;\r\n\r\nasync function resolveBeamApiModule(): Promise<Record<string, unknown>> {\r\n if (!cachedBeamApiModule) {\r\n const imported = await import('beamable-sdk/api');\r\n cachedBeamApiModule =\r\n imported && typeof imported === 'object' && 'default' in imported\r\n ? (imported.default as Record<string, unknown>)\r\n : (imported as Record<string, unknown>);\r\n }\r\n return cachedBeamApiModule;\r\n}\r\n\r\nasync function bindBeamApi(requester: HttpRequester): Promise<BoundBeamApi> {\r\n const module = await resolveBeamApiModule();\r\n const bound: Record<string, (...args: unknown[]) => unknown> = {};\r\n for (const key of Object.keys(module)) {\r\n const value = module[key];\r\n if (typeof value === 'function') {\r\n bound[key] = (...args: unknown[]) => (value as (r: HttpRequester, ...params: unknown[]) => unknown)(requester, ...args);\r\n }\r\n }\r\n return bound;\r\n}\r\n\r\nfunction createFailingApi(error: Error): BoundBeamApi {\r\n return new Proxy(\r\n {},\r\n {\r\n get() {\r\n throw error;\r\n },\r\n },\r\n ) as BoundBeamApi;\r\n}\r\n\r\ntype ServiceMap = {\r\n account: AccountService;\r\n announcements: AnnouncementsService;\r\n auth: AuthService;\r\n content: ContentService;\r\n leaderboards: LeaderboardsService;\r\n stats: StatsService;\r\n};\r\n\r\ntype ServiceKey = keyof ServiceMap;\r\n\r\nclass UnavailableRequester implements HttpRequester {\r\n constructor(private readonly error: Error) {}\r\n\r\n async request(): Promise<never> {\r\n throw this.error;\r\n }\r\n\r\n set baseUrl(_: string) {\r\n // no-op\r\n }\r\n\r\n set defaultHeaders(_: Record<string, string>) {\r\n // no-op\r\n }\r\n}\r\n\r\nclass UnavailableBeamableServices implements BeamableMicroserviceServices {\r\n private readonly requesterImpl: HttpRequester;\r\n private readonly apiBindings: BoundBeamApi;\r\n\r\n constructor(private readonly error: Error) {\r\n this.requesterImpl = new UnavailableRequester(this.error);\r\n this.apiBindings = createFailingApi(this.error);\r\n }\r\n\r\n private fail(): never {\r\n throw this.error;\r\n }\r\n\r\n get account(): AccountService {\r\n return this.fail();\r\n }\r\n\r\n get announcements(): AnnouncementsService {\r\n return this.fail();\r\n }\r\n\r\n get auth(): AuthService {\r\n return this.fail();\r\n }\r\n\r\n get content(): ContentService {\r\n return this.fail();\r\n }\r\n\r\n get leaderboards(): LeaderboardsService {\r\n return this.fail();\r\n }\r\n\r\n get stats(): StatsService {\r\n return this.fail();\r\n }\r\n\r\n get inventory(): InventoryService {\r\n return this.fail();\r\n }\r\n\r\n get storage(): StorageService {\r\n return this.fail();\r\n }\r\n\r\n get federation(): FederationRegistry {\r\n return this.fail();\r\n }\r\n\r\n get api(): BoundBeamApi {\r\n return this.apiBindings;\r\n }\r\n\r\n get requester(): HttpRequester {\r\n return this.requesterImpl;\r\n }\r\n\r\n hasScopes(..._scopes: string[]): boolean {\r\n return false;\r\n }\r\n\r\n requireScopes(...scopes: string[]): void {\r\n throw new MissingScopesError(scopes);\r\n }\r\n\r\n assumeUser(): BeamableMicroserviceServices {\r\n return this;\r\n }\r\n\r\n getLogger(): Logger {\r\n // For unavailable services, return a basic logger that logs to stdout\r\n // This allows logging even when services are unavailable\r\n return pino({ name: 'beamable-unavailable', level: 'info' }, process.stdout);\r\n }\r\n}\r\n\r\nclass BeamableServicesFacade implements BeamableMicroserviceServices {\r\n private readonly cache: Partial<Record<ServiceKey, ServiceMap[ServiceKey]>> = {};\r\n private readonly apiBindings: BoundBeamApi;\r\n private readonly storageService: StorageService;\r\n private readonly scopes: Set<string>;\r\n private readonly logger: Logger;\r\n private readonly serviceName?: string;\r\n private readonly federationRegistry?: FederationRegistry;\r\n private inventoryClient?: InventoryService;\r\n\r\n constructor(\r\n private readonly manager: BeamableServiceManager,\r\n private readonly beamServer: BeamServer,\r\n private readonly userId: string,\r\n scopes: Set<string>,\r\n serviceName?: string,\r\n ) {\r\n this.apiBindings = this.manager.getBoundApi();\r\n this.storageService = this.manager.getStorageService();\r\n this.scopes = scopes;\r\n this.serviceName = serviceName;\r\n this.federationRegistry = serviceName ? this.manager.getFederationRegistry(serviceName) : undefined;\r\n this.logger = this.manager.getLogger().child({ component: 'BeamableServicesFacade', service: serviceName });\r\n }\r\n\r\n private getOrCreate<K extends ServiceKey>(key: K, factory: () => ServiceMap[K]): ServiceMap[K] {\r\n if (!this.cache[key]) {\r\n this.cache[key] = factory();\r\n }\r\n return this.cache[key] as ServiceMap[K];\r\n }\r\n\r\n get account(): AccountService {\r\n return this.getOrCreate('account', () => this.beamServer.account(this.userId));\r\n }\r\n\r\n get announcements(): AnnouncementsService {\r\n return this.getOrCreate('announcements', () => this.beamServer.announcements(this.userId));\r\n }\r\n\r\n get auth(): AuthService {\r\n return this.getOrCreate('auth', () => this.beamServer.auth(this.userId));\r\n }\r\n\r\n get content(): ContentService {\r\n return this.getOrCreate('content', () => this.beamServer.content(this.userId));\r\n }\r\n\r\n get leaderboards(): LeaderboardsService {\r\n return this.getOrCreate('leaderboards', () => this.beamServer.leaderboards(this.userId));\r\n }\r\n\r\n get stats(): StatsService {\r\n return this.getOrCreate('stats', () => this.beamServer.stats(this.userId));\r\n }\r\n\r\n get inventory(): InventoryService {\r\n if (!this.inventoryClient) {\r\n this.inventoryClient = createInventoryService(\r\n this.apiBindings,\r\n this.logger.child({ component: 'InventoryClient' }),\r\n this.userId,\r\n (requiredScopes) => this.hasScopes(...requiredScopes),\r\n );\r\n }\r\n return this.inventoryClient;\r\n }\r\n\r\n get storage(): StorageService {\r\n return this.storageService;\r\n }\r\n\r\n get federation(): FederationRegistry {\r\n if (!this.federationRegistry) {\r\n throw new Error(\r\n this.serviceName\r\n ? `Federation registry is not configured for service \"${this.serviceName}\".`\r\n : 'Federation registry is not configured.',\r\n );\r\n }\r\n return this.federationRegistry;\r\n }\r\n\r\n get api(): BoundBeamApi {\r\n return this.apiBindings;\r\n }\r\n\r\n get requester(): HttpRequester {\r\n return this.manager.getRequester();\r\n }\r\n\r\n hasScopes(...requiredScopes: string[]): boolean {\r\n if (requiredScopes.length === 0) {\r\n return true;\r\n }\r\n return requiredScopes.every((scope) => this.scopeSetHas(scope));\r\n }\r\n\r\n requireScopes(...requiredScopes: string[]): void {\r\n if (!this.hasScopes(...requiredScopes)) {\r\n throw new MissingScopesError(requiredScopes);\r\n }\r\n }\r\n\r\n assumeUser(userId: string | number): BeamableMicroserviceServices {\r\n return this.manager.createFacade(String(userId), new Set(this.scopes), this.serviceName);\r\n }\r\n\r\n getLogger(): Logger {\r\n return this.logger;\r\n }\r\n\r\n private scopeSetHas(scope: string): boolean {\r\n const normalized = scope.trim().toLowerCase();\r\n if (!normalized) {\r\n return false;\r\n }\r\n return this.scopes.has('*') || this.scopes.has(normalized);\r\n }\r\n}\r\n\r\nexport interface BeamableMicroserviceServices {\r\n readonly account: AccountService;\r\n readonly announcements: AnnouncementsService;\r\n readonly auth: AuthService;\r\n readonly content: ContentService;\r\n readonly leaderboards: LeaderboardsService;\r\n readonly stats: StatsService;\r\n readonly inventory: InventoryService;\r\n readonly storage: StorageService;\r\n readonly federation: FederationRegistry;\r\n readonly api: BoundBeamApi;\r\n readonly requester: HttpRequester;\r\n hasScopes(...scopes: string[]): boolean;\r\n requireScopes(...scopes: string[]): void;\r\n assumeUser(userId: string | number): BeamableMicroserviceServices;\r\n getLogger(): Logger;\r\n}\r\n\r\nexport class BeamableServiceManager {\r\n private readonly logger: Logger;\r\n private readonly tokenStorage: ReturnType<typeof defaultTokenStorage>;\r\n private readonly env: EnvironmentConfig;\r\n private beamServer?: BeamServer;\r\n private boundApi?: BoundBeamApi;\r\n private storageService?: StorageService;\r\n private initialized = false;\r\n private readonly federationRegistries = new Map<string, FederationRegistry>();\r\n\r\n constructor(env: EnvironmentConfig, logger: Logger) {\r\n this.env = env;\r\n this.logger = logger.child({ component: 'BeamableServiceManager' });\r\n this.tokenStorage = defaultTokenStorage({ pid: env.pid, tag: env.routingKey ?? RUNTIME_ENVIRONMENT_NAME });\r\n }\r\n\r\n async initialize(): Promise<void> {\r\n if (this.initialized) {\r\n return;\r\n }\r\n\r\n this.registerEnvironment();\r\n this.configureSharedEnvironment();\r\n\r\n if (this.env.refreshToken) {\r\n await this.tokenStorage.setTokenData({ refreshToken: this.env.refreshToken });\r\n }\r\n\r\n const useSignedRequest = Boolean(this.env.secret);\r\n if (!useSignedRequest && !this.env.refreshToken) {\r\n this.logger.warn(\r\n 'Beamable realm secret and refresh token are both missing; Beamable SDK requests may fail due to missing credentials.',\r\n );\r\n }\r\n\r\n try {\r\n this.beamServer = await BeamServer.init({\r\n cid: this.env.cid,\r\n pid: this.env.pid,\r\n environment: RUNTIME_ENVIRONMENT_NAME,\r\n useSignedRequest,\r\n tokenStorage: this.tokenStorage,\r\n serverEvents: { enabled: false },\r\n });\r\n } catch (error) {\r\n this.logger.error({ err: error }, 'Failed to initialize Beamable SDK. Services layer will be unavailable.');\r\n this.beamServer = undefined;\r\n this.initialized = false;\r\n return;\r\n }\r\n\r\n this.boundApi = await bindBeamApi(this.beamServer.requester);\r\n \r\n // Configure the requester's default headers to include the routing key in the correct format\r\n // The routing key format is: serviceName:routingKey\r\n // We'll set this per-request in createFacade since we need the service name\r\n this.storageService = new StorageService({\r\n requester: this.beamServer.requester,\r\n api: this.boundApi,\r\n env: this.env,\r\n logger: this.logger.child({ component: 'StorageService' }),\r\n });\r\n\r\n this.registerDefaultServices();\r\n this.initialized = true;\r\n this.logger.debug('Beamable SDK services initialized.');\r\n }\r\n\r\n createFacade(userId: string | number, scopes: Set<string>, serviceName?: string): BeamableMicroserviceServices {\r\n if (!this.initialized || !this.beamServer || !this.boundApi || !this.storageService) {\r\n return new UnavailableBeamableServices(new Error('Beamable services are not initialized.'));\r\n }\r\n \r\n // Set the routing key in the format serviceName:routingKey for the SDK\r\n // The SDK uses BEAM_ROUTING_KEY environment variable to construct the X-BEAM-SERVICE-ROUTING-KEY header\r\n // We need to set it to the full format: serviceName:routingKey\r\n if (serviceName && this.beamServer.requester) {\r\n const fullRoutingKey = `micro_${serviceName}:${this.env.routingKey}`;\r\n BeamServer.env.BEAM_ROUTING_KEY = fullRoutingKey;\r\n \r\n // Set default headers on the requester for all SDK requests\r\n // These headers are required for signature validation and routing\r\n const scopeHeader = `${this.env.cid}.${this.env.pid}`;\r\n this.beamServer.requester.defaultHeaders = {\r\n ...this.beamServer.requester.defaultHeaders,\r\n 'X-BEAM-SCOPE': scopeHeader,\r\n 'X-BEAM-SERVICE-ROUTING-KEY': fullRoutingKey,\r\n };\r\n }\r\n \r\n return new BeamableServicesFacade(this, this.beamServer, String(userId), new Set(scopes), serviceName);\r\n }\r\n\r\n getRequester(): HttpRequester {\r\n if (!this.initialized || !this.beamServer) {\r\n return new UnavailableRequester(new Error('Beamable services are not initialized.'));\r\n }\r\n return this.beamServer.requester;\r\n }\r\n\r\n getBoundApi(): BoundBeamApi {\r\n if (!this.boundApi) {\r\n throw new Error('Beamable bound API is not available.');\r\n }\r\n return this.boundApi;\r\n }\r\n\r\n getStorageService(): StorageService {\r\n if (!this.storageService) {\r\n throw new Error('Storage service is not initialized.');\r\n }\r\n return this.storageService;\r\n }\r\n\r\n getLogger(): Logger {\r\n return this.logger;\r\n }\r\n\r\n registerFederationRegistry(serviceName: string, registry: FederationRegistry): void {\r\n this.federationRegistries.set(serviceName, registry);\r\n }\r\n\r\n getFederationRegistry(serviceName: string): FederationRegistry | undefined {\r\n return this.federationRegistries.get(serviceName);\r\n }\r\n\r\n private registerEnvironment(): void {\r\n const apiUrl = hostToHttpUrl(this.env.host);\r\n const portalUrl = hostToPortalUrl(apiUrl);\r\n const storageUrl = hostToStorageUrl(apiUrl);\r\n const registryUrl = hostToMicroserviceRegistryUrl(apiUrl);\r\n\r\n try {\r\n BeamEnvironment.register(RUNTIME_ENVIRONMENT_NAME, {\r\n apiUrl,\r\n portalUrl,\r\n beamMongoExpressUrl: storageUrl,\r\n dockerRegistryUrl: `${registryUrl}/v2/`,\r\n });\r\n } catch (error) {\r\n this.logger.debug({ err: error }, 'Beamable environment was already registered. Reusing existing configuration.');\r\n }\r\n }\r\n\r\n private configureSharedEnvironment(): void {\r\n if (this.env.secret) {\r\n BeamServer.env.BEAM_REALM_SECRET = this.env.secret;\r\n }\r\n // BEAM_ROUTING_KEY is used by the SDK to construct the X-BEAM-SERVICE-ROUTING-KEY header\r\n // We set it to just the routing key value here, and will set the full format in createFacade\r\n // BEAM_ROUTING_KEY is used by the SDK to construct the X-BEAM-SERVICE-ROUTING-KEY header\r\n // For deployed services, routingKey is undefined, so we set it to empty string\r\n // The SDK will handle this appropriately\r\n BeamServer.env.BEAM_ROUTING_KEY = this.env.routingKey ?? '';\r\n }\r\n\r\n private registerDefaultServices(): void {\r\n if (!this.beamServer) {\r\n return;\r\n }\r\n this.beamServer.use(AccountService);\r\n this.beamServer.use(AnnouncementsService);\r\n this.beamServer.use(AuthService);\r\n this.beamServer.use(ContentService);\r\n this.beamServer.use(LeaderboardsService);\r\n this.beamServer.use(StatsService);\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"services.js","sourceRoot":"","sources":["../src/services.ts"],"names":[],"mappings":"AAAA,OAAO,IAAqB,MAAM,MAAM,CAAC;AACzC,OAAO,EACL,UAAU,EACV,eAAe,EACf,mBAAmB,EAEnB,cAAc,EACd,oBAAoB,EACpB,WAAW,EACX,cAAc,EACd,mBAAmB,EACnB,YAAY,GACb,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,6BAA6B,EAAE,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BAA0B;QAChC,IAAI,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC;YACpB,UAAU,CAAC,GAAG,CAAC,iBAAiB,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC;QACrD,CAAC;QACD,8EAA8E;QAC9E,iFAAiF;QACjF,UAAU,CAAC,GAAG,CAAC,gBAAgB,GAAG,EAAE,CAAC;IACvC,CAAC;IAEO,uBAAuB;QAC7B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;QAC1C,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;QACjC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QACpC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,mBAAmB,CAAC,CAAC;QACzC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;IACpC,CAAC;CACF","sourcesContent":["import pino, { type Logger } from 'pino';\r\nimport {\r\n BeamServer,\r\n BeamEnvironment,\r\n defaultTokenStorage,\r\n type HttpRequester,\r\n AccountService,\r\n AnnouncementsService,\r\n AuthService,\r\n ContentService,\r\n LeaderboardsService,\r\n StatsService,\r\n} from 'beamable-sdk';\r\nimport type { EnvironmentConfig } from './types.js';\r\nimport { hostToHttpUrl, hostToPortalUrl, hostToStorageUrl, hostToMicroserviceRegistryUrl } from './utils/urls.js';\r\nimport { createInventoryService, type InventoryService } from './inventory.js';\r\nimport { StorageService } from './storage.js';\r\nimport type { FederationRegistry } from './federation.js';\r\nimport { MissingScopesError } from './errors.js';\r\n\r\nconst RUNTIME_ENVIRONMENT_NAME = 'node-runtime';\r\n\r\nexport type BoundBeamApi = Record<string, (...args: unknown[]) => unknown>;\r\n\r\nlet cachedBeamApiModule: Record<string, unknown> | null = null;\r\n\r\nasync function resolveBeamApiModule(): Promise<Record<string, unknown>> {\r\n if (!cachedBeamApiModule) {\r\n const imported = await import('beamable-sdk/api');\r\n cachedBeamApiModule =\r\n imported && typeof imported === 'object' && 'default' in imported\r\n ? (imported.default as Record<string, unknown>)\r\n : (imported as Record<string, unknown>);\r\n }\r\n return cachedBeamApiModule;\r\n}\r\n\r\nasync function bindBeamApi(requester: HttpRequester): Promise<BoundBeamApi> {\r\n const module = await resolveBeamApiModule();\r\n const bound: Record<string, (...args: unknown[]) => unknown> = {};\r\n for (const key of Object.keys(module)) {\r\n const value = module[key];\r\n if (typeof value === 'function') {\r\n bound[key] = (...args: unknown[]) => (value as (r: HttpRequester, ...params: unknown[]) => unknown)(requester, ...args);\r\n }\r\n }\r\n return bound;\r\n}\r\n\r\nfunction createFailingApi(error: Error): BoundBeamApi {\r\n return new Proxy(\r\n {},\r\n {\r\n get() {\r\n throw error;\r\n },\r\n },\r\n ) as BoundBeamApi;\r\n}\r\n\r\ntype ServiceMap = {\r\n account: AccountService;\r\n announcements: AnnouncementsService;\r\n auth: AuthService;\r\n content: ContentService;\r\n leaderboards: LeaderboardsService;\r\n stats: StatsService;\r\n};\r\n\r\ntype ServiceKey = keyof ServiceMap;\r\n\r\nclass UnavailableRequester implements HttpRequester {\r\n constructor(private readonly error: Error) {}\r\n\r\n async request(): Promise<never> {\r\n throw this.error;\r\n }\r\n\r\n set baseUrl(_: string) {\r\n // no-op\r\n }\r\n\r\n set defaultHeaders(_: Record<string, string>) {\r\n // no-op\r\n }\r\n}\r\n\r\nclass UnavailableBeamableServices implements BeamableMicroserviceServices {\r\n private readonly requesterImpl: HttpRequester;\r\n private readonly apiBindings: BoundBeamApi;\r\n\r\n constructor(private readonly error: Error) {\r\n this.requesterImpl = new UnavailableRequester(this.error);\r\n this.apiBindings = createFailingApi(this.error);\r\n }\r\n\r\n private fail(): never {\r\n throw this.error;\r\n }\r\n\r\n get account(): AccountService {\r\n return this.fail();\r\n }\r\n\r\n get announcements(): AnnouncementsService {\r\n return this.fail();\r\n }\r\n\r\n get auth(): AuthService {\r\n return this.fail();\r\n }\r\n\r\n get content(): ContentService {\r\n return this.fail();\r\n }\r\n\r\n get leaderboards(): LeaderboardsService {\r\n return this.fail();\r\n }\r\n\r\n get stats(): StatsService {\r\n return this.fail();\r\n }\r\n\r\n get inventory(): InventoryService {\r\n return this.fail();\r\n }\r\n\r\n get storage(): StorageService {\r\n return this.fail();\r\n }\r\n\r\n get federation(): FederationRegistry {\r\n return this.fail();\r\n }\r\n\r\n get api(): BoundBeamApi {\r\n return this.apiBindings;\r\n }\r\n\r\n get requester(): HttpRequester {\r\n return this.requesterImpl;\r\n }\r\n\r\n hasScopes(..._scopes: string[]): boolean {\r\n return false;\r\n }\r\n\r\n requireScopes(...scopes: string[]): void {\r\n throw new MissingScopesError(scopes);\r\n }\r\n\r\n assumeUser(): BeamableMicroserviceServices {\r\n return this;\r\n }\r\n\r\n getLogger(): Logger {\r\n // For unavailable services, return a basic logger that logs to stdout\r\n // This allows logging even when services are unavailable\r\n return pino({ name: 'beamable-unavailable', level: 'info' }, process.stdout);\r\n }\r\n}\r\n\r\nclass BeamableServicesFacade implements BeamableMicroserviceServices {\r\n private readonly cache: Partial<Record<ServiceKey, ServiceMap[ServiceKey]>> = {};\r\n private readonly apiBindings: BoundBeamApi;\r\n private readonly storageService: StorageService;\r\n private readonly scopes: Set<string>;\r\n private readonly logger: Logger;\r\n private readonly serviceName?: string;\r\n private readonly federationRegistry?: FederationRegistry;\r\n private inventoryClient?: InventoryService;\r\n\r\n constructor(\r\n private readonly manager: BeamableServiceManager,\r\n private readonly beamServer: BeamServer,\r\n private readonly userId: string,\r\n scopes: Set<string>,\r\n serviceName?: string,\r\n ) {\r\n this.apiBindings = this.manager.getBoundApi();\r\n this.storageService = this.manager.getStorageService();\r\n this.scopes = scopes;\r\n this.serviceName = serviceName;\r\n this.federationRegistry = serviceName ? this.manager.getFederationRegistry(serviceName) : undefined;\r\n this.logger = this.manager.getLogger().child({ component: 'BeamableServicesFacade', service: serviceName });\r\n }\r\n\r\n private getOrCreate<K extends ServiceKey>(key: K, factory: () => ServiceMap[K]): ServiceMap[K] {\r\n if (!this.cache[key]) {\r\n this.cache[key] = factory();\r\n }\r\n return this.cache[key] as ServiceMap[K];\r\n }\r\n\r\n get account(): AccountService {\r\n return this.getOrCreate('account', () => this.beamServer.account(this.userId));\r\n }\r\n\r\n get announcements(): AnnouncementsService {\r\n return this.getOrCreate('announcements', () => this.beamServer.announcements(this.userId));\r\n }\r\n\r\n get auth(): AuthService {\r\n return this.getOrCreate('auth', () => this.beamServer.auth(this.userId));\r\n }\r\n\r\n get content(): ContentService {\r\n return this.getOrCreate('content', () => this.beamServer.content(this.userId));\r\n }\r\n\r\n get leaderboards(): LeaderboardsService {\r\n return this.getOrCreate('leaderboards', () => this.beamServer.leaderboards(this.userId));\r\n }\r\n\r\n get stats(): StatsService {\r\n return this.getOrCreate('stats', () => this.beamServer.stats(this.userId));\r\n }\r\n\r\n get inventory(): InventoryService {\r\n if (!this.inventoryClient) {\r\n this.inventoryClient = createInventoryService(\r\n this.apiBindings,\r\n this.logger.child({ component: 'InventoryClient' }),\r\n this.userId,\r\n (requiredScopes) => this.hasScopes(...requiredScopes),\r\n );\r\n }\r\n return this.inventoryClient;\r\n }\r\n\r\n get storage(): StorageService {\r\n return this.storageService;\r\n }\r\n\r\n get federation(): FederationRegistry {\r\n if (!this.federationRegistry) {\r\n throw new Error(\r\n this.serviceName\r\n ? `Federation registry is not configured for service \"${this.serviceName}\".`\r\n : 'Federation registry is not configured.',\r\n );\r\n }\r\n return this.federationRegistry;\r\n }\r\n\r\n get api(): BoundBeamApi {\r\n return this.apiBindings;\r\n }\r\n\r\n get requester(): HttpRequester {\r\n return this.manager.getRequester();\r\n }\r\n\r\n hasScopes(...requiredScopes: string[]): boolean {\r\n if (requiredScopes.length === 0) {\r\n return true;\r\n }\r\n return requiredScopes.every((scope) => this.scopeSetHas(scope));\r\n }\r\n\r\n requireScopes(...requiredScopes: string[]): void {\r\n if (!this.hasScopes(...requiredScopes)) {\r\n throw new MissingScopesError(requiredScopes);\r\n }\r\n }\r\n\r\n assumeUser(userId: string | number): BeamableMicroserviceServices {\r\n return this.manager.createFacade(String(userId), new Set(this.scopes), this.serviceName);\r\n }\r\n\r\n getLogger(): Logger {\r\n return this.logger;\r\n }\r\n\r\n private scopeSetHas(scope: string): boolean {\r\n const normalized = scope.trim().toLowerCase();\r\n if (!normalized) {\r\n return false;\r\n }\r\n return this.scopes.has('*') || this.scopes.has(normalized);\r\n }\r\n}\r\n\r\nexport interface BeamableMicroserviceServices {\r\n readonly account: AccountService;\r\n readonly announcements: AnnouncementsService;\r\n readonly auth: AuthService;\r\n readonly content: ContentService;\r\n readonly leaderboards: LeaderboardsService;\r\n readonly stats: StatsService;\r\n readonly inventory: InventoryService;\r\n readonly storage: StorageService;\r\n readonly federation: FederationRegistry;\r\n readonly api: BoundBeamApi;\r\n readonly requester: HttpRequester;\r\n hasScopes(...scopes: string[]): boolean;\r\n requireScopes(...scopes: string[]): void;\r\n assumeUser(userId: string | number): BeamableMicroserviceServices;\r\n getLogger(): Logger;\r\n}\r\n\r\nexport class BeamableServiceManager {\r\n private readonly logger: Logger;\r\n private readonly tokenStorage: ReturnType<typeof defaultTokenStorage>;\r\n private readonly env: EnvironmentConfig;\r\n private beamServer?: BeamServer;\r\n private boundApi?: BoundBeamApi;\r\n private storageService?: StorageService;\r\n private initialized = false;\r\n private readonly federationRegistries = new Map<string, FederationRegistry>();\r\n\r\n constructor(env: EnvironmentConfig, logger: Logger) {\r\n this.env = env;\r\n this.logger = logger.child({ component: 'BeamableServiceManager' });\r\n this.tokenStorage = defaultTokenStorage({ pid: env.pid, tag: env.routingKey ?? RUNTIME_ENVIRONMENT_NAME });\r\n }\r\n\r\n async initialize(serviceName?: string): Promise<void> {\r\n if (this.initialized) {\r\n return;\r\n }\r\n\r\n this.registerEnvironment();\r\n this.configureSharedEnvironment();\r\n\r\n if (this.env.refreshToken) {\r\n await this.tokenStorage.setTokenData({ refreshToken: this.env.refreshToken });\r\n }\r\n\r\n const useSignedRequest = Boolean(this.env.secret);\r\n if (!useSignedRequest && !this.env.refreshToken) {\r\n this.logger.warn(\r\n 'Beamable realm secret and refresh token are both missing; Beamable SDK requests may fail due to missing credentials.',\r\n );\r\n }\r\n\r\n try {\r\n this.beamServer = await BeamServer.init({\r\n cid: this.env.cid,\r\n pid: this.env.pid,\r\n environment: RUNTIME_ENVIRONMENT_NAME,\r\n useSignedRequest,\r\n tokenStorage: this.tokenStorage,\r\n serverEvents: { enabled: false },\r\n });\r\n } catch (error) {\r\n this.logger.error({ err: error }, 'Failed to initialize Beamable SDK. Services layer will be unavailable.');\r\n this.beamServer = undefined;\r\n this.initialized = false;\r\n return;\r\n }\r\n\r\n this.boundApi = await bindBeamApi(this.beamServer.requester);\r\n \r\n // Configure the routing key for service-level requests (used by StorageService)\r\n // The routing key format is: micro_<serviceName>:<routingKey>\r\n // This is needed when StorageService is used outside of request context\r\n if (serviceName && this.beamServer.requester && this.env.routingKey) {\r\n const fullRoutingKey = `micro_${serviceName}:${this.env.routingKey}`;\r\n BeamServer.env.BEAM_ROUTING_KEY = fullRoutingKey;\r\n \r\n const scopeHeader = `${this.env.cid}.${this.env.pid}`;\r\n this.beamServer.requester.defaultHeaders = {\r\n ...this.beamServer.requester.defaultHeaders,\r\n 'X-BEAM-SCOPE': scopeHeader,\r\n 'X-BEAM-SERVICE-ROUTING-KEY': fullRoutingKey,\r\n };\r\n }\r\n \r\n this.storageService = new StorageService({\r\n requester: this.beamServer.requester,\r\n api: this.boundApi,\r\n env: this.env,\r\n logger: this.logger.child({ component: 'StorageService' }),\r\n });\r\n\r\n this.registerDefaultServices();\r\n this.initialized = true;\r\n this.logger.debug('Beamable SDK services initialized.');\r\n }\r\n\r\n createFacade(userId: string | number, scopes: Set<string>, serviceName?: string): BeamableMicroserviceServices {\r\n if (!this.initialized || !this.beamServer || !this.boundApi || !this.storageService) {\r\n return new UnavailableBeamableServices(new Error('Beamable services are not initialized.'));\r\n }\r\n \r\n // Set the routing key in the format serviceName:routingKey for the SDK\r\n // The SDK uses BEAM_ROUTING_KEY environment variable to construct the X-BEAM-SERVICE-ROUTING-KEY header\r\n // We need to set it to the full format: serviceName:routingKey\r\n if (serviceName && this.beamServer.requester) {\r\n const fullRoutingKey = `micro_${serviceName}:${this.env.routingKey}`;\r\n BeamServer.env.BEAM_ROUTING_KEY = fullRoutingKey;\r\n \r\n // Set default headers on the requester for all SDK requests\r\n // These headers are required for signature validation and routing\r\n const scopeHeader = `${this.env.cid}.${this.env.pid}`;\r\n this.beamServer.requester.defaultHeaders = {\r\n ...this.beamServer.requester.defaultHeaders,\r\n 'X-BEAM-SCOPE': scopeHeader,\r\n 'X-BEAM-SERVICE-ROUTING-KEY': fullRoutingKey,\r\n };\r\n }\r\n \r\n return new BeamableServicesFacade(this, this.beamServer, String(userId), new Set(scopes), serviceName);\r\n }\r\n\r\n getRequester(): HttpRequester {\r\n if (!this.initialized || !this.beamServer) {\r\n return new UnavailableRequester(new Error('Beamable services are not initialized.'));\r\n }\r\n return this.beamServer.requester;\r\n }\r\n\r\n getBoundApi(): BoundBeamApi {\r\n if (!this.boundApi) {\r\n throw new Error('Beamable bound API is not available.');\r\n }\r\n return this.boundApi;\r\n }\r\n\r\n getStorageService(): StorageService {\r\n if (!this.storageService) {\r\n throw new Error('Storage service is not initialized.');\r\n }\r\n return this.storageService;\r\n }\r\n\r\n getLogger(): Logger {\r\n return this.logger;\r\n }\r\n\r\n registerFederationRegistry(serviceName: string, registry: FederationRegistry): void {\r\n this.federationRegistries.set(serviceName, registry);\r\n }\r\n\r\n getFederationRegistry(serviceName: string): FederationRegistry | undefined {\r\n return this.federationRegistries.get(serviceName);\r\n }\r\n\r\n private registerEnvironment(): void {\r\n const apiUrl = hostToHttpUrl(this.env.host);\r\n const portalUrl = hostToPortalUrl(apiUrl);\r\n const storageUrl = hostToStorageUrl(apiUrl);\r\n const registryUrl = hostToMicroserviceRegistryUrl(apiUrl);\r\n\r\n try {\r\n BeamEnvironment.register(RUNTIME_ENVIRONMENT_NAME, {\r\n apiUrl,\r\n portalUrl,\r\n beamMongoExpressUrl: storageUrl,\r\n dockerRegistryUrl: `${registryUrl}/v2/`,\r\n });\r\n } catch (error) {\r\n this.logger.debug({ err: error }, 'Beamable environment was already registered. Reusing existing configuration.');\r\n }\r\n }\r\n\r\n private configureSharedEnvironment(): void {\r\n if (this.env.secret) {\r\n BeamServer.env.BEAM_REALM_SECRET = this.env.secret;\r\n }\r\n // BEAM_ROUTING_KEY will be set in initialize() after we have the service name\r\n // For now, just set it to empty string - it will be updated with the full format\r\n BeamServer.env.BEAM_ROUTING_KEY = '';\r\n }\r\n\r\n private registerDefaultServices(): void {\r\n if (!this.beamServer) {\r\n return;\r\n }\r\n this.beamServer.use(AccountService);\r\n this.beamServer.use(AnnouncementsService);\r\n this.beamServer.use(AuthService);\r\n this.beamServer.use(ContentService);\r\n this.beamServer.use(LeaderboardsService);\r\n this.beamServer.use(StatsService);\r\n }\r\n}\r\n"]}
|