@tearleads/client-sdk 0.1.262 → 0.1.263

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,7 +9,7 @@ behavior into the SDK rather than duplicate its setup.
9
9
  | Entry point | Use for |
10
10
  | --- | --- |
11
11
  | `@tearleads/client-sdk` | `Tearleads`, SDK service types, local keyring helpers, document contracts, sync diagnostics, stores, purchase capabilities, and public workflow symbols |
12
- | `@tearleads/client-sdk/sqlite` | SQLite worker runtime factory, executor contracts, and adapter helpers |
12
+ | `@tearleads/client-sdk/sqlite` | SQLite worker runtime factory, executor contracts, the lost-connection error (`DatabaseConnectionLostError`, `isDatabaseConnectionLostError`), and adapter helpers |
13
13
  | `@tearleads/client-sdk/sqlite/worker.js` | The SQLite worker module to serve |
14
14
  | `@tearleads/client-sdk/sqlite/sqlite3.wasm` | The SQLite WebAssembly to serve beside `worker.js` |
15
15
  | `@tearleads/client-sdk/sqlite/sqlite3-licenses.md` | The licenses that ship with the two SQLite files |
@@ -0,0 +1,67 @@
1
+ import { isDatabaseDeletedNotice, responseOutcome } from "./crossTabProtocol.js";
2
+ import { DATABASE_DELETED_MESSAGE, DATABASE_NOT_INITIALIZED_MESSAGE, } from "./types.js";
3
+ export const UNBOUND_CONNECTION = {
4
+ status: "unbound",
5
+ };
6
+ const BOUND_CONNECTION = { status: "bound" };
7
+ const CLOSING_CONNECTION = { status: "closing" };
8
+ const LOST_CONNECTION = { status: "lost" };
9
+ function transitionOpenConnection(state, event) {
10
+ switch (event.type) {
11
+ case "opened":
12
+ return BOUND_CONNECTION;
13
+ case "closeRequested":
14
+ return CLOSING_CONNECTION;
15
+ case "databaseDeleted":
16
+ return UNBOUND_CONNECTION;
17
+ case "databaseMissing":
18
+ case "ownerGone":
19
+ return state.status === "bound" ? LOST_CONNECTION : state;
20
+ }
21
+ }
22
+ export function transitionCrossTabConnection(state, event) {
23
+ switch (state.status) {
24
+ case "lost":
25
+ return state;
26
+ case "closing":
27
+ // Its requests to a vanished owner can never be answered; fail them as
28
+ // lost so the teardown does not wait on them, or retry them elsewhere.
29
+ return event.type === "ownerGone" ? LOST_CONNECTION : state;
30
+ case "unbound":
31
+ case "bound":
32
+ return transitionOpenConnection(state, event);
33
+ }
34
+ }
35
+ /** Whether the client still needs an owner to serve it. */
36
+ export function isOpenCrossTabConnection(state) {
37
+ return state.status === "unbound" || state.status === "bound";
38
+ }
39
+ /** The event a request implies for the client sending it, if any. */
40
+ export function connectionEventForRequest(method) {
41
+ return method === "close" || method === "delete"
42
+ ? { type: "closeRequested" }
43
+ : null;
44
+ }
45
+ /**
46
+ * The event a worker message implies for the client: a response to its
47
+ * `method` request, or an unprompted notice.
48
+ */
49
+ export function connectionEventForResponse(method, response) {
50
+ if (isDatabaseDeletedNotice(response)) {
51
+ return { type: "databaseDeleted" };
52
+ }
53
+ const outcome = responseOutcome(response);
54
+ if (!outcome) {
55
+ return null;
56
+ }
57
+ if (outcome.ok) {
58
+ return method === "init" ? { type: "opened" } : null;
59
+ }
60
+ if (outcome.message === DATABASE_DELETED_MESSAGE) {
61
+ return { type: "databaseDeleted" };
62
+ }
63
+ return outcome.message === DATABASE_NOT_INITIALIZED_MESSAGE
64
+ ? { type: "databaseMissing" }
65
+ : null;
66
+ }
67
+ //# sourceMappingURL=crossTabConnectionMachine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crossTabConnectionMachine.js","sourceRoot":"","sources":["crossTabConnectionMachine.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC9E,OAAO,EACL,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,SAAS,CAAC;AAkDjB,MAAM,CAAC,MAAM,kBAAkB,GAA4B;IACzD,MAAM,EAAE,SAAS;CAClB,CAAC;AACF,MAAM,gBAAgB,GAA4B,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AACtE,MAAM,kBAA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AAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,0BAA0B,CACxC,MAAqB,EACrB,QAAiB;IAEjB,IAAI,uBAAuB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtC,OAAO,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC;IACrC,CAAC;IAED,MAAM,OAAO,GAAG,eAAe,CAAC,QAAQ,CAAC,CAAC;IAC1C,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,OAAO,CAAC,EAAE,EAAE,CAAC;QACf,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACvD,CAAC;IAED,IAAI,OAAO,CAAC,OAAO,KAAK,wBAAwB,EAAE,CAAC;QACjD,OAAO,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC;IACrC,CAAC;IACD,OAAO,OAAO,CAAC,OAAO,KAAK,gCAAgC;QACzD,CAAC,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE;QAC7B,CAAC,CAAC,IAAI,CAAC;AACX,CAAC","sourcesContent":["import { isDatabaseDeletedNotice, responseOutcome } from \"./crossTabProtocol\";\nimport {\n DATABASE_DELETED_MESSAGE,\n DATABASE_NOT_INITIALIZED_MESSAGE,\n} from \"./types\";\n\n/**\n * Where one tab-local client's open database lives, as its coordinator sees it.\n *\n * The SQLite worker keeps a client's open database on that client's own\n * connection, so the database exists only in the owner worker that answered\n * the client's `init`. When ownership moves to another tab's worker, the\n * client's later statements reach a connection with no database, and the\n * worker answers every one with \"Database has not been initialized.\" while the\n * host still believes it is ready. This machine lets the coordinator notice\n * that and retire the client instead.\n *\n * - `unbound`: no database is open for the client: before its `init`, or\n * after another connection deliberately deleted it.\n * - `bound`: an `init` succeeded, and the owner worker that answered it holds\n * the client's open database.\n * - `closing`: the client sent `close` or `delete`, so it is being retired.\n * A missing database is the expected end of its last statements racing the\n * teardown, and the client no longer needs an owner.\n * - `lost`: the client's database went away with the owner that held it.\n * Terminal: the host must open a new client. The coordinator answers this\n * one's requests itself, so they never reach an owner that did not open its\n * database.\n *\n * A database another connection deleted is not lost: the worker tells every\n * other connection at once, and answers their later statements that it was\n * deleted. Either unbinds the client, so a later owner change does not turn a\n * deliberate delete (logout, destroying an identity) into a loss the host\n * would reopen behind the tab that made it.\n */\nexport type CrossTabConnectionState =\n | { readonly status: \"unbound\" }\n | { readonly status: \"bound\" }\n | { readonly status: \"closing\" }\n | { readonly status: \"lost\" };\n\nexport type CrossTabConnectionEvent =\n // An `init` succeeded.\n | { readonly type: \"opened\" }\n // The client sent a `close` or `delete`.\n | { readonly type: \"closeRequested\" }\n // A worker answered that the client's connection has no open database.\n | { readonly type: \"databaseMissing\" }\n // A worker said another connection deleted the client's database.\n | { readonly type: \"databaseDeleted\" }\n // The owner worker that served this tab is gone: this tab took the owner\n // lock from it, or the owner worker crashed.\n | { readonly type: \"ownerGone\" };\n\nexport const UNBOUND_CONNECTION: CrossTabConnectionState = {\n status: \"unbound\",\n};\nconst BOUND_CONNECTION: CrossTabConnectionState = { status: \"bound\" };\nconst CLOSING_CONNECTION: CrossTabConnectionState = { status: \"closing\" };\nconst LOST_CONNECTION: CrossTabConnectionState = { status: \"lost\" };\n\nfunction transitionOpenConnection(\n state: CrossTabConnectionState,\n event: CrossTabConnectionEvent,\n): CrossTabConnectionState {\n switch (event.type) {\n case \"opened\":\n return BOUND_CONNECTION;\n case \"closeRequested\":\n return CLOSING_CONNECTION;\n case \"databaseDeleted\":\n return UNBOUND_CONNECTION;\n case \"databaseMissing\":\n case \"ownerGone\":\n return state.status === \"bound\" ? LOST_CONNECTION : state;\n }\n}\n\nexport function transitionCrossTabConnection(\n state: CrossTabConnectionState,\n event: CrossTabConnectionEvent,\n): CrossTabConnectionState {\n switch (state.status) {\n case \"lost\":\n return state;\n case \"closing\":\n // Its requests to a vanished owner can never be answered; fail them as\n // lost so the teardown does not wait on them, or retry them elsewhere.\n return event.type === \"ownerGone\" ? LOST_CONNECTION : state;\n case \"unbound\":\n case \"bound\":\n return transitionOpenConnection(state, event);\n }\n}\n\n/** Whether the client still needs an owner to serve it. */\nexport function isOpenCrossTabConnection(\n state: CrossTabConnectionState,\n): boolean {\n return state.status === \"unbound\" || state.status === \"bound\";\n}\n\n/** The event a request implies for the client sending it, if any. */\nexport function connectionEventForRequest(\n method: string | null,\n): CrossTabConnectionEvent | null {\n return method === \"close\" || method === \"delete\"\n ? { type: \"closeRequested\" }\n : null;\n}\n\n/**\n * The event a worker message implies for the client: a response to its\n * `method` request, or an unprompted notice.\n */\nexport function connectionEventForResponse(\n method: string | null,\n response: unknown,\n): CrossTabConnectionEvent | null {\n if (isDatabaseDeletedNotice(response)) {\n return { type: \"databaseDeleted\" };\n }\n\n const outcome = responseOutcome(response);\n if (!outcome) {\n return null;\n }\n\n if (outcome.ok) {\n return method === \"init\" ? { type: \"opened\" } : null;\n }\n\n if (outcome.message === DATABASE_DELETED_MESSAGE) {\n return { type: \"databaseDeleted\" };\n }\n return outcome.message === DATABASE_NOT_INITIALIZED_MESSAGE\n ? { type: \"databaseMissing\" }\n : null;\n}\n"]}
@@ -1,8 +1,10 @@
1
+ import { connectionEventForRequest, connectionEventForResponse, isOpenCrossTabConnection, transitionCrossTabConnection, UNBOUND_CONNECTION, } from "./crossTabConnectionMachine.js";
1
2
  import { createClientLivenessLock, } from "./crossTabLocks.js";
