@pmate/chat-sdk 0.13.0-profile.1 → 0.13.0-profile.10

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.
Files changed (37) hide show
  1. package/README.md +26 -0
  2. package/lib/profile.d.ts +4 -1
  3. package/lib/profile.js +4 -1
  4. package/lib/runtime/profileChat.d.ts +118 -1
  5. package/lib/runtime/profileChat.js +98 -30
  6. package/lib/runtime/profileCommitQueue.d.ts +2 -1
  7. package/lib/runtime/profileCommitQueue.js +26 -7
  8. package/lib/runtime/profileCoordinator.d.ts +19 -19
  9. package/lib/runtime/profileCoordinator.js +127 -94
  10. package/lib/runtime/profileDatabase.d.ts +7 -7
  11. package/lib/runtime/profileDatabase.js +57 -42
  12. package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
  13. package/lib/runtime/profileGenerationBuilder.js +60 -26
  14. package/lib/runtime/profileInboxFeed.d.ts +1 -0
  15. package/lib/runtime/profileInboxFeed.js +12 -2
  16. package/lib/runtime/profileLegacyInbox.d.ts +8 -0
  17. package/lib/runtime/profileLegacyInbox.js +114 -0
  18. package/lib/runtime/profileLegacyOutbox.d.ts +7 -0
  19. package/lib/runtime/profileLegacyOutbox.js +106 -0
  20. package/lib/runtime/profileLegacyReading.d.ts +7 -0
  21. package/lib/runtime/profileLegacyReading.js +110 -0
  22. package/lib/runtime/profileMemoryStore.d.ts +22 -2
  23. package/lib/runtime/profileMemoryStore.js +140 -12
  24. package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
  25. package/lib/runtime/profileOutboxDispatcher.js +41 -5
  26. package/lib/runtime/profileOwner.d.ts +11 -6
  27. package/lib/runtime/profileOwner.js +71 -46
  28. package/lib/runtime/profileProjection.d.ts +54 -5
  29. package/lib/runtime/profileProjection.js +336 -51
  30. package/lib/runtime/profileReadingIndex.d.ts +1 -0
  31. package/lib/runtime/profileReadingIndex.js +17 -1
  32. package/lib/runtime/profileStoreTypes.d.ts +15 -9
  33. package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +10 -26
  34. package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +55 -102
  35. package/lib/runtime/profileWorkerHost.d.ts +4 -6
  36. package/lib/runtime/profileWorkerHost.js +58 -21
  37. 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 = 1;
5
- export const PROFILE_PROJECTION_VERSION = 1;
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();
@@ -38,7 +47,16 @@ export class ProfileMemoryStore {
38
47
  getStatus() { return { phase: this.phase, generation: this.current?.activeGeneration, revision: this.current?.commitRevision }; }
39
48
  getThread(threadId) { return this.threads.get(threadId); }
40
49
  getMessage(messageId) { return this.entities.get(messageId); }
41
- getPresentedMessage(messageId) { return this.presented.get(messageId); }
50
+ getAccessRevision() { return this.current?.teamAccessRevision ?? 0; }
51
+ isTeamAvailable(teamId) { return !teamId || !this.current?.revokedTeamIds?.includes(teamId); }
52
+ isThreadAvailable(threadId) {
53
+ const thread = this.threads.get(threadId);
54
+ 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));
55
+ }
56
+ getPresentedMessage(messageId) {
57
+ const message = this.entities.get(messageId);
58
+ return message && this.isThreadAvailable(message.threadId) ? this.presented.get(messageId) : undefined;
59
+ }
42
60
  getThreadList = () => this.list;
43
61
  subscribeThreadList = (listener) => { this.listListeners.add(listener); return () => { this.listListeners.delete(listener); }; };
44
62
  subscribeMessages(listener) { this.messageListeners.add(listener); return () => { this.messageListeners.delete(listener); }; }
@@ -52,9 +70,68 @@ export class ProfileMemoryStore {
52
70
  return () => { listeners.delete(listener); if (!listeners.size)
53
71
  this.listeners.delete(threadId); };
54
72
  }
