@pmate/chat-sdk 0.13.0-profile.8 → 0.13.0-profile.9
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 +16 -0
- package/lib/profile.d.ts +1 -1
- package/lib/profile.js +1 -1
- package/lib/runtime/profileCommitQueue.js +3 -3
- package/lib/runtime/profileCoordinator.d.ts +19 -20
- package/lib/runtime/profileCoordinator.js +123 -128
- package/lib/runtime/profileDatabase.d.ts +6 -9
- package/lib/runtime/profileDatabase.js +8 -38
- package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
- package/lib/runtime/profileGenerationBuilder.js +6 -10
- package/lib/runtime/profileMemoryStore.d.ts +1 -1
- package/lib/runtime/profileMemoryStore.js +1 -1
- package/lib/runtime/profileOwner.d.ts +0 -7
- package/lib/runtime/profileOwner.js +9 -41
- package/lib/runtime/profileStoreTypes.d.ts +1 -10
- package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +9 -26
- package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +45 -97
- package/lib/runtime/profileWorkerHost.d.ts +3 -6
- package/lib/runtime/profileWorkerHost.js +23 -30
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -373,3 +373,19 @@ Empty ten-second checks and duplicate notifications do not open a projection
|
|
|
373
373
|
write transaction. Received receipt batches insert only new keys in one bulk
|
|
374
374
|
write. Own viewport read observations are coalesced over 100ms before their
|
|
375
375
|
pending intents become durable; callers resolve after commit.
|
|
376
|
+
|
|
377
|
+
## Profile Worker runtime (0.13 preview)
|
|
378
|
+
|
|
379
|
+
### Background
|
|
380
|
+
|
|
381
|
+
The Profile runtime prepares the full retained Inbox range once and exposes message windows from memory. Merry runs one application document: creating a distributed writer, lease and replica for every page is unnecessary and can block a healthy UI after a backgrounded WebView stops responding.
|
|
382
|
+
|
|
383
|
+
`ProfileCoordinator` now creates one Dedicated Worker for the active Profile and receives committed deltas over that Worker's ordered message port. `start()` is shared, `memory` retains its identity across Worker restarts, and `submit`, `synchronize`, `waitForCommand` and `voiceAttachment` delegate to the direct connection. Consumers must remove calls to the former `replica.repair()`; normal synchronization publishes its committed changes before its reply. `ProfileWorkerClient` replaces the former distributed `ProfileReplica` export.
|
|
384
|
+
|
|
385
|
+
There is no BroadcastChannel, delta journal, status poll, TTL lease, renewal or writer takeover in this runtime. A lifetime Web Lock excludes another document using the same Profile; the second gets `PROFILE_ALREADY_OPEN` and should ask the user to return to the original tab. This lock uses the previous writer lock name so an older lock-based client cannot race the upgrade. Supported browsers must provide Web Locks. Native page navigation stays inside the original document.
|
|
386
|
+
|
|
387
|
+
The per-Profile database upgrades to schema 2 by deleting only the obsolete `lease` record. Existing messages, windows, reading facts, generation progress, cursor and outbox remain. The serial commit queue still atomically persists changed records and the Inbox cursor before publication. Failed disk transactions retry after the existing ten-second interval. A revision conflict requires restarting from committed state rather than endlessly retrying a stale projection.
|
|
388
|
+
|
|
389
|
+
On a Worker error or command timeout, the coordinator terminates the old Worker before replacement. The replacement restores committed data into the same UI memory store. An interrupted command is replayed with its original IDs; a message committed before a lost reply remains one message. Waiting for remote delivery does not itself time out or repeatedly restart an offline Worker. Completed generation switches publish one prepared snapshot; routine updates send only their delta.
|
|
390
|
+
|
|
391
|
+
Tests cover v1 upgrade preservation, atomic writes, idle zero transactions, one Worker on concurrent startup, serial restart, crash after commit/before reply, immediate startup cancellation, generation switching, and memory-only reads/subscriptions. Native frame rate, real-account upgrade and server synchronization still require application acceptance.
|
package/lib/profile.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { ProfileDatabase, profileDatabaseName } from "./runtime/profileDatabase.js";
|
|
2
2
|
export { ProfileOwner } from "./runtime/profileOwner.js";
|
|
3
3
|
export { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./runtime/profileMemoryStore.js";
|
|
4
|
-
export {
|
|
4
|
+
export { ProfileWorkerClient, serveProfileWorker } from "./runtime/profileWorkerClient.js";
|
|
5
5
|
export { connectProfileWorker, installProfileWorker, profileChannelName } from "./runtime/profileWorkerHost.js";
|
|
6
6
|
export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
7
7
|
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
package/lib/profile.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { ProfileDatabase, profileDatabaseName } from "./runtime/profileDatabase.js";
|
|
2
2
|
export { ProfileOwner } from "./runtime/profileOwner.js";
|
|
3
3
|
export { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./runtime/profileMemoryStore.js";
|
|
4
|
-
export {
|
|
4
|
+
export { ProfileWorkerClient, serveProfileWorker } from "./runtime/profileWorkerClient.js";
|
|
5
5
|
export { connectProfileWorker, installProfileWorker, profileChannelName } from "./runtime/profileWorkerHost.js";
|
|
6
6
|
export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
7
7
|
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
|
@@ -84,9 +84,9 @@ export class ProfileCommitQueue {
|
|
|
84
84
|
entry.resolve(); });
|
|
85
85
|
}
|
|
86
86
|
catch (error) {
|
|
87
|
-
if (error?.message
|
|
88
|
-
//
|
|
89
|
-
//
|
|
87
|
+
if (["PROFILE_REVISION_CONFLICT", "PROFILE_GENERATION_MISMATCH"].includes(error?.message)) {
|
|
88
|
+
// A stale projection cannot become valid by retrying the same batch.
|
|
89
|
+
// Restart the Worker from its last committed database state.
|
|
90
90
|
this.closed = true;
|
|
91
91
|
clearTimeout(this.timer);
|
|
92
92
|
const pending = this.entries.splice(0);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
2
|
+
import { ProfileWorkerClient, type ProfileMessagePort } from "./profileWorkerClient.js";
|
|
2
3
|
import { type ProfileWorkerConfiguration } from "./profileWorkerHost.js";
|
|
3
4
|
import type { ProfileOperation } from "./profileProjection.js";
|
|
4
5
|
type WorkerHandle = ProfileMessagePort & {
|
|
@@ -7,40 +8,38 @@ type WorkerHandle = ProfileMessagePort & {
|
|
|
7
8
|
export type ProfileCoordinatorOptions = {
|
|
8
9
|
configuration: ProfileWorkerConfiguration;
|
|
9
10
|
createWorker: () => WorkerHandle;
|
|
10
|
-
channel?: (name: string) => ProfileMessagePort & {
|
|
11
|
-
close(): void;
|
|
12
|
-
};
|
|
13
11
|
onError?: (error: unknown) => void;
|
|
14
12
|
onProgress?: (progress: unknown) => void;
|
|
15
13
|
requestTimeoutMs?: number;
|
|
16
|
-
retryMs?: number;
|
|
17
14
|
};
|
|
18
|
-
/**
|
|
19
|
-
*
|
|
15
|
+
/** One application document, one dedicated Worker and one stable UI memory store.
|
|
16
|
+
* A failed Worker is terminated before its replacement is created. */
|
|
20
17
|
export declare class ProfileCoordinator {
|
|
21
18
|
private options;
|
|
22
|
-
readonly
|
|
23
|
-
private channel;
|
|
19
|
+
readonly memory: ProfileMemoryStore;
|
|
24
20
|
private worker?;
|
|
21
|
+
private connection?;
|
|
25
22
|
private host?;
|
|
26
|
-
private acquiring?;
|
|
27
|
-
private timer?;
|
|
28
|
-
private closed;
|
|
29
|
-
private needsOwner;
|
|
30
23
|
private starting?;
|
|
31
|
-
private
|
|
24
|
+
private restarting?;
|
|
25
|
+
private openingAbort?;
|
|
26
|
+
private closed;
|
|
32
27
|
get identity(): import("./inboxStore.js").InboxScope;
|
|
33
|
-
get
|
|
34
|
-
submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
|
|
35
|
-
synchronize(): Promise<void>;
|
|
36
|
-
waitForCommand(id: string): Promise<void>;
|
|
37
|
-
voiceAttachment(id: string): Promise<Blob | null>;
|
|
28
|
+
get client(): ProfileWorkerClient;
|
|
38
29
|
constructor(options: ProfileCoordinatorOptions);
|
|
39
30
|
private report;
|
|
40
31
|
private workerMessage;
|
|
32
|
+
private workerFailed;
|
|
33
|
+
private listenFailure;
|
|
41
34
|
start(): Promise<void>;
|
|
42
35
|
private initialize;
|
|
43
|
-
private
|
|
36
|
+
private disposeWorker;
|
|
37
|
+
restart(): Promise<void>;
|
|
38
|
+
private invoke;
|
|
39
|
+
submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
|
|
40
|
+
synchronize(): Promise<void>;
|
|
41
|
+
waitForCommand(id: string): Promise<void>;
|
|
42
|
+
voiceAttachment(id: string): Promise<Blob | null>;
|
|
44
43
|
updateToken(token: string): Promise<void>;
|
|
45
44
|
close(): Promise<void>;
|
|
46
45
|
}
|
|
@@ -1,173 +1,168 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
2
|
+
import { ProfileWorkerClient } from "./profileWorkerClient.js";
|
|
2
3
|
import { openProfileWorker, profileChannelName } from "./profileWorkerHost.js";
|
|
3
|
-
/**
|
|
4
|
-
*
|
|
4
|
+
/** One application document, one dedicated Worker and one stable UI memory store.
|
|
5
|
+
* A failed Worker is terminated before its replacement is created. */
|
|
5
6
|
export class ProfileCoordinator {
|
|
6
7
|
options;
|
|
7
|
-
|
|
8
|
-
channel;
|
|
8
|
+
memory;
|
|
9
9
|
worker;
|
|
10
|
+
connection;
|
|
10
11
|
host;
|
|
11
|
-
acquiring;
|
|
12
|
-
timer;
|
|
13
|
-
closed = false;
|
|
14
|
-
needsOwner = false;
|
|
15
12
|
starting;
|
|
16
|
-
|
|
13
|
+
restarting;
|
|
14
|
+
openingAbort;
|
|
15
|
+
closed = false;
|
|
17
16
|
get identity() { return this.options.configuration.identity; }
|
|
18
|
-
get
|
|
19
|
-
|
|
20
|
-
synchronize() { return this.replica.synchronize(); }
|
|
21
|
-
waitForCommand(id) { return this.replica.waitForCommand(id); }
|
|
22
|
-
voiceAttachment(id) { return this.replica.voiceAttachment(id); }
|
|
17
|
+
get client() { if (!this.connection)
|
|
18
|
+
throw Error("PROFILE_WORKER_NOT_STARTED"); return this.connection; }
|
|
23
19
|
constructor(options) {
|
|
24
20
|
this.options = options;
|
|
25
|
-
|
|
26
|
-
this.channel = options.channel?.(scope) ?? new BroadcastChannel(scope);
|
|
27
|
-
this.channel.addEventListener("message", this.workerMessage);
|
|
28
|
-
this.replica = new ProfileReplica(this.channel, scope, error => {
|
|
29
|
-
this.report(error);
|
|
30
|
-
if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
|
|
31
|
-
this.needsOwner = true;
|
|
32
|
-
void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
|
|
33
|
-
}
|
|
34
|
-
}, options.requestTimeoutMs ?? 5000, options.configuration.identity.profileId);
|
|
21
|
+
this.memory = new ProfileMemoryStore(error => this.report(error), this.identity.profileId);
|
|
35
22
|
}
|
|
36
23
|
report(error) { try {
|
|
37
24
|
this.options.onError?.(error);
|
|
38
25
|
}
|
|
39
26
|
catch { } }
|
|
40
27
|
workerMessage = (event) => {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
if (event.data?.profileControl === "progress") {
|
|
28
|
+
const data = event.data;
|
|
29
|
+
if (data?.profileControl === "credentials" && typeof data.token === "string" && data.token && data.token.length <= 65536 && this.options.configuration.network)
|
|
30
|
+
this.options.configuration.network = { ...this.options.configuration.network, token: data.token };
|
|
31
|
+
if (data?.profileControl === "progress") {
|
|
47
32
|
try {
|
|
48
|
-
this.options.onProgress?.(
|
|
33
|
+
this.options.onProgress?.(data.progress);
|
|
49
34
|
}
|
|
50
35
|
catch { }
|
|
51
36
|
}
|
|
52
|
-
if (
|
|
53
|
-
this.report(Error(
|
|
54
|
-
if (
|
|
55
|
-
this.
|
|
56
|
-
void this.acquire().then(() => this.replica.repair()).catch(error => this.report(error));
|
|
57
|
-
}
|
|
37
|
+
if (data?.profileControl === "error") {
|
|
38
|
+
this.report(Error(data.error));
|
|
39
|
+
if (["PROFILE_REVISION_CONFLICT", "PROFILE_GENERATION_MISMATCH"].includes(data.error))
|
|
40
|
+
this.workerFailed();
|
|
58
41
|
}
|
|
59
42
|
};
|
|
43
|
+
workerFailed = () => { void this.restart().catch(error => this.report(error)); };
|
|
44
|
+
listenFailure(worker, add) {
|
|
45
|
+
// Dedicated Workers have error/messageerror; structural test ports may omit them.
|
|
46
|
+
const target = worker;
|
|
47
|
+
const method = add ? "addEventListener" : "removeEventListener";
|
|
48
|
+
target[method]("error", this.workerFailed);
|
|
49
|
+
target[method]("messageerror", this.workerFailed);
|
|
50
|
+
}
|
|
60
51
|
start() {
|
|
52
|
+
if (this.closed)
|
|
53
|
+
return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
|
|
54
|
+
if (this.restarting)
|
|
55
|
+
return this.restarting;
|
|
61
56
|
if (this.starting)
|
|
62
57
|
return this.starting;
|
|
63
|
-
|
|
58
|
+
if (this.connection)
|
|
59
|
+
return Promise.resolve();
|
|
60
|
+
const task = this.initialize().catch(error => {
|
|
61
|
+
if (this.starting === task)
|
|
62
|
+
this.starting = undefined;
|
|
63
|
+
if (!this.closed)
|
|
64
|
+
this.report(error);
|
|
65
|
+
throw error;
|
|
66
|
+
});
|
|
64
67
|
this.starting = task;
|
|
65
68
|
return task;
|
|
66
69
|
}
|
|
67
70
|
async initialize() {
|
|
68
|
-
|
|
69
|
-
|
|
71
|
+
const worker = this.options.createWorker();
|
|
72
|
+
this.worker = worker;
|
|
73
|
+
const abort = new AbortController();
|
|
74
|
+
this.openingAbort = abort;
|
|
75
|
+
worker.addEventListener("message", this.workerMessage);
|
|
76
|
+
this.listenFailure(worker, true);
|
|
77
|
+
try {
|
|
78
|
+
const host = await openProfileWorker(worker, this.options.configuration, this.options.requestTimeoutMs, abort.signal);
|
|
79
|
+
if (this.closed || this.worker !== worker)
|
|
70
80
|
throw Error("PROFILE_COORDINATOR_CLOSED");
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
await this.replica.start(false);
|
|
74
|
-
break;
|
|
75
|
-
}
|
|
76
|
-
catch (error) {
|
|
77
|
-
if (this.closed)
|
|
78
|
-
throw Error("PROFILE_COORDINATOR_CLOSED");
|
|
79
|
-
if (!["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE", "PROFILE_WORKER_TIMEOUT"].includes(error?.message))
|
|
80
|
-
throw error;
|
|
81
|
+
this.host = host;
|
|
82
|
+
const client = new ProfileWorkerClient(worker, profileChannelName(this.identity), error => {
|
|
81
83
|
this.report(error);
|
|
82
|
-
this.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
84
|
+
this.workerFailed();
|
|
85
|
+
}, this.options.requestTimeoutMs, this.identity.profileId, this.memory);
|
|
86
|
+
this.connection = client;
|
|
87
|
+
await client.start();
|
|
88
|
+
if (this.closed || this.worker !== worker)
|
|
89
|
+
throw Error("PROFILE_COORDINATOR_CLOSED");
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (this.worker === worker)
|
|
93
|
+
this.disposeWorker();
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
disposeWorker() {
|
|
98
|
+
this.openingAbort?.abort(Error("PROFILE_WORKER_CLIENT_CLOSED"));
|
|
99
|
+
this.openingAbort = undefined;
|
|
100
|
+
this.connection?.close();
|
|
101
|
+
this.connection = undefined;
|
|
102
|
+
this.host = undefined;
|
|
103
|
+
const worker = this.worker;
|
|
104
|
+
this.worker = undefined;
|
|
105
|
+
if (worker) {
|
|
106
|
+
worker.removeEventListener("message", this.workerMessage);
|
|
107
|
+
this.listenFailure(worker, false);
|
|
108
|
+
worker.terminate();
|
|
88
109
|
}
|
|
89
|
-
if (!this.timer)
|
|
90
|
-
this.timer = setInterval(() => {
|
|
91
|
-
void this.replica.check().catch(error => {
|
|
92
|
-
this.report(error);
|
|
93
|
-
if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
|
|
94
|
-
this.needsOwner = true;
|
|
95
|
-
void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
|
|
96
|
-
}
|
|
97
|
-
});
|
|
98
|
-
}, this.options.retryMs ?? 10000);
|
|
99
110
|
}
|
|
100
|
-
|
|
111
|
+
restart() {
|
|
101
112
|
if (this.closed)
|
|
102
113
|
return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
|
|
103
|
-
if (this.
|
|
104
|
-
return this.
|
|
105
|
-
|
|
106
|
-
|
|
114
|
+
if (this.restarting)
|
|
115
|
+
return this.restarting;
|
|
116
|
+
const previous = this.starting;
|
|
117
|
+
this.disposeWorker();
|
|
118
|
+
this.starting = undefined;
|
|
107
119
|
const task = (async () => {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
this.host = undefined;
|
|
113
|
-
}
|
|
114
|
-
const worker = this.options.createWorker();
|
|
115
|
-
worker.addEventListener("message", this.workerMessage);
|
|
116
|
-
try {
|
|
117
|
-
const host = await openProfileWorker(worker, this.options.configuration);
|
|
118
|
-
if (this.closed) {
|
|
119
|
-
await host.close();
|
|
120
|
-
worker.terminate();
|
|
121
|
-
return;
|
|
122
|
-
}
|
|
123
|
-
this.worker = worker;
|
|
124
|
-
this.host = host;
|
|
125
|
-
this.needsOwner = false;
|
|
126
|
-
}
|
|
127
|
-
catch (error) {
|
|
128
|
-
worker.removeEventListener("message", this.workerMessage);
|
|
129
|
-
worker.terminate();
|
|
130
|
-
if (error?.message !== "PROFILE_OWNER_UNAVAILABLE")
|
|
131
|
-
throw error;
|
|
132
|
-
// Another healthy writer serves this replica through the shared channel.
|
|
133
|
-
this.needsOwner = false;
|
|
134
|
-
}
|
|
120
|
+
await previous?.catch(() => { });
|
|
121
|
+
if (this.closed)
|
|
122
|
+
throw Error("PROFILE_COORDINATOR_CLOSED");
|
|
123
|
+
await this.initialize();
|
|
135
124
|
})();
|
|
136
|
-
this.
|
|
137
|
-
void task.finally(() => {
|
|
138
|
-
this.
|
|
125
|
+
this.restarting = task;
|
|
126
|
+
void task.finally(() => {
|
|
127
|
+
if (this.restarting === task) {
|
|
128
|
+
this.restarting = undefined;
|
|
129
|
+
this.starting = undefined;
|
|
130
|
+
}
|
|
131
|
+
}).catch(() => { });
|
|
139
132
|
return task;
|
|
140
133
|
}
|
|
134
|
+
async invoke(call) {
|
|
135
|
+
await this.start();
|
|
136
|
+
try {
|
|
137
|
+
return await call(this.client);
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (!["PROFILE_WORKER_TIMEOUT", "PROFILE_WORKER_CLIENT_CLOSED"].includes(error?.message) || this.closed)
|
|
141
|
+
throw error;
|
|
142
|
+
await this.restart();
|
|
143
|
+
// Commands retain their original message/command IDs, making replay safe
|
|
144
|
+
// when the old Worker committed before its response was interrupted.
|
|
145
|
+
return call(this.client);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
submit(operation, immediate = false) { return this.invoke(client => client.submit(operation, immediate)); }
|
|
149
|
+
synchronize() { return this.invoke(client => client.synchronize()); }
|
|
150
|
+
waitForCommand(id) { return this.invoke(client => client.waitForCommand(id)); }
|
|
151
|
+
voiceAttachment(id) { return this.invoke(client => client.voiceAttachment(id)); }
|
|
141
152
|
async updateToken(token) {
|
|
142
|
-
|
|
143
|
-
if (!configuration.network)
|
|
153
|
+
if (!this.options.configuration.network)
|
|
144
154
|
return;
|
|
145
|
-
configuration.network = { ...configuration.network, token };
|
|
146
|
-
if (this.starting)
|
|
147
|
-
await this.
|
|
148
|
-
await this.replica.updateCredentials(token);
|
|
149
|
-
}
|
|
155
|
+
this.options.configuration.network = { ...this.options.configuration.network, token };
|
|
156
|
+
if (this.starting || this.connection)
|
|
157
|
+
await this.invoke(client => client.updateCredentials(token));
|
|
150
158
|
}
|
|
151
159
|
async close() {
|
|
160
|
+
if (this.closed)
|
|
161
|
+
return;
|
|
152
162
|
this.closed = true;
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
this.startupRetry = undefined;
|
|
158
|
-
}
|
|
159
|
-
this.replica.close();
|
|
160
|
-
this.channel.removeEventListener("message", this.workerMessage);
|
|
161
|
-
this.channel.close();
|
|
162
|
-
await this.acquiring;
|
|
163
|
-
try {
|
|
164
|
-
await this.host?.close();
|
|
165
|
-
}
|
|
166
|
-
finally {
|
|
167
|
-
this.worker?.removeEventListener("message", this.workerMessage);
|
|
168
|
-
this.worker?.terminate();
|
|
169
|
-
this.worker = undefined;
|
|
170
|
-
this.host = undefined;
|
|
171
|
-
}
|
|
163
|
+
// Stop the port immediately so requests cannot outlive the Profile.
|
|
164
|
+
this.disposeWorker();
|
|
165
|
+
await this.starting?.catch(() => { });
|
|
166
|
+
await this.restarting?.catch(() => { });
|
|
172
167
|
}
|
|
173
168
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import Dexie, { type Table } from "dexie";
|
|
2
|
-
import type { ProfileCurrentState, ProfileGenerationState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileStateRecord, ProfileThread, ProfileWindow, ProfileWriteBatch
|
|
2
|
+
import type { ProfileCurrentState, ProfileGenerationState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileStateRecord, ProfileThread, ProfileWindow, ProfileWriteBatch } from "./profileStoreTypes.js";
|
|
3
3
|
export declare function profileDatabaseName(identity: ProfileIdentity): string;
|
|
4
4
|
/** One Profile, five stores, one transaction boundary. No page-facing read API:
|
|
5
5
|
* restoration is explicit and normal queries belong to the in-memory view. */
|
|
@@ -14,10 +14,7 @@ export declare class ProfileDatabase extends Dexie {
|
|
|
14
14
|
indexedDB?: IDBFactory;
|
|
15
15
|
name?: string;
|
|
16
16
|
});
|
|
17
|
-
|
|
18
|
-
private assertWriter;
|
|
19
|
-
releaseWriter(ownerId: string, fence: number): Promise<void>;
|
|
20
|
-
initialize(ownerId: string, fence: number, state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
|
|
17
|
+
initialize(state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
|
|
21
18
|
commit(batch: ProfileWriteBatch): Promise<ProfileCurrentState>;
|
|
22
19
|
/** Restore from one consistent transaction, never mix data across a switch. */
|
|
23
20
|
restore(): Promise<{
|
|
@@ -27,19 +24,19 @@ export declare class ProfileDatabase extends Dexie {
|
|
|
27
24
|
messages: ProfileMessage[];
|
|
28
25
|
outbox: ProfileOutboxCommand[];
|
|
29
26
|
}>;
|
|
30
|
-
saveGeneration(
|
|
27
|
+
saveGeneration(build: ProfileGenerationState, rows: {
|
|
31
28
|
threads?: ProfileThread[];
|
|
32
29
|
windows?: ProfileWindow[];
|
|
33
30
|
messages?: ProfileMessage[];
|
|
34
31
|
}): Promise<void>;
|
|
35
|
-
/** Bounded maintenance
|
|
32
|
+
/** Bounded maintenance on the serial Worker queue. Building
|
|
36
33
|
* and validated generations remain resumable; outbox is never involved. */
|
|
37
|
-
cleanupGenerations(
|
|
34
|
+
cleanupGenerations(limit?: number): Promise<number>;
|
|
38
35
|
restoreGeneration(generation: string): Promise<{
|
|
39
36
|
build: ProfileGenerationState | undefined;
|
|
40
37
|
threads: ProfileThread[];
|
|
41
38
|
windows: ProfileWindow[];
|
|
42
39
|
messages: ProfileMessage[];
|
|
43
40
|
}>;
|
|
44
|
-
activateGeneration(
|
|
41
|
+
activateGeneration(generation: string, expectedRevision: number): Promise<ProfileCurrentState>;
|
|
45
42
|
}
|
|
@@ -22,40 +22,14 @@ export class ProfileDatabase extends Dexie {
|
|
|
22
22
|
inboxState: "key",
|
|
23
23
|
outbox: "commandId,[state+createdAt],threadId,messageId",
|
|
24
24
|
});
|
|
25
|
+
// Additive upgrade: retain projections, reading facts and outbox; retire only
|
|
26
|
+
// the old TTL lease. The lifetime browser lock is acquired before opening.
|
|
27
|
+
this.version(2).stores({}).upgrade(transaction => transaction.table("inboxState").delete("lease"));
|
|
25
28
|
this.on("versionchange", () => { this.close(); return false; });
|
|
26
29
|
}
|
|
27
|
-
async
|
|
28
|
-
if (!ownerId || !Number.isSafeInteger(ttlMs) || ttlMs < 1)
|
|
29
|
-
throw Error("INVALID_PROFILE_LEASE");
|
|
30
|
-
return this.transaction("rw", this.inboxState, async () => {
|
|
31
|
-
const old = await this.inboxState.get("lease");
|
|
32
|
-
if (old && old.ownerId !== ownerId && old.expiresAt > now && (!writerLock || old.writerLock !== writerLock))
|
|
33
|
-
return undefined;
|
|
34
|
-
const fence = old ? old.ownerId === ownerId && old.expiresAt > now ? old.fence : old.fence + 1 : 1;
|
|
35
|
-
if (!Number.isSafeInteger(fence))
|
|
36
|
-
throw Error("PROFILE_FENCE_EXHAUSTED");
|
|
37
|
-
const lease = { key: "lease", ownerId, fence, expiresAt: now + ttlMs, ...(writerLock ? { writerLock } : {}) };
|
|
38
|
-
await this.inboxState.put(lease);
|
|
39
|
-
return lease;
|
|
40
|
-
});
|
|
41
|
-
}
|
|
42
|
-
async assertWriter(ownerId, fence) {
|
|
43
|
-
const lease = await this.inboxState.get("lease");
|
|
44
|
-
if (!lease || lease.ownerId !== ownerId || lease.fence !== fence || lease.expiresAt <= Date.now())
|
|
45
|
-
throw Error("PROFILE_WRITER_FENCED");
|
|
46
|
-
}
|
|
47
|
-
async releaseWriter(ownerId, fence) {
|
|
48
|
-
await this.transaction("rw", this.inboxState, async () => {
|
|
49
|
-
const lease = await this.inboxState.get("lease");
|
|
50
|
-
// Keep the counter: deleting it would allow a stale producer to reuse fence 1.
|
|
51
|
-
if (lease?.ownerId === ownerId && lease.fence === fence)
|
|
52
|
-
await this.inboxState.put({ ...lease, expiresAt: 0 });
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
async initialize(ownerId, fence, state) {
|
|
30
|
+
async initialize(state) {
|
|
56
31
|
inboxSequence(state.committedSeq);
|
|
57
32
|
return this.transaction("rw", this.inboxState, async () => {
|
|
58
|
-
await this.assertWriter(ownerId, fence);
|
|
59
33
|
const previous = await this.inboxState.get("current");
|
|
60
34
|
if (previous)
|
|
61
35
|
return previous;
|
|
@@ -71,7 +45,6 @@ export class ProfileDatabase extends Dexie {
|
|
|
71
45
|
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
72
46
|
}
|
|
73
47
|
return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
|
|
74
|
-
await this.assertWriter(batch.ownerId, batch.fence);
|
|
75
48
|
const current = await this.inboxState.get("current");
|
|
76
49
|
if (!current || current.activeGeneration !== batch.generation || current.epoch !== batch.epoch)
|
|
77
50
|
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
@@ -125,7 +98,7 @@ export class ProfileDatabase extends Dexie {
|
|
|
125
98
|
};
|
|
126
99
|
});
|
|
127
100
|
}
|
|
128
|
-
async saveGeneration(
|
|
101
|
+
async saveGeneration(build, rows) {
|
|
129
102
|
inboxSequence(build.committedSeq);
|
|
130
103
|
for (const row of [...rows.threads ?? [], ...rows.windows ?? [], ...rows.messages ?? []])
|
|
131
104
|
if (row.generation !== build.generation)
|
|
@@ -133,7 +106,6 @@ export class ProfileDatabase extends Dexie {
|
|
|
133
106
|
if (build.key !== `build:${build.generation}`)
|
|
134
107
|
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
135
108
|
await this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
|
|
136
|
-
await this.assertWriter(ownerId, fence);
|
|
137
109
|
const current = await this.inboxState.get("current");
|
|
138
110
|
if (current?.activeGeneration === build.generation)
|
|
139
111
|
throw Error("PROFILE_BUILD_IS_ACTIVE");
|
|
@@ -146,13 +118,12 @@ export class ProfileDatabase extends Dexie {
|
|
|
146
118
|
await this.inboxState.put(build);
|
|
147
119
|
});
|
|
148
120
|
}
|
|
149
|
-
/** Bounded maintenance
|
|
121
|
+
/** Bounded maintenance on the serial Worker queue. Building
|
|
150
122
|
* and validated generations remain resumable; outbox is never involved. */
|
|
151
|
-
async cleanupGenerations(
|
|
123
|
+
async cleanupGenerations(limit = 200) {
|
|
152
124
|
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)
|
|
153
125
|
throw Error("INVALID_PROFILE_CLEANUP_LIMIT");
|
|
154
126
|
return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
|
|
155
|
-
await this.assertWriter(ownerId, fence);
|
|
156
127
|
const current = await this.inboxState.get("current");
|
|
157
128
|
if (!current)
|
|
158
129
|
return 0;
|
|
@@ -189,9 +160,8 @@ export class ProfileDatabase extends Dexie {
|
|
|
189
160
|
messages: await this.messages.where("generation").equals(generation).toArray(),
|
|
190
161
|
}));
|
|
191
162
|
}
|
|
192
|
-
async activateGeneration(
|
|
163
|
+
async activateGeneration(generation, expectedRevision) {
|
|
193
164
|
return this.transaction("rw", this.inboxState, async () => {
|
|
194
|
-
await this.assertWriter(ownerId, fence);
|
|
195
165
|
const current = await this.inboxState.get("current");
|
|
196
166
|
const build = await this.inboxState.get(`build:${generation}`);
|
|
197
167
|
if (!current || current.commitRevision !== expectedRevision || build?.sourceRevision !== expectedRevision)
|
|
@@ -1,14 +1,13 @@
|
|
|
1
1
|
import { ProfileDatabase } from "./profileDatabase.js";
|
|
2
2
|
import { ProfileProjection, type ProfileOperation } from "./profileProjection.js";
|
|
3
3
|
import { type InboxBootstrap } from "./inboxStore.js";
|
|
4
|
-
import type { ProfileGenerationState
|
|
4
|
+
import type { ProfileGenerationState } from "./profileStoreTypes.js";
|
|
5
5
|
/** Called only by the owner's serial commit queue. Network catch-up happens
|
|
6
6
|
* outside this class; each staged page is one bounded local transaction. */
|
|
7
7
|
export declare class ProfileGenerationBuilder {
|
|
8
8
|
private database;
|
|
9
|
-
private lease;
|
|
10
9
|
private cache;
|
|
11
|
-
constructor(database: ProfileDatabase
|
|
10
|
+
constructor(database: ProfileDatabase);
|
|
12
11
|
private persist;
|
|
13
12
|
private load;
|
|
14
13
|
begin(generation: string, bootstrap: InboxBootstrap, sourceRevision: number): Promise<void>;
|
|
@@ -6,17 +6,14 @@ import { inboxSequence } from "./inboxStore.js";
|
|
|
6
6
|
* outside this class; each staged page is one bounded local transaction. */
|
|
7
7
|
export class ProfileGenerationBuilder {
|
|
8
8
|
database;
|
|
9
|
-
lease;
|
|
10
9
|
cache = new Map();
|
|
11
|
-
constructor(database
|
|
10
|
+
constructor(database) {
|
|
12
11
|
this.database = database;
|
|
13
|
-
this.lease = lease;
|
|
14
12
|
}
|
|
15
13
|
async persist(build, projection, events) {
|
|
16
14
|
const prepared = projection.prepare(events);
|
|
17
15
|
const next = { ...build, committedSeq: prepared.current.committedSeq, buildRevision: prepared.current.commitRevision, receiptsReady: prepared.current.receiptsReady };
|
|
18
|
-
|
|
19
|
-
await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
|
|
16
|
+
await this.database.saveGeneration(next, prepared);
|
|
20
17
|
projection.accept(prepared);
|
|
21
18
|
this.cache.set(build.generation, { build: next, projection });
|
|
22
19
|
return { build: next, projection };
|
|
@@ -50,9 +47,9 @@ export class ProfileGenerationBuilder {
|
|
|
50
47
|
windowStart: bootstrap.windowStart, buildRevision: 0 };
|
|
51
48
|
const projection = new ProfileProjection(this.database.identity, { current: { key: "current", activeGeneration: generation,
|
|
52
49
|
epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
|
|
53
|
-
const prepared = projection.prepareBasis(bootstrap)
|
|
50
|
+
const prepared = projection.prepareBasis(bootstrap);
|
|
54
51
|
const next = { ...build, buildRevision: prepared.current.commitRevision };
|
|
55
|
-
await this.database.saveGeneration(
|
|
52
|
+
await this.database.saveGeneration(next, prepared);
|
|
56
53
|
projection.accept(prepared);
|
|
57
54
|
this.cache.set(generation, { build: next, projection });
|
|
58
55
|
}
|
|
@@ -135,10 +132,9 @@ export class ProfileGenerationBuilder {
|
|
|
135
132
|
await flush();
|
|
136
133
|
const snapshot = projection.snapshot();
|
|
137
134
|
new ProfileMemoryStore().restore(snapshot);
|
|
138
|
-
const lease = this.lease();
|
|
139
135
|
const validated = { ...build, status: "validated", sourceRevision: active.current.commitRevision };
|
|
140
|
-
await this.database.saveGeneration(
|
|
141
|
-
const current = await this.database.activateGeneration(
|
|
136
|
+
await this.database.saveGeneration(validated, {});
|
|
137
|
+
const current = await this.database.activateGeneration(generation, active.current.commitRevision);
|
|
142
138
|
const result = new ProfileProjection(this.database.identity, { ...snapshot, current, outbox: [...active.outbox.values()] }, build.windowStart ?? 0);
|
|
143
139
|
this.cache.delete(generation);
|
|
144
140
|
return result;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ProfileCurrentState, ProfileMessage, ProfileThread, ProfileWindow } from "./profileStoreTypes.js";
|
|
2
2
|
import type { ChatMessage } from "../chatTypes.js";
|
|
3
|
-
export declare const PROFILE_PROTOCOL_VERSION =
|
|
3
|
+
export declare const PROFILE_PROTOCOL_VERSION = 2;
|
|
4
4
|
export declare const PROFILE_PROJECTION_VERSION = 1;
|
|
5
5
|
export type ProfileSnapshot = {
|
|
6
6
|
current: ProfileCurrentState;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { ProfileWindowDirectory } from "./profileWindows.js";
|
|
2
2
|
import { ProfileReadingIndex } from "./profileReadingIndex.js";
|
|
3
3
|
import { projectMessageContent } from "../messageView.js";
|
|
4
|
-
export const PROFILE_PROTOCOL_VERSION =
|
|
4
|
+
export const PROFILE_PROTOCOL_VERSION = 2;
|
|
5
5
|
export const PROFILE_PROJECTION_VERSION = 1;
|
|
6
6
|
/** Storage-free consumer shared by the owner, page adapters and WebView replicas.
|
|
7
7
|
* Only committed snapshots/deltas enter here; reads cannot initiate I/O. */
|