11import * as lib_mongo from '@powersync/lib-service-mongodb' ;
2- import { logger , ServiceAssertionError } from '@powersync/lib-services-framework' ;
2+ import { ErrorCode , logger , ServiceAssertionError , ServiceError } from '@powersync/lib-services-framework' ;
33import { storage } from '@powersync/service-core' ;
44import { MongoStorageConfig } from '../../types/types.js' ;
55import { MongoBucketStorage } from '../MongoBucketStorage.js' ;
@@ -26,6 +26,15 @@ export class MongoStorageProvider implements storage.BucketStorageProvider {
2626 maxPoolSize : resolvedConfig . storage . max_pool_size ?? 8
2727 } ) ;
2828
29+ let shuttingDown = false ;
30+
31+ // Explicitly connect on startup.
32+ // Connection errors during startup are typically not recoverable - we get topologyClosed.
33+ // This helps to catch the error early, along with the cause, and before the process starts
34+ // to serve API requests.
35+ // Errors here will cause the process to exit.
36+ await client . connect ( ) ;
37+
2938 const database = new PowerSyncMongo ( client , { database : resolvedConfig . storage . database } ) ;
3039 const factory = new MongoBucketStorage ( database , {
3140 // TODO currently need the entire resolved config due to this
@@ -34,12 +43,29 @@ export class MongoStorageProvider implements storage.BucketStorageProvider {
3443 return {
3544 storage : factory ,
3645 shutDown : async ( ) => {
46+ shuttingDown = true ;
3747 await factory [ Symbol . asyncDispose ] ( ) ;
3848 await client . close ( ) ;
3949 } ,
4050 tearDown : ( ) => {
4151 logger . info ( `Tearing down storage: ${ database . db . namespace } ...` ) ;
4252 return database . db . dropDatabase ( ) ;
53+ } ,
54+ onFatalError : ( callback ) => {
55+ client . addListener ( 'topologyClosed' , ( ) => {
56+ // If we're shutting down, this is expected and we can ignore it.
57+ if ( ! shuttingDown ) {
58+ // Unfortunately there is no simple way to catch the cause of this issue.
59+ // It most commonly happens when the process fails to _ever_ connect - connection issues after
60+ // the initial connection are usually recoverable.
61+ callback (
62+ new ServiceError ( {
63+ code : ErrorCode . PSYNC_S2402 ,
64+ description : 'MongoDB topology closed - failed to connect to MongoDB storage.'
65+ } )
66+ ) ;
67+ }
68+ } ) ;
4369 }
4470 } satisfies storage . ActiveStorage ;
4571 }
0 commit comments