@pmate/chat-sdk 0.13.0-profile.1 → 0.13.0-profile.11
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 +38 -0
- package/lib/profile.d.ts +4 -1
- package/lib/profile.js +4 -1
- package/lib/runtime/profileChat.d.ts +118 -1
- package/lib/runtime/profileChat.js +98 -30
- package/lib/runtime/profileCommitQueue.d.ts +2 -1
- package/lib/runtime/profileCommitQueue.js +26 -7
- package/lib/runtime/profileCoordinator.d.ts +19 -19
- package/lib/runtime/profileCoordinator.js +128 -94
- package/lib/runtime/profileDatabase.d.ts +7 -7
- package/lib/runtime/profileDatabase.js +57 -42
- package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
- package/lib/runtime/profileGenerationBuilder.js +60 -26
- package/lib/runtime/profileInboxFeed.d.ts +1 -0
- package/lib/runtime/profileInboxFeed.js +12 -2
- package/lib/runtime/profileLegacyInbox.d.ts +8 -0
- package/lib/runtime/profileLegacyInbox.js +114 -0
- package/lib/runtime/profileLegacyOutbox.d.ts +7 -0
- package/lib/runtime/profileLegacyOutbox.js +106 -0
- package/lib/runtime/profileLegacyReading.d.ts +7 -0
- package/lib/runtime/profileLegacyReading.js +110 -0
- package/lib/runtime/profileMemoryStore.d.ts +26 -2
- package/lib/runtime/profileMemoryStore.js +167 -12
- package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
- package/lib/runtime/profileOutboxDispatcher.js +41 -5
- package/lib/runtime/profileOwner.d.ts +11 -6
- package/lib/runtime/profileOwner.js +71 -46
- package/lib/runtime/profileProjection.d.ts +54 -5
- package/lib/runtime/profileProjection.js +336 -51
- package/lib/runtime/profileReadingIndex.d.ts +1 -0
- package/lib/runtime/profileReadingIndex.js +17 -1
- package/lib/runtime/profileStoreTypes.d.ts +15 -9
- package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +10 -26
- package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +56 -102
- package/lib/runtime/profileWorkerHost.d.ts +4 -6
- package/lib/runtime/profileWorkerHost.js +58 -21
- package/package.json +2 -2
|
@@ -1,13 +1,22 @@
|
|
|
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 =
|
|
5
|
-
export const PROFILE_PROJECTION_VERSION =
|
|
4
|
+
export const PROFILE_PROTOCOL_VERSION = 2;
|
|
5
|
+
export const PROFILE_PROJECTION_VERSION = 2;
|
|
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. */
|
|
8
8
|
export class ProfileMemoryStore {
|
|
9
9
|
onError;
|
|
10
10
|
profileId;
|
|
11
|
+
windowRows = new Map();
|
|
12
|
+
messageWindows = new Map();
|
|
13
|
+
windowPages = new Map();
|
|
14
|
+
windowAccess = new Map();
|
|
15
|
+
windowIds = new Map();
|
|
16
|
+
windowListeners = new Map();
|
|
17
|
+
windowListListeners = new Map();
|
|
18
|
+
dirtyWindows = new Set();
|
|
19
|
+
emptyWindowIds = [];
|
|
11
20
|
current;
|
|
12
21
|
entities = new Map();
|
|
13
22
|
threads = new Map();
|
|
@@ -26,6 +35,33 @@ export class ProfileMemoryStore {
|
|
|
26
35
|
this.onError = onError;
|
|
27
36
|
this.profileId = profileId;
|
|
28
37
|
}
|
|
38
|
+
/** Release a disposed Profile without mutating snapshots held by React.
|
|
39
|
+
* Worker replacement deliberately keeps this store alive; only final close
|
|
40
|
+
* may discard its entities and subscriptions. */
|
|
41
|
+
dispose() {
|
|
42
|
+
this.windowRows.clear();
|
|
43
|
+
this.messageWindows.clear();
|
|
44
|
+
this.windowPages.clear();
|
|
45
|
+
this.windowAccess.clear();
|
|
46
|
+
this.windowIds.clear();
|
|
47
|
+
this.windowListeners.clear();
|
|
48
|
+
this.windowListListeners.clear();
|
|
49
|
+
this.dirtyWindows.clear();
|
|
50
|
+
this.entities.clear();
|
|
51
|
+
this.threads.clear();
|
|
52
|
+
this.directories.clear();
|
|
53
|
+
this.listeners.clear();
|
|
54
|
+
this.listListeners.clear();
|
|
55
|
+
this.messageListeners.clear();
|
|
56
|
+
this.pageCache.clear();
|
|
57
|
+
this.epochs.clear();
|
|
58
|
+
this.presented.clear();
|
|
59
|
+
this.readingIndices.clear();
|
|
60
|
+
this.presentedPages = new WeakMap();
|
|
61
|
+
this.list = [];
|
|
62
|
+
this.current = undefined;
|
|
63
|
+
this.phase = "restoring";
|
|
64
|
+
}
|
|
29
65
|
notify(listener) { try {
|
|
30
66
|
listener();
|
|
31
67
|
}
|
|
@@ -38,7 +74,16 @@ export class ProfileMemoryStore {
|
|
|
38
74
|
getStatus() { return { phase: this.phase, generation: this.current?.activeGeneration, revision: this.current?.commitRevision }; }
|
|
39
75
|
getThread(threadId) { return this.threads.get(threadId); }
|
|
40
76
|
getMessage(messageId) { return this.entities.get(messageId); }
|
|
41
|
-
|
|
77
|
+
getAccessRevision() { return this.current?.teamAccessRevision ?? 0; }
|
|
78
|
+
isTeamAvailable(teamId) { return !teamId || !this.current?.revokedTeamIds?.includes(teamId); }
|
|
79
|
+
isThreadAvailable(threadId) {
|
|
80
|
+
const thread = this.threads.get(threadId);
|
|
81
|
+
return thread?.status === "ready" && this.isTeamAvailable(thread.teamId) && (!thread.parentThreadId || this.threads.get(thread.parentThreadId)?.status === "ready" && this.isTeamAvailable(this.threads.get(thread.parentThreadId)?.teamId));
|
|
82
|
+
}
|
|
83
|
+
getPresentedMessage(messageId) {
|
|
84
|
+
const message = this.entities.get(messageId);
|
|
85
|
+
return message && this.isThreadAvailable(message.threadId) ? this.presented.get(messageId) : undefined;
|
|
86
|
+
}
|
|
42
87
|
getThreadList = () => this.list;
|
|
43
88
|
subscribeThreadList = (listener) => { this.listListeners.add(listener); return () => { this.listListeners.delete(listener); }; };
|
|
44
89
|
subscribeMessages(listener) { this.messageListeners.add(listener); return () => { this.messageListeners.delete(listener); }; }
|
|
@@ -52,9 +97,68 @@ export class ProfileMemoryStore {
|
|
|
52
97
|
return () => { listeners.delete(listener); if (!listeners.size)
|
|
53
98
|
this.listeners.delete(threadId); };
|
|
54
99
|
}
|
|
100
|
+
windowKey(threadId, windowId) { return JSON.stringify([threadId, windowId]); }
|
|
101
|
+
installWindow(window) {
|
|
102
|
+
const key = this.windowKey(window.threadId, window.windowId);
|
|
103
|
+
for (const ref of this.windowRows.get(key)?.refs ?? [])
|
|
104
|
+
if (this.messageWindows.get(ref.messageId) === key)
|
|
105
|
+
this.messageWindows.delete(ref.messageId);
|
|
106
|
+
this.windowRows.set(key, window);
|
|
107
|
+
for (const ref of window.refs)
|
|
108
|
+
this.messageWindows.set(ref.messageId, key);
|
|
109
|
+
this.windowPages.delete(key);
|
|
110
|
+
this.dirtyWindows.add(key);
|
|
111
|
+
}
|
|
112
|
+
getWindowIds(threadId) {
|
|
113
|
+
if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
|
|
114
|
+
throw Error("PROFILE_THREAD_NOT_READY");
|
|
115
|
+
return this.windowIds.get(threadId) ?? this.emptyWindowIds;
|
|
116
|
+
}
|
|
117
|
+
findMessageWindow(threadId, messageId) {
|
|
118
|
+
if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
|
|
119
|
+
throw Error("PROFILE_THREAD_NOT_READY");
|
|
120
|
+
const key = this.messageWindows.get(messageId);
|
|
121
|
+
const window = key ? this.windowRows.get(key) : undefined;
|
|
122
|
+
return window?.threadId === threadId ? window.windowId : undefined;
|
|
123
|
+
}
|
|
124
|
+
readPresentedWindow(threadId, windowId) {
|
|
125
|
+
if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
|
|
126
|
+
throw Error("PROFILE_THREAD_NOT_READY");
|
|
127
|
+
const key = this.windowKey(threadId, windowId);
|
|
128
|
+
const cached = this.windowPages.get(key);
|
|
129
|
+
if (cached)
|
|
130
|
+
return cached;
|
|
131
|
+
const window = this.windowRows.get(key);
|
|
132
|
+
if (!window)
|
|
133
|
+
throw Error("PROFILE_WINDOW_UNAVAILABLE");
|
|
134
|
+
const page = window.refs.map(ref => {
|
|
135
|
+
const message = this.presented.get(ref.messageId);
|
|
136
|
+
if (!message)
|
|
137
|
+
throw Error("PROFILE_SNAPSHOT_INCOMPLETE");
|
|
138
|
+
return message;
|
|
139
|
+
});
|
|
140
|
+
this.windowPages.set(key, page);
|
|
141
|
+
return page;
|
|
142
|
+
}
|
|
143
|
+
subscribeWindow(threadId, windowId, listener) {
|
|
144
|
+
return this.subscribeKey(this.windowListeners, this.windowKey(threadId, windowId), listener);
|
|
145
|
+
}
|
|
146
|
+
subscribeWindowList(threadId, listener) {
|
|
147
|
+
return this.subscribeKey(this.windowListListeners, threadId, listener);
|
|
148
|
+
}
|
|
149
|
+
subscribeKey(map, key, listener) {
|
|
150
|
+
let listeners = map.get(key);
|
|
151
|
+
if (!listeners) {
|
|
152
|
+
listeners = new Set();
|
|
153
|
+
map.set(key, listeners);
|
|
154
|
+
}
|
|
155
|
+
listeners.add(listener);
|
|
156
|
+
return () => { listeners.delete(listener); if (!listeners.size)
|
|
157
|
+
map.delete(key); };
|
|
158
|
+
}
|
|
55
159
|
restore(snapshot) {
|
|
56
160
|
const generation = snapshot.current.activeGeneration;
|
|
57
|
-
if (snapshot.current.projectionVersion
|
|
161
|
+
if (![1, PROFILE_PROJECTION_VERSION].includes(snapshot.current.projectionVersion))
|
|
58
162
|
throw Error("PROFILE_PROJECTION_INCOMPATIBLE");
|
|
59
163
|
for (const row of [...snapshot.threads, ...snapshot.windows, ...snapshot.messages])
|
|
60
164
|
if (row.generation !== generation)
|
|
@@ -78,6 +182,14 @@ export class ProfileMemoryStore {
|
|
|
78
182
|
}
|
|
79
183
|
// Install only after complete validation: a bad handoff retains the old view.
|
|
80
184
|
const affected = new Set([...this.threads.keys(), ...threads.keys()]);
|
|
185
|
+
for (const key of this.windowRows.keys())
|
|
186
|
+
this.dirtyWindows.add(key);
|
|
187
|
+
this.windowRows.clear();
|
|
188
|
+
this.messageWindows.clear();
|
|
189
|
+
this.windowPages.clear();
|
|
190
|
+
this.windowIds.clear();
|
|
191
|
+
for (const window of snapshot.windows)
|
|
192
|
+
this.installWindow(window);
|
|
81
193
|
this.entities = entities;
|
|
82
194
|
this.threads = threads;
|
|
83
195
|
this.directories = directories;
|
|
@@ -89,7 +201,7 @@ export class ProfileMemoryStore {
|
|
|
89
201
|
this.prepareMessageView(row);
|
|
90
202
|
}
|
|
91
203
|
this.current = snapshot.current;
|
|
92
|
-
this.phase = snapshot.current.epoch === "uninitialized" ? "restoring" : "ready";
|
|
204
|
+
this.phase = snapshot.current.epoch === "uninitialized" || snapshot.current.projectionVersion !== PROFILE_PROJECTION_VERSION ? "restoring" : "ready";
|
|
93
205
|
this.pageCache.clear();
|
|
94
206
|
this.epochs.clear();
|
|
95
207
|
this.publish(affected, true);
|
|
@@ -144,6 +256,7 @@ export class ProfileMemoryStore {
|
|
|
144
256
|
for (const thread of delta.threads)
|
|
145
257
|
this.threads.set(thread.threadId, thread);
|
|
146
258
|
for (const window of delta.windows) {
|
|
259
|
+
this.installWindow(window);
|
|
147
260
|
let directory = this.directories.get(window.threadId);
|
|
148
261
|
if (!directory) {
|
|
149
262
|
directory = new ProfileWindowDirectory(delta.generation, window.threadId);
|
|
@@ -152,6 +265,11 @@ export class ProfileMemoryStore {
|
|
|
152
265
|
directory.accept({ windows: [window], windowCount: 0 });
|
|
153
266
|
affected.add(window.threadId);
|
|
154
267
|
}
|
|
268
|
+
const accessChanged = new Set([...(this.current.revokedTeamIds ?? []), ...(delta.current.revokedTeamIds ?? [])].filter(id => this.current.revokedTeamIds?.includes(id) !== delta.current.revokedTeamIds?.includes(id)));
|
|
269
|
+
if (accessChanged.size)
|
|
270
|
+
for (const thread of this.threads.values())
|
|
271
|
+
if (thread.teamId && accessChanged.has(thread.teamId))
|
|
272
|
+
affected.add(thread.threadId);
|
|
155
273
|
this.current = delta.current;
|
|
156
274
|
for (const message of delta.messages) {
|
|
157
275
|
this.indexMessage(message);
|
|
@@ -159,6 +277,10 @@ export class ProfileMemoryStore {
|
|
|
159
277
|
}
|
|
160
278
|
for (const thread of delta.threads) {
|
|
161
279
|
const previous = previousThreads.get(thread.threadId);
|
|
280
|
+
if (previous?.status !== thread.status)
|
|
281
|
+
for (const child of this.threads.values())
|
|
282
|
+
if (child.parentThreadId === thread.threadId)
|
|
283
|
+
affected.add(child.threadId);
|
|
162
284
|
const index = this.readingIndices.get(thread.threadId);
|
|
163
285
|
for (const source of thread.readingSources) {
|
|
164
286
|
const before = previous?.readingSources.find(row => row.sourceThreadId === source.sourceThreadId);
|
|
@@ -185,7 +307,7 @@ export class ProfileMemoryStore {
|
|
|
185
307
|
}
|
|
186
308
|
}
|
|
187
309
|
}
|
|
188
|
-
this.publish(affected, delta.threads.length > 0);
|
|
310
|
+
this.publish(affected, delta.threads.length > 0 || accessChanged.size > 0);
|
|
189
311
|
if (added.length)
|
|
190
312
|
for (const listener of this.messageListeners)
|
|
191
313
|
this.notify(() => listener(added));
|
|
@@ -200,23 +322,56 @@ export class ProfileMemoryStore {
|
|
|
200
322
|
const source = thread?.readingSources.find(row => row.sourceThreadId === message.sourceThreadId);
|
|
201
323
|
const mine = message.from === this.profileId;
|
|
202
324
|
const policy = message.readPolicy ?? "visible";
|
|
203
|
-
const read =
|
|
204
|
-
message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
|
|
325
|
+
const read = message.recalled === true || (policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus === "read" :
|
|
326
|
+
mine || message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
|
|
205
327
|
source?.pendingExplicitReadMessageIds?.includes(message.messageId) === true || source?.preservedReadMessageIds.includes(message.messageId) === true ||
|
|
206
328
|
policy === "visible" && message.sourceSeq !== undefined && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0));
|
|
329
|
+
const discussionStatus = policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus : undefined;
|
|
330
|
+
const readingUnknown = policy === "discussion" && discussionStatus !== "read" && discussionStatus !== "unread" || !message.sourceSeq && !mine && !read || thread?.readingStatus === "unknown" && !thread.internal?.unknownReadingCount;
|
|
207
331
|
const content = message.presentation ?? projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0],
|
|
208
332
|
from: message.from, recipients: message.recipients, body: message.content, threadKind: thread?.kind === "dm" ? "dm" : "group", teamId: thread?.teamId });
|
|
209
333
|
const visibleContent = message.recalled ? { kind: "system", text: "" } : content;
|
|
210
334
|
const value = { ...visibleContent, id: message.messageId, threadId: thread?.parentThreadId ?? message.threadId,
|
|
211
335
|
...(thread?.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), timestamp: message.orderKey[0], from: message.from, mine,
|
|
212
336
|
status: message.sendStatus === "failed" ? "failed" : message.sendStatus === "sending" ? "sending" : mine && message.readBy.length ? "read" : "sent",
|
|
213
|
-
recalled: message.recalled ?? false, unread:
|
|
214
|
-
attentionEligible: message.mention, reading:
|
|
337
|
+
recalled: message.recalled ?? false, unread: readingUnknown ? undefined : !read,
|
|
338
|
+
attentionEligible: message.mention, reading: readingUnknown ? undefined : { seq: message.sourceSeq, read,
|
|
215
339
|
readPolicy: policy === "visible" ? "visible" : "explicit" },
|
|
216
340
|
reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
|
|
217
341
|
this.presented.set(message.messageId, value);
|
|
342
|
+
const key = this.messageWindows.get(message.messageId);
|
|
343
|
+
if (key) {
|
|
344
|
+
this.windowPages.delete(key);
|
|
345
|
+
this.dirtyWindows.add(key);
|
|
346
|
+
}
|
|
218
347
|
}
|
|
219
348
|
publish(affected, directoryChanged) {
|
|
349
|
+
const changedLists = new Set();
|
|
350
|
+
for (const threadId of affected) {
|
|
351
|
+
const blocks = this.directories.get(threadId)?.blocks ?? [];
|
|
352
|
+
const previous = this.windowIds.get(threadId);
|
|
353
|
+
// Window sequence and IDs never shift on body/reading updates. Only a
|
|
354
|
+
// newly appended block or a full restoration changes this directory.
|
|
355
|
+
if (!previous || previous.length !== blocks.length) {
|
|
356
|
+
this.windowIds.set(threadId, blocks.map(window => window.windowId));
|
|
357
|
+
changedLists.add(threadId);
|
|
358
|
+
}
|
|
359
|
+
const available = this.isThreadAvailable(threadId);
|
|
360
|
+
if (this.windowAccess.get(threadId) !== available) {
|
|
361
|
+
this.windowAccess.set(threadId, available);
|
|
362
|
+
changedLists.add(threadId);
|
|
363
|
+
for (const block of blocks)
|
|
364
|
+
this.dirtyWindows.add(this.windowKey(threadId, block.windowId));
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const dirtyWindows = this.dirtyWindows;
|
|
368
|
+
this.dirtyWindows = new Set();
|
|
369
|
+
for (const key of dirtyWindows)
|
|
370
|
+
for (const listener of this.windowListeners.get(key) ?? [])
|
|
371
|
+
this.notify(listener);
|
|
372
|
+
for (const thread of changedLists)
|
|
373
|
+
for (const listener of this.windowListListeners.get(thread) ?? [])
|
|
374
|
+
this.notify(listener);
|
|
220
375
|
for (const thread of affected)
|
|
221
376
|
this.epochs.set(thread, (this.epochs.get(thread) ?? 0) + 1);
|
|
222
377
|
// Cached pages live only until that thread changes; no unbounded scroll cache.
|
|
@@ -224,7 +379,7 @@ export class ProfileMemoryStore {
|
|
|
224
379
|
if (affected.has(JSON.parse(key)[0]))
|
|
225
380
|
this.pageCache.delete(key);
|
|
226
381
|
if (directoryChanged) {
|
|
227
|
-
this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion")
|
|
382
|
+
this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion" && this.isTeamAvailable(thread.teamId))
|
|
228
383
|
.sort((a, b) => b.lastActivityAt - a.lastActivityAt || a.threadId.localeCompare(b.threadId));
|
|
229
384
|
}
|
|
230
385
|
for (const thread of affected)
|
|
@@ -235,7 +390,7 @@ export class ProfileMemoryStore {
|
|
|
235
390
|
this.notify(listener);
|
|
236
391
|
}
|
|
237
392
|
readPage(threadId, anchor, limit, direction = "older") {
|
|
238
|
-
if (this.phase !== "ready" || this.
|
|
393
|
+
if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
|
|
239
394
|
throw Error("PROFILE_THREAD_NOT_READY");
|
|
240
395
|
const key = JSON.stringify([threadId, anchor ?? null, limit, direction]), epoch = this.epochs.get(threadId) ?? 0;
|
|
241
396
|
const cached = this.pageCache.get(key);
|
|
@@ -17,6 +17,7 @@ export declare class ProfileOutboxDispatcher {
|
|
|
17
17
|
private timer?;
|
|
18
18
|
private scheduled?;
|
|
19
19
|
private off?;
|
|
20
|
+
private retryAt;
|
|
20
21
|
private closed;
|
|
21
22
|
private controller;
|
|
22
23
|
constructor(options: ProfileOutboxDispatcherOptions);
|
|
@@ -25,6 +26,8 @@ export declare class ProfileOutboxDispatcher {
|
|
|
25
26
|
private schedule;
|
|
26
27
|
drain(): Promise<void>;
|
|
27
28
|
private transition;
|
|
29
|
+
private target;
|
|
30
|
+
private nextCommand;
|
|
28
31
|
private run;
|
|
29
32
|
private reading;
|
|
30
33
|
close(): Promise<void>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { voiceUploader } from "./voiceUpload.js";
|
|
2
|
+
import { profileDiscussionId } from "./profileProjection.js";
|
|
2
3
|
/** Reads committed commands from owner memory. All status/ACK transitions return
|
|
3
4
|
* to the same durable queue; network waits never block local event processing. */
|
|
4
5
|
export class ProfileOutboxDispatcher {
|
|
@@ -7,6 +8,7 @@ export class ProfileOutboxDispatcher {
|
|
|
7
8
|
timer;
|
|
8
9
|
scheduled;
|
|
9
10
|
off;
|
|
11
|
+
retryAt = new Map();
|
|
10
12
|
closed = false;
|
|
11
13
|
controller = new AbortController();
|
|
12
14
|
constructor(options) {
|
|
@@ -37,19 +39,51 @@ export class ProfileOutboxDispatcher {
|
|
|
37
39
|
return this.running;
|
|
38
40
|
const task = this.run();
|
|
39
41
|
this.running = task;
|
|
40
|
-
void task.finally(() => { if (this.running === task)
|
|
41
|
-
this.running = undefined;
|
|
42
|
+
void task.finally(() => { if (this.running === task) {
|
|
43
|
+
this.running = undefined;
|
|
44
|
+
if (!this.closed && this.options.owner.active && this.nextCommand())
|
|
45
|
+
this.schedule();
|
|
46
|
+
} }).catch(() => { });
|
|
42
47
|
return task;
|
|
43
48
|
}
|
|
44
49
|
async transition(command, state) {
|
|
45
50
|
await this.options.owner.enqueue({ type: "commandResult", commandId: command.commandId, state }, 128, true);
|
|
46
51
|
}
|
|
47
|
-
|
|
52
|
+
target(command) {
|
|
53
|
+
const memory = this.options.owner.memory, thread = memory.getThread(command.threadId);
|
|
54
|
+
const parent = thread?.parentThreadId ? memory.getThread(thread.parentThreadId) : thread;
|
|
55
|
+
const canonical = parent?.internal?.assignments?.[parent.threadId] ?? parent?.threadId ?? command.threadId;
|
|
56
|
+
const root = command.kind !== "message" ? command.payload.threadRootId : thread?.rootMessageId;
|
|
57
|
+
return { scope: JSON.stringify([canonical, command.kind === "message" ? "message" : "reading", command.kind === "message" ? null : root ?? null]), threadId: root ? profileDiscussionId(canonical, root) : canonical };
|
|
58
|
+
}
|
|
59
|
+
nextCommand(blocked = new Set()) {
|
|
48
60
|
const owner = this.options.owner;
|
|
61
|
+
if (owner.memory.getStatus().phase !== "ready")
|
|
62
|
+
return;
|
|
63
|
+
const commands = owner.commands().sort((a, b) => a.createdAt - b.createdAt || a.commandId.localeCompare(b.commandId));
|
|
64
|
+
const existing = new Set(commands.map(command => command.commandId));
|
|
65
|
+
for (const id of this.retryAt.keys())
|
|
66
|
+
if (!existing.has(id))
|
|
67
|
+
this.retryAt.delete(id);
|
|
68
|
+
for (const command of commands) {
|
|
69
|
+
const target = this.target(command);
|
|
70
|
+
if (blocked.has(target.scope) || !owner.memory.isThreadAvailable(target.threadId))
|
|
71
|
+
continue;
|
|
72
|
+
if (command.state === "failed" && (this.retryAt.get(command.commandId) ?? 0) > Date.now()) {
|
|
73
|
+
blocked.add(target.scope);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
return command;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async run() {
|
|
80
|
+
const owner = this.options.owner, blocked = new Set();
|
|
49
81
|
// Refresh from committed memory after each ACK so work accepted during a
|
|
50
82
|
// network wait is picked up without waiting for another ten-second tick.
|
|
51
83
|
while (!this.closed && owner.active) {
|
|
52
|
-
|
|
84
|
+
if (owner.memory.getStatus().phase !== "ready")
|
|
85
|
+
return;
|
|
86
|
+
const command = this.nextCommand(blocked);
|
|
53
87
|
if (!command)
|
|
54
88
|
return;
|
|
55
89
|
await this.transition(command, "sending");
|
|
@@ -74,12 +108,14 @@ export class ProfileOutboxDispatcher {
|
|
|
74
108
|
await this.reading(command);
|
|
75
109
|
if (!this.closed && owner.active)
|
|
76
110
|
await this.transition(command, "confirmed");
|
|
111
|
+
this.retryAt.delete(command.commandId);
|
|
77
112
|
}
|
|
78
113
|
catch (error) {
|
|
114
|
+
this.retryAt.set(command.commandId, Date.now() + 10000);
|
|
115
|
+
blocked.add(this.target(command).scope);
|
|
79
116
|
if (!this.closed && owner.active)
|
|
80
117
|
await this.transition(command, "failed");
|
|
81
118
|
this.report(error);
|
|
82
|
-
return;
|
|
83
119
|
}
|
|
84
120
|
}
|
|
85
121
|
}
|
|
@@ -7,10 +7,10 @@ export type ProfileOwnerOptions = {
|
|
|
7
7
|
database: ProfileDatabase;
|
|
8
8
|
epoch: string;
|
|
9
9
|
windowStart: number;
|
|
10
|
-
ownerId?: string;
|
|
11
10
|
onCommitted?: (delta: ProfileDelta) => void;
|
|
12
11
|
onError?: (error: unknown) => void;
|
|
13
12
|
windowMs?: number;
|
|
13
|
+
readingWindowMs?: number;
|
|
14
14
|
retryMs?: number;
|
|
15
15
|
};
|
|
16
16
|
/** The durable owner publishes only after commit. Network requests belong to
|
|
@@ -21,12 +21,14 @@ export declare class ProfileOwner {
|
|
|
21
21
|
private projection;
|
|
22
22
|
private queue;
|
|
23
23
|
private builder;
|
|
24
|
-
private
|
|
25
|
-
private
|
|
26
|
-
private
|
|
24
|
+
private cleanupTimer?;
|
|
25
|
+
private cleanupMore;
|
|
26
|
+
private cleanupTask?;
|
|
27
|
+
private cleanupStopping;
|
|
27
28
|
private closed;
|
|
28
29
|
private committedListeners;
|
|
29
30
|
private synchronizer;
|
|
31
|
+
private credentialUpdater;
|
|
30
32
|
private constructor();
|
|
31
33
|
static open(options: ProfileOwnerOptions): Promise<ProfileOwner>;
|
|
32
34
|
get current(): import("./profileStoreTypes.js").ProfileCurrentState;
|
|
@@ -40,17 +42,20 @@ export declare class ProfileOwner {
|
|
|
40
42
|
commands(): import("./profileStoreTypes.js").ProfileOutboxCommand[];
|
|
41
43
|
subscribeCommitted(listener: (delta: ProfileDelta) => void): () => void;
|
|
42
44
|
setSynchronizer(synchronize: () => Promise<void>): void;
|
|
45
|
+
setCredentialUpdater(update: (token: string) => void): void;
|
|
46
|
+
updateCredentials(token: string): void;
|
|
43
47
|
synchronize(): Promise<void>;
|
|
44
48
|
waitForCommand(commandId: string, signal: AbortSignal): Promise<void>;
|
|
45
49
|
enqueue(event: ProfileOperation, bytes: number, immediate?: boolean): Promise<void>;
|
|
46
50
|
flush(): void;
|
|
47
|
-
beginGeneration(bootstrap: InboxBootstrap, generation?:
|
|
51
|
+
beginGeneration(bootstrap: InboxBootstrap, generation?: string): Promise<string>;
|
|
48
52
|
appendGeneration(generation: string, events: ProfileOperation[]): Promise<void>;
|
|
49
53
|
generationProgress(generation: string): Promise<ProfileGenerationState>;
|
|
50
54
|
pendingGenerations(): Promise<ProfileGenerationState[]>;
|
|
51
55
|
activateGeneration(generation: string): Promise<void>;
|
|
56
|
+
private scheduleCleanup;
|
|
57
|
+
private materializeReadingIntents;
|
|
52
58
|
private report;
|
|
53
|
-
private renew;
|
|
54
59
|
private notify;
|
|
55
60
|
private commit;
|
|
56
61
|
close(): Promise<void>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProfileCommitQueue } from "./profileCommitQueue.js";
|
|
2
2
|
import { ProfileDatabase } from "./profileDatabase.js";
|
|
3
|
-
import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
|
|
3
|
+
import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION, PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
4
4
|
import { ProfileProjection } from "./profileProjection.js";
|
|
5
5
|
import { ProfileGenerationBuilder } from "./profileGenerationBuilder.js";
|
|
6
6
|
/** The durable owner publishes only after commit. Network requests belong to
|
|
@@ -11,51 +11,51 @@ export class ProfileOwner {
|
|
|
11
11
|
projection;
|
|
12
12
|
queue;
|
|
13
13
|
builder;
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
cleanupTimer;
|
|
15
|
+
cleanupMore = false;
|
|
16
|
+
cleanupTask;
|
|
17
|
+
cleanupStopping = false;
|
|
17
18
|
closed = false;
|
|
18
19
|
committedListeners = new Set();
|
|
19
20
|
synchronizer = () => Promise.resolve();
|
|
21
|
+
credentialUpdater = () => { throw Error("PROFILE_NETWORK_UNAVAILABLE"); };
|
|
20
22
|
constructor(options) {
|
|
21
23
|
this.options = options;
|
|
22
24
|
this.memory = new ProfileMemoryStore(options.onError, options.database.identity.profileId);
|
|
23
25
|
}
|
|
24
26
|
static async open(options) {
|
|
25
27
|
const owner = new ProfileOwner(options);
|
|
26
|
-
const ownerId = options.ownerId ?? crypto.randomUUID();
|
|
27
|
-
const lease = await options.database.claimWriter(ownerId);
|
|
28
|
-
if (!lease)
|
|
29
|
-
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
30
|
-
owner.lease = lease;
|
|
31
28
|
try {
|
|
32
|
-
await options.database.initialize(
|
|
33
|
-
committedSeq: "0", projectionVersion:
|
|
29
|
+
await options.database.initialize({ activeGeneration: crypto.randomUUID(), epoch: options.epoch,
|
|
30
|
+
committedSeq: "0", projectionVersion: PROFILE_PROJECTION_VERSION, windowStart: options.windowStart });
|
|
34
31
|
const restored = await options.database.restore();
|
|
35
32
|
if (!restored.current || restored.current.epoch !== options.epoch)
|
|
36
33
|
throw Error("PROFILE_EPOCH_REBUILD_REQUIRED");
|
|
37
34
|
const snapshot = { ...restored, current: restored.current };
|
|
38
|
-
owner.projection = new ProfileProjection(options.database.identity, snapshot, options.windowStart);
|
|
39
|
-
owner.builder = new ProfileGenerationBuilder(options.database
|
|
35
|
+
owner.projection = new ProfileProjection(options.database.identity, snapshot, restored.current.windowStart ?? options.windowStart);
|
|
36
|
+
owner.builder = new ProfileGenerationBuilder(options.database);
|
|
40
37
|
owner.memory.restore(snapshot);
|
|
41
38
|
owner.queue = new ProfileCommitQueue({ commit: events => owner.commit(events), windowMs: options.windowMs,
|
|
39
|
+
windowMsForEvent: event => "type" in event && event.type === "observe" && event.policy === "visible" ? options.readingWindowMs ?? 500 : options.windowMs ?? 200,
|
|
42
40
|
retryMs: options.retryMs, onError: error => owner.report(error) });
|
|
43
|
-
|
|
41
|
+
await owner.materializeReadingIntents();
|
|
42
|
+
owner.scheduleCleanup();
|
|
44
43
|
return owner;
|
|
45
44
|
}
|
|
46
45
|
catch (error) {
|
|
47
|
-
await options.database.releaseWriter(ownerId, lease.fence);
|
|
48
46
|
throw error;
|
|
49
47
|
}
|
|
50
48
|
}
|
|
51
49
|
get current() { return this.projection.current; }
|
|
52
50
|
get identity() { return this.options.database.identity; }
|
|
53
|
-
get active() { return !this.closed
|
|
51
|
+
get active() { return !this.closed; }
|
|
54
52
|
get pending() { return this.queue.pending; }
|
|
55
53
|
snapshot() { return this.projection.snapshot(); }
|
|
56
54
|
commands() { return [...this.projection.outbox.values()]; }
|
|
57
55
|
subscribeCommitted(listener) { this.committedListeners.add(listener); return () => { this.committedListeners.delete(listener); }; }
|
|
58
56
|
setSynchronizer(synchronize) { this.synchronizer = synchronize; }
|
|
57
|
+
setCredentialUpdater(update) { this.credentialUpdater = update; }
|
|
58
|
+
updateCredentials(token) { this.credentialUpdater(token); }
|
|
59
59
|
synchronize() { return this.synchronizer(); }
|
|
60
60
|
waitForCommand(commandId, signal) {
|
|
61
61
|
return new Promise((resolve, reject) => {
|
|
@@ -81,19 +81,19 @@ export class ProfileOwner {
|
|
|
81
81
|
});
|
|
82
82
|
}
|
|
83
83
|
enqueue(event, bytes, immediate = false) {
|
|
84
|
-
if (this.closed
|
|
84
|
+
if (this.closed)
|
|
85
85
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
86
86
|
return this.queue.enqueue(event, bytes, immediate);
|
|
87
87
|
}
|
|
88
88
|
flush() { this.queue.flush(); }
|
|
89
89
|
async beginGeneration(bootstrap, generation = crypto.randomUUID()) {
|
|
90
|
-
if (this.closed
|
|
90
|
+
if (this.closed)
|
|
91
91
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
92
92
|
await this.queue.enqueue({ ownerType: "begin", generation, bootstrap }, new TextEncoder().encode(JSON.stringify(bootstrap)).byteLength, true, true);
|
|
93
93
|
return generation;
|
|
94
94
|
}
|
|
95
95
|
async appendGeneration(generation, events) {
|
|
96
|
-
if (this.closed
|
|
96
|
+
if (this.closed)
|
|
97
97
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
98
98
|
await this.queue.enqueue({ ownerType: "append", generation, events }, new TextEncoder().encode(JSON.stringify(events)).byteLength, true, true);
|
|
99
99
|
}
|
|
@@ -103,34 +103,50 @@ export class ProfileOwner {
|
|
|
103
103
|
return rows.filter((row) => row.key.startsWith("build:") && "status" in row && ["building", "validated"].includes(row.status));
|
|
104
104
|
}
|
|
105
105
|
async activateGeneration(generation) {
|
|
106
|
-
if (this.closed
|
|
106
|
+
if (this.closed)
|
|
107
107
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
108
108
|
await this.queue.enqueue({ ownerType: "activate", generation }, 128, true, true);
|
|
109
|
+
await this.materializeReadingIntents();
|
|
110
|
+
this.scheduleCleanup();
|
|
111
|
+
}
|
|
112
|
+
scheduleCleanup() {
|
|
113
|
+
if (this.cleanupStopping || this.cleanupTimer || !this.active)
|
|
114
|
+
return;
|
|
115
|
+
this.cleanupTimer = setTimeout(() => {
|
|
116
|
+
this.cleanupTimer = undefined;
|
|
117
|
+
if (!this.active)
|
|
118
|
+
return;
|
|
119
|
+
this.cleanupTask = this.queue.enqueue({ ownerType: "cleanup" }, 0, true, true).then(() => {
|
|
120
|
+
if (this.cleanupMore)
|
|
121
|
+
this.scheduleCleanup();
|
|
122
|
+
}).catch(error => this.report(error));
|
|
123
|
+
}, 0);
|
|
124
|
+
}
|
|
125
|
+
async materializeReadingIntents() {
|
|
126
|
+
let pending = [];
|
|
127
|
+
const flush = async () => { if (pending.length) {
|
|
128
|
+
this.queue.flush();
|
|
129
|
+
await Promise.all(pending);
|
|
130
|
+
pending = [];
|
|
131
|
+
} };
|
|
132
|
+
for (const thread of this.projection.threads.values())
|
|
133
|
+
for (const [messageId, intents] of Object.entries(thread.internal?.pendingReadingIntents ?? {})) {
|
|
134
|
+
if (!this.projection.messages.get(messageId)?.sourceSeq)
|
|
135
|
+
continue;
|
|
136
|
+
for (const intent of intents) {
|
|
137
|
+
if (pending.length >= 200)
|
|
138
|
+
await flush();
|
|
139
|
+
pending.push(this.enqueue({ type: "restoreReadingIntent", threadId: thread.threadId, messageId, ...intent }, 256));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
await flush();
|
|
109
143
|
}
|
|
110
144
|
report(error) {
|
|
111
|
-
if (error?.message === "PROFILE_WRITER_FENCED")
|
|
112
|
-
this.lost = true;
|
|
113
145
|
try {
|
|
114
146
|
this.options.onError?.(error);
|
|
115
147
|
}
|
|
116
148
|
catch { /* Reporting cannot break the commit loop. */ }
|
|
117
149
|
}
|
|
118
|
-
async renew() {
|
|
119
|
-
if (this.closed || this.lost)
|
|
120
|
-
return;
|
|
121
|
-
try {
|
|
122
|
-
const next = await this.options.database.claimWriter(this.lease.ownerId);
|
|
123
|
-
if (!next || next.fence !== this.lease.fence) {
|
|
124
|
-
this.lost = true;
|
|
125
|
-
this.report(Error("PROFILE_WRITER_FENCED"));
|
|
126
|
-
return;
|
|
127
|
-
}
|
|
128
|
-
this.lease = next;
|
|
129
|
-
}
|
|
130
|
-
catch (error) {
|
|
131
|
-
this.report(error);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
150
|
notify(delta) {
|
|
135
151
|
try {
|
|
136
152
|
this.options.onCommitted?.(delta);
|
|
@@ -148,13 +164,13 @@ export class ProfileOwner {
|
|
|
148
164
|
}
|
|
149
165
|
}
|
|
150
166
|
async commit(events) {
|
|
151
|
-
if (this.lost)
|
|
152
|
-
throw Error("PROFILE_WRITER_FENCED");
|
|
153
167
|
const first = events[0];
|
|
154
168
|
if (first && "ownerType" in first) {
|
|
155
169
|
if (events.length !== 1)
|
|
156
170
|
throw Error("PROFILE_BARRIER_NOT_ISOLATED");
|
|
157
|
-
if (first.ownerType === "
|
|
171
|
+
if (first.ownerType === "cleanup")
|
|
172
|
+
this.cleanupMore = await this.options.database.cleanupGenerations() === 200;
|
|
173
|
+
else if (first.ownerType === "begin")
|
|
158
174
|
await this.builder.begin(first.generation, first.bootstrap, this.current.commitRevision);
|
|
159
175
|
else if (first.ownerType === "append")
|
|
160
176
|
await this.builder.append(first.generation, first.events);
|
|
@@ -170,11 +186,17 @@ export class ProfileOwner {
|
|
|
170
186
|
}
|
|
171
187
|
const fromRevision = this.projection.current.commitRevision;
|
|
172
188
|
const prepared = this.projection.prepare(events);
|
|
173
|
-
|
|
189
|
+
// A replayed cursor or already-observed reading candidate must not even
|
|
190
|
+
// open a readwrite transaction. Only small sync metadata is compared here.
|
|
191
|
+
const unchanged = ![prepared.messages, prepared.windows, prepared.threads, prepared.outbox, prepared.deleteOutbox].some(rows => rows.length) &&
|
|
192
|
+
JSON.stringify({ ...prepared.current, commitRevision: fromRevision }) === JSON.stringify(this.current);
|
|
193
|
+
if (unchanged)
|
|
194
|
+
return prepared.rejected;
|
|
195
|
+
const committed = await this.options.database.commit({ ...prepared,
|
|
174
196
|
generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
|
|
175
|
-
committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady });
|
|
197
|
+
committedSeq: prepared.current.committedSeq, windowStart: prepared.current.windowStart, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
|
|
176
198
|
if (committed.commitRevision === fromRevision)
|
|
177
|
-
return;
|
|
199
|
+
return prepared.rejected;
|
|
178
200
|
prepared.current = committed;
|
|
179
201
|
const delta = { current: committed, threads: prepared.threads, windows: prepared.windows, messages: prepared.messages,
|
|
180
202
|
protocolVersion: PROFILE_PROTOCOL_VERSION, generation: committed.activeGeneration,
|
|
@@ -189,14 +211,17 @@ export class ProfileOwner {
|
|
|
189
211
|
this.memory.restore(this.projection.snapshot());
|
|
190
212
|
}
|
|
191
213
|
this.notify(delta);
|
|
214
|
+
return prepared.rejected;
|
|
192
215
|
}
|
|
193
216
|
async close() {
|
|
194
217
|
if (this.closed)
|
|
195
218
|
return;
|
|
196
219
|
// The producer must stop intake and await accepted enqueue promises first.
|
|
220
|
+
this.cleanupStopping = true;
|
|
221
|
+
if (this.cleanupTimer)
|
|
222
|
+
clearTimeout(this.cleanupTimer);
|
|
223
|
+
await this.cleanupTask;
|
|
197
224
|
this.queue.close();
|
|
198
225
|
this.closed = true;
|
|
199
|
-
clearInterval(this.timer);
|
|
200
|
-
await this.options.database.releaseWriter(this.lease.ownerId, this.lease.fence);
|
|
201
226
|
}
|
|
202
227
|
}
|