@@ -151,13 +151,15 @@ export class LockedAsyncDatabaseAdapter
151151 * Returns a pending operation if one is already in progress.
152152 */
153153 async reOpenInternalDB ( ) : Promise < void > {
154- if ( ! this . options . reOpenOnConnectionClosed ) {
155- throw new Error ( `Cannot re-open underlying database, reOpenOnConnectionClosed is not enabled` ) ;
156- }
157- if ( this . databaseOpenPromise ) {
154+ if ( this . closing || ! this . options . reOpenOnConnectionClosed ) {
155+ // No-op
156+ return ;
157+ } else if ( this . databaseOpenPromise ) {
158+ // Already busy opening
158159 return this . databaseOpenPromise ;
160+ } else {
161+ return this . _reOpen ( ) ;
159162 }
160- return this . _reOpen ( ) ;
161163 }
162164
163165 protected async _init ( ) {
@@ -317,9 +319,17 @@ export class LockedAsyncDatabaseAdapter
317319 protected async acquireLock ( callback : ( ) => Promise < any > , options ?: { timeoutMs ?: number } ) : Promise < any > {
318320 await this . waitForInitialized ( ) ;
319321
320- // The database is being opened in the background. Wait for it here.
322+ // The database is being (re) opened in the background. Wait for it here.
321323 if ( this . databaseOpenPromise ) {
322324 await this . databaseOpenPromise ;
325+ } else if ( ! this . _db ) {
326+ /**
327+ * The database is not open anymore, we might need to re-open it.
328+ * Typically, _db, can be `null` if we tried to reOpen the database, but failed to succeed in re-opening.
329+ * This can happen when disconnecting the client.
330+ * Note: It is safe to re-enter this method multiple times.
331+ */
332+ await this . reOpenInternalDB ( ) ;
323333 }
324334
325335 return this . _acquireLock ( async ( ) => {
@@ -339,11 +349,9 @@ export class LockedAsyncDatabaseAdapter
339349 return await callback ( ) ;
340350 } catch ( ex ) {
341351 if ( ConnectionClosedError . MATCHES ( ex ) ) {
342- if ( this . options . reOpenOnConnectionClosed && ! this . databaseOpenPromise && ! this . closing ) {
343- // Immediately re-open the database. We need to miss as little table updates as possible.
344- // Note, don't await this since it uses the same lock as we're in now.
345- this . reOpenInternalDB ( ) ;
346- }
352+ // Immediately re-open the database. We need to miss as little table updates as possible.
353+ // Note, don't await this since it uses the same lock as we're in now.
354+ this . reOpenInternalDB ( ) ;
347355 }
348356 throw ex ;
349357 } finally {
0 commit comments