Skip to content

Shared worker: Release mutex when tab closes #98

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 7 additions & 0 deletions packages/sqlite_async/build.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
targets:
$default:
builders:
build_web_compilers:entrypoint:
options:
# Workers can't be compiled with dartdevc, so use dart2js for the example
compiler: dart2js
29 changes: 29 additions & 0 deletions packages/sqlite_async/example/web/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8">
<title>sqlite_async web demo</title>
<script defer src="main.dart.js"></script>
</head>

<body>

<h1>sqlite_async demo</h1>

<main>
This page is used to test the sqlite_async package on the web.
Use the console to open and interact with databases.

<pre>
<code>
const db = await open('test.db');
const lock = await write_lock(db);
release_lock(lock);
</code>
</pre>
</main>


</body>
</html>
41 changes: 41 additions & 0 deletions packages/sqlite_async/example/web/main.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'dart:async';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';

import 'package:sqlite_async/sqlite_async.dart';

void main() {
globalContext['open'] = (String path) {
return Future(() async {
final db = SqliteDatabase(
path: path,
options: SqliteOptions(
webSqliteOptions: WebSqliteOptions(
wasmUri:
'https://cdn.jsdelivr.net/npm/@powersync/dart-wasm-bundles@latest/dist/sqlite3.wasm',
workerUri: 'worker.dart.js',
),
),
);
await db.initialize();
return db.toJSBox;
}).toJS;
}.toJS;

globalContext['write_lock'] = (JSBoxedDartObject db) {
final hasLock = Completer<void>();
final completer = Completer<void>();

(db.toDart as SqliteDatabase).writeLock((_) async {
print('has write lock!');
hasLock.complete();
await completer.future;
});

return hasLock.future.then((_) => completer.toJSBox).toJS;
}.toJS;

globalContext['release_lock'] = (JSBoxedDartObject db) {
(db.toDart as Completer<void>).complete();
}.toJS;
}
6 changes: 6 additions & 0 deletions packages/sqlite_async/example/web/worker.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import 'package:sqlite_async/sqlite3_web.dart';
import 'package:sqlite_async/sqlite3_web_worker.dart';

void main() {
WebSqlite.workerEntrypoint(controller: AsyncSqliteController());
}
26 changes: 26 additions & 0 deletions packages/sqlite_async/lib/src/web/worker/worker_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,27 @@ class AsyncSqliteDatabase extends WorkerDatabase {
// these requests for shared workers, so we can assume each database is only
// opened once and we don't need web locks here.
final mutex = ReadWriteMutex();
final Map<ClientConnection, _ConnectionState> _state = {};

AsyncSqliteDatabase({required this.database});

_ConnectionState _findState(ClientConnection connection) {
return _state.putIfAbsent(connection, _ConnectionState.new);
}

void _markHoldsMutex(ClientConnection connection) {
final state = _findState(connection);
state.holdsMutex = true;
if (!state.hasOnCloseListener) {
state.hasOnCloseListener = true;
connection.closed.then((_) {
if (state.holdsMutex) {
mutex.release();
}
});
}
}

@override
Future<JSAny?> handleCustomRequest(
ClientConnection connection, JSAny? request) async {
Expand All @@ -67,9 +85,12 @@ class AsyncSqliteDatabase extends WorkerDatabase {
switch (message.kind) {
case CustomDatabaseMessageKind.requestSharedLock:
await mutex.acquireRead();
_markHoldsMutex(connection);
case CustomDatabaseMessageKind.requestExclusiveLock:
await mutex.acquireWrite();
_markHoldsMutex(connection);
case CustomDatabaseMessageKind.releaseLock:
_findState(connection).holdsMutex = false;
mutex.release();
case CustomDatabaseMessageKind.lockObtained:
throw UnsupportedError('This is a response, not a request');
Expand Down Expand Up @@ -123,3 +144,8 @@ class AsyncSqliteDatabase extends WorkerDatabase {
return resultSetMap;
}
}

final class _ConnectionState {
bool hasOnCloseListener = false;
bool holdsMutex = false;
}