2
- import { errorResponse, responseId } from "./crossTabProtocol.js";
3
+ import { errorResponse, requestId, requestMethod, responseId, } from "./crossTabProtocol.js";
4
+ import { DatabaseConnectionLostError, } from "./workerCrash.js";
3
5
  export function createLocalClient(clientId, events) {
4
6
  return {
5
- closing: false,
7
+ connection: UNBOUND_CONNECTION,
6
8
  dispatch: (response) => {
7
9
  events.dispatchEvent(new MessageEvent("message", { data: response }));
8
10
  },
@@ -12,12 +14,61 @@ export function createLocalClient(clientId, events) {
12
14
  events.dispatchEvent(new ErrorEvent("error", { error, message: error.message }));
13
15
  },
14
16
  liveness: createClientLivenessLock(clientId),
17
+ methodsByRequestId: new Map(),
15
18
  timeoutsByRequestId: new Map(),
16
19
  pendingRemoteRequestIds: new Set(),
17
20
  };
18
21
  }
22
+ // Apply an event; true when it just made the client lost.
23
+ function applyConnectionEvent(localClient, event) {
24
+ if (!event) {
25
+ return false;
26
+ }
27
+ const previous = localClient.connection;
28
+ localClient.connection = transitionCrossTabConnection(previous, event);
29
+ return previous.status !== "lost" && localClient.connection.status === "lost";
30
+ }
31
+ /**
32
+ * Note what a request will do to the client before it is routed. A lost
33
+ * client needs no owner, so its requests fail here instead of waiting for one.
34
+ */
35
+ export function admitLocalClientRequest(localClient, request) {
36
+ assertLocalClientConnected(localClient);
37
+ const id = requestId(request);
38
+ const method = requestMethod(request);
39
+ applyConnectionEvent(localClient, connectionEventForRequest(method));
40
+ if (id !== null && method !== null) {
41
+ localClient.methodsByRequestId.set(id, method);
42
+ }
43
+ }
44
+ /**
45
+ * No owner holds a lost client's database, so its requests fail here rather
46
+ * than reach one that would answer as if the database had never been opened.
47
+ */
48
+ export function assertLocalClientConnected(localClient) {
49
+ if (localClient.connection.status === "lost") {
50
+ throw new DatabaseConnectionLostError();
51
+ }
52
+ }
53
+ /** Whether the client still needs an owner to serve it. */
54
+ export function isOpenLocalClient(localClient) {
55
+ return isOpenCrossTabConnection(localClient.connection);
56
+ }
57
+ // Every request this client has outstanding — routed locally or posted to a
58
+ // remote owner — is lost with the crashed worker, so drop their timeouts too:
59
+ // the client rejects them all at once and would only ignore the late errors.
60
+ function crashLocalClient(localClient, error) {
61
+ for (const timeoutId of localClient.timeoutsByRequestId.values()) {
62
+ clearTimeout(timeoutId);
63
+ }
64
+ localClient.timeoutsByRequestId.clear();
65
+ localClient.pendingRemoteRequestIds.clear();
66
+ localClient.methodsByRequestId.clear();
67
+ localClient.dispatchError(error);
68
+ }
19
69
  export function dispatchResponseToLocalClient(localClient, response) {
20
70
  const id = responseId(response);
71
+ let method = null;
21
72
  if (id !== null) {
22
73
  const timeoutId = localClient.timeoutsByRequestId.get(id);
23
74
  if (timeoutId !== undefined) {
@@ -25,26 +76,37 @@ export function dispatchResponseToLocalClient(localClient, response) {
25
76
  localClient.timeoutsByRequestId.delete(id);
26
77
  }
27
78
  localClient.pendingRemoteRequestIds.delete(id);
79
+ method = localClient.methodsByRequestId.get(id) ?? null;
80
+ localClient.methodsByRequestId.delete(id);
81
+ }
82
+ const event = connectionEventForResponse(method, response);
83
+ if (applyConnectionEvent(localClient, event)) {
84
+ // This answer and every other outstanding request fail as one loss.
85
+ crashLocalClient(localClient, new DatabaseConnectionLostError());
86
+ return;
28
87
  }
29
88
  localClient.dispatch(response);
30
89
  }
31
- // Every request this client has outstanding — routed locally or posted to a
32
- // remote owner — is lost with the crashed worker, so drop their timeouts too:
33
- // the client rejects them all at once and would only ignore the late errors.
90
+ // The worker serving this client died, so a database it had open died with
91
+ // it. A client already lost was told so when it was lost.
34
92
  export function dispatchCrashToLocalClient(localClient, error) {
35
- for (const timeoutId of localClient.timeoutsByRequestId.values()) {
36
- clearTimeout(timeoutId);
93
+ if (localClient.connection.status === "lost") {
94
+ return;
37
95
  }
38
- localClient.timeoutsByRequestId.clear();
39
- localClient.pendingRemoteRequestIds.clear();
40
- localClient.dispatchError(error);
96
+ applyConnectionEvent(localClient, { type: "ownerGone" });
97
+ crashLocalClient(localClient, error);
41
98
  }
42
99
  /**
43
- * Fail every still-outstanding remote request of this client with a retryable
44
- * error. Called when this tab is promoted to owner, because the owner it had
45
- * posted those requests to is now gone.
100
+ * This tab just took the owner lock, so the owner it had been routing to is
101
+ * gone. A client with a database open there, or retiring from it, has lost it;
102
+ * any other client only loses the requests it had posted there, which fail
103
+ * with a retryable error rather than waiting out the timeout.
46
104
  */
47
- export function failPendingRemoteRequests(localClient) {
105
+ export function releaseLocalClientFromPreviousOwner(localClient) {
106
+ if (applyConnectionEvent(localClient, { type: "ownerGone" })) {
107
+ crashLocalClient(localClient, new DatabaseConnectionLostError());
108
+ return;
109
+ }
48
110
  for (const id of [...localClient.pendingRemoteRequestIds]) {
49
111
  dispatchResponseToLocalClient(localClient, errorResponse(id, "The database owner tab changed; retry the request."));
50
112
  }
@@ -1 +1 @@
1
- {"version":3,"file":"crossTabLocalClient.js","sourceRoot":"","sources":["crossTabLocalClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,wBAAwB,GACzB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAoB/D,MAAM,UAAU,iBAAiB,CAC/B,QAAgB,EAChB,MAAmB;IAEnB,OAAO;QACL,OAAO,EAAE,KAAK;QACd,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE;YACrB,MAAM,CAAC,aAAa,CAAC,IAAI,YAAY,CAAC,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;QACxE,CAAC;QACD,sEAAsE;QACtE,kEAAkE;QAClE,aAAa,EAAE,CAAC,KAAK,EAAE,EAAE;YACvB,MAAM,CAAC,aAAa,CAClB,IAAI,UAAU,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAC3D,CAAC;QACJ,CAAC;QACD,QAAQ,EAAE,wBAAwB,CAAC,QAAQ,CAAC;QAC5C,mBAAmB,EAAE,IAAI,GAAG,EAAE;QAC9B,uBAAuB,EAAE,IAAI,GAAG,EAAE;KACnC,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,WAAwB,EACxB,QAAiB;IAEjB,MAAM,EAAE,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;IAChC,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;QAChB,MAAM,SAAS,GAAG,WAAW,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC1D,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC5B,YAAY,CAAC,SAAS,CAAC,CAAC;YACxB,WAAW,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QAC7C,CAAC;QACD,WAAW,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AACjC,CAAC;AAED,4EAA4E;AAC5E,8EAA8E;AAC9E,6EAA6E;AAC7E,MAAM,UAAU,0BAA0B,CACxC,WAAwB,EACxB,KAA+B;IAE/B,KAAK,MAAM,SAAS,IAAI,WAAW,CAAC,mBAAmB,CAAC,MAAM,EAAE,EAAE,CAAC;QACjE,YAAY,CAAC,SAAS,CAAC,CAAC;IAC1B,CAAC;IACD,WAAW,CAAC,mBAAmB,CAAC,KAAK,EAAE,CAAC;IACxC,WAAW,CAAC,uBAAuB,CAAC,KAAK,EAAE,CAAC;IAC5C,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;AACnC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CAAC,WAAwB;IAChE,KAAK,MAAM,EAAE,IAAI,CAAC,GAAG,WAAW,CAAC,uBAAuB,CAAC,EAAE,CAAC;QAC1D,6BAA6B,CAC3B,WAAW,EACX,aAAa,CAAC,EAAE,EAAE,oDAAoD,CAAC,CACxE,CAAC;IACJ,CAAC;AACH,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,WAAwB;IACzD,KAAK,MAAM,SAAS,IAAI,WAAW,CAAC,mBAAmB,CAAC,MAAM,EAAE,EAAE,CAAC;QACjE,YAAY,CAAC,SAAS,CAAC,CAAC;IAC1B,CAAC;IACD,WAAW,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;AACjC,CAAC","sourcesContent":["import {\n type ClientLivenessLock,\n createClientLivenessLock,\n} from \"./crossTabLocks\";\nimport { errorResponse, responseId } from \"./crossTabProtocol\";\nimport type { DatabaseWorkerCrashError } from \"./workerCrash\";\n\n/**\n * One logical client of this tab's coordinator: the synthetic worker handed to a\n * runtime, its liveness lock, and the bookkeeping for requests it has posted to\n * a remote owner tab.\n */\nexport interface LocalClient {\n closing: boolean;\n readonly dispatch: (response: unknown) => void;\n readonly dispatchError: (error: DatabaseWorkerCrashError) => void;\n readonly liveness: ClientLivenessLock;\n readonly timeoutsByRequestId: Map<number, ReturnType<typeof setTimeout>>;\n // Request ids this client posted over BroadcastChannel that have not yet been\n // answered by the owner tab. Used to fail them fast (rather than wait out the\n // timeout) when this tab is promoted to owner after the previous owner died.\n readonly pendingRemoteRequestIds: Set<number>;\n}\n\nexport function createLocalClient(\n clientId: string,\n events: EventTarget,\n): LocalClient {\n return {\n closing: false,\n dispatch: (response) => {\n events.dispatchEvent(new MessageEvent(\"message\", { data: response }));\n },\n // Carries the instance so the client's error handler rejects with the\n // stack minted where the crash was observed, not one rooted here.\n dispatchError: (error) => {\n events.dispatchEvent(\n new ErrorEvent(\"error\", { error, message: error.message }),\n );\n },\n liveness: createClientLivenessLock(clientId),\n timeoutsByRequestId: new Map(),\n pendingRemoteRequestIds: new Set(),\n };\n}\n\nexport function dispatchResponseToLocalClient(\n localClient: LocalClient,\n response: unknown,\n): void {\n const id = responseId(response);\n if (id !== null) {\n const timeoutId = localClient.timeoutsByRequestId.get(id);\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n localClient.timeoutsByRequestId.delete(id);\n }\n localClient.pendingRemoteRequestIds.delete(id);\n }\n\n localClient.dispatch(response);\n}\n\n// Every request this client has outstanding — routed locally or posted to a\n// remote owner — is lost with the crashed worker, so drop their timeouts too:\n// the client rejects them all at once and would only ignore the late errors.\nexport function dispatchCrashToLocalClient(\n localClient: LocalClient,\n error: DatabaseWorkerCrashError,\n): void {\n for (const timeoutId of localClient.timeoutsByRequestId.values()) {\n clearTimeout(timeoutId);\n }\n localClient.timeoutsByRequestId.clear();\n localClient.pendingRemoteRequestIds.clear();\n localClient.dispatchError(error);\n}\n\n/**\n * Fail every still-outstanding remote request of this client with a retryable\n * error. Called when this tab is promoted to owner, because the owner it had\n * posted those requests to is now gone.\n */\nexport function failPendingRemoteRequests(localClient: LocalClient): void {\n for (const id of [...localClient.pendingRemoteRequestIds]) {\n dispatchResponseToLocalClient(\n localClient,\n errorResponse(id, \"The database owner tab changed; retry the request.\"),\n );\n }\n}\n\nexport function releaseLocalClient(localClient: LocalClient): void {\n for (const timeoutId of localClient.timeoutsByRequestId.values()) {\n clearTimeout(timeoutId);\n }\n localClient.liveness.release();\n}\n"]}
1
+ {"version":3,"file":"crossTabLocalClient.js","sourceRoot":"","sources":["crossTabLocalClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,yBAAyB,EACzB,0BAA0B,EAC1B,wBAAwB,EACxB,4BAA4B,EAC5B,kBAAkB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAEL,wBAAwB,GACzB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,aAAa,EACb,SAAS,EACT,aAAa,EACb,UAAU,GACX,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,2BAA2B,GAE5B,MAAM,eAAe,CAAC;AAsBvB,MAAM,UAAU,iBAAiB,CAC/B,QAAgB,EAChB,MAAmB;IAEnB,OAAO;QACL,UAAU,EAAE,kBAAkB;QAC9B,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE;YACrB,MAAM,CAAC,aAAa,CAAC,IAAI,YAAY,CAAC,SAAS,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC;QACxE,CAAC;QACD,sEAAsE;QACtE,kEAAkE;QAClE,aAAa,EAAE,CAAC,KAAK,EAAE,EAAE;YACvB,MAAM,CAAC,aAAa,CAClB,IAAI,UAAU,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAC3D,CAAC;QACJ,CAAC;QACD,Q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EventForRequest,\n connectionEventForResponse,\n isOpenCrossTabConnection,\n transitionCrossTabConnection,\n UNBOUND_CONNECTION,\n} from \"./crossTabConnectionMachine\";\nimport {\n type ClientLivenessLock,\n createClientLivenessLock,\n} from \"./crossTabLocks\";\nimport {\n errorResponse,\n requestId,\n requestMethod,\n responseId,\n} from \"./crossTabProtocol\";\nimport {\n DatabaseConnectionLostError,\n type DatabaseWorkerCrashError,\n} from \"./workerCrash\";\n\n/**\n * One logical client of this tab's coordinator: the synthetic worker handed to a\n * runtime, its liveness lock, the bookkeeping for requests it has posted to\n * a remote owner tab, and where its open database lives.\n */\nexport interface LocalClient {\n connection: CrossTabConnectionState;\n readonly dispatch: (response: unknown) => void;\n readonly dispatchError: (error: DatabaseWorkerCrashError) => void;\n readonly liveness: ClientLivenessLock;\n // The method of every request still awaiting its response, so a response\n // can say whether it opened the client's database.\n readonly methodsByRequestId: Map<number, string>;\n readonly timeoutsByRequestId: Map<number, ReturnType<typeof setTimeout>>;\n // Request ids this client posted over BroadcastChannel that have not yet been\n // answered by the owner tab. Used to fail them fast (rather than wait out the\n // timeout) when this tab is promoted to owner after the previous owner died.\n readonly pendingRemoteRequestIds: Set<number>;\n}\n\nexport function createLocalClient(\n clientId: string,\n events: EventTarget,\n): LocalClient {\n return {\n connection: UNBOUND_CONNECTION,\n dispatch: (response) => {\n events.dispatchEvent(new MessageEvent(\"message\", { data: response }));\n },\n // Carries the instance so the client's error handler rejects with the\n // stack minted where the crash was observed, not one rooted here.\n dispatchError: (error) => {\n events.dispatchEvent(\n new ErrorEvent(\"error\", { error, message: error.message }),\n );\n },\n liveness: createClientLivenessLock(clientId),\n methodsByRequestId: new Map(),\n timeoutsByRequestId: new Map(),\n pendingRemoteRequestIds: new Set(),\n };\n}\n\n// Apply an event; true when it just made the client lost.\nfunction applyConnectionEvent(\n localClient: LocalClient,\n event: CrossTabConnectionEvent | null,\n): boolean {\n if (!event) {\n return false;\n }\n\n const previous = localClient.connection;\n localClient.connection = transitionCrossTabConnection(previous, event);\n return previous.status !== \"lost\" && localClient.connection.status === \"lost\";\n}\n\n/**\n * Note what a request will do to the client before it is routed. A lost\n * client needs no owner, so its requests fail here instead of waiting for one.\n */\nexport function admitLocalClientRequest(\n localClient: LocalClient,\n request: unknown,\n): void {\n assertLocalClientConnected(localClient);\n const id = requestId(request);\n const method = requestMethod(request);\n applyConnectionEvent(localClient, connectionEventForRequest(method));\n if (id !== null && method !== null) {\n localClient.methodsByRequestId.set(id, method);\n }\n}\n\n/**\n * No owner holds a lost client's database, so its requests fail here rather\n * than reach one that would answer as if the database had never been opened.\n */\nexport function assertLocalClientConnected(localClient: LocalClient): void {\n if (localClient.connection.status === \"lost\") {\n throw new DatabaseConnectionLostError();\n }\n}\n\n/** Whether the client still needs an owner to serve it. */\nexport function isOpenLocalClient(localClient: LocalClient): boolean {\n return isOpenCrossTabConnection(localClient.connection);\n}\n\n// Every request this client has outstanding — routed locally or posted to a\n// remote owner — is lost with the crashed worker, so drop their timeouts too:\n// the client rejects them all at once and would only ignore the late errors.\nfunction crashLocalClient(\n localClient: LocalClient,\n error: DatabaseWorkerCrashError,\n): void {\n for (const timeoutId of localClient.timeoutsByRequestId.values()) {\n clearTimeout(timeoutId);\n }\n localClient.timeoutsByRequestId.clear();\n localClient.pendingRemoteRequestIds.clear();\n localClient.methodsByRequestId.clear();\n localClient.dispatchError(error);\n}\n\nexport function dispatchResponseToLocalClient(\n localClient: LocalClient,\n response: unknown,\n): void {\n const id = responseId(response);\n let method: string | null = null;\n if (id !== null) {\n const timeoutId = localClient.timeoutsByRequestId.get(id);\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n localClient.timeoutsByRequestId.delete(id);\n }\n localClient.pendingRemoteRequestIds.delete(id);\n method = localClient.methodsByRequestId.get(id) ?? null;\n localClient.methodsByRequestId.delete(id);\n }\n\n const event = connectionEventForResponse(method, response);\n if (applyConnectionEvent(localClient, event)) {\n // This answer and every other outstanding request fail as one loss.\n crashLocalClient(localClient, new DatabaseConnectionLostError());\n return;\n }\n\n localClient.dispatch(response);\n}\n\n// The worker serving this client died, so a database it had open died with\n// it. A client already lost was told so when it was lost.\nexport function dispatchCrashToLocalClient(\n localClient: LocalClient,\n error: DatabaseWorkerCrashError,\n): void {\n if (localClient.connection.status === \"lost\") {\n return;\n }\n\n applyConnectionEvent(localClient, { type: \"ownerGone\" });\n crashLocalClient(localClient, error);\n}\n\n/**\n * This tab just took the owner lock, so the owner it had been routing to is\n * gone. A client with a database open there, or retiring from it, has lost it;\n * any other client only loses the requests it had posted there, which fail\n * with a retryable error rather than waiting out the timeout.\n */\nexport function releaseLocalClientFromPreviousOwner(\n localClient: LocalClient,\n): void {\n if (applyConnectionEvent(localClient, { type: \"ownerGone\" })) {\n crashLocalClient(localClient, new DatabaseConnectionLostError());\n return;\n }\n\n for (const id of [...localClient.pendingRemoteRequestIds]) {\n dispatchResponseToLocalClient(\n localClient,\n errorResponse(id, \"The database owner tab changed; retry the request.\"),\n );\n }\n}\n\nexport function releaseLocalClient(localClient: LocalClient): void {\n for (const timeoutId of localClient.timeoutsByRequestId.values()) {\n clearTimeout(timeoutId);\n }\n localClient.liveness.release();\n}\n"]}
@@ -1,3 +1,4 @@
1
+ import { WORKER_DATABASE_DELETED_MESSAGE_TYPE, } from "./types.js";
1
2
  function isObject(value) {
2
3
  return typeof value === "object" && value !== null;
3
4
  }
@@ -24,6 +25,22 @@ export function requestMethod(request) {
24
25
  export function responseId(response) {
25
26
  return getNumber(response, "id");
26
27
  }
28
+ // The worker's unprompted notice that another connection deleted the database.
29
+ export function isDatabaseDeletedNotice(message) {
30
+ return getString(message, "type") === WORKER_DATABASE_DELETED_MESSAGE_TYPE;
31
+ }
32
+ // The outcome a worker response reports, or null for anything that is not one.
33
+ export function responseOutcome(response) {
34
+ if (!isObject(response)) {
35
+ return null;
36
+ }
37
+ const result = Reflect.get(response, "result");
38
+ const ok = isObject(result) ? Reflect.get(result, "ok") : undefined;
39
+ if (typeof ok !== "boolean") {
40
+ return null;
41
+ }
42
+ return { ok, message: getString(result, "message") };
43
+ }
27
44
  export function errorResponse(id, message) {
28
45
  return {
29
46
  id,
@@ -1 +1 @@
1
- {"version":3,"file":"crossTabProtocol.js","sourceRoot":"","sources":["crossTabProtocol.ts"],"names":[],"mappings":"AAwBA,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACrD,CAAC;AAED,SAAS,SAAS,CAAC,KAAc,EAAE,GAAW;IAC5C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;AACxD,CAAC;AAED,SAAS,SAAS,CAAC,KAAc,EAAE,GAAW;IAC5C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,OAAgB;IACxC,OAAO,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,OAAO,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,QAAiB;IAC1C,OAAO,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,EAAU,EAAE,OAAe;IACvD,OAAO;QACL,EAAE;QACF,MAAM,EAAE;YACN,EAAE,EAAE,KAAK;YACT,OAAO;SACR;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACxC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAChD,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACjC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;QACrB,OAAO,CACL,OAAO,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,SAAS,CAAC,KAAK,QAAQ,CACvE,CAAC;IACJ,CAAC;IAED,OAAO,IAAI,KAAK,UAAU,CAAC;AAC7B,CAAC","sourcesContent":["import type { WorkerResponse } from \"./types\";\nimport type { WorkerCrashDetail } from \"./workerCrash\";\n\ntype CrossTabEnvelope =\n | {\n readonly type: \"request\";\n readonly clientId: string;\n readonly hasClientLock?: boolean;\n readonly request: unknown;\n }\n | {\n readonly type: \"response\";\n readonly clientId: string;\n readonly response: unknown;\n }\n // The owner's worker crashed while serving `clientId` from another tab. An\n // Error cannot cross the channel, so the receiving tab mints its own from the\n // detail (see workerCrash.ts).\n | {\n readonly type: \"error\";\n readonly clientId: string;\n readonly detail: WorkerCrashDetail;\n };\n\nfunction isObject(value: unknown): value is object {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getString(value: unknown, key: string): string | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"string\" ? property : null;\n}\n\nfunction getNumber(value: unknown, key: string): number | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"number\" ? property : null;\n}\n\nexport function requestId(request: unknown): number | null {\n return getNumber(request, \"id\");\n}\n\nexport function requestMethod(request: unknown): string | null {\n return getString(request, \"method\");\n}\n\nexport function responseId(response: unknown): number | null {\n return getNumber(response, \"id\");\n}\n\nexport function errorResponse(id: number, message: string): WorkerResponse {\n return {\n id,\n result: {\n ok: false,\n message,\n },\n };\n}\n\nexport function isCrossTabEnvelope(value: unknown): value is CrossTabEnvelope {\n if (!isObject(value)) {\n return false;\n }\n\n const type = Reflect.get(value, \"type\");\n const clientId = Reflect.get(value, \"clientId\");\n if (typeof clientId !== \"string\") {\n return false;\n }\n\n if (type === \"request\") {\n return true;\n }\n\n if (type === \"error\") {\n return (\n typeof getString(Reflect.get(value, \"detail\"), \"message\") === \"string\"\n );\n }\n\n return type === \"response\";\n}\n"]}
1
+ {"version":3,"file":"crossTabProtocol.js","sourceRoot":"","sources":["crossTabProtocol.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,GAErC,MAAM,SAAS,CAAC;AAwBjB,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACrD,CAAC;AAED,SAAS,SAAS,CAAC,KAAc,EAAE,GAAW;IAC5C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAA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C;IAED,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,EAAU,EAAE,OAAe;IACvD,OAAO;QACL,EAAE;QACF,MAAM,EAAE;YACN,EAAE,EAAE,KAAK;YACT,OAAO;SACR;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACxC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAChD,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACjC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;QACrB,OAAO,CACL,OAAO,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,SAAS,CAAC,KAAK,QAAQ,CACvE,CAAC;IACJ,CAAC;IAED,OAAO,IAAI,KAAK,UAAU,CAAC;AAC7B,CAAC","sourcesContent":["import {\n WORKER_DATABASE_DELETED_MESSAGE_TYPE,\n type WorkerResponse,\n} from \"./types\";\nimport type { WorkerCrashDetail } from \"./workerCrash\";\n\ntype CrossTabEnvelope =\n | {\n readonly type: \"request\";\n readonly clientId: string;\n readonly hasClientLock?: boolean;\n readonly request: unknown;\n }\n | {\n readonly type: \"response\";\n readonly clientId: string;\n readonly response: unknown;\n }\n // The owner's worker crashed while serving `clientId` from another tab. An\n // Error cannot cross the channel, so the receiving tab mints its own from the\n // detail (see workerCrash.ts).\n | {\n readonly type: \"error\";\n readonly clientId: string;\n readonly detail: WorkerCrashDetail;\n };\n\nfunction isObject(value: unknown): value is object {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getString(value: unknown, key: string): string | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"string\" ? property : null;\n}\n\nfunction getNumber(value: unknown, key: string): number | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"number\" ? property : null;\n}\n\nexport function requestId(request: unknown): number | null {\n return getNumber(request, \"id\");\n}\n\nexport function requestMethod(request: unknown): string | null {\n return getString(request, \"method\");\n}\n\nexport function responseId(response: unknown): number | null {\n return getNumber(response, \"id\");\n}\n\n// The worker's unprompted notice that another connection deleted the database.\nexport function isDatabaseDeletedNotice(message: unknown): boolean {\n return getString(message, \"type\") === WORKER_DATABASE_DELETED_MESSAGE_TYPE;\n}\n\n// The outcome a worker response reports, or null for anything that is not one.\nexport function responseOutcome(\n response: unknown,\n): { readonly ok: boolean; readonly message: string | null } | null {\n if (!isObject(response)) {\n return null;\n }\n\n const result = Reflect.get(response, \"result\");\n const ok = isObject(result) ? Reflect.get(result, \"ok\") : undefined;\n if (typeof ok !== \"boolean\") {\n return null;\n }\n\n return { ok, message: getString(result, \"message\") };\n}\n\nexport function errorResponse(id: number, message: string): WorkerResponse {\n return {\n id,\n result: {\n ok: false,\n message,\n },\n };\n}\n\nexport function isCrossTabEnvelope(value: unknown): value is CrossTabEnvelope {\n if (!isObject(value)) {\n return false;\n }\n\n const type = Reflect.get(value, \"type\");\n const clientId = Reflect.get(value, \"clientId\");\n if (typeof clientId !== \"string\") {\n return false;\n }\n\n if (type === \"request\") {\n return true;\n }\n\n if (type === \"error\") {\n return (\n typeof getString(Reflect.get(value, \"detail\"), \"message\") === \"string\"\n );\n }\n\n return type === \"response\";\n}\n"]}
@@ -1,16 +1,12 @@
1
- import { createLocalClient, dispatchCrashToLocalClient, dispatchResponseToLocalClient, failPendingRemoteRequests, releaseLocalClient, } from "./crossTabLocalClient.js";
1
+ import { admitLocalClientRequest, assertLocalClientConnected, createLocalClient, dispatchCrashToLocalClient, dispatchResponseToLocalClient, isOpenLocalClient, releaseLocalClient, releaseLocalClientFromPreviousOwner, } from "./crossTabLocalClient.js";
2
2
  import { canUseCrossTabPrimitives, lockManager, } from "./crossTabLocks.js";
3
3
  import { CrossTabOwner } from "./crossTabOwner.js";
4
4
  import { isOwnerLockHeld, pollForOwner } from "./crossTabOwnership.js";
5
- import { errorResponse, isCrossTabEnvelope, requestId, requestMethod, } from "./crossTabProtocol.js";
5
+ import { errorResponse, isCrossTabEnvelope, requestId, } from "./crossTabProtocol.js";
6
6
  import { DatabaseWorkerCrashError } from "./workerCrash.js";
7
7
  const CROSS_TAB_CHANNEL_NAME = "tearleads-sqlite-worker";
8
8
  const CROSS_TAB_OWNER_LOCK_NAME = "tearleads-sqlite-worker-owner";
9
9
  const CROSS_TAB_REQUEST_TIMEOUT_MS = 10_000;
10
- function isTeardownRequest(request) {
11
- const method = requestMethod(request);
12
- return method === "close" || method === "delete";
13
- }
14
10
  class CrossTabCoordinator {
15
11
  workerUrl;
16
12
  workerConstructor;
@@ -99,8 +95,11 @@ class CrossTabCoordinator {
99
95
  * only ever risks a missed heal, never wrongly stranding a real remote tab.
100
96
  */
101
97
  forceStopOwnerFor(clientId) {
98
+ // A lost client's database died with an earlier owner; the current owner
99
+ // may never have served it, so its silence is no reason to stop it.
100
+ const lost = this.localClientsById.get(clientId)?.connection.status === "lost";
102
101
  this.unregisterLocalClient(clientId);
103
- if (this.hasOpenLocalClients()) {
102
+ if (lost || this.hasOpenLocalClients()) {
104
103
  return;
105
104
  }
106
105
  const owner = this.owner;
@@ -115,8 +114,8 @@ class CrossTabCoordinator {
115
114
  const id = requestId(request);
116
115
  try {
117
116
  const localClient = this.localClientsById.get(clientId);
118
- if (localClient && isTeardownRequest(request)) {
119
- localClient.closing = true;
117
+ if (localClient) {
118
+ admitLocalClientRequest(localClient, request);
120
119
  }
121
120
  const hasClientLock = await this.waitForLocalClientLock(clientId);
122
121
  if (!this.localClientsById.has(clientId)) {
@@ -130,6 +129,10 @@ class CrossTabCoordinator {
130
129
  if (!this.localClientsById.has(clientId)) {
131
130
  return;
132
131
  }
132
+ // A client can be lost while it waits, when this tab is promoted.
133
+ if (localClient) {
134
+ assertLocalClientConnected(localClient);
135
+ }
133
136
  if (this.owner) {
134
137
  this.owner.route(clientId, request, { hasClientLock });
135
138
  return;
@@ -268,9 +271,8 @@ class CrossTabCoordinator {
268
271
  });
269
272
  this.owner = owner;
270
273
  this.ownerError = null;
271
- // Requests posted to the previous owner are orphaned; fail them with a
272
- // retryable error instead of waiting out the timeout.
273
- this.failPendingRemoteRequests();
274
+ // The previous owner is gone, with every database it had open.
275
+ this.releaseClientsFromPreviousOwner();
274
276
  this.settleOwnership(generation);
275
277
  await ownerReleased;
276
278
  releasedNormally = true;
@@ -282,7 +284,7 @@ class CrossTabCoordinator {
282
284
  this.owner = null;
283
285
  this.ownerError =
284
286
  error instanceof Error ? error : new Error(String(error));
285
- this.failPendingRemoteRequests();
287
+ this.releaseClientsFromPreviousOwner();
286
288
  this.settleOwnership(generation);
287
289
  throw error;
288
290
  }
@@ -308,7 +310,7 @@ class CrossTabCoordinator {
308
310
  }
309
311
  hasOpenLocalClients() {
310
312
  for (const localClient of this.localClientsById.values()) {
311
- if (!localClient.closing) {
313
+ if (isOpenLocalClient(localClient)) {
312
314
  return true;
313
315
  }
314
316
  }
@@ -363,11 +365,11 @@ class CrossTabCoordinator {
363
365
  const locks = lockManager();
364
366
  return locks ? isOwnerLockHeld(locks, CROSS_TAB_OWNER_LOCK_NAME) : false;
365
367
  }
366
- // Called when this tab is promoted to owner: the owner its clients had posted
367
- // their remote requests to is gone, so fail them fast rather than time out.
368
- failPendingRemoteRequests() {
368
+ // Called when this tab takes the owner lock: the owner its clients had been
369
+ // routing to is gone (see releaseLocalClientFromPreviousOwner).
370
+ releaseClientsFromPreviousOwner() {
369
371
  for (const localClient of this.localClientsById.values()) {
370
- failPendingRemoteRequests(localClient);
372
+ releaseLocalClientFromPreviousOwner(localClient);
371
373
  }
372
374
  }
373
375
  }
@@ -1 +1 @@
1
- {"version":3,"file":"crossTabRuntime.js","sourceRoot":"","sources":["crossTabRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EACL,iBAAiB,EACjB,0BAA0B,EAC1B,6BAA6B,EAC7B,yBAAyB,EAEzB,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,wBAAwB,EAExB,WAAW,GACZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAgC,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,SAAS,EACT,aAAa,GACd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEzD,MAAM,sBAAsB,GAAG,yBAAyB,CAAC;AACzD,MAAM,yBAAyB,GAAG,+BAA+B,CAAC;AAClE,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAc5C,SAAS,iBAAiB,CAAC,OAAgB;IACzC,MAAM,MAAM,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IACtC,OAAO,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,QAAQ,CAAC;AACnD,CAAC;AAED,MAAM,mBAAmB;IAkBJ;IACA;IAlBF,OAAO,GAAG,IAAI,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;IAChE,gBAAgB,GAAG,KAAK,CAAC;IAChB,gBAAgB,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC3D,KAAK,GAAyB,IAAI,CAAC;IAC3C,0EAA0E;IAC1E,0DAA0D;IAClD,UAAU,GAAiB,IAAI,CAAC;IACxC,gFAAgF;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AAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACnD,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,mBAAmB,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;QACpE,uBAAuB,CAAC,GAAG,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IAChD,CAAC;IAED,OAAO,WAAW,CAAC,YAAY,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type { WorkerLike } from \"./client\";\nimport {\n createLocalClient,\n dispatchCrashToLocalClient,\n dispatchResponseToLocalClient,\n failPendingRemoteRequests,\n type LocalClient,\n releaseLocalClient,\n} from \"./crossTabLocalClient\";\nimport {\n canUseCrossTabPrimitives,\n type LockManagerLike,\n lockManager,\n} from \"./crossTabLocks\";\nimport { CrossTabOwner, type ModuleWorkerConstructor } from \"./crossTabOwner\";\nimport { isOwnerLockHeld, pollForOwner } from \"./crossTabOwnership\";\nimport {\n errorResponse,\n isCrossTabEnvelope,\n requestId,\n requestMethod,\n} from \"./crossTabProtocol\";\nimport { DatabaseWorkerCrashError } from \"./workerCrash\";\n\nconst CROSS_TAB_CHANNEL_NAME = \"tearleads-sqlite-worker\";\nconst CROSS_TAB_OWNER_LOCK_NAME = \"tearleads-sqlite-worker-owner\";\nconst CROSS_TAB_REQUEST_TIMEOUT_MS = 10_000;\n\ninterface CrossTabDatabaseWorker extends WorkerLike {\n close(): void;\n /**\n * Abrupt teardown for a runtime that could not close gracefully — its worker\n * went silent, so the `close` round-trip never came back to stop the owner via\n * {@link CrossTabOwner.stop}. Unregisters this client and, when safe, force-stops\n * the owner so the next boot re-contends and builds a fresh owner instead of\n * routing into the dead one. See {@link CrossTabCoordinator.forceStopOwnerFor}.\n */\n forceStopOwner(): void;\n}\n\nfunction isTeardownRequest(request: unknown): boolean {\n const method = requestMethod(request);\n return method === \"close\" || method === \"delete\";\n}\n\nclass CrossTabCoordinator {\n private readonly channel = new BroadcastChannel(CROSS_TAB_CHANNEL_NAME);\n private hasCreatedClient = false;\n private readonly localClientsById = new Map<string, LocalClient>();\n private owner: CrossTabOwner | null = null;\n // Set if this tab won ownership but its owner worker failed to construct.\n // Cleared if a later bid succeeds in installing an owner.\n private ownerError: Error | null = null;\n // Resolves when ownership is settled for the current owner generation (this tab\n // won and installed/failed to construct an owner, or it observed another tab\n // already owns), so routing never posts remotely while no owner exists.\n private ownershipBidActive = false;\n private ownershipGeneration = 0;\n private ownershipSettled: Promise<void> = Promise.resolve();\n private retryOwnershipAfterBid = false;\n private settleOwnershipGate: () => void = () => {};\n\n constructor(\n private readonly workerUrl: string | URL,\n private readonly workerConstructor: ModuleWorkerConstructor,\n ) {\n this.resetOwnershipGate();\n this.channel.addEventListener(\"message\", (event) => {\n this.handleChannelMessage(event);\n });\n // Start the first ownership bid; later clients can restart it after teardown.\n this.contendForOwnership();\n }\n\n createWorker(): CrossTabDatabaseWorker {\n const clientId = crypto.randomUUID();\n const events = new EventTarget();\n if (this.ownerError && this.hasCreatedClient) {\n this.ownerError = null;\n this.retryOwnershipAfterBid = this.ownershipBidActive;\n this.resetOwnershipGate();\n }\n this.localClientsById.set(clientId, createLocalClient(clientId, events));\n this.hasCreatedClient = true;\n this.contendForOwnership();\n\n return {\n postMessage: (message) => {\n this.route(clientId, message);\n },\n addEventListener(type, listener) {\n events.addEventListener(type, listener);\n },\n removeEventListener(type, listener) {\n events.removeEventListener(type, listener);\n },\n close: () => {\n this.unregisterLocalClient(clientId);\n },\n forceStopOwner: () => {\n this.forceStopOwnerFor(clientId);\n },\n };\n }\n\n /**\n * Tear down a possibly-wedged owner on abrupt runtime teardown.\n *\n * `this.owner` is normally cleared only when the dedicated worker answers a\n * `close`/`delete` (→ {@link CrossTabOwner.stop} via `handleWorkerResponse`). A\n * worker hung inside OPFS never answers, so that path never runs and the plain\n * client `close()` (just {@link unregisterLocalClient}) leaves `this.owner`\n * pinned to the dead worker — every later boot then routes its `init` straight\n * into it over the untimed local path and hangs. Because the coordinator is a\n * per-URL module singleton, that pins EVERY database, not just the one that\n * wedged.\n *\n * So on abrupt teardown, after unregistering the client, stop the owner —\n * `stop()` terminates the worker, releases the owner lock, and (via the release\n * callback) nulls `this.owner` + resets the gate, so the next `createWorker()`\n * re-contends and constructs a fresh owner. Gated to stay multi-tab-safe: only\n * when this tab has no other open local client AND the owner serves no other\n * (remote) client, so it can never strand a sibling tab still routing here.\n *\n * The remote-client half of the gate reads the owner's `activeClientIds`, which\n * is coarse: a wedged local client that was force-torn-down without a close\n * response leaves a *stale* id there (only a close-response or the liveness sweep\n * removes it). So if TWO local clients on one coordinator were wedged and torn\n * down in the same tick, the second would see the first's stale id and decline to\n * stop — leaving the wedge unhealed. That cannot happen here: the app drives a\n * single runtime at a time (`useManagedSQLiteRuntime` holds one runtimeRef and\n * defers each spawn on the prior release), so a coordinator never has two live\n * local clients. The gate therefore errs, at worst, toward NOT stopping — which\n * only ever risks a missed heal, never wrongly stranding a real remote tab.\n */\n private forceStopOwnerFor(clientId: string): void {\n this.unregisterLocalClient(clientId);\n if (this.hasOpenLocalClients()) {\n return;\n }\n\n const owner = this.owner;\n if (owner && !owner.hasActiveClientsExcept(clientId)) {\n owner.stop();\n }\n }\n\n private route(clientId: string, request: unknown): void {\n void this.routeAsync(clientId, request);\n }\n\n private async routeAsync(clientId: string, request: unknown): Promise<void> {\n const id = requestId(request);\n try {\n const localClient = this.localClientsById.get(clientId);\n if (localClient && isTeardownRequest(request)) {\n localClient.closing = true;\n }\n\n const hasClientLock = await this.waitForLocalClientLock(clientId);\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n // Wait for ownership so this request is not posted into the void.\n if (!this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n await this.ownershipSettled;\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n if (this.owner) {\n this.owner.route(clientId, request, { hasClientLock });\n return;\n }\n\n // This tab won ownership earlier but its owner worker failed to construct.\n // If another tab has since become a healthy owner, fall back to it; only\n // surface the construction error when no owner exists anywhere, so a single\n // tab whose worker cannot start fails fast instead of hanging on the timeout.\n if (this.ownerError && !(await this.anotherTabOwns())) {\n throw this.ownerError;\n }\n\n this.postRemoteRequest(clientId, request, hasClientLock);\n } catch (error: unknown) {\n if (id !== null) {\n this.dispatchLocalResponse(\n clientId,\n errorResponse(\n id,\n error instanceof Error\n ? error.message\n : \"Failed to route database request.\",\n ),\n );\n }\n }\n }\n\n private async waitForLocalClientLock(clientId: string): Promise<boolean> {\n const localClient = this.localClientsById.get(clientId);\n if (!localClient) {\n return false;\n }\n\n return localClient.liveness.ready;\n }\n\n private postRemoteRequest(\n clientId: string,\n request: unknown,\n hasClientLock: boolean,\n ): void {\n const id = requestId(request);\n if (id !== null) {\n const localClient = this.localClientsById.get(clientId);\n localClient?.pendingRemoteRequestIds.add(id);\n const timeoutId = setTimeout(() => {\n localClient?.timeoutsByRequestId.delete(id);\n localClient?.pendingRemoteRequestIds.delete(id);\n this.dispatchLocalResponse(\n clientId,\n errorResponse(id, \"Timed out waiting for the database owner tab.\"),\n );\n }, CROSS_TAB_REQUEST_TIMEOUT_MS);\n localClient?.timeoutsByRequestId.set(id, timeoutId);\n }\n\n this.channel.postMessage({\n type: \"request\",\n clientId,\n hasClientLock,\n request,\n });\n }\n\n private dispatchLocalResponse(clientId: string, response: unknown): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchResponseToLocalClient(localClient, response);\n }\n }\n\n private dispatchLocalError(\n clientId: string,\n error: DatabaseWorkerCrashError,\n ): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n // A crashed owner worker is the same failure class as one that never\n // constructed: record it so routing fails fast instead of rebuilding the\n // crashed worker on the next bid (`contendForOwnership` and the post-release\n // retry both stop on `ownerError`), and fail every local client — including\n // one whose first request has not been routed yet, which is exactly where a\n // script-load failure lands. The next `createWorker()` (a fresh runtime boot)\n // clears the error and re-contends.\n private handleOwnerCrash(error: DatabaseWorkerCrashError): void {\n this.ownerError = error;\n for (const localClient of this.localClientsById.values()) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n private unregisterLocalClient(clientId: string): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n releaseLocalClient(localClient);\n }\n\n this.localClientsById.delete(clientId);\n }\n\n private handleChannelMessage(event: MessageEvent): void {\n const envelope = event.data;\n if (!isCrossTabEnvelope(envelope)) {\n return;\n }\n\n if (envelope.type === \"request\") {\n this.owner?.route(envelope.clientId, envelope.request, {\n hasClientLock: envelope.hasClientLock === true,\n });\n return;\n }\n\n if (envelope.type === \"error\") {\n this.dispatchLocalError(\n envelope.clientId,\n new DatabaseWorkerCrashError(envelope.detail),\n );\n return;\n }\n\n this.dispatchLocalResponse(envelope.clientId, envelope.response);\n }\n\n /**\n * Hold one blocking owner-lock bid. The current holder owns until it releases;\n * queued bidders are promoted when the holder disappears.\n */\n private contendForOwnership(): void {\n if (this.owner || this.ownershipBidActive || this.ownerError) {\n return;\n }\n\n const locks = lockManager();\n if (!locks) {\n // No Web Locks: unblock routing and rely on the request timeout.\n this.settleOwnership();\n return;\n }\n\n this.ownershipBidActive = true;\n const generation = this.ownershipGeneration;\n // A non-owner tab's blocking bid stays queued (never enters its callback)\n // until the current owner dies, so it cannot settle the routing gate on its\n // own. Settle it from here as soon as ownership is known either way.\n this.observeExistingOwner(locks, generation);\n\n let releasedNormally = false;\n\n void locks\n .request(CROSS_TAB_OWNER_LOCK_NAME, null, async () => {\n let releaseOwner: (() => void) | null = null;\n const ownerReleased = new Promise<void>((resolve) => {\n releaseOwner = resolve;\n });\n try {\n const owner = new CrossTabOwner(\n this.workerUrl,\n this.workerConstructor,\n this.channel,\n (clientId, response) =>\n this.dispatchLocalResponse(clientId, response),\n (error) => this.handleOwnerCrash(error),\n () => {\n if (this.owner === owner) {\n this.owner = null;\n // After a crash the gate stays settled: routing fails fast on\n // the recorded error instead of waiting for a bid that must\n // not run until a fresh client asks for one.\n if (!this.ownerError) {\n this.resetOwnershipGate();\n }\n }\n releaseOwner?.();\n },\n );\n this.owner = owner;\n this.ownerError = null;\n // Requests posted to the previous owner are orphaned; fail them with a\n // retryable error instead of waiting out the timeout.\n this.failPendingRemoteRequests();\n this.settleOwnership(generation);\n await ownerReleased;\n releasedNormally = true;\n } catch (error) {\n // This tab won ownership but could not stand up the owner worker. Record\n // the failure so its own clients see the error instead of hanging, then\n // rethrow to release the lock so another tab can try to own.\n this.owner = null;\n this.ownerError =\n error instanceof Error ? error : new Error(String(error));\n this.failPendingRemoteRequests();\n this.settleOwnership(generation);\n throw error;\n }\n })\n .catch(() => {\n // The bid itself failed (e.g. the lock manager rejected). Unblock routing\n // so requests fall back to the remote path instead of hanging forever.\n this.settleOwnership(generation);\n })\n .finally(() => {\n this.ownershipBidActive = false;\n const shouldRetryOwnership =\n releasedNormally || this.retryOwnershipAfterBid;\n this.retryOwnershipAfterBid = false;\n if (!shouldRetryOwnership) {\n return;\n }\n\n queueMicrotask(() => {\n if (this.hasOpenLocalClients() && !this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n });\n });\n }\n\n private hasOpenLocalClients(): boolean {\n for (const localClient of this.localClientsById.values()) {\n if (!localClient.closing) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Settle the initial routing gate on a tab that did NOT win ownership. Runs\n * concurrently with the blocking bid above; whichever resolves first settles the\n * gate (the bid settles it on the tab that becomes owner, this settles it on\n * every other tab). See {@link pollForOwner} for why this polls.\n *\n * Falls back to settling immediately when the lock manager cannot be queried, so\n * routing is never blocked indefinitely.\n */\n private observeExistingOwner(\n locks: LockManagerLike,\n generation: number,\n ): void {\n if (!locks.query) {\n // No query support: cannot observe another tab's owner without contending\n // for the lock (which would steal it). Settle so routing proceeds remotely.\n this.settleOwnership(generation);\n return;\n }\n\n void pollForOwner({\n locks,\n lockName: CROSS_TAB_OWNER_LOCK_NAME,\n hasOwner: () => this.owner !== null,\n settle: () => this.settleOwnership(generation),\n });\n }\n\n private resetOwnershipGate(): void {\n this.ownershipGeneration += 1;\n this.ownershipSettled = new Promise((resolve) => {\n this.settleOwnershipGate = resolve;\n });\n }\n\n private settleOwnership(generation = this.ownershipGeneration): void {\n if (generation !== this.ownershipGeneration) {\n return;\n }\n\n this.settleOwnershipGate();\n }\n\n /**\n * Whether some other tab currently holds the owner lock. Used by routing to\n * decide, when this tab's own owner failed to construct, between surfacing that\n * error (no owner anywhere) and falling back to a healthy remote owner. Returns\n * false when the lock cannot be queried, so routing posts remotely and lets the\n * request/timeout path decide rather than throwing a possibly-stale error.\n */\n private async anotherTabOwns(): Promise<boolean> {\n if (this.owner) {\n return false;\n }\n\n const locks = lockManager();\n return locks ? isOwnerLockHeld(locks, CROSS_TAB_OWNER_LOCK_NAME) : false;\n }\n\n // Called when this tab is promoted to owner: the owner its clients had posted\n // their remote requests to is gone, so fail them fast rather than time out.\n private failPendingRemoteRequests(): void {\n for (const localClient of this.localClientsById.values()) {\n failPendingRemoteRequests(localClient);\n }\n }\n}\n\nconst coordinatorsByWorkerUrl = new Map<string, CrossTabCoordinator>();\n\nexport function createCrossTabDatabaseWorker(\n workerUrl: string | URL,\n workerConstructor: ModuleWorkerConstructor,\n): CrossTabDatabaseWorker | null {\n if (!canUseCrossTabPrimitives()) {\n return null;\n }\n\n const key = String(workerUrl);\n let coordinator = coordinatorsByWorkerUrl.get(key);\n if (!coordinator) {\n coordinator = new CrossTabCoordinator(workerUrl, workerConstructor);\n coordinatorsByWorkerUrl.set(key, coordinator);\n }\n\n return coordinator.createWorker();\n}\n"]}
1
+ {"version":3,"file":"crossTabRuntime.js","sourceRoot":"","sources":["crossTabRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,0BAA0B,EAC1B,iBAAiB,EACjB,0BAA0B,EAC1B,6BAA6B,EAC7B,iBAAiB,EAEjB,kBAAkB,EAClB,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,wBAAwB,EAExB,WAAW,GACZ,MAAM,iBAAi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AAI,UAAU,KAAK,IAAI,CAAC,mBAAmB,EAAE,CAAC;YAC5C,OAAO;QACT,CAAC;QAED,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IAED;;;;;;OAMG;IACK,KAAK,CAAC,cAAc;QAC1B,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YACf,OAAO,KAAK,CAAC;QACf,CAAC;QAED,MAAM,KAAK,GAAG,WAAW,EAAE,CAAC;QAC5B,OAAO,KAAK,CAAC,CAAC,CAAC,eAAe,CAAC,KAAK,EAAE,yBAAyB,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC3E,CAAC;IAED,4EAA4E;IAC5E,gEAAgE;IACxD,+BAA+B;QACrC,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,EAAE,CAAC;YACzD,mCAAmC,CAAC,WAAW,CAAC,CAAC;QACnD,CAAC;IACH,CAAC;CACF;AAED,MAAM,uBAAuB,GAAG,IAAI,GAAG,EAA+B,CAAC;AAEvE,MAAM,UAAU,4BAA4B,CAC1C,SAAuB,EACvB,iBAA0C;IAE1C,IAAI,CAAC,wBAAwB,EAAE,EAAE,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;IAC9B,IAAI,WAAW,GAAG,uBAAuB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACnD,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,mBAAmB,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;QACpE,uBAAuB,CAAC,GAAG,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IAChD,CAAC;IAED,OAAO,WAAW,CAAC,YAAY,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type { WorkerLike } from \"./client\";\nimport {\n admitLocalClientRequest,\n assertLocalClientConnected,\n createLocalClient,\n dispatchCrashToLocalClient,\n dispatchResponseToLocalClient,\n isOpenLocalClient,\n type LocalClient,\n releaseLocalClient,\n releaseLocalClientFromPreviousOwner,\n} from \"./crossTabLocalClient\";\nimport {\n canUseCrossTabPrimitives,\n type LockManagerLike,\n lockManager,\n} from \"./crossTabLocks\";\nimport { CrossTabOwner, type ModuleWorkerConstructor } from \"./crossTabOwner\";\nimport { isOwnerLockHeld, pollForOwner } from \"./crossTabOwnership\";\nimport {\n errorResponse,\n isCrossTabEnvelope,\n requestId,\n} from \"./crossTabProtocol\";\nimport { DatabaseWorkerCrashError } from \"./workerCrash\";\n\nconst CROSS_TAB_CHANNEL_NAME = \"tearleads-sqlite-worker\";\nconst CROSS_TAB_OWNER_LOCK_NAME = \"tearleads-sqlite-worker-owner\";\nconst CROSS_TAB_REQUEST_TIMEOUT_MS = 10_000;\n\ninterface CrossTabDatabaseWorker extends WorkerLike {\n close(): void;\n /**\n * Abrupt teardown for a runtime that could not close gracefully — its worker\n * went silent, so the `close` round-trip never came back to stop the owner via\n * {@link CrossTabOwner.stop}. Unregisters this client and, when safe, force-stops\n * the owner so the next boot re-contends and builds a fresh owner instead of\n * routing into the dead one. See {@link CrossTabCoordinator.forceStopOwnerFor}.\n */\n forceStopOwner(): void;\n}\n\nclass CrossTabCoordinator {\n private readonly channel = new BroadcastChannel(CROSS_TAB_CHANNEL_NAME);\n private hasCreatedClient = false;\n private readonly localClientsById = new Map<string, LocalClient>();\n private owner: CrossTabOwner | null = null;\n // Set if this tab won ownership but its owner worker failed to construct.\n // Cleared if a later bid succeeds in installing an owner.\n private ownerError: Error | null = null;\n // Resolves when ownership is settled for the current owner generation (this tab\n // won and installed/failed to construct an owner, or it observed another tab\n // already owns), so routing never posts remotely while no owner exists.\n private ownershipBidActive = false;\n private ownershipGeneration = 0;\n private ownershipSettled: Promise<void> = Promise.resolve();\n private retryOwnershipAfterBid = false;\n private settleOwnershipGate: () => void = () => {};\n\n constructor(\n private readonly workerUrl: string | URL,\n private readonly workerConstructor: ModuleWorkerConstructor,\n ) {\n this.resetOwnershipGate();\n this.channel.addEventListener(\"message\", (event) => {\n this.handleChannelMessage(event);\n });\n // Start the first ownership bid; later clients can restart it after teardown.\n this.contendForOwnership();\n }\n\n createWorker(): CrossTabDatabaseWorker {\n const clientId = crypto.randomUUID();\n const events = new EventTarget();\n if (this.ownerError && this.hasCreatedClient) {\n this.ownerError = null;\n this.retryOwnershipAfterBid = this.ownershipBidActive;\n this.resetOwnershipGate();\n }\n this.localClientsById.set(clientId, createLocalClient(clientId, events));\n this.hasCreatedClient = true;\n this.contendForOwnership();\n\n return {\n postMessage: (message) => {\n this.route(clientId, message);\n },\n addEventListener(type, listener) {\n events.addEventListener(type, listener);\n },\n removeEventListener(type, listener) {\n events.removeEventListener(type, listener);\n },\n close: () => {\n this.unregisterLocalClient(clientId);\n },\n forceStopOwner: () => {\n this.forceStopOwnerFor(clientId);\n },\n };\n }\n\n /**\n * Tear down a possibly-wedged owner on abrupt runtime teardown.\n *\n * `this.owner` is normally cleared only when the dedicated worker answers a\n * `close`/`delete` (→ {@link CrossTabOwner.stop} via `handleWorkerResponse`). A\n * worker hung inside OPFS never answers, so that path never runs and the plain\n * client `close()` (just {@link unregisterLocalClient}) leaves `this.owner`\n * pinned to the dead worker — every later boot then routes its `init` straight\n * into it over the untimed local path and hangs. Because the coordinator is a\n * per-URL module singleton, that pins EVERY database, not just the one that\n * wedged.\n *\n * So on abrupt teardown, after unregistering the client, stop the owner —\n * `stop()` terminates the worker, releases the owner lock, and (via the release\n * callback) nulls `this.owner` + resets the gate, so the next `createWorker()`\n * re-contends and constructs a fresh owner. Gated to stay multi-tab-safe: only\n * when this tab has no other open local client AND the owner serves no other\n * (remote) client, so it can never strand a sibling tab still routing here.\n *\n * The remote-client half of the gate reads the owner's `activeClientIds`, which\n * is coarse: a wedged local client that was force-torn-down without a close\n * response leaves a *stale* id there (only a close-response or the liveness sweep\n * removes it). So if TWO local clients on one coordinator were wedged and torn\n * down in the same tick, the second would see the first's stale id and decline to\n * stop — leaving the wedge unhealed. That cannot happen here: the app drives a\n * single runtime at a time (`useManagedSQLiteRuntime` holds one runtimeRef and\n * defers each spawn on the prior release), so a coordinator never has two live\n * local clients. The gate therefore errs, at worst, toward NOT stopping — which\n * only ever risks a missed heal, never wrongly stranding a real remote tab.\n */\n private forceStopOwnerFor(clientId: string): void {\n // A lost client's database died with an earlier owner; the current owner\n // may never have served it, so its silence is no reason to stop it.\n const lost =\n this.localClientsById.get(clientId)?.connection.status === \"lost\";\n this.unregisterLocalClient(clientId);\n if (lost || this.hasOpenLocalClients()) {\n return;\n }\n\n const owner = this.owner;\n if (owner && !owner.hasActiveClientsExcept(clientId)) {\n owner.stop();\n }\n }\n\n private route(clientId: string, request: unknown): void {\n void this.routeAsync(clientId, request);\n }\n\n private async routeAsync(clientId: string, request: unknown): Promise<void> {\n const id = requestId(request);\n try {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n admitLocalClientRequest(localClient, request);\n }\n\n const hasClientLock = await this.waitForLocalClientLock(clientId);\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n // Wait for ownership so this request is not posted into the void.\n if (!this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n await this.ownershipSettled;\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n // A client can be lost while it waits, when this tab is promoted.\n if (localClient) {\n assertLocalClientConnected(localClient);\n }\n\n if (this.owner) {\n this.owner.route(clientId, request, { hasClientLock });\n return;\n }\n\n // This tab won ownership earlier but its owner worker failed to construct.\n // If another tab has since become a healthy owner, fall back to it; only\n // surface the construction error when no owner exists anywhere, so a single\n // tab whose worker cannot start fails fast instead of hanging on the timeout.\n if (this.ownerError && !(await this.anotherTabOwns())) {\n throw this.ownerError;\n }\n\n this.postRemoteRequest(clientId, request, hasClientLock);\n } catch (error: unknown) {\n if (id !== null) {\n this.dispatchLocalResponse(\n clientId,\n errorResponse(\n id,\n error instanceof Error\n ? error.message\n : \"Failed to route database request.\",\n ),\n );\n }\n }\n }\n\n private async waitForLocalClientLock(clientId: string): Promise<boolean> {\n const localClient = this.localClientsById.get(clientId);\n if (!localClient) {\n return false;\n }\n\n return localClient.liveness.ready;\n }\n\n private postRemoteRequest(\n clientId: string,\n request: unknown,\n hasClientLock: boolean,\n ): void {\n const id = requestId(request);\n if (id !== null) {\n const localClient = this.localClientsById.get(clientId);\n localClient?.pendingRemoteRequestIds.add(id);\n const timeoutId = setTimeout(() => {\n localClient?.timeoutsByRequestId.delete(id);\n localClient?.pendingRemoteRequestIds.delete(id);\n this.dispatchLocalResponse(\n clientId,\n errorResponse(id, \"Timed out waiting for the database owner tab.\"),\n );\n }, CROSS_TAB_REQUEST_TIMEOUT_MS);\n localClient?.timeoutsByRequestId.set(id, timeoutId);\n }\n\n this.channel.postMessage({\n type: \"request\",\n clientId,\n hasClientLock,\n request,\n });\n }\n\n private dispatchLocalResponse(clientId: string, response: unknown): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchResponseToLocalClient(localClient, response);\n }\n }\n\n private dispatchLocalError(\n clientId: string,\n error: DatabaseWorkerCrashError,\n ): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n // A crashed owner worker is the same failure class as one that never\n // constructed: record it so routing fails fast instead of rebuilding the\n // crashed worker on the next bid (`contendForOwnership` and the post-release\n // retry both stop on `ownerError`), and fail every local client — including\n // one whose first request has not been routed yet, which is exactly where a\n // script-load failure lands. The next `createWorker()` (a fresh runtime boot)\n // clears the error and re-contends.\n private handleOwnerCrash(error: DatabaseWorkerCrashError): void {\n this.ownerError = error;\n for (const localClient of this.localClientsById.values()) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n private unregisterLocalClient(clientId: string): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n releaseLocalClient(localClient);\n }\n\n this.localClientsById.delete(clientId);\n }\n\n private handleChannelMessage(event: MessageEvent): void {\n const envelope = event.data;\n if (!isCrossTabEnvelope(envelope)) {\n return;\n }\n\n if (envelope.type === \"request\") {\n this.owner?.route(envelope.clientId, envelope.request, {\n hasClientLock: envelope.hasClientLock === true,\n });\n return;\n }\n\n if (envelope.type === \"error\") {\n this.dispatchLocalError(\n envelope.clientId,\n new DatabaseWorkerCrashError(envelope.detail),\n );\n return;\n }\n\n this.dispatchLocalResponse(envelope.clientId, envelope.response);\n }\n\n /**\n * Hold one blocking owner-lock bid. The current holder owns until it releases;\n * queued bidders are promoted when the holder disappears.\n */\n private contendForOwnership(): void {\n if (this.owner || this.ownershipBidActive || this.ownerError) {\n return;\n }\n\n const locks = lockManager();\n if (!locks) {\n // No Web Locks: unblock routing and rely on the request timeout.\n this.settleOwnership();\n return;\n }\n\n this.ownershipBidActive = true;\n const generation = this.ownershipGeneration;\n // A non-owner tab's blocking bid stays queued (never enters its callback)\n // until the current owner dies, so it cannot settle the routing gate on its\n // own. Settle it from here as soon as ownership is known either way.\n this.observeExistingOwner(locks, generation);\n\n let releasedNormally = false;\n\n void locks\n .request(CROSS_TAB_OWNER_LOCK_NAME, null, async () => {\n let releaseOwner: (() => void) | null = null;\n const ownerReleased = new Promise<void>((resolve) => {\n releaseOwner = resolve;\n });\n try {\n const owner = new CrossTabOwner(\n this.workerUrl,\n this.workerConstructor,\n this.channel,\n (clientId, response) =>\n this.dispatchLocalResponse(clientId, response),\n (error) => this.handleOwnerCrash(error),\n () => {\n if (this.owner === owner) {\n this.owner = null;\n // After a crash the gate stays settled: routing fails fast on\n // the recorded error instead of waiting for a bid that must\n // not run until a fresh client asks for one.\n if (!this.ownerError) {\n this.resetOwnershipGate();\n }\n }\n releaseOwner?.();\n },\n );\n this.owner = owner;\n this.ownerError = null;\n // The previous owner is gone, with every database it had open.\n this.releaseClientsFromPreviousOwner();\n this.settleOwnership(generation);\n await ownerReleased;\n releasedNormally = true;\n } catch (error) {\n // This tab won ownership but could not stand up the owner worker. Record\n // the failure so its own clients see the error instead of hanging, then\n // rethrow to release the lock so another tab can try to own.\n this.owner = null;\n this.ownerError =\n error instanceof Error ? error : new Error(String(error));\n this.releaseClientsFromPreviousOwner();\n this.settleOwnership(generation);\n throw error;\n }\n })\n .catch(() => {\n // The bid itself failed (e.g. the lock manager rejected). Unblock routing\n // so requests fall back to the remote path instead of hanging forever.\n this.settleOwnership(generation);\n })\n .finally(() => {\n this.ownershipBidActive = false;\n const shouldRetryOwnership =\n releasedNormally || this.retryOwnershipAfterBid;\n this.retryOwnershipAfterBid = false;\n if (!shouldRetryOwnership) {\n return;\n }\n\n queueMicrotask(() => {\n if (this.hasOpenLocalClients() && !this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n });\n });\n }\n\n private hasOpenLocalClients(): boolean {\n for (const localClient of this.localClientsById.values()) {\n if (isOpenLocalClient(localClient)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Settle the initial routing gate on a tab that did NOT win ownership. Runs\n * concurrently with the blocking bid above; whichever resolves first settles the\n * gate (the bid settles it on the tab that becomes owner, this settles it on\n * every other tab). See {@link pollForOwner} for why this polls.\n *\n * Falls back to settling immediately when the lock manager cannot be queried, so\n * routing is never blocked indefinitely.\n */\n private observeExistingOwner(\n locks: LockManagerLike,\n generation: number,\n ): void {\n if (!locks.query) {\n // No query support: cannot observe another tab's owner without contending\n // for the lock (which would steal it). Settle so routing proceeds remotely.\n this.settleOwnership(generation);\n return;\n }\n\n void pollForOwner({\n locks,\n lockName: CROSS_TAB_OWNER_LOCK_NAME,\n hasOwner: () => this.owner !== null,\n settle: () => this.settleOwnership(generation),\n });\n }\n\n private resetOwnershipGate(): void {\n this.ownershipGeneration += 1;\n this.ownershipSettled = new Promise((resolve) => {\n this.settleOwnershipGate = resolve;\n });\n }\n\n private settleOwnership(generation = this.ownershipGeneration): void {\n if (generation !== this.ownershipGeneration) {\n return;\n }\n\n this.settleOwnershipGate();\n }\n\n /**\n * Whether some other tab currently holds the owner lock. Used by routing to\n * decide, when this tab's own owner failed to construct, between surfacing that\n * error (no owner anywhere) and falling back to a healthy remote owner. Returns\n * false when the lock cannot be queried, so routing posts remotely and lets the\n * request/timeout path decide rather than throwing a possibly-stale error.\n */\n private async anotherTabOwns(): Promise<boolean> {\n if (this.owner) {\n return false;\n }\n\n const locks = lockManager();\n return locks ? isOwnerLockHeld(locks, CROSS_TAB_OWNER_LOCK_NAME) : false;\n }\n\n // Called when this tab takes the owner lock: the owner its clients had been\n // routing to is gone (see releaseLocalClientFromPreviousOwner).\n private releaseClientsFromPreviousOwner(): void {\n for (const localClient of this.localClientsById.values()) {\n releaseLocalClientFromPreviousOwner(localClient);\n }\n }\n}\n\nconst coordinatorsByWorkerUrl = new Map<string, CrossTabCoordinator>();\n\nexport function createCrossTabDatabaseWorker(\n workerUrl: string | URL,\n workerConstructor: ModuleWorkerConstructor,\n): CrossTabDatabaseWorker | null {\n if (!canUseCrossTabPrimitives()) {\n return null;\n }\n\n const key = String(workerUrl);\n let coordinator = coordinatorsByWorkerUrl.get(key);\n if (!coordinator) {\n coordinator = new CrossTabCoordinator(workerUrl, workerConstructor);\n coordinatorsByWorkerUrl.set(key, coordinator);\n }\n\n return coordinator.createWorker();\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { type DatabaseWorkerClient, type WorkerLike } from "./client.js";
2
2
  import { type DatabaseRuntimeMessageChannelConstructor } from "./renewedClientTransport.js";
3
+ export { DatabaseConnectionLostError, isDatabaseConnectionLostError, } from "./workerCrash.js";
3
4
  interface TerminableWorkerLike extends WorkerLike {
4
5
  terminate(): void;
5
6
  }
@@ -93,4 +94,3 @@ export interface CreateModuleDatabaseRuntimeOptions {
93
94
  export declare function createDatabaseRuntime(worker: TerminableWorkerLike, messageChannelConstructor?: DatabaseRuntimeMessageChannelConstructor | null): DatabaseRuntime;
94
95
  export declare function createSharedDatabaseRuntime(worker: CloseableWorkerLike): DatabaseRuntime;
95
96
  export declare function createModuleDatabaseRuntime(options?: CreateModuleDatabaseRuntimeOptions): DatabaseRuntime;
96
- export {};
@@ -3,6 +3,7 @@ import { createDatabaseWorkerClient, } from "./client.js";
3
3
  import { createCrossTabDatabaseWorker } from "./crossTabRuntime.js";
4
4
  import { availableMessageChannelConstructor, closeMessagePort, createRenewedDatabaseClient, disconnectMessagePort, } from "./renewedClientTransport.js";
5
5
  import { workerCrashErrorFromEvent } from "./workerCrash.js";
6
+ export { DatabaseConnectionLostError, isDatabaseConnectionLostError, } from "./workerCrash.js";
6
7
  const DEFAULT_DATABASE_WORKER_URL = "/worker.js";
7
8
  const DEFAULT_SHARED_DATABASE_WORKER_NAME = "tearleads-sqlite-worker";
8
9
  function subscribeWorkerError(worker) {