@emmett-community/emmett-google-services-bootstrap 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,919 @@
1
+ // src/firebase/FirebaseInitializer.ts
2
+ import admin from "firebase-admin";
3
+ var normalizeContext = (data) => {
4
+ if (data === void 0 || data === null) return {};
5
+ if (typeof data === "object" && !Array.isArray(data)) {
6
+ return { ...data };
7
+ }
8
+ return { data };
9
+ };
10
+ var normalizeErrorContext = (error) => {
11
+ if (error === void 0 || error === null) return {};
12
+ if (error instanceof Error) return { err: error };
13
+ if (typeof error === "object" && !Array.isArray(error)) {
14
+ return { ...error };
15
+ }
16
+ return { err: error };
17
+ };
18
+ var safeLog = {
19
+ debug: (logger, msg, data) => {
20
+ if (!logger) return;
21
+ logger.debug(normalizeContext(data), msg);
22
+ },
23
+ info: (logger, msg, data) => {
24
+ if (!logger) return;
25
+ logger.info(normalizeContext(data), msg);
26
+ },
27
+ warn: (logger, msg, data) => {
28
+ if (!logger) return;
29
+ logger.warn(normalizeContext(data), msg);
30
+ },
31
+ error: (logger, msg, error) => {
32
+ if (!logger) return;
33
+ logger.error(normalizeErrorContext(error), msg);
34
+ }
35
+ };
36
+ var FirebaseInitializer = class {
37
+ options;
38
+ constructor(options) {
39
+ this.options = options;
40
+ }
41
+ /**
42
+ * Returns true if emulator hosts are configured.
43
+ */
44
+ isEmulatorMode() {
45
+ return Boolean(
46
+ this.options.firestoreEmulatorHost || this.options.databaseEmulatorHost || process.env.FIRESTORE_EMULATOR_HOST || process.env.FIREBASE_DATABASE_EMULATOR_HOST
47
+ );
48
+ }
49
+ /**
50
+ * Initialize Firebase Admin and return service handles.
51
+ */
52
+ async initialize() {
53
+ const {
54
+ projectId,
55
+ databaseURL,
56
+ firestoreEmulatorHost,
57
+ databaseEmulatorHost,
58
+ logger
59
+ } = this.options;
60
+ if (firestoreEmulatorHost && !process.env.FIRESTORE_EMULATOR_HOST) {
61
+ process.env.FIRESTORE_EMULATOR_HOST = firestoreEmulatorHost;
62
+ }
63
+ if (databaseEmulatorHost && !process.env.FIREBASE_DATABASE_EMULATOR_HOST) {
64
+ process.env.FIREBASE_DATABASE_EMULATOR_HOST = databaseEmulatorHost;
65
+ }
66
+ const resolvedDatabaseURL = databaseURL ?? this.getDatabaseURL(projectId, databaseEmulatorHost);
67
+ const firebaseAdmin = this.options._firebaseAdmin ?? admin;
68
+ const app = this.getOrCreateApp(firebaseAdmin, projectId, resolvedDatabaseURL);
69
+ safeLog.info(logger, "Firebase initialized", {
70
+ projectId,
71
+ databaseURL: resolvedDatabaseURL,
72
+ emulatorMode: this.isEmulatorMode()
73
+ });
74
+ const firestore = app.firestore();
75
+ const database = app.database();
76
+ const auth = app.auth();
77
+ if (firestoreEmulatorHost) {
78
+ firestore.settings({
79
+ host: firestoreEmulatorHost,
80
+ ssl: false
81
+ });
82
+ safeLog.info(logger, "Firestore emulator configured", {
83
+ host: firestoreEmulatorHost
84
+ });
85
+ }
86
+ return { app, firestore, database, auth };
87
+ }
88
+ getOrCreateApp(firebaseAdmin, projectId, databaseURL) {
89
+ const apps = (firebaseAdmin.apps ?? []).filter(
90
+ (app) => app !== null
91
+ );
92
+ if (apps.length > 0 && firebaseAdmin.app) {
93
+ safeLog.debug(this.options.logger, "Reusing existing Firebase app");
94
+ return firebaseAdmin.app();
95
+ }
96
+ safeLog.debug(this.options.logger, "Creating Firebase app");
97
+ return firebaseAdmin.initializeApp(
98
+ {
99
+ projectId,
100
+ databaseURL
101
+ }
102
+ );
103
+ }
104
+ getDatabaseURL(projectId, emulatorHost) {
105
+ if (emulatorHost) {
106
+ return `http://${emulatorHost}?ns=${projectId}`;
107
+ }
108
+ return `https://${projectId}-default-rtdb.firebaseio.com`;
109
+ }
110
+ };
111
+
112
+ // src/pubsub/PubSubInitializer.ts
113
+ import { PubSub } from "@google-cloud/pubsub";
114
+ var normalizeContext2 = (data) => {
115
+ if (data === void 0 || data === null) return {};
116
+ if (typeof data === "object" && !Array.isArray(data)) {
117
+ return { ...data };
118
+ }
119
+ return { data };
120
+ };
121
+ var normalizeErrorContext2 = (error) => {
122
+ if (error === void 0 || error === null) return {};
123
+ if (error instanceof Error) return { err: error };
124
+ if (typeof error === "object" && !Array.isArray(error)) {
125
+ return { ...error };
126
+ }
127
+ return { err: error };
128
+ };
129
+ var safeLog2 = {
130
+ debug: (logger, msg, data) => {
131
+ if (!logger) return;
132
+ logger.debug(normalizeContext2(data), msg);
133
+ },
134
+ info: (logger, msg, data) => {
135
+ if (!logger) return;
136
+ logger.info(normalizeContext2(data), msg);
137
+ },
138
+ warn: (logger, msg, data) => {
139
+ if (!logger) return;
140
+ logger.warn(normalizeContext2(data), msg);
141
+ },
142
+ error: (logger, msg, error) => {
143
+ if (!logger) return;
144
+ logger.error(normalizeErrorContext2(error), msg);
145
+ }
146
+ };
147
+ var PubSubInitializer = class {
148
+ options;
149
+ constructor(options) {
150
+ this.options = options;
151
+ }
152
+ /**
153
+ * Returns true if emulator host is configured.
154
+ */
155
+ isEmulatorMode() {
156
+ return Boolean(
157
+ this.options.emulatorHost || process.env.PUBSUB_EMULATOR_HOST
158
+ );
159
+ }
160
+ /**
161
+ * Initialize PubSub client or return injected instance.
162
+ */
163
+ async initialize() {
164
+ const { projectId, emulatorHost, logger } = this.options;
165
+ if (emulatorHost && !process.env.PUBSUB_EMULATOR_HOST) {
166
+ process.env.PUBSUB_EMULATOR_HOST = emulatorHost;
167
+ }
168
+ if (this.options._pubsub) {
169
+ safeLog2.info(logger, "Using provided PubSub client", {
170
+ projectId,
171
+ emulatorHost: emulatorHost ?? process.env.PUBSUB_EMULATOR_HOST
172
+ });
173
+ return this.options._pubsub;
174
+ }
175
+ const pubsub = new PubSub({ projectId });
176
+ safeLog2.info(logger, "PubSub initialized", {
177
+ projectId,
178
+ emulatorHost: emulatorHost ?? process.env.PUBSUB_EMULATOR_HOST,
179
+ emulatorMode: this.isEmulatorMode()
180
+ });
181
+ return pubsub;
182
+ }
183
+ };
184
+
185
+ // src/eventstore/EventStoreFactory.ts
186
+ import {
187
+ asEventStore,
188
+ getFirestoreEventStore
189
+ } from "@emmett-community/emmett-google-firestore";
190
+ import {
191
+ wireRealtimeDBProjections
192
+ } from "@emmett-community/emmett-google-realtime-db";
193
+ var createEventStore = (options) => {
194
+ const { firestore, database, projections, logger, collections } = options;
195
+ const observability = logger ? { logger } : void 0;
196
+ const baseEventStore = asEventStore(
197
+ getFirestoreEventStore(firestore, {
198
+ observability,
199
+ collections
200
+ })
201
+ );
202
+ if (projections && projections.length > 0) {
203
+ return wireRealtimeDBProjections({
204
+ eventStore: baseEventStore,
205
+ database,
206
+ projections,
207
+ observability
208
+ });
209
+ }
210
+ return baseEventStore;
211
+ };
212
+
213
+ // src/lifecycle/DependencyChecker.ts
214
+ var DependencyTimeoutError = class extends Error {
215
+ constructor(timeoutMs) {
216
+ super(`Dependency check timed out after ${timeoutMs}ms`);
217
+ this.name = "DependencyTimeoutError";
218
+ }
219
+ };
220
+ var normalizeErrorContext3 = (error) => {
221
+ if (error === void 0 || error === null) return {};
222
+ if (error instanceof Error) return { err: error };
223
+ if (typeof error === "object" && !Array.isArray(error)) {
224
+ return { ...error };
225
+ }
226
+ return { err: error };
227
+ };
228
+ var withTimeout = async (promise, timeoutMs) => {
229
+ if (!timeoutMs || timeoutMs <= 0) return promise;
230
+ let timeoutId;
231
+ const timeoutPromise = new Promise((_, reject) => {
232
+ timeoutId = setTimeout(() => {
233
+ reject(new DependencyTimeoutError(timeoutMs));
234
+ }, timeoutMs);
235
+ });
236
+ try {
237
+ return await Promise.race([promise, timeoutPromise]);
238
+ } finally {
239
+ if (timeoutId) {
240
+ clearTimeout(timeoutId);
241
+ }
242
+ }
243
+ };
244
+ var startDependency = async (dependency, startFn, options) => {
245
+ const { logger, successMessage, timeoutMs } = options ?? {};
246
+ const startTime = Date.now();
247
+ try {
248
+ await withTimeout(startFn(), timeoutMs);
249
+ logger?.info({ dependency, durationMs: Date.now() - startTime }, successMessage);
250
+ return true;
251
+ } catch (error) {
252
+ logger?.warn(
253
+ { dependency, durationMs: Date.now() - startTime, ...normalizeErrorContext3(error) },
254
+ "Unable to reach dependency"
255
+ );
256
+ return false;
257
+ }
258
+ };
259
+ var DependencyChecker = class {
260
+ logger;
261
+ defaultTimeoutMs;
262
+ constructor(options) {
263
+ this.logger = options?.logger;
264
+ this.defaultTimeoutMs = options?.defaultTimeoutMs;
265
+ }
266
+ async check(dependency) {
267
+ const start = Date.now();
268
+ const timeoutMs = dependency.timeoutMs ?? this.defaultTimeoutMs;
269
+ try {
270
+ await withTimeout(dependency.check(), timeoutMs);
271
+ if (dependency.successMessage) {
272
+ this.logger?.info(
273
+ { dependency: dependency.name, durationMs: Date.now() - start },
274
+ dependency.successMessage
275
+ );
276
+ }
277
+ return {
278
+ name: dependency.name,
279
+ ok: true,
280
+ required: dependency.required ?? true,
281
+ durationMs: Date.now() - start,
282
+ timedOut: false
283
+ };
284
+ } catch (error) {
285
+ const timedOut = error instanceof DependencyTimeoutError;
286
+ this.logger?.warn(
287
+ {
288
+ dependency: dependency.name,
289
+ durationMs: Date.now() - start,
290
+ timedOut,
291
+ ...normalizeErrorContext3(error)
292
+ },
293
+ "Dependency check failed"
294
+ );
295
+ return {
296
+ name: dependency.name,
297
+ ok: false,
298
+ required: dependency.required ?? true,
299
+ durationMs: Date.now() - start,
300
+ timedOut,
301
+ error
302
+ };
303
+ }
304
+ }
305
+ async checkAll(dependencies) {
306
+ const results = [];
307
+ for (const dependency of dependencies) {
308
+ results.push(await this.check(dependency));
309
+ }
310
+ const ok = results.every((result) => result.ok || !result.required);
311
+ return { ok, results };
312
+ }
313
+ };
314
+
315
+ // src/lifecycle/GracefulShutdown.ts
316
+ var ShutdownTimeoutError = class extends Error {
317
+ constructor(timeoutMs) {
318
+ super(`Shutdown task timed out after ${timeoutMs}ms`);
319
+ this.name = "ShutdownTimeoutError";
320
+ }
321
+ };
322
+ var normalizeContext3 = (data) => {
323
+ if (data === void 0 || data === null) return {};
324
+ if (typeof data === "object" && !Array.isArray(data)) {
325
+ return { ...data };
326
+ }
327
+ return { data };
328
+ };
329
+ var normalizeErrorContext4 = (error) => {
330
+ if (error === void 0 || error === null) return {};
331
+ if (error instanceof Error) return { err: error };
332
+ if (typeof error === "object" && !Array.isArray(error)) {
333
+ return { ...error };
334
+ }
335
+ return { err: error };
336
+ };
337
+ var withTimeout2 = async (promise, timeoutMs) => {
338
+ if (!timeoutMs || timeoutMs <= 0) return promise;
339
+ let timeoutId;
340
+ const timeoutPromise = new Promise((_, reject) => {
341
+ timeoutId = setTimeout(() => {
342
+ reject(new ShutdownTimeoutError(timeoutMs));
343
+ }, timeoutMs);
344
+ });
345
+ try {
346
+ return await Promise.race([promise, timeoutPromise]);
347
+ } finally {
348
+ if (timeoutId) {
349
+ clearTimeout(timeoutId);
350
+ }
351
+ }
352
+ };
353
+ var GracefulShutdown = class {
354
+ logger;
355
+ timeoutMs;
356
+ exitOnComplete;
357
+ exitFn;
358
+ tasks = [];
359
+ shuttingDown = false;
360
+ lastResult;
361
+ constructor(options) {
362
+ this.logger = options?.logger;
363
+ this.timeoutMs = options?.timeoutMs;
364
+ this.exitOnComplete = options?.exitOnComplete ?? false;
365
+ this.exitFn = options?.exitFn ?? process.exit;
366
+ }
367
+ /**
368
+ * Register a shutdown task.
369
+ */
370
+ register(task) {
371
+ this.tasks.push(task);
372
+ }
373
+ /**
374
+ * Register a shutdown task that runs before the ones already registered.
375
+ */
376
+ registerFirst(task) {
377
+ this.tasks.unshift(task);
378
+ }
379
+ /**
380
+ * Execute all shutdown tasks and return the aggregated result.
381
+ */
382
+ async shutdown(reason, exitCode = 1) {
383
+ if (this.shuttingDown && this.lastResult) {
384
+ return this.lastResult;
385
+ }
386
+ this.shuttingDown = true;
387
+ this.logger?.info({ reason }, "Shutting down gracefully");
388
+ const results = [];
389
+ for (const task of this.tasks) {
390
+ const start = Date.now();
391
+ const timeoutMs = task.timeoutMs ?? this.timeoutMs;
392
+ try {
393
+ await withTimeout2(task.close(), timeoutMs);
394
+ results.push({
395
+ name: task.name,
396
+ ok: true,
397
+ timedOut: false,
398
+ durationMs: Date.now() - start
399
+ });
400
+ this.logger?.info(
401
+ { task: task.name, durationMs: Date.now() - start },
402
+ "Shutdown task completed"
403
+ );
404
+ } catch (error) {
405
+ const timedOut = error instanceof ShutdownTimeoutError;
406
+ results.push({
407
+ name: task.name,
408
+ ok: false,
409
+ timedOut,
410
+ durationMs: Date.now() - start,
411
+ error
412
+ });
413
+ this.logger?.warn(
414
+ {
415
+ task: task.name,
416
+ timedOut,
417
+ durationMs: Date.now() - start,
418
+ ...normalizeErrorContext4(error)
419
+ },
420
+ "Shutdown task failed"
421
+ );
422
+ }
423
+ }
424
+ const failed = results.some((result2) => !result2.ok || result2.timedOut);
425
+ const finalExitCode = failed ? exitCode : 0;
426
+ if (failed) {
427
+ const failedTasks = results.filter((result2) => !result2.ok || result2.timedOut).map((result2) => result2.name);
428
+ this.logger?.error(
429
+ normalizeContext3({ failedTasks }),
430
+ "Shutdown completed with failures"
431
+ );
432
+ } else {
433
+ this.logger?.info({}, "Shutdown completed");
434
+ }
435
+ const result = { reason, exitCode: finalExitCode, tasks: results };
436
+ this.lastResult = result;
437
+ if (this.exitOnComplete) {
438
+ this.exitFn(finalExitCode);
439
+ }
440
+ return result;
441
+ }
442
+ };
443
+
444
+ // src/lifecycle/SignalHandlers.ts
445
+ var registerSignalHandlers = (options) => {
446
+ const signals = options.signals ?? ["SIGINT", "SIGTERM"];
447
+ const handlers = /* @__PURE__ */ new Map();
448
+ for (const signal of signals) {
449
+ const handler = () => {
450
+ options.logger?.info({ signal }, "Shutdown signal received");
451
+ void options.shutdown(`Signal ${signal} received`, options.exitCode ?? 0);
452
+ };
453
+ handlers.set(signal, handler);
454
+ process.on(signal, handler);
455
+ }
456
+ return () => {
457
+ for (const [signal, handler] of handlers.entries()) {
458
+ process.off(signal, handler);
459
+ }
460
+ };
461
+ };
462
+
463
+ // src/bootstrap/ServiceBootstrap.ts
464
+ import path from "path";
465
+ import { createLogger } from "@emmett-community/emmett-observability";
466
+ import {
467
+ createOpenApiValidatorOptions,
468
+ getApplication,
469
+ startAPI
470
+ } from "@emmett-community/emmett-expressjs-with-openapi";
471
+ import { getPubSubMessageBus } from "@emmett-community/emmett-google-pubsub";
472
+ var DependencyUnavailableError = class extends Error {
473
+ summary;
474
+ constructor(summary) {
475
+ const failed = summary.results.filter((result) => result.required && !result.ok).map((result) => result.name).join(", ");
476
+ super(`Dependency check failed: ${failed}`);
477
+ this.name = "DependencyUnavailableError";
478
+ this.summary = summary;
479
+ }
480
+ };
481
+ var READINESS_CHECK_TIMEOUT_MS = 3e3;
482
+ var resolvePath = (inputPath) => {
483
+ return path.isAbsolute(inputPath) ? inputPath : path.resolve(process.cwd(), inputPath);
484
+ };
485
+ var ServiceBootstrap = class {
486
+ config;
487
+ resolvedConfig;
488
+ logger;
489
+ context;
490
+ dependencyChecker;
491
+ shutdownManager;
492
+ constructor(config) {
493
+ this.config = config;
494
+ }
495
+ /**
496
+ * Resolve configuration with defaults and environment variables.
497
+ */
498
+ getConfig() {
499
+ return this.resolveConfig();
500
+ }
501
+ /**
502
+ * Return the initialized context if available.
503
+ */
504
+ getContext() {
505
+ return this.context;
506
+ }
507
+ /**
508
+ * Register process signal handlers that trigger shutdown.
509
+ */
510
+ registerSignalHandlers(options) {
511
+ return registerSignalHandlers({
512
+ shutdown: async (reason, exitCode) => {
513
+ await this.shutdown(reason, exitCode);
514
+ },
515
+ signals: options?.signals,
516
+ logger: this.getLogger(),
517
+ exitCode: options?.exitCode
518
+ });
519
+ }
520
+ /**
521
+ * Create an Express app using emmett-expressjs-with-openapi defaults.
522
+ */
523
+ async createApp(options) {
524
+ const logger = this.getLogger();
525
+ const openApiValidator = createOpenApiValidatorOptions(
526
+ resolvePath(options.openApiPath),
527
+ {
528
+ ...options.openApiOptions,
529
+ operationHandlers: resolvePath(options.handlersPath),
530
+ initializeHandlers: options.initializeHandlers
531
+ }
532
+ );
533
+ return getApplication({
534
+ ...options.appOptions ?? {},
535
+ openApiValidator,
536
+ observability: logger ? { logger } : void 0
537
+ });
538
+ }
539
+ /**
540
+ * Initialize, run dependency checks, create the app, and start the HTTP server.
541
+ */
542
+ async startApi(options) {
543
+ const {
544
+ port,
545
+ registerSignalHandlers: registerSignalHandlers2,
546
+ beforeStart,
547
+ initializeHandlers,
548
+ ...createAppOptions
549
+ } = options;
550
+ const logger = this.getLogger();
551
+ try {
552
+ const ctx = await this.initialize();
553
+ if (beforeStart) {
554
+ await beforeStart(ctx);
555
+ }
556
+ if (registerSignalHandlers2 !== false) {
557
+ this.registerSignalHandlers();
558
+ }
559
+ await this.start();
560
+ const app = await this.createApp({
561
+ ...createAppOptions,
562
+ initializeHandlers: (handlers) => initializeHandlers(handlers, ctx)
563
+ });
564
+ const server = startAPI(app, { port, logger });
565
+ this.getShutdownManager().registerFirst({
566
+ name: "httpServer",
567
+ close: () => new Promise((resolve, reject) => {
568
+ server.close((error) => {
569
+ if (error) {
570
+ reject(error);
571
+ return;
572
+ }
573
+ resolve();
574
+ });
575
+ })
576
+ });
577
+ logger?.info({ port: port ?? 3e3 }, "API server started");
578
+ return { app, server, context: ctx };
579
+ } catch (error) {
580
+ logger?.error({ err: error }, "Startup failed");
581
+ await this.shutdown("Startup failed");
582
+ throw error;
583
+ }
584
+ }
585
+ /**
586
+ * Initialize Firebase, PubSub, and event store wiring.
587
+ * Does not execute dependency checks.
588
+ */
589
+ async initialize() {
590
+ if (this.context) {
591
+ return this.context;
592
+ }
593
+ const resolvedConfig = this.resolveConfig();
594
+ const logger = this.getLogger();
595
+ const firebaseInitializer = new FirebaseInitializer({
596
+ projectId: resolvedConfig.firebase.projectId,
597
+ databaseURL: resolvedConfig.firebase.databaseURL,
598
+ firestoreEmulatorHost: resolvedConfig.firebase.firestoreEmulatorHost,
599
+ databaseEmulatorHost: resolvedConfig.firebase.databaseEmulatorHost,
600
+ logger,
601
+ _firebaseAdmin: resolvedConfig._testOverrides?.firebaseAdmin
602
+ });
603
+ const firebase = await firebaseInitializer.initialize();
604
+ const firestore = resolvedConfig._testOverrides?.firestore ?? firebase.firestore;
605
+ const database = resolvedConfig._testOverrides?.database ?? firebase.database;
606
+ const auth = resolvedConfig._testOverrides?.auth ?? firebase.auth;
607
+ const pubsubInitializer = new PubSubInitializer({
608
+ projectId: resolvedConfig.pubsub.projectId,
609
+ emulatorHost: resolvedConfig.pubsub.emulatorHost,
610
+ logger,
611
+ _pubsub: resolvedConfig._testOverrides?.pubsub
612
+ });
613
+ const pubsub = await pubsubInitializer.initialize();
614
+ const eventStore = resolvedConfig._testOverrides?.eventStore ?? createEventStore({
615
+ firestore,
616
+ database,
617
+ projections: resolvedConfig.projections,
618
+ collections: resolvedConfig.eventStore.collections,
619
+ logger
620
+ });
621
+ const messageBus = resolvedConfig._testOverrides?.messageBus ?? getPubSubMessageBus({
622
+ pubsub,
623
+ useEmulator: pubsubInitializer.isEmulatorMode(),
624
+ topicPrefix: resolvedConfig.pubsub.topicPrefix,
625
+ // Event subscriptions are shared by the replicas of the service and survive restarts
626
+ subscriptionId: resolvedConfig.pubsub.subscriptionId,
627
+ // Command subscriptions are shared too, so a command has one handler
628
+ instanceId: resolvedConfig.pubsub.subscriptionId,
629
+ subscriptionOptions: resolvedConfig.pubsub.subscriptionOptions,
630
+ autoCreateResources: resolvedConfig.pubsub.autoCreateResources,
631
+ cleanupOnClose: resolvedConfig.pubsub.cleanupOnClose,
632
+ closePubSubClient: resolvedConfig.pubsub.closePubSubClient,
633
+ observability: { logger }
634
+ });
635
+ this.shutdownManager = new GracefulShutdown({
636
+ ...resolvedConfig.shutdown,
637
+ logger
638
+ });
639
+ this.registerDefaultShutdownTasks({
640
+ messageBus,
641
+ firestore,
642
+ firebaseApp: firebase.app
643
+ });
644
+ this.dependencyChecker = new DependencyChecker({ logger });
645
+ this.context = {
646
+ serviceName: resolvedConfig.serviceName,
647
+ firebase: {
648
+ app: firebase.app,
649
+ firestore,
650
+ database,
651
+ auth
652
+ },
653
+ firestore,
654
+ database,
655
+ auth,
656
+ pubsub,
657
+ eventStore,
658
+ messageBus,
659
+ logger,
660
+ getCurrentTime: resolvedConfig.getCurrentTime,
661
+ config: resolvedConfig,
662
+ checkReadiness: () => this.checkReadiness()
663
+ };
664
+ return this.context;
665
+ }
666
+ /**
667
+ * Initialize and run dependency checks before returning context.
668
+ */
669
+ async start() {
670
+ const ctx = await this.initialize();
671
+ const resolvedConfig = this.resolveConfig();
672
+ const checks = [];
673
+ if (resolvedConfig.includeDefaultDependencyChecks) {
674
+ checks.push(...this.buildDefaultDependencyChecks(ctx));
675
+ }
676
+ if (resolvedConfig.dependencies.length > 0) {
677
+ checks.push(...resolvedConfig.dependencies);
678
+ }
679
+ if (checks.length > 0) {
680
+ const summary = await this.getDependencyChecker().checkAll(checks);
681
+ if (!summary.ok) {
682
+ const error = new DependencyUnavailableError(summary);
683
+ this.logger?.error(
684
+ {
685
+ err: error,
686
+ results: summary.results
687
+ },
688
+ "Dependency checks failed"
689
+ );
690
+ if (resolvedConfig.shutdownOnDependencyFailure) {
691
+ await this.shutdown("Dependency check failed");
692
+ }
693
+ throw error;
694
+ }
695
+ }
696
+ this.logger?.info(
697
+ { serviceName: resolvedConfig.serviceName },
698
+ "Service is running"
699
+ );
700
+ return ctx;
701
+ }
702
+ /**
703
+ * Run the readiness checks: the stores and the message bus must answer, plus the configured
704
+ * dependencies. A hung dependency fails the check instead of hanging the probe.
705
+ */
706
+ async checkReadiness() {
707
+ const ctx = await this.initialize();
708
+ const resolvedConfig = this.resolveConfig();
709
+ const checks = [];
710
+ if (resolvedConfig.includeDefaultDependencyChecks) {
711
+ checks.push(...this.buildStoreDependencyChecks(ctx));
712
+ if (resolvedConfig.autoStartMessageBus) {
713
+ checks.push({
714
+ name: "PubSub",
715
+ check: async () => {
716
+ if (!ctx.messageBus.isStarted?.()) {
717
+ throw new Error("Message bus is not started");
718
+ }
719
+ }
720
+ });
721
+ }
722
+ }
723
+ checks.push(...resolvedConfig.dependencies);
724
+ return this.getDependencyChecker().checkAll(
725
+ checks.map((check) => ({
726
+ ...check,
727
+ timeoutMs: check.timeoutMs ?? READINESS_CHECK_TIMEOUT_MS
728
+ }))
729
+ );
730
+ }
731
+ /**
732
+ * Execute graceful shutdown tasks and return the shutdown result.
733
+ */
734
+ async shutdown(reason, exitCode = 1) {
735
+ return this.getShutdownManager().shutdown(reason, exitCode);
736
+ }
737
+ getLogger() {
738
+ if (this.logger !== void 0) {
739
+ return this.logger;
740
+ }
741
+ const resolvedConfig = this.resolveConfig();
742
+ const observability = resolvedConfig.observability;
743
+ if (observability.logger) {
744
+ this.logger = observability.logger;
745
+ return this.logger;
746
+ }
747
+ if (observability.createLogger === false) {
748
+ this.logger = void 0;
749
+ return this.logger;
750
+ }
751
+ this.logger = createLogger({
752
+ serviceName: resolvedConfig.serviceName,
753
+ environment: observability.environment,
754
+ logLevel: observability.logLevel
755
+ });
756
+ return this.logger;
757
+ }
758
+ resolveConfig() {
759
+ if (this.resolvedConfig) {
760
+ return this.resolvedConfig;
761
+ }
762
+ const missing = [];
763
+ const serviceName = this.config.serviceName?.trim();
764
+ if (!serviceName) {
765
+ missing.push("serviceName");
766
+ }
767
+ const firestoreEmulatorHost = this.config.firebase?.firestoreEmulatorHost ?? process.env.FIRESTORE_EMULATOR_HOST;
768
+ const databaseEmulatorHost = this.config.firebase?.databaseEmulatorHost ?? process.env.FIREBASE_DATABASE_EMULATOR_HOST;
769
+ const pubsubEmulatorHost = this.config.pubsub?.emulatorHost ?? process.env.PUBSUB_EMULATOR_HOST;
770
+ const hasEmulator = Boolean(firestoreEmulatorHost) || Boolean(databaseEmulatorHost) || Boolean(pubsubEmulatorHost);
771
+ const firebaseProjectId = this.config.firebase?.projectId ?? process.env.FIRESTORE_PROJECT_ID ?? process.env.GCLOUD_PROJECT ?? process.env.GOOGLE_CLOUD_PROJECT ?? (hasEmulator ? "demo-project" : void 0);
772
+ if (!firebaseProjectId) {
773
+ missing.push("firebase.projectId (or FIRESTORE_PROJECT_ID)");
774
+ }
775
+ const pubsubProjectId = this.config.pubsub?.projectId ?? process.env.PUBSUB_PROJECT_ID ?? firebaseProjectId ?? (hasEmulator ? "demo-project" : void 0);
776
+ if (!pubsubProjectId) {
777
+ missing.push("pubsub.projectId (or PUBSUB_PROJECT_ID)");
778
+ }
779
+ if (missing.length > 0) {
780
+ throw new Error(`Missing required configuration: ${missing.join(", ")}`);
781
+ }
782
+ const resolvedServiceName = serviceName;
783
+ const resolvedFirebaseProjectId = firebaseProjectId;
784
+ const resolvedPubsubProjectId = pubsubProjectId;
785
+ const databaseURL = this.config.firebase?.databaseURL ?? this.getDatabaseURL(resolvedFirebaseProjectId, databaseEmulatorHost);
786
+ const observability = {
787
+ ...this.config.observability,
788
+ environment: this.config.observability?.environment ?? process.env.NODE_ENV,
789
+ logLevel: this.config.observability?.logLevel ?? process.env.LOG_LEVEL,
790
+ createLogger: this.config.observability?.createLogger ?? true
791
+ };
792
+ const getCurrentTime = this.config.getCurrentTime ?? (() => /* @__PURE__ */ new Date());
793
+ this.resolvedConfig = {
794
+ serviceName: resolvedServiceName,
795
+ firebase: {
796
+ projectId: resolvedFirebaseProjectId,
797
+ databaseURL,
798
+ firestoreEmulatorHost,
799
+ databaseEmulatorHost
800
+ },
801
+ pubsub: {
802
+ projectId: resolvedPubsubProjectId,
803
+ emulatorHost: pubsubEmulatorHost,
804
+ topicPrefix: this.config.pubsub?.topicPrefix ?? process.env.PUBSUB_TOPIC_PREFIX ?? resolvedServiceName,
805
+ subscriptionId: this.config.pubsub?.subscriptionId ?? resolvedServiceName,
806
+ subscriptionOptions: this.config.pubsub?.subscriptionOptions,
807
+ autoCreateResources: this.config.pubsub?.autoCreateResources ?? true,
808
+ cleanupOnClose: this.config.pubsub?.cleanupOnClose ?? false,
809
+ closePubSubClient: this.config.pubsub?.closePubSubClient ?? true
810
+ },
811
+ observability,
812
+ projections: this.config.projections ?? [],
813
+ getCurrentTime,
814
+ dependencies: this.config.dependencies ?? [],
815
+ includeDefaultDependencyChecks: this.config.includeDefaultDependencyChecks ?? true,
816
+ includeRealtimeDatabaseCheck: this.config.includeRealtimeDatabaseCheck ?? true,
817
+ autoStartMessageBus: this.config.autoStartMessageBus ?? true,
818
+ shutdownOnDependencyFailure: this.config.shutdownOnDependencyFailure ?? true,
819
+ shutdown: {
820
+ timeoutMs: this.config.shutdown?.timeoutMs ?? 3e4,
821
+ exitOnComplete: this.config.shutdown?.exitOnComplete ?? false,
822
+ exitFn: this.config.shutdown?.exitFn
823
+ },
824
+ eventStore: {
825
+ collections: this.config.eventStore?.collections
826
+ },
827
+ _testOverrides: this.config._testOverrides
828
+ };
829
+ return this.resolvedConfig;
830
+ }
831
+ getDatabaseURL(projectId, emulatorHost) {
832
+ if (emulatorHost) {
833
+ return `http://${emulatorHost}?ns=${projectId}`;
834
+ }
835
+ return `https://${projectId}-default-rtdb.firebaseio.com`;
836
+ }
837
+ getDependencyChecker() {
838
+ if (!this.dependencyChecker) {
839
+ this.dependencyChecker = new DependencyChecker({ logger: this.getLogger() });
840
+ }
841
+ return this.dependencyChecker;
842
+ }
843
+ getShutdownManager() {
844
+ if (!this.shutdownManager) {
845
+ this.shutdownManager = new GracefulShutdown({
846
+ ...this.resolveConfig().shutdown,
847
+ logger: this.getLogger()
848
+ });
849
+ }
850
+ return this.shutdownManager;
851
+ }
852
+ registerDefaultShutdownTasks(options) {
853
+ const shutdownManager = this.getShutdownManager();
854
+ if (options.messageBus?.close) {
855
+ shutdownManager.register({
856
+ name: "messageBus",
857
+ close: () => options.messageBus.close()
858
+ });
859
+ }
860
+ if (typeof options.firestore.terminate === "function") {
861
+ shutdownManager.register({
862
+ name: "firestore",
863
+ close: () => options.firestore.terminate()
864
+ });
865
+ }
866
+ if (typeof options.firebaseApp.delete === "function") {
867
+ shutdownManager.register({
868
+ name: "firebaseApp",
869
+ close: () => options.firebaseApp.delete()
870
+ });
871
+ }
872
+ }
873
+ buildDefaultDependencyChecks(ctx) {
874
+ const checks = [];
875
+ if (this.resolveConfig().autoStartMessageBus) {
876
+ checks.push({
877
+ name: "PubSub",
878
+ check: () => ctx.messageBus.start(),
879
+ successMessage: "Message bus started"
880
+ });
881
+ }
882
+ checks.push(...this.buildStoreDependencyChecks(ctx));
883
+ return checks;
884
+ }
885
+ buildStoreDependencyChecks(ctx) {
886
+ const checks = [
887
+ {
888
+ name: "Firestore",
889
+ check: async () => {
890
+ await ctx.firestore.collection("_healthcheck").limit(1).get();
891
+ }
892
+ }
893
+ ];
894
+ if (this.resolveConfig().includeRealtimeDatabaseCheck) {
895
+ checks.push({
896
+ name: "Realtime Database",
897
+ check: async () => {
898
+ await ctx.database.ref("_healthcheck/connection").once("value");
899
+ }
900
+ });
901
+ }
902
+ return checks;
903
+ }
904
+ };
905
+
906
+ export {
907
+ FirebaseInitializer,
908
+ PubSubInitializer,
909
+ createEventStore,
910
+ DependencyTimeoutError,
911
+ startDependency,
912
+ DependencyChecker,
913
+ ShutdownTimeoutError,
914
+ GracefulShutdown,
915
+ registerSignalHandlers,
916
+ DependencyUnavailableError,
917
+ ServiceBootstrap
918
+ };
919
+ //# sourceMappingURL=chunk-XUV26TX4.js.map