@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
|
@@ -7,9 +7,6 @@ export type ProfileOwnerOptions = {
|
|
|
7
7
|
database: ProfileDatabase;
|
|
8
8
|
epoch: string;
|
|
9
9
|
windowStart: number;
|
|
10
|
-
ownerId?: string;
|
|
11
|
-
/** Set only while the Worker holds the matching exclusive browser lock. */
|
|
12
|
-
writerLock?: string;
|
|
13
10
|
onCommitted?: (delta: ProfileDelta) => void;
|
|
14
11
|
onError?: (error: unknown) => void;
|
|
15
12
|
windowMs?: number;
|
|
@@ -24,13 +21,10 @@ export declare class ProfileOwner {
|
|
|
24
21
|
private projection;
|
|
25
22
|
private queue;
|
|
26
23
|
private builder;
|
|
27
|
-
private lease;
|
|
28
|
-
private timer?;
|
|
29
24
|
private cleanupTimer?;
|
|
30
25
|
private cleanupMore;
|
|
31
26
|
private cleanupTask?;
|
|
32
27
|
private cleanupStopping;
|
|
33
|
-
private lost;
|
|
34
28
|
private closed;
|
|
35
29
|
private committedListeners;
|
|
36
30
|
private synchronizer;
|
|
@@ -62,7 +56,6 @@ export declare class ProfileOwner {
|
|
|
62
56
|
private scheduleCleanup;
|
|
63
57
|
private materializeReadingIntents;
|
|
64
58
|
private report;
|
|
65
|
-
private renew;
|
|
66
59
|
private notify;
|
|
67
60
|
private commit;
|
|
68
61
|
close(): Promise<void>;
|
|
@@ -11,13 +11,10 @@ export class ProfileOwner {
|
|
|
11
11
|
projection;
|
|
12
12
|
queue;
|
|
13
13
|
builder;
|
|
14
|
-
lease;
|
|
15
|
-
timer;
|
|
16
14
|
cleanupTimer;
|
|
17
15
|
cleanupMore = false;
|
|
18
16
|
cleanupTask;
|
|
19
17
|
cleanupStopping = false;
|
|
20
|
-
lost = false;
|
|
21
18
|
closed = false;
|
|
22
19
|
committedListeners = new Set();
|
|
23
20
|
synchronizer = () => Promise.resolve();
|
|
@@ -28,37 +25,30 @@ export class ProfileOwner {
|
|
|
28
25
|
}
|
|
29
26
|
static async open(options) {
|
|
30
27
|
const owner = new ProfileOwner(options);
|
|
31
|
-
const ownerId = options.ownerId ?? crypto.randomUUID();
|
|
32
|
-
const lease = await options.database.claimWriter(ownerId, undefined, undefined, options.writerLock);
|
|
33
|
-
if (!lease)
|
|
34
|
-
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
35
|
-
owner.lease = lease;
|
|
36
28
|
try {
|
|
37
|
-
await options.database.initialize(
|
|
29
|
+
await options.database.initialize({ activeGeneration: crypto.randomUUID(), epoch: options.epoch,
|
|
38
30
|
committedSeq: "0", projectionVersion: 1, windowStart: options.windowStart });
|
|
39
31
|
const restored = await options.database.restore();
|
|
40
32
|
if (!restored.current || restored.current.epoch !== options.epoch)
|
|
41
33
|
throw Error("PROFILE_EPOCH_REBUILD_REQUIRED");
|
|
42
34
|
const snapshot = { ...restored, current: restored.current };
|
|
43
35
|
owner.projection = new ProfileProjection(options.database.identity, snapshot, restored.current.windowStart ?? options.windowStart);
|
|
44
|
-
owner.builder = new ProfileGenerationBuilder(options.database
|
|
36
|
+
owner.builder = new ProfileGenerationBuilder(options.database);
|
|
45
37
|
owner.memory.restore(snapshot);
|
|
46
38
|
owner.queue = new ProfileCommitQueue({ commit: events => owner.commit(events), windowMs: options.windowMs,
|
|
47
39
|
windowMsForEvent: event => "type" in event && event.type === "observe" && event.policy === "visible" ? options.readingWindowMs ?? 500 : options.windowMs ?? 200,
|
|
48
40
|
retryMs: options.retryMs, onError: error => owner.report(error) });
|
|
49
|
-
owner.timer = setInterval(() => { void owner.renew(); }, 10000);
|
|
50
41
|
await owner.materializeReadingIntents();
|
|
51
42
|
owner.scheduleCleanup();
|
|
52
43
|
return owner;
|
|
53
44
|
}
|
|
54
45
|
catch (error) {
|
|
55
|
-
await options.database.releaseWriter(ownerId, lease.fence);
|
|
56
46
|
throw error;
|
|
57
47
|
}
|
|
58
48
|
}
|
|
59
49
|
get current() { return this.projection.current; }
|
|
60
50
|
get identity() { return this.options.database.identity; }
|
|
61
|
-
get active() { return !this.closed
|
|
51
|
+
get active() { return !this.closed; }
|
|
62
52
|
get pending() { return this.queue.pending; }
|
|
63
53
|
snapshot() { return this.projection.snapshot(); }
|
|
64
54
|
commands() { return [...this.projection.outbox.values()]; }
|
|
@@ -91,19 +81,19 @@ export class ProfileOwner {
|
|
|
91
81
|
});
|
|
92
82
|
}
|
|
93
83
|
enqueue(event, bytes, immediate = false) {
|
|
94
|
-
if (this.closed
|
|
84
|
+
if (this.closed)
|
|
95
85
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
96
86
|
return this.queue.enqueue(event, bytes, immediate);
|
|
97
87
|
}
|
|
98
88
|
flush() { this.queue.flush(); }
|
|
99
89
|
async beginGeneration(bootstrap, generation = crypto.randomUUID()) {
|
|
100
|
-
if (this.closed
|
|
90
|
+
if (this.closed)
|
|
101
91
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
102
92
|
await this.queue.enqueue({ ownerType: "begin", generation, bootstrap }, new TextEncoder().encode(JSON.stringify(bootstrap)).byteLength, true, true);
|
|
103
93
|
return generation;
|
|
104
94
|
}
|
|
105
95
|
async appendGeneration(generation, events) {
|
|
106
|
-
if (this.closed
|
|
96
|
+
if (this.closed)
|
|
107
97
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
108
98
|
await this.queue.enqueue({ ownerType: "append", generation, events }, new TextEncoder().encode(JSON.stringify(events)).byteLength, true, true);
|
|
109
99
|
}
|
|
@@ -113,7 +103,7 @@ export class ProfileOwner {
|
|
|
113
103
|
return rows.filter((row) => row.key.startsWith("build:") && "status" in row && ["building", "validated"].includes(row.status));
|
|
114
104
|
}
|
|
115
105
|
async activateGeneration(generation) {
|
|
116
|
-
if (this.closed
|
|
106
|
+
if (this.closed)
|
|
117
107
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
118
108
|
await this.queue.enqueue({ ownerType: "activate", generation }, 128, true, true);
|
|
119
109
|
await this.materializeReadingIntents();
|
|
@@ -152,29 +142,11 @@ export class ProfileOwner {
|
|
|
152
142
|
await flush();
|
|
153
143
|
}
|
|
154
144
|
report(error) {
|
|
155
|
-
if (error?.message === "PROFILE_WRITER_FENCED")
|
|
156
|
-
this.lost = true;
|
|
157
145
|
try {
|
|
158
146
|
this.options.onError?.(error);
|
|
159
147
|
}
|
|
160
148
|
catch { /* Reporting cannot break the commit loop. */ }
|
|
161
149
|
}
|
|
162
|
-
async renew() {
|
|
163
|
-
if (this.closed || this.lost)
|
|
164
|
-
return;
|
|
165
|
-
try {
|
|
166
|
-
const next = await this.options.database.claimWriter(this.lease.ownerId, undefined, undefined, this.lease.writerLock);
|
|
167
|
-
if (!next || next.fence !== this.lease.fence) {
|
|
168
|
-
this.lost = true;
|
|
169
|
-
this.report(Error("PROFILE_WRITER_FENCED"));
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
this.lease = next;
|
|
173
|
-
}
|
|
174
|
-
catch (error) {
|
|
175
|
-
this.report(error);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
150
|
notify(delta) {
|
|
179
151
|
try {
|
|
180
152
|
this.options.onCommitted?.(delta);
|
|
@@ -192,14 +164,12 @@ export class ProfileOwner {
|
|
|
192
164
|
}
|
|
193
165
|
}
|
|
194
166
|
async commit(events) {
|
|
195
|
-
if (this.lost)
|
|
196
|
-
throw Error("PROFILE_WRITER_FENCED");
|
|
197
167
|
const first = events[0];
|
|
198
168
|
if (first && "ownerType" in first) {
|
|
199
169
|
if (events.length !== 1)
|
|
200
170
|
throw Error("PROFILE_BARRIER_NOT_ISOLATED");
|
|
201
171
|
if (first.ownerType === "cleanup")
|
|
202
|
-
this.cleanupMore = await this.options.database.cleanupGenerations(
|
|
172
|
+
this.cleanupMore = await this.options.database.cleanupGenerations() === 200;
|
|
203
173
|
else if (first.ownerType === "begin")
|
|
204
174
|
await this.builder.begin(first.generation, first.bootstrap, this.current.commitRevision);
|
|
205
175
|
else if (first.ownerType === "append")
|
|
@@ -216,7 +186,7 @@ export class ProfileOwner {
|
|
|
216
186
|
}
|
|
217
187
|
const fromRevision = this.projection.current.commitRevision;
|
|
218
188
|
const prepared = this.projection.prepare(events);
|
|
219
|
-
const committed = await this.options.database.commit({ ...prepared,
|
|
189
|
+
const committed = await this.options.database.commit({ ...prepared,
|
|
220
190
|
generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
|
|
221
191
|
committedSeq: prepared.current.committedSeq, windowStart: prepared.current.windowStart, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
|
|
222
192
|
if (committed.commitRevision === fromRevision)
|
|
@@ -247,7 +217,5 @@ export class ProfileOwner {
|
|
|
247
217
|
await this.cleanupTask;
|
|
248
218
|
this.queue.close();
|
|
249
219
|
this.closed = true;
|
|
250
|
-
clearInterval(this.timer);
|
|
251
|
-
await this.options.database.releaseWriter(this.lease.ownerId, this.lease.fence);
|
|
252
220
|
}
|
|
253
221
|
}
|
|
@@ -124,13 +124,6 @@ export type ProfileCurrentState = {
|
|
|
124
124
|
revokedTeamIds?: string[];
|
|
125
125
|
teamAccessRevision?: number;
|
|
126
126
|
};
|
|
127
|
-
export type ProfileWriterLease = {
|
|
128
|
-
key: "lease";
|
|
129
|
-
ownerId: string;
|
|
130
|
-
fence: number;
|
|
131
|
-
expiresAt: number;
|
|
132
|
-
writerLock?: string;
|
|
133
|
-
};
|
|
134
127
|
export type ProfileGenerationState = {
|
|
135
128
|
key: `build:${string}`;
|
|
136
129
|
generation: string;
|
|
@@ -145,7 +138,7 @@ export type ProfileGenerationState = {
|
|
|
145
138
|
windowStart?: number;
|
|
146
139
|
receiptsReady?: boolean;
|
|
147
140
|
};
|
|
148
|
-
export type ProfileStateRecord = ProfileCurrentState |
|
|
141
|
+
export type ProfileStateRecord = ProfileCurrentState | ProfileGenerationState;
|
|
149
142
|
export type ProfileOutboxCommand = {
|
|
150
143
|
commandId: string;
|
|
151
144
|
kind: "message" | "reading" | "played";
|
|
@@ -157,8 +150,6 @@ export type ProfileOutboxCommand = {
|
|
|
157
150
|
attempts: number;
|
|
158
151
|
};
|
|
159
152
|
export type ProfileWriteBatch = {
|
|
160
|
-
ownerId: string;
|
|
161
|
-
fence: number;
|
|
162
153
|
expectedRevision: number;
|
|
163
154
|
generation: string;
|
|
164
155
|
epoch: string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ProfileMemoryStore
|
|
1
|
+
import { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
2
2
|
import type { ProfileOperation } from "./profileProjection.js";
|
|
3
3
|
import type { ProfileOwner } from "./profileOwner.js";
|
|
4
4
|
export type ProfileMessagePort = {
|
|
@@ -7,25 +7,11 @@ export type ProfileMessagePort = {
|
|
|
7
7
|
removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
|
|
8
8
|
start?(): void;
|
|
9
9
|
};
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
private rows;
|
|
16
|
-
private bytes;
|
|
17
|
-
constructor(maxEntries?: number, maxBytes?: number);
|
|
18
|
-
append(delta: ProfileDelta): void;
|
|
19
|
-
since(generation: string | undefined, revision: number | undefined, current: {
|
|
20
|
-
activeGeneration: string;
|
|
21
|
-
commitRevision: number;
|
|
22
|
-
}): ProfileDelta[] | undefined;
|
|
23
|
-
}
|
|
24
|
-
/** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
|
|
25
|
-
export declare function serveProfileOwner(owner: ProfileOwner, port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void): () => void;
|
|
26
|
-
/** UI/WebView replica. Reads and subscriptions use memory; only commands and
|
|
27
|
-
* revision repair cross the message boundary. Normal deltas never read disk. */
|
|
28
|
-
export declare class ProfileReplica {
|
|
10
|
+
/** Direct Dedicated Worker port; the rendering document is its only consumer. */
|
|
11
|
+
export declare function serveProfileWorker(owner: ProfileOwner, port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void): () => void;
|
|
12
|
+
/** One rendering document consumes committed projections from its own Worker.
|
|
13
|
+
* Ordered port delivery needs no journal, polling or distributed repair. */
|
|
14
|
+
export declare class ProfileWorkerClient {
|
|
29
15
|
private port;
|
|
30
16
|
private scope;
|
|
31
17
|
private onError;
|
|
@@ -33,18 +19,15 @@ export declare class ProfileReplica {
|
|
|
33
19
|
readonly memory: ProfileMemoryStore;
|
|
34
20
|
private clientId;
|
|
35
21
|
private requests;
|
|
36
|
-
private
|
|
22
|
+
private restoring;
|
|
37
23
|
private closed;
|
|
38
24
|
private buffered;
|
|
39
|
-
private timer?;
|
|
40
25
|
private lastError?;
|
|
41
|
-
constructor(port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void, timeoutMs?: number, profileId?: string);
|
|
26
|
+
constructor(port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void, timeoutMs?: number, profileId?: string, memory?: ProfileMemoryStore);
|
|
42
27
|
private receive;
|
|
43
28
|
private fail;
|
|
44
29
|
private request;
|
|
45
|
-
start(
|
|
46
|
-
check(): Promise<void>;
|
|
47
|
-
repair(): Promise<void>;
|
|
30
|
+
start(): Promise<void>;
|
|
48
31
|
submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
|
|
49
32
|
synchronize(): Promise<void>;
|
|
50
33
|
updateCredentials(token: string): Promise<void>;
|
|
@@ -1,44 +1,15 @@
|
|
|
1
1
|
import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
export class ProfileDeltaJournal {
|
|
5
|
-
maxEntries;
|
|
6
|
-
maxBytes;
|
|
7
|
-
rows = [];
|
|
8
|
-
bytes = 0;
|
|
9
|
-
constructor(maxEntries = 256, maxBytes = 8 * 1024 * 1024) {
|
|
10
|
-
this.maxEntries = maxEntries;
|
|
11
|
-
this.maxBytes = maxBytes;
|
|
12
|
-
}
|
|
13
|
-
append(delta) {
|
|
14
|
-
if (this.rows.length && (this.rows.at(-1).delta.generation !== delta.generation || this.rows.at(-1).delta.toRevision !== delta.fromRevision)) {
|
|
15
|
-
this.rows = [];
|
|
16
|
-
this.bytes = 0;
|
|
17
|
-
}
|
|
18
|
-
const bytes = new TextEncoder().encode(JSON.stringify(delta)).byteLength;
|
|
19
|
-
this.rows.push({ delta, bytes });
|
|
20
|
-
this.bytes += bytes;
|
|
21
|
-
while (this.rows.length && (this.rows.length > this.maxEntries || this.bytes > this.maxBytes))
|
|
22
|
-
this.bytes -= this.rows.shift().bytes;
|
|
23
|
-
}
|
|
24
|
-
since(generation, revision, current) {
|
|
25
|
-
if (generation !== current.activeGeneration || revision === undefined || revision > current.commitRevision)
|
|
26
|
-
return;
|
|
27
|
-
if (revision === current.commitRevision)
|
|
28
|
-
return [];
|
|
29
|
-
const start = this.rows.findIndex(row => row.delta.fromRevision === revision && row.delta.generation === generation);
|
|
30
|
-
if (start < 0 || this.rows.at(-1)?.delta.toRevision !== current.commitRevision)
|
|
31
|
-
return;
|
|
32
|
-
return this.rows.slice(start).map(row => row.delta);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
/** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
|
|
36
|
-
export function serveProfileOwner(owner, port, scope, onError = () => { }) {
|
|
37
|
-
const journal = new ProfileDeltaJournal();
|
|
2
|
+
/** Direct Dedicated Worker port; the rendering document is its only consumer. */
|
|
3
|
+
export function serveProfileWorker(owner, port, scope, onError = () => { }) {
|
|
38
4
|
const send = (response) => port.postMessage({ ...response, profileProtocol: PROFILE_PROTOCOL_VERSION, scope });
|
|
5
|
+
let generation = owner.current.activeGeneration;
|
|
39
6
|
const off = owner.subscribeCommitted(delta => {
|
|
40
|
-
|
|
41
|
-
|
|
7
|
+
if (delta.generation !== generation) {
|
|
8
|
+
generation = delta.generation;
|
|
9
|
+
send({ clientId: "*", snapshot: owner.snapshot() });
|
|
10
|
+
}
|
|
11
|
+
else
|
|
12
|
+
send({ clientId: "*", delta });
|
|
42
13
|
});
|
|
43
14
|
let active = true;
|
|
44
15
|
const controller = new AbortController();
|
|
@@ -50,12 +21,8 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
|
|
|
50
21
|
if (request.profileProtocol !== PROFILE_PROTOCOL_VERSION)
|
|
51
22
|
throw Error("PROFILE_PROTOCOL_INCOMPATIBLE");
|
|
52
23
|
let result;
|
|
53
|
-
if (request.action === "
|
|
54
|
-
|
|
55
|
-
result = deltas ? { deltas } : { snapshot: owner.snapshot() };
|
|
56
|
-
}
|
|
57
|
-
else if (request.action === "status")
|
|
58
|
-
result = { generation: owner.current.activeGeneration, revision: owner.current.commitRevision };
|
|
24
|
+
if (request.action === "snapshot")
|
|
25
|
+
result = { snapshot: owner.snapshot() };
|
|
59
26
|
else if (request.action === "synchronize") {
|
|
60
27
|
await owner.synchronize();
|
|
61
28
|
result = null;
|
|
@@ -102,9 +69,9 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
|
|
|
102
69
|
port.start?.();
|
|
103
70
|
return () => { active = false; controller.abort(); off(); port.removeEventListener("message", listener); };
|
|
104
71
|
}
|
|
105
|
-
/**
|
|
106
|
-
*
|
|
107
|
-
export class
|
|
72
|
+
/** One rendering document consumes committed projections from its own Worker.
|
|
73
|
+
* Ordered port delivery needs no journal, polling or distributed repair. */
|
|
74
|
+
export class ProfileWorkerClient {
|
|
108
75
|
port;
|
|
109
76
|
scope;
|
|
110
77
|
onError;
|
|
@@ -112,17 +79,16 @@ export class ProfileReplica {
|
|
|
112
79
|
memory;
|
|
113
80
|
clientId = crypto.randomUUID();
|
|
114
81
|
requests = new Map();
|
|
115
|
-
|
|
82
|
+
restoring = true;
|
|
116
83
|
closed = false;
|
|
117
84
|
buffered = [];
|
|
118
|
-
timer;
|
|
119
85
|
lastError;
|
|
120
|
-
constructor(port, scope, onError = () => { }, timeoutMs = 30000, profileId = "") {
|
|
86
|
+
constructor(port, scope, onError = () => { }, timeoutMs = 30000, profileId = "", memory) {
|
|
121
87
|
this.port = port;
|
|
122
88
|
this.scope = scope;
|
|
123
89
|
this.onError = onError;
|
|
124
90
|
this.timeoutMs = timeoutMs;
|
|
125
|
-
this.memory = new ProfileMemoryStore(onError, profileId);
|
|
91
|
+
this.memory = memory ?? new ProfileMemoryStore(onError, profileId);
|
|
126
92
|
port.addEventListener("message", this.receive);
|
|
127
93
|
port.start?.();
|
|
128
94
|
}
|
|
@@ -145,36 +111,39 @@ export class ProfileReplica {
|
|
|
145
111
|
else
|
|
146
112
|
request.resolve(response.result);
|
|
147
113
|
}
|
|
114
|
+
if (response.snapshot) {
|
|
115
|
+
if (this.restoring)
|
|
116
|
+
return; // The requested startup snapshot follows this message.
|
|
117
|
+
try {
|
|
118
|
+
this.memory.restore(response.snapshot);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
this.fail(error);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
148
124
|
if (response.delta) {
|
|
149
|
-
if (this.
|
|
125
|
+
if (this.restoring)
|
|
150
126
|
this.buffered.push(response.delta);
|
|
151
|
-
|
|
152
|
-
void this.repair().catch(failure => this.fail(failure));
|
|
153
|
-
}
|
|
154
|
-
else {
|
|
127
|
+
else
|
|
155
128
|
try {
|
|
156
129
|
this.memory.apply(response.delta);
|
|
157
130
|
}
|
|
158
131
|
catch (error) {
|
|
159
|
-
this.
|
|
160
|
-
void this.repair().catch(failure => this.fail(failure));
|
|
132
|
+
this.fail(error);
|
|
161
133
|
}
|
|
162
|
-
}
|
|
163
|
-
if (this.buffered.length > 256)
|
|
164
|
-
this.buffered = this.buffered.slice(-256);
|
|
165
134
|
}
|
|
166
135
|
};
|
|
167
|
-
fail(error) { this.lastError = error instanceof Error ? error : Error("
|
|
136
|
+
fail(error) { this.lastError = error instanceof Error ? error : Error("PROFILE_WORKER_PROTOCOL_FAILED"); try {
|
|
168
137
|
this.onError(this.lastError);
|
|
169
138
|
}
|
|
170
139
|
catch { } }
|
|
171
140
|
request(action, fields = {}) {
|
|
172
141
|
if (this.closed)
|
|
173
|
-
return Promise.reject(Error("
|
|
142
|
+
return Promise.reject(Error("PROFILE_WORKER_CLIENT_CLOSED"));
|
|
174
143
|
const requestId = crypto.randomUUID();
|
|
175
144
|
return new Promise((resolve, reject) => {
|
|
176
|
-
const timeout = action === "
|
|
177
|
-
const timer = setTimeout(() => { this.requests.delete(requestId); reject(Error("
|
|
145
|
+
const timeout = action === "snapshot" ? this.timeoutMs : Math.max(this.timeoutMs, 30000);
|
|
146
|
+
const timer = action === "waitCommand" ? undefined : setTimeout(() => { this.requests.delete(requestId); reject(Error("PROFILE_WORKER_TIMEOUT")); }, timeout);
|
|
178
147
|
this.requests.set(requestId, { resolve, reject, timer });
|
|
179
148
|
try {
|
|
180
149
|
this.port.postMessage({ ...fields, profileProtocol: PROFILE_PROTOCOL_VERSION, scope: this.scope, clientId: this.clientId, requestId, action });
|
|
@@ -186,37 +155,17 @@ export class ProfileReplica {
|
|
|
186
155
|
}
|
|
187
156
|
});
|
|
188
157
|
}
|
|
189
|
-
async start(
|
|
190
|
-
await this.
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const remote = await this.request("status"), local = this.memory.getStatus();
|
|
196
|
-
if (remote.generation !== local.generation || remote.revision !== local.revision)
|
|
197
|
-
await this.repair();
|
|
198
|
-
}
|
|
199
|
-
repair() {
|
|
200
|
-
if (this.repairing)
|
|
201
|
-
return this.repairing;
|
|
202
|
-
const task = Promise.resolve().then(async () => {
|
|
203
|
-
const local = this.memory.getStatus();
|
|
204
|
-
const result = await this.request("catchUp", { generation: local.generation, revision: local.revision });
|
|
205
|
-
if ("snapshot" in result)
|
|
206
|
-
this.memory.restore(result.snapshot);
|
|
207
|
-
else
|
|
208
|
-
for (const delta of result.deltas)
|
|
209
|
-
this.memory.apply(delta);
|
|
210
|
-
const buffered = this.buffered;
|
|
211
|
-
this.buffered = [];
|
|
212
|
-
for (const delta of buffered)
|
|
158
|
+
async start() {
|
|
159
|
+
const result = await this.request("snapshot");
|
|
160
|
+
this.memory.restore(result.snapshot);
|
|
161
|
+
for (const delta of this.buffered) {
|
|
162
|
+
const status = this.memory.getStatus();
|
|
163
|
+
if (delta.generation === status.generation && delta.toRevision > (status.revision ?? -1))
|
|
213
164
|
this.memory.apply(delta);
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
this.
|
|
217
|
-
|
|
218
|
-
this.repairing = undefined; }).catch(() => { });
|
|
219
|
-
return task;
|
|
165
|
+
}
|
|
166
|
+
this.buffered = [];
|
|
167
|
+
this.restoring = false;
|
|
168
|
+
this.lastError = undefined;
|
|
220
169
|
}
|
|
221
170
|
submit(operation, immediate = false) {
|
|
222
171
|
const payload = "type" in operation && operation.type === "send" ? operation.command.payload : undefined;
|
|
@@ -230,11 +179,10 @@ export class ProfileReplica {
|
|
|
230
179
|
getStatus() { return { ...this.memory.getStatus(), error: this.lastError }; }
|
|
231
180
|
close() {
|
|
232
181
|
this.closed = true;
|
|
233
|
-
clearInterval(this.timer);
|
|
234
182
|
this.port.removeEventListener("message", this.receive);
|
|
235
183
|
for (const request of this.requests.values()) {
|
|
236
184
|
clearTimeout(request.timer);
|
|
237
|
-
request.reject(Error("
|
|
185
|
+
request.reject(Error("PROFILE_WORKER_CLIENT_CLOSED"));
|
|
238
186
|
}
|
|
239
187
|
this.requests.clear();
|
|
240
188
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ProfileDatabase } from "./profileDatabase.js";
|
|
2
|
-
import {
|
|
2
|
+
import { ProfileWorkerClient, type ProfileMessagePort } from "./profileWorkerClient.js";
|
|
3
3
|
import type { ProfileIdentity } from "./profileStoreTypes.js";
|
|
4
4
|
export type ProfileWorkerConfiguration = {
|
|
5
5
|
identity: ProfileIdentity;
|
|
@@ -16,19 +16,16 @@ export declare const profileChannelName: (identity: ProfileIdentity) => string;
|
|
|
16
16
|
* Identity cannot change within a host; a Profile switch creates another host. */
|
|
17
17
|
export declare function installProfileWorker(port: ProfileMessagePort, options?: {
|
|
18
18
|
database?: (identity: ProfileIdentity) => ProfileDatabase;
|
|
19
|
-
channel?: (name: string) => ProfileMessagePort & {
|
|
20
|
-
close(): void;
|
|
21
|
-
};
|
|
22
19
|
fetch?: typeof fetch;
|
|
23
20
|
locks?: Pick<LockManager, "request"> | null;
|
|
24
21
|
}): () => Promise<void>;
|
|
25
22
|
/** The application passes its bundler-created Worker. Worker code and main-page
|
|
26
23
|
* code ship together, so protocol negotiation precedes any snapshot handoff. */
|
|
27
|
-
export declare function openProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number): Promise<{
|
|
24
|
+
export declare function openProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number, signal?: AbortSignal): Promise<{
|
|
28
25
|
close: () => Promise<void>;
|
|
29
26
|
update: (config: ProfileWorkerConfiguration) => Promise<void>;
|
|
30
27
|
}>;
|
|
31
28
|
export declare function connectProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number): Promise<{
|
|
32
|
-
|
|
29
|
+
client: ProfileWorkerClient;
|
|
33
30
|
close: () => Promise<void>;
|
|
34
31
|
}>;
|