Skip to content
Draft
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
e61059a
No longer awaiting when aborting connection on tab closure. Fixes som…
Chriztiaan Nov 26, 2025
a12145f
fix opfs deadlocks
stevensJourney Nov 27, 2025
b4f5c1b
Add multiple tabs test
stevensJourney Nov 27, 2025
355e396
enable headless
stevensJourney Nov 27, 2025
c6ba9f6
reenable browsers
stevensJourney Nov 27, 2025
9730337
cleanup tests
stevensJourney Nov 27, 2025
58f412b
Merge branch 'dead-tab-detection' into fix/opfs-multitab-issue
stevensJourney Nov 27, 2025
8721538
Add default lock timeout for shared sync workers. Add flagging for u…
stevensJourney Nov 28, 2025
feca863
fix broken test
stevensJourney Nov 28, 2025
b0dd596
cleanup tests
stevensJourney Nov 28, 2025
de7804f
restore collectActiveSubscriptions
stevensJourney Nov 28, 2025
c08e664
cleanup code flow
stevensJourney Nov 28, 2025
aedc855
Add withTimeout for opening db connections
stevensJourney Nov 28, 2025
62b04de
reduce number of iframes for CI
stevensJourney Nov 28, 2025
0fc0d73
Use a distributed database adapter instead of reconnecting. Retry ope…
stevensJourney Nov 28, 2025
91db686
Catch closed errors for hold requests. Use crud throttle time for cru…
stevensJourney Nov 28, 2025
deaf83c
Synchronize lock requests better.
stevensJourney Nov 28, 2025
3780223
Re-open database as soon as it's closed. Trigger uploads if database …
stevensJourney Nov 29, 2025
8f95e10
Update tabs test to be more indicative of the actual issues.
stevensJourney Nov 29, 2025
1e880d6
Add mocked sync tests for shared webworkers
stevensJourney Dec 1, 2025
da53396
Update tests for shared web workers
stevensJourney Dec 1, 2025
28472e3
Add automatic responses or mocked sync service.
stevensJourney Dec 1, 2025
11b7a36
Update more tests to use mocked sync service
stevensJourney Dec 1, 2025
7e7ec91
increase timeout for ci
stevensJourney Dec 1, 2025
1e9fa3f
Improve test stability
stevensJourney Dec 1, 2025
07231cb
cleanup port assignments and init flow
stevensJourney Dec 1, 2025
cbfb683
cleanup test code
stevensJourney Dec 1, 2025
f881992
Listen for database close events to catch closed items earlier.
stevensJourney Dec 1, 2025
ffe5abe
Fire and forget close operations.
stevensJourney Dec 1, 2025
58d9194
Common changeset.
Chriztiaan Dec 1, 2025
1ef44a3
Try and catch Accesshandle errors. Fork OPFSCoopSyncVFS for potential…
stevensJourney Dec 2, 2025
d73d9d2
Cleanup aborted operations if aborted. Try and gracefully handle Acce…
stevensJourney Dec 2, 2025
a1fd0bb
cleanup
stevensJourney Dec 2, 2025
445ec69
add a finalization registry entry to release access handles
stevensJourney Dec 2, 2025
6630097
Wrap entire open operation init in writeLock.
stevensJourney Dec 3, 2025
bbfdcf7
revert opfs test
stevensJourney Dec 3, 2025
8cfc0e6
update wa-sqlite
stevensJourney Dec 3, 2025
abdec98
Update changesets
stevensJourney Dec 3, 2025
9cadf24
try stabilize test
stevensJourney Dec 3, 2025
4a12be8
increase timeouts
stevensJourney Dec 3, 2025
eb88fde
cleanup any opened access handles if an error is caught.
stevensJourney Dec 3, 2025
423e4e4
cleanup tests structure
stevensJourney Dec 3, 2025
59b9ce9
remove dev logs
stevensJourney Dec 3, 2025
23ae289
fix types
stevensJourney Dec 3, 2025
4108c8e
Changesets for Drizzle/Kysely.
Chriztiaan Dec 3, 2025
cf14827
use latest dev packages
stevensJourney Dec 4, 2025
0f1cb7c
Code cleanup. make minor bump.
stevensJourney Dec 4, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rare-windows-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/web': patch
---

