@@ -7,18 +7,15 @@ import {
7
7
} from '@powersync/common' ;
8
8
import * as Comlink from 'comlink' ;
9
9
import { AbstractSharedSyncClientProvider } from '../../worker/sync/AbstractSharedSyncClientProvider' ;
10
- import {
11
- ManualSharedSyncPayload ,
12
- SharedSyncClientEvent ,
13
- SharedSyncImplementation
14
- } from '../../worker/sync/SharedSyncImplementation' ;
10
+ import { ManualSharedSyncPayload , SharedSyncClientEvent } from '../../worker/sync/SharedSyncImplementation' ;
15
11
import { DEFAULT_CACHE_SIZE_KB , resolveWebSQLFlags , TemporaryStorageOption } from '../adapters/web-sql-flags' ;
16
12
import { WebDBAdapter } from '../adapters/WebDBAdapter' ;
17
13
import {
18
14
WebStreamingSyncImplementation ,
19
15
WebStreamingSyncImplementationOptions
20
16
} from './WebStreamingSyncImplementation' ;
21
17
import { WorkerClient } from '../../worker/sync/WorkerClient' ;
18
+ import { getNavigatorLocks } from '../../shared/navigator' ;
22
19
23
20
/**
24
21
* The shared worker will trigger methods on this side of the message port
@@ -111,6 +108,7 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
111
108
112
109
protected isInitialized : Promise < void > ;
113
110
protected dbAdapter : WebDBAdapter ;
111
+ private abortOnClose = new AbortController ( ) ;
114
112
115
113
constructor ( options : SharedWebStreamingSyncImplementationOptions ) {
116
114
super ( options ) ;
@@ -192,6 +190,19 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
192
190
* This performs bi-directional method calling.
193
191
*/
194
192
Comlink . expose ( this . clientProvider , this . messagePort ) ;
193
+
194
+ // Request a random lock until this client is disposed. The name of the lock is sent to the shared worker, which
195
+ // will also attempt to acquire it. Since the lock is returned when the tab is closed, this allows the share worker
196
+ // to free resources associated with this tab.
197
+ getNavigatorLocks ( ) . request ( `tab-close-signal-${ crypto . randomUUID ( ) } ` , async ( lock ) => {
198
+ if ( ! this . abortOnClose . signal . aborted ) {
199
+ this . syncManager . addLockBasedCloseSignal ( lock ! . name ) ;
200
+
201
+ await new Promise < void > ( ( r ) => {
202
+ this . abortOnClose . signal . onabort = ( ) => r ( ) ;
203
+ } ) ;
204
+ }
205
+ } ) ;
195
206
}
196
207
197
208
/**
@@ -238,6 +249,7 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
238
249
} ;
239
250
this . messagePort . postMessage ( closeMessagePayload ) ;
240
251
} ) ;
252
+ this . abortOnClose . abort ( ) ;
241
253
242
254
// Release the proxy
243
255
this . syncManager [ Comlink . releaseProxy ] ( ) ;
0 commit comments