73
+ windowKey(threadId, windowId) { return JSON.stringify([threadId, windowId]); }
74
+ installWindow(window) {
75
+ const key = this.windowKey(window.threadId, window.windowId);
76
+ for (const ref of this.windowRows.get(key)?.refs ?? [])
77
+ if (this.messageWindows.get(ref.messageId) === key)
78
+ this.messageWindows.delete(ref.messageId);
79
+ this.windowRows.set(key, window);
80
+ for (const ref of window.refs)
81
+ this.messageWindows.set(ref.messageId, key);
82
+ this.windowPages.delete(key);
83
+ this.dirtyWindows.add(key);
84
+ }
85
+ getWindowIds(threadId) {
86
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
87
+ throw Error("PROFILE_THREAD_NOT_READY");
88
+ return this.windowIds.get(threadId) ?? this.emptyWindowIds;
89
+ }
90
+ findMessageWindow(threadId, messageId) {
91
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
92
+ throw Error("PROFILE_THREAD_NOT_READY");
93
+ const key = this.messageWindows.get(messageId);
94
+ const window = key ? this.windowRows.get(key) : undefined;
95
+ return window?.threadId === threadId ? window.windowId : undefined;
96
+ }
97
+ readPresentedWindow(threadId, windowId) {
98
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
99
+ throw Error("PROFILE_THREAD_NOT_READY");
100
+ const key = this.windowKey(threadId, windowId);
101
+ const cached = this.windowPages.get(key);
102
+ if (cached)
103
+ return cached;
104
+ const window = this.windowRows.get(key);
105
+ if (!window)
106
+ throw Error("PROFILE_WINDOW_UNAVAILABLE");
107
+ const page = window.refs.map(ref => {
108
+ const message = this.presented.get(ref.messageId);
109
+ if (!message)
110
+ throw Error("PROFILE_SNAPSHOT_INCOMPLETE");
111
+ return message;
112
+ });
113
+ this.windowPages.set(key, page);
114
+ return page;
115
+ }
116
+ subscribeWindow(threadId, windowId, listener) {
117
+ return this.subscribeKey(this.windowListeners, this.windowKey(threadId, windowId), listener);
118
+ }
119
+ subscribeWindowList(threadId, listener) {
120
+ return this.subscribeKey(this.windowListListeners, threadId, listener);
121
+ }
122
+ subscribeKey(map, key, listener) {
123
+ let listeners = map.get(key);
124
+ if (!listeners) {
125
+ listeners = new Set();
126
+ map.set(key, listeners);
127
+ }
128
+ listeners.add(listener);
129
+ return () => { listeners.delete(listener); if (!listeners.size)
130
+ map.delete(key); };
131
+ }
55
132
  restore(snapshot) {
56
133
  const generation = snapshot.current.activeGeneration;
57
- if (snapshot.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
134
+ if (![1, PROFILE_PROJECTION_VERSION].includes(snapshot.current.projectionVersion))
58
135
  throw Error("PROFILE_PROJECTION_INCOMPATIBLE");
59
136
  for (const row of [...snapshot.threads, ...snapshot.windows, ...snapshot.messages])
60
137
  if (row.generation !== generation)
@@ -78,6 +155,14 @@ export class ProfileMemoryStore {
78
155
  }
79
156
  // Install only after complete validation: a bad handoff retains the old view.
80
157
  const affected = new Set([...this.threads.keys(), ...threads.keys()]);
158
+ for (const key of this.windowRows.keys())
159
+ this.dirtyWindows.add(key);
160
+ this.windowRows.clear();
161
+ this.messageWindows.clear();
162
+ this.windowPages.clear();
163
+ this.windowIds.clear();
164
+ for (const window of snapshot.windows)
165
+ this.installWindow(window);
81
166
  this.entities = entities;
82
167
  this.threads = threads;
83
168
  this.directories = directories;
@@ -89,7 +174,7 @@ export class ProfileMemoryStore {
89
174
  this.prepareMessageView(row);
90
175
  }
91
176
  this.current = snapshot.current;
92
- this.phase = snapshot.current.epoch === "uninitialized" ? "restoring" : "ready";
177
+ this.phase = snapshot.current.epoch === "uninitialized" || snapshot.current.projectionVersion !== PROFILE_PROJECTION_VERSION ? "restoring" : "ready";
93
178
  this.pageCache.clear();
94
179
  this.epochs.clear();
95
180
  this.publish(affected, true);
@@ -144,6 +229,7 @@ export class ProfileMemoryStore {
144
229
  for (const thread of delta.threads)
145
230
  this.threads.set(thread.threadId, thread);
146
231
  for (const window of delta.windows) {
232
+ this.installWindow(window);
147
233
  let directory = this.directories.get(window.threadId);
148
234
  if (!directory) {
149
235
  directory = new ProfileWindowDirectory(delta.generation, window.threadId);
@@ -152,6 +238,11 @@ export class ProfileMemoryStore {
152
238
  directory.accept({ windows: [window], windowCount: 0 });
153
239
  affected.add(window.threadId);
154
240
  }
241
+ const accessChanged = new Set([...(this.current.revokedTeamIds ?? []), ...(delta.current.revokedTeamIds ?? [])].filter(id => this.current.revokedTeamIds?.includes(id) !== delta.current.revokedTeamIds?.includes(id)));
242
+ if (accessChanged.size)
243
+ for (const thread of this.threads.values())
244
+ if (thread.teamId && accessChanged.has(thread.teamId))
245
+ affected.add(thread.threadId);
155
246
  this.current = delta.current;
156
247
  for (const message of delta.messages) {
157
248
  this.indexMessage(message);
@@ -159,6 +250,10 @@ export class ProfileMemoryStore {
159
250
  }
160
251
  for (const thread of delta.threads) {
161
252
  const previous = previousThreads.get(thread.threadId);
253
+ if (previous?.status !== thread.status)
254
+ for (const child of this.threads.values())
255
+ if (child.parentThreadId === thread.threadId)
256
+ affected.add(child.threadId);
162
257
  const index = this.readingIndices.get(thread.threadId);
163
258
  for (const source of thread.readingSources) {
164
259
  const before = previous?.readingSources.find(row => row.sourceThreadId === source.sourceThreadId);
@@ -185,7 +280,7 @@ export class ProfileMemoryStore {
185
280
  }
186
281
  }
187
282
  }
188
- this.publish(affected, delta.threads.length > 0);
283
+ this.publish(affected, delta.threads.length > 0 || accessChanged.size > 0);
189
284
  if (added.length)
190
285
  for (const listener of this.messageListeners)
191
286
  this.notify(() => listener(added));
@@ -200,23 +295,56 @@ export class ProfileMemoryStore {
200
295
  const source = thread?.readingSources.find(row => row.sourceThreadId === message.sourceThreadId);
201
296
  const mine = message.from === this.profileId;
202
297
  const policy = message.readPolicy ?? "visible";
203
- const read = mine || message.recalled === true || (policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus === "read" :
204
- message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
298
+ const read = message.recalled === true || (policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus === "read" :
299
+ mine || message.explicitReadingFacts.some(row => row.profileId === this.profileId) || source?.explicitReadMessageIds.includes(message.messageId) === true ||
205
300
  source?.pendingExplicitReadMessageIds?.includes(message.messageId) === true || source?.preservedReadMessageIds.includes(message.messageId) === true ||
206
301
  policy === "visible" && message.sourceSeq !== undefined && message.sourceSeq <= Math.max(source?.readThroughSeq ?? 0, source?.pendingReadThroughSeq ?? 0));
302
+ const discussionStatus = policy === "discussion" ? this.threads.get(message.discussionThreadId)?.readingStatus : undefined;
303
+ const readingUnknown = policy === "discussion" && discussionStatus !== "read" && discussionStatus !== "unread" || !message.sourceSeq && !mine && !read || thread?.readingStatus === "unknown" && !thread.internal?.unknownReadingCount;
207
304
  const content = message.presentation ?? projectMessageContent({ id: message.messageId, threadId: message.threadId, timestamp: message.orderKey[0],
208
305
  from: message.from, recipients: message.recipients, body: message.content, threadKind: thread?.kind === "dm" ? "dm" : "group", teamId: thread?.teamId });
209
306
  const visibleContent = message.recalled ? { kind: "system", text: "" } : content;
210
307
  const value = { ...visibleContent, id: message.messageId, threadId: thread?.parentThreadId ?? message.threadId,
211
308
  ...(thread?.rootMessageId ? { threadRootId: thread.rootMessageId } : {}), timestamp: message.orderKey[0], from: message.from, mine,
212
309
  status: message.sendStatus === "failed" ? "failed" : message.sendStatus === "sending" ? "sending" : mine && message.readBy.length ? "read" : "sent",
213
- recalled: message.recalled ?? false, unread: thread?.readingStatus === "unknown" ? undefined : !read,
214
- attentionEligible: message.mention, reading: thread?.readingStatus === "unknown" ? undefined : { seq: message.sourceSeq, read,
310
+ recalled: message.recalled ?? false, unread: readingUnknown ? undefined : !read,
311
+ attentionEligible: message.mention, reading: readingUnknown ? undefined : { seq: message.sourceSeq, read,
215
312
  readPolicy: policy === "visible" ? "visible" : "explicit" },
216
313
  reactions: message.reactions.map(row => ({ emojiId: row.emojiId, userIds: row.profileIds, mine: row.profileIds.includes(this.profileId) })) };
217
314
  this.presented.set(message.messageId, value);
315
+ const key = this.messageWindows.get(message.messageId);
316
+ if (key) {
317
+ this.windowPages.delete(key);
318
+ this.dirtyWindows.add(key);
319
+ }
218
320
  }
219
321
  publish(affected, directoryChanged) {
322
+ const changedLists = new Set();
323
+ for (const threadId of affected) {
324
+ const blocks = this.directories.get(threadId)?.blocks ?? [];
325
+ const previous = this.windowIds.get(threadId);
326
+ // Window sequence and IDs never shift on body/reading updates. Only a
327
+ // newly appended block or a full restoration changes this directory.
328
+ if (!previous || previous.length !== blocks.length) {
329
+ this.windowIds.set(threadId, blocks.map(window => window.windowId));
330
+ changedLists.add(threadId);
331
+ }
332
+ const available = this.isThreadAvailable(threadId);
333
+ if (this.windowAccess.get(threadId) !== available) {
334
+ this.windowAccess.set(threadId, available);
335
+ changedLists.add(threadId);
336
+ for (const block of blocks)
337
+ this.dirtyWindows.add(this.windowKey(threadId, block.windowId));
338
+ }
339
+ }
340
+ const dirtyWindows = this.dirtyWindows;
341
+ this.dirtyWindows = new Set();
342
+ for (const key of dirtyWindows)
343
+ for (const listener of this.windowListeners.get(key) ?? [])
344
+ this.notify(listener);
345
+ for (const thread of changedLists)
346
+ for (const listener of this.windowListListeners.get(thread) ?? [])
347
+ this.notify(listener);
220
348
  for (const thread of affected)
221
349
  this.epochs.set(thread, (this.epochs.get(thread) ?? 0) + 1);
222
350
  // Cached pages live only until that thread changes; no unbounded scroll cache.
@@ -224,7 +352,7 @@ export class ProfileMemoryStore {
224
352
  if (affected.has(JSON.parse(key)[0]))
225
353
  this.pageCache.delete(key);
226
354
  if (directoryChanged) {
227
- this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion")
355
+ this.list = [...this.threads.values()].filter(thread => thread.kind !== "discussion" && this.isTeamAvailable(thread.teamId))
228
356
  .sort((a, b) => b.lastActivityAt - a.lastActivityAt || a.threadId.localeCompare(b.threadId));
229
357
  }
230
358
  for (const thread of affected)
@@ -235,7 +363,7 @@ export class ProfileMemoryStore {
235
363
  this.notify(listener);
236
364
  }
237
365
  readPage(threadId, anchor, limit, direction = "older") {
238
- if (this.phase !== "ready" || this.threads.get(threadId)?.status !== "ready")
366
+ if (this.phase !== "ready" || !this.isThreadAvailable(threadId))
239
367
  throw Error("PROFILE_THREAD_NOT_READY");
240
368
  const key = JSON.stringify([threadId, anchor ?? null, limit, direction]), epoch = this.epochs.get(threadId) ?? 0;
241
369
  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; }).catch(() => { });
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
- async run() {
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
- const command = owner.commands().sort((a, b) => a.createdAt - b.createdAt || a.commandId.localeCompare(b.commandId))[0];
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 lease;
25
- private timer?;
26
- private lost;
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?: `${string}-${string}-${string}-${string}-${string}`): Promise<`${string}-${string}-${string}-${string}-${string}`>;
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
- lease;
15
- timer;
16
- lost = false;
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(ownerId, lease.fence, { activeGeneration: crypto.randomUUID(), epoch: options.epoch,
33
- committedSeq: "0", projectionVersion: 1 });
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, () => owner.lease);
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
- owner.timer = setInterval(() => { void owner.renew(); }, 10000);
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 && !this.lost && this.lease.expiresAt > Date.now(); }
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 || this.lost)
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 || this.lost)
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 || this.lost)
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 || this.lost)
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 === "begin")
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
- const committed = await this.options.database.commit({ ...prepared, ownerId: this.lease.ownerId, fence: this.lease.fence,
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
  }