No longer awaiting when aborting connection on tab closure. Fixes some edge cases where multiple tabs with OPFS/Safari can cause deadlocks.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { AppSchema, ListRecord, LISTS_TABLE, TODOS_TABLE } from '@/library/power
import { SupabaseConnector } from '@/library/powersync/SupabaseConnector';
import { CircularProgress } from '@mui/material';
import { PowerSyncContext } from '@powersync/react';
import { createBaseLogger, DifferentialWatchedQuery, LogLevel, PowerSyncDatabase } from '@powersync/web';
import {
createBaseLogger,
DifferentialWatchedQuery,
LogLevel,
PowerSyncDatabase,
WASQLiteOpenFactory,
WASQLiteVFS
} from '@powersync/web';
import React, { Suspense } from 'react';
import { NavigationPanelContextProvider } from '../navigation/NavigationPanelContext';

Expand All @@ -12,8 +19,15 @@ export const useSupabase = () => React.useContext(SupabaseContext);

export const db = new PowerSyncDatabase({
schema: AppSchema,
database: {
dbFilename: 'example.db'
database: new WASQLiteOpenFactory({
dbFilename: 'example.db',
vfs: WASQLiteVFS.OPFSCoopSyncVFS,
flags: {
enableMultiTabs: typeof SharedWorker !== 'undefined'
}
}),
flags: {
enableMultiTabs: typeof SharedWorker !== 'undefined'
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { CrudEntry } from '../bucket/CrudEntry.js';
import { SyncDataBucket } from '../bucket/SyncDataBucket.js';
import { AbstractRemote, FetchStrategy, SyncStreamOptions } from './AbstractRemote.js';
import { coreStatusToJs, EstablishSyncStream, Instruction, SyncPriorityStatus } from './core-instruction.js';
import { EstablishSyncStream, Instruction, coreStatusToJs } from './core-instruction.js';
import {
BucketRequest,
CrudUploadNotification,
Expand Down
5 changes: 3 additions & 2 deletions packages/web/src/db/adapters/LockedAsyncDatabaseAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface LockedAsyncDatabaseAdapterOptions {
openConnection: () => Promise<AsyncDatabaseConnection>;
debugMode?: boolean;
logger?: ILogger;
defaultLockTimeoutMs?: number;
}

export type LockedAsyncDatabaseAdapterListener = DBAdapterListener & {
Expand Down Expand Up @@ -196,7 +197,7 @@ export class LockedAsyncDatabaseAdapter
return this.acquireLock(
async () => fn(this.generateDBHelpers({ execute: this._execute, executeRaw: this._executeRaw })),
{
timeoutMs: options?.timeoutMs
timeoutMs: options?.timeoutMs ?? this.options.defaultLockTimeoutMs
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The timeouts here are meant to help expose potentially held locks. E.g. in the past we've seen some DBAdapters created in the shared sync worker - which were not completely closed - could hold on to a lock indefinitely.
Without a timeout it just seems like the whole process is stuck. With a timeout, we'll at least get some indication of this.

}
);
}
Expand All @@ -206,7 +207,7 @@ export class LockedAsyncDatabaseAdapter
return this.acquireLock(
async () => fn(this.generateDBHelpers({ execute: this._execute, executeRaw: this._executeRaw })),
{
timeoutMs: options?.timeoutMs
timeoutMs: options?.timeoutMs ?? this.options.defaultLockTimeoutMs
}
);
}
Expand Down
96 changes: 60 additions & 36 deletions packages/web/src/db/sync/SharedWebStreamingSyncImplementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ import {
SyncStatusOptions
} from '@powersync/common';
import * as Comlink from 'comlink';
import { getNavigatorLocks } from '../../shared/navigator';
import { AbstractSharedSyncClientProvider } from '../../worker/sync/AbstractSharedSyncClientProvider';
import { ManualSharedSyncPayload, SharedSyncClientEvent } from '../../worker/sync/SharedSyncImplementation';
import { DEFAULT_CACHE_SIZE_KB, resolveWebSQLFlags, TemporaryStorageOption } from '../adapters/web-sql-flags';
import { WorkerClient } from '../../worker/sync/WorkerClient';
import { WebDBAdapter } from '../adapters/WebDBAdapter';
import { DEFAULT_CACHE_SIZE_KB, TemporaryStorageOption, resolveWebSQLFlags } from '../adapters/web-sql-flags';
import {
WebStreamingSyncImplementation,
WebStreamingSyncImplementationOptions
} from './WebStreamingSyncImplementation';
import { WorkerClient } from '../../worker/sync/WorkerClient';
import { getNavigatorLocks } from '../../shared/navigator';

/**
* The shared worker will trigger methods on this side of the message port
Expand Down Expand Up @@ -146,7 +146,25 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
).port;
}

/**
* Pass along any sync status updates to this listener
*/
this.clientProvider = new SharedSyncClientProvider(
this.webOptions,
(status) => {
this.updateSyncStatus(status);
},
options.db
);

this.syncManager = Comlink.wrap<WorkerClient>(this.messagePort);
/**
* The sync worker will call this client provider when it needs
* to fetch credentials or upload data.
* This performs bi-directional method calling.
*/
Comlink.expose(this.clientProvider, this.messagePort);

this.syncManager.setLogLevel(this.logger.getLevel());

this.triggerCrudUpload = this.syncManager.triggerCrudUpload;
Expand All @@ -157,10 +175,47 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
* DB worker, but a port to the DB worker can be transferred to the
* sync worker.
*/

this.isInitialized = this._init();
}

protected async _init() {
/**
* The general flow of initialization is:
* - The client requests a unique navigator lock.
* - Once the lock is acquired, we register the lock with the shared worker.
* - The shared worker can then request the same lock. The client has been closed if the shared worker can acquire the lock.
* - Once the shared worker knows the client's lock, we can guarentee that the shared worker will detect if the client has been closed.
* - This makes the client safe for the shared worker to use.
* - The client side lock is held until the client is disposed.
* - We resolve the top-level promise after the lock has been registered with the shared worker.
* - The client sends the params to the shared worker after locks have been registered.
*/
await new Promise<void>((resolve) => {
// Request a random lock until this client is disposed. The name of the lock is sent to the shared worker, which
// will also attempt to acquire it. Since the lock is returned when the tab is closed, this allows the share worker
// to free resources associated with this tab.
// We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.
getNavigatorLocks().request(`tab-close-signal-${crypto.randomUUID()}`, async (lock) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The initialisation flow here is meant to assist the Shared Sync worker to only use clients which have a navigator-lock based close detection established. We don't want to use clients which might have been registered, but closed before the lock has been configured.

if (this.abortOnClose.signal.aborted) {
return;
}
// Awaiting here ensures the worker is waiting for the lock
await this.syncManager.addLockBasedCloseSignal(lock!.name);

// The lock has been registered, we can continue with the initialization
resolve();

await new Promise<void>((r) => {
this.abortOnClose.signal.onabort = () => r();
});
});
});

const { crudUploadThrottleMs, identifier, retryDelayMs } = this.options;
const flags = { ...this.webOptions.flags, workers: undefined };

this.isInitialized = this.syncManager.setParams(
await this.syncManager.setParams(
{
dbParams: this.dbAdapter.getConfiguration(),
streamOptions: {
Expand All @@ -170,39 +225,8 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
flags: flags
}
},
options.subscriptions
);

/**
* Pass along any sync status updates to this listener
*/
this.clientProvider = new SharedSyncClientProvider(
this.webOptions,
(status) => {
this.iterateListeners((l) => this.updateSyncStatus(status));
},
options.db
this.options.subscriptions
);

/**
* The sync worker will call this client provider when it needs
* to fetch credentials or upload data.
* This performs bi-directional method calling.
*/
Comlink.expose(this.clientProvider, this.messagePort);

// Request a random lock until this client is disposed. The name of the lock is sent to the shared worker, which
// will also attempt to acquire it. Since the lock is returned when the tab is closed, this allows the share worker
// to free resources associated with this tab.
getNavigatorLocks().request(`tab-close-signal-${crypto.randomUUID()}`, async (lock) => {
if (!this.abortOnClose.signal.aborted) {
this.syncManager.addLockBasedCloseSignal(lock!.name);

await new Promise<void>((r) => {
this.abortOnClose.signal.onabort = () => r();
});
}
});
}

/**
Expand Down
Loading
Loading