@pmate/chat-sdk 0.12.0-next.4 → 0.12.0-next.41

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 (50) hide show
  1. package/README.md +41 -1
  2. package/lib/runtime/batchedReadIndex.d.ts +11 -2
  3. package/lib/runtime/batchedReadIndex.js +21 -1
  4. package/lib/runtime/cachedMessage.d.ts +12 -0
  5. package/lib/runtime/cachedMessage.js +18 -0
  6. package/lib/runtime/chatClient.d.ts +1 -0
  7. package/lib/runtime/chatClient.js +1 -1
  8. package/lib/runtime/chatSession.d.ts +78 -8
  9. package/lib/runtime/chatSession.js +504 -39
  10. package/lib/runtime/connectivity.d.ts +4 -0
  11. package/lib/runtime/connectivity.js +8 -0
  12. package/lib/runtime/conversationRead.d.ts +13 -0
  13. package/lib/runtime/conversationRead.js +34 -0
  14. package/lib/runtime/conversationReading.d.ts +28 -0
  15. package/lib/runtime/conversationReading.js +47 -0
  16. package/lib/runtime/createChat.d.ts +4 -5
  17. package/lib/runtime/createChat.js +14 -17
  18. package/lib/runtime/durableSender.d.ts +30 -4
  19. package/lib/runtime/durableSender.js +174 -34
  20. package/lib/runtime/index.d.ts +4 -0
  21. package/lib/runtime/index.js +4 -0
  22. package/lib/runtime/messageClient.d.ts +33 -6
  23. package/lib/runtime/messageClient.js +443 -71
  24. package/lib/runtime/messageControls.d.ts +19 -0
  25. package/lib/runtime/messageControls.js +44 -0
  26. package/lib/runtime/messageLaunch.d.ts +42 -0
  27. package/lib/runtime/messageLaunch.js +127 -0
  28. package/lib/runtime/messageQuotes.d.ts +3 -0
  29. package/lib/runtime/messageQuotes.js +17 -0
  30. package/lib/runtime/messageReaders.d.ts +12 -1
  31. package/lib/runtime/messageReaders.js +67 -3
  32. package/lib/runtime/messageStore.d.ts +47 -2
  33. package/lib/runtime/messageStore.js +233 -10
  34. package/lib/runtime/messageTimeline.d.ts +50 -0
  35. package/lib/runtime/messageTimeline.js +120 -0
  36. package/lib/runtime/readCounts.d.ts +15 -1
  37. package/lib/runtime/readCounts.js +96 -8
  38. package/lib/runtime/readIndex.d.ts +44 -6
  39. package/lib/runtime/readIndex.js +238 -11
  40. package/lib/runtime/readSync.d.ts +1 -0
  41. package/lib/runtime/readSync.js +21 -8
  42. package/lib/runtime/readingClient.d.ts +19 -0
  43. package/lib/runtime/readingClient.js +121 -18
  44. package/lib/runtime/readingContent.d.ts +5 -0
  45. package/lib/runtime/readingContent.js +23 -0
  46. package/lib/runtime/recordCache.d.ts +9 -0
  47. package/lib/runtime/recordCache.js +62 -5
  48. package/lib/runtime/responseCache.d.ts +44 -0
  49. package/lib/runtime/responseCache.js +173 -0
  50. package/package.json +6 -1
@@ -1,4 +1,4 @@
1
- import { applyReadChange, ReadSyncGap, createReadIndex, installReadSnapshot } from "./readIndex.js";
1
+ import { readingMetadata, assertReadIndexVersions, applyReadChange, ReadSyncGap, createReadIndex, installReadSnapshot } from "./readIndex.js";
2
2
  /** Keeps local operations until an authoritative projection covers them. */
3
3
  export class ReadSyncClient {
4
4
  options;
@@ -9,8 +9,11 @@ export class ReadSyncClient {
9
9
  this.options = options;
10
10
  }
11
11
  async loadLocal() {
12
- return await this.options.persistence.load(this.options.appId, this.options.profileId)
13
- ?? createReadIndex(this.options.appId, this.options.profileId);
12
+ const { appId, profileId, persistence, metadataOnly } = this.options;
13
+ const state = await persistence.load(appId, profileId) ?? createReadIndex(appId, profileId);
14
+ if (!metadataOnly || readingMetadata(state) === state)
15
+ return state;
16
+ return persistence.update(appId, profileId, readingMetadata);
14
17
  }
15
18
  stop() { this.controller.abort(); }
16
19
  synchronize() {
@@ -46,7 +49,9 @@ export class ReadSyncClient {
46
49
  }
47
50
  async run() {
48
51
  const { appId, profileId, persistence } = this.options;
49
- const current = await this.loadLocal();
52
+ const loaded = persistence.loadVersioned ? await persistence.loadVersioned(appId, profileId) : { state: await persistence.load(appId, profileId), versions: {} };
53
+ const current = loaded.state ?? createReadIndex(appId, profileId);
54
+ const versions = loaded.versions;
50
55
  // Ordinary reads are monotonic: only the furthest position per thread needs
51
56
  // sending. Keep every original operation in storage until the projection
52
57
  // confirms it, and never rewrite an operation ID's payload during retries.
@@ -60,6 +65,8 @@ export class ReadSyncClient {
60
65
  }
61
66
  const outgoing = current.pending.filter(operation => operation.explicitReadMessageIds.length || operation.readThroughSeq <= 0 || latest.get(operation.threadId) === operation);
62
67
  for (const operation of outgoing) {
68
+ if (persistence.loadVersions)
69
+ assertReadIndexVersions(versions, await persistence.loadVersions(appId, profileId));
63
70
  const receipt = await this.request("/api/social/reading", {
64
71
  method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ...operation, appId, profileId }),
65
72
  });
@@ -69,8 +76,10 @@ export class ReadSyncClient {
69
76
  this.readAfter = Math.max(this.readAfter, receipt.acceptedAt);
70
77
  }
71
78
  const query = new URLSearchParams({ appId, profileId });
79
+ if (this.options.metadataOnly)
80
+ query.set("metadataOnly", "true");
72
81
  if (!this.readAfter && current.syncCursor !== "0") {
73
- const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor })}`);
82
+ const delta = await this.request(`/api/social/reading/changes?${new URLSearchParams({ appId, profileId, after: current.syncCursor, ...(this.options.metadataOnly ? { metadataOnly: "true" } : {}) })}`);
74
83
  if (delta.appId !== appId || delta.profileId !== profileId || typeof delta.syncCursor !== "string"
75
84
  || typeof delta.snapshotRequired !== "boolean" || !Array.isArray(delta.changes))
76
85
  throw new Error("INVALID_READ_DELTA");
@@ -78,8 +87,9 @@ export class ReadSyncClient {
78
87
  try {
79
88
  if (this.controller.signal.aborted)
80
89
  throw new Error("READ_SYNC_STOPPED");
81
- const next = await persistence.update(appId, profileId, state => {
82
- const applied = delta.changes.reduce(applyReadChange, state);
90
+ const next = await persistence.update(appId, profileId, (state, currentVersions) => {
91
+ assertReadIndexVersions(versions, currentVersions);
92
+ const applied = delta.changes.reduce((current, change) => applyReadChange(current, this.options.metadataOnly ? { ...change, thread: readingMetadata({ appId, threads: [change.thread] }).threads[0] } : change), this.options.metadataOnly ? readingMetadata(state) : state);
83
93
  if (applied.syncCursor !== delta.syncCursor)
84
94
  throw new ReadSyncGap(applied.syncCursor);
85
95
  return applied;
@@ -100,7 +110,10 @@ export class ReadSyncClient {
100
110
  if (this.controller.signal.aborted)
101
111
  throw new Error("READ_SYNC_STOPPED");
102
112
  // Merge into the latest transaction, including reads made while HTTP was pending.
103
- const next = await persistence.update(appId, profileId, state => installReadSnapshot(state, snapshot));
113
+ const next = await persistence.update(appId, profileId, (state, currentVersions) => {
114
+ assertReadIndexVersions(versions, currentVersions);
115
+ return installReadSnapshot(state, this.options.metadataOnly ? readingMetadata(snapshot) : snapshot);
116
+ });
104
117
  if (!next.pending.length)
105
118
  this.readAfter = 0;
106
119
  if (!this.controller.signal.aborted)
@@ -1,11 +1,15 @@
1
+ import { type ConversationReadMessage } from "./conversationRead.js";
1
2
  import { type ReadIndexPersistence, type ReadIndexState } from "./readIndex.js";
2
3
  export type ReadingClientOptions = {
3
4
  appId: string;
4
5
  profileId: string;
5
6
  sessionToken: string;
6
7
  hubHttpUrl: string;
8
+ teamId?: string;
9
+ metadataOnly?: boolean;
7
10
  persistence?: ReadIndexPersistence;
8
11
  storageScope?: string;
12
+ migrateLegacy?: boolean;
9
13
  fetch?: typeof fetch;
10
14
  onError?: (error: unknown) => void;
11
15
  onRecovered?: () => void;
@@ -15,6 +19,12 @@ export type ReadingClientOptions = {
15
19
  export declare class ReadingClient {
16
20
  private options;
17
21
  private storage;
22
+ private backing;
23
+ private closing?;
24
+ private revoking?;
25
+ private versions?;
26
+ private prepared;
27
+ private accepted;
18
28
  private persistence;
19
29
  private sync;
20
30
  private tasks;
@@ -34,8 +44,17 @@ export declare class ReadingClient {
34
44
  refresh: () => void;
35
45
  synchronize(targetCursor?: string, profileId?: string): Promise<ReadIndexState>;
36
46
  update(transform: (state: ReadIndexState) => ReadIndexState): Promise<ReadIndexState>;
47
+ private updateScoped;
48
+ prepareTeam(teamId: string, version: number): Promise<void>;
49
+ private assertThreadTeam;
50
+ markRead(threadId: string, messages?: readonly ConversationReadMessage[]): Promise<ReadIndexState>;
37
51
  recordVisible(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
38
52
  recordExplicit(threadId: string, messageIds: string[]): Promise<ReadIndexState>;
39
53
  private record;
54
+ withdraw(): void;
55
+ private stop;
56
+ /** This client is retired permanently. Drain accepted local observations
57
+ * before deleting one team's profile-wide projection; sibling teams survive. */
58
+ revokeTeam(teamId: string, version: number, knownThreadIds?: readonly string[]): Promise<void>;
40
59
  close(): Promise<void>;
41
60
  }
@@ -1,12 +1,21 @@
1
+ import { isValidChatTeamId } from "./thread.js";
2
+ import { isOffline, isOfflineNetworkFailure } from "./connectivity.js";
3
+ import { recordConversationRead } from "./conversationRead.js";
1
4
  import { BatchedReadIndex } from "./batchedReadIndex.js";
2
5
  import { WindowedTasks } from "./coalescer.js";
3
- import { IndexedDbReadIndex, recordReadIntent } from "./readIndex.js";
6
+ import { IndexedDbReadIndex, readingMetadata, recordReadIntent, assertReadIndexVersions } from "./readIndex.js";
4
7
  import { ReadSyncClient } from "./readSync.js";
5
8
  /** Owns durable local reads, network coalescing, retries and state notifications.
6
9
  * Hosts report actual visibility; loading or subscribing never marks messages read. */
7
10
  export class ReadingClient {
8
11
  options;
9
12
  storage;
13
+ backing;
14
+ closing;
15
+ revoking;
16
+ versions;
17
+ prepared = new Map();
18
+ accepted = new Set();
10
19
  persistence;
11
20
  sync;
12
21
  tasks;
@@ -19,7 +28,10 @@ export class ReadingClient {
19
28
  generation = 0;
20
29
  constructor(options) {
21
30
  this.options = options;
22
- const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope));
31
+ if (options.teamId !== undefined && !isValidChatTeamId(options.teamId))
32
+ throw new Error("INVALID_READ_TEAM");
33
+ const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope, options.migrateLegacy, options.metadataOnly));
34
+ this.backing = storage;
23
35
  this.persistence = new BatchedReadIndex(storage);
24
36
  this.tasks = new WindowedTasks(1000, error => this.failed(error));
25
37
  this.sync = new ReadSyncClient({ ...options, persistence: this.persistence, onChange: state => this.publish(state) });
@@ -33,7 +45,7 @@ export class ReadingClient {
33
45
  this.listeners.forEach(listener => listener());
34
46
  }
35
47
  failed(error) {
36
- if (this.closed)
48
+ if (this.closed || isOfflineNetworkFailure(error))
37
49
  return;
38
50
  this.options.onError?.(error);
39
51
  if (/HTTP_(400|401|403)/.test(String(error)) || (typeof navigator !== "undefined" && !navigator.onLine) || this.retry)
@@ -56,8 +68,9 @@ export class ReadingClient {
56
68
  this.refresh();
57
69
  }
58
70
  refresh = () => {
59
- if (!this.closed)
60
- this.tasks.schedule("reading", async () => { await this.synchronize(); });
71
+ if (!this.closed && !isOffline())
72
+ this.tasks.schedule("reading", async () => { if (!isOffline())
73
+ await this.synchronize(); });
61
74
  };
62
75
  async synchronize(targetCursor, profileId) {
63
76
  if (this.closed)
@@ -84,32 +97,122 @@ export class ReadingClient {
84
97
  }
85
98
  throw new Error("Reading projection has not reached the announced version");
86
99
  }
87
- async update(transform) {
100
+ update(transform) {
101
+ // Advanced transforms may replace profile-wide state. Typed observation
102
+ // methods below only derive changes for their configured team.
103
+ return this.updateScoped(transform);
104
+ }
105
+ updateScoped(transform, teamId) {
88
106
  if (this.closed)
89
- throw new Error("READING_CLIENT_CLOSED");
90
- const next = await this.persistence.update(this.options.appId, this.options.profileId, transform);
91
- if (!this.closed) {
92
- this.publish(next);
93
- if (next.pending.length || next.observedReadIntents?.length)
94
- this.refresh();
95
- }
96
- return next;
107
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
108
+ // One shared metadata read per local authority generation, rather than one
109
+ // IndexedDB lookup for every viewport observation.
110
+ const versions = this.versions ??= this.persistence.loadVersions(this.options.appId, this.options.profileId);
111
+ const task = (async () => {
112
+ const expected = await versions;
113
+ const next = await this.persistence.update(this.options.appId, this.options.profileId, (state, currentVersions) => {
114
+ assertReadIndexVersions(expected, currentVersions, teamId);
115
+ const next = transform(state);
116
+ return this.options.metadataOnly ? readingMetadata(next) : next;
117
+ });
118
+ if (!this.closed) {
119
+ this.publish(next);
120
+ if (next.pending.length || next.observedReadIntents?.length)
121
+ this.refresh();
122
+ }
123
+ return next;
124
+ })().catch(error => {
125
+ if (String(error).includes("READ_SCOPE_CHANGED")) {
126
+ if (teamId !== undefined)
127
+ this.withdraw();
128
+ else
129
+ this.versions = undefined;
130
+ }
131
+ throw error;
132
+ });
133
+ this.accepted.add(task);
134
+ void task.finally(() => this.accepted.delete(task)).catch(() => { });
135
+ return task;
136
+ }
137
+ prepareTeam(teamId, version) {
138
+ if (this.closed)
139
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
140
+ if (!isValidChatTeamId(teamId) || !Number.isSafeInteger(version) || version < 0)
141
+ return Promise.reject(new Error("INVALID_READ_SCOPE_VERSION"));
142
+ const previous = this.prepared.get(teamId);
143
+ if (previous && previous.version >= version)
144
+ return previous.task;
145
+ const task = (async () => {
146
+ if (version > 0)
147
+ await this.persistence.invalidateTeam(this.options.appId, this.options.profileId, teamId, version);
148
+ this.versions = undefined;
149
+ })().catch(error => { if (this.prepared.get(teamId)?.task === task)
150
+ this.prepared.delete(teamId); throw error; });
151
+ this.prepared.set(teamId, { version, task });
152
+ return task;
153
+ }
154
+ assertThreadTeam(state, threadId) {
155
+ if (this.options.teamId !== undefined && state.threads.some(thread => (thread.id === threadId || thread.conversationId === threadId) && thread.teamId !== undefined && thread.teamId !== this.options.teamId))
156
+ throw new Error("READ_CONVERSATION_TEAM_MISMATCH");
157
+ }
158
+ markRead(threadId, messages = []) {
159
+ return this.updateScoped(state => { this.assertThreadTeam(state, threadId); return recordConversationRead(state, threadId, messages); }, this.options.teamId);
97
160
  }
98
161
  recordVisible(threadId, messageIds) { return this.record(threadId, messageIds, "visible"); }
99
162
  recordExplicit(threadId, messageIds) { return this.record(threadId, messageIds, "explicit"); }
100
163
  record(threadId, ids, readPolicy) {
101
164
  const messageIds = [...new Set(ids)];
102
- return this.update(state => messageIds.reduce((next, messageId) => recordReadIntent(next, { threadId, messageId, readPolicy, operationId: crypto.randomUUID() }), state));
165
+ return this.updateScoped(state => { this.assertThreadTeam(state, threadId); return messageIds.reduce((next, messageId) => recordReadIntent(next, { threadId, messageId, readPolicy, operationId: crypto.randomUUID() }), state); }, this.options.teamId);
103
166
  }
104
- async close() {
167
+ withdraw() { this.stop(); }
168
+ stop() {
169
+ if (this.closed)
170
+ return;
105
171
  this.closed = true;
106
172
  this.generation++;
107
173
  this.offWake?.();
108
174
  this.tasks.close();
109
175
  clearTimeout(this.retry);
110
176
  this.sync.stop();
177
+ this.state = undefined;
178
+ this.listeners.forEach(listener => listener());
111
179
  this.listeners.clear();
112
- await this.persistence.close();
113
- await this.storage?.close();
180
+ }
181
+ /** This client is retired permanently. Drain accepted local observations
182
+ * before deleting one team's profile-wide projection; sibling teams survive. */
183
+ revokeTeam(teamId, version, knownThreadIds = []) {
184
+ if (this.revoking)
185
+ return this.revoking;
186
+ if (this.closing)
187
+ return Promise.reject(new Error("READING_CLIENT_CLOSED"));
188
+ this.stop();
189
+ return this.revoking = (async () => {
190
+ try {
191
+ await Promise.allSettled([...this.accepted]);
192
+ await this.persistence.close();
193
+ if (!this.backing.invalidateTeam)
194
+ throw new Error("READ_SCOPE_INVALIDATION_UNAVAILABLE");
195
+ await this.backing.invalidateTeam(this.options.appId, this.options.profileId, teamId, version, knownThreadIds);
196
+ }
197
+ finally {
198
+ await this.storage?.close();
199
+ }
200
+ })();
201
+ }
202
+ close() {
203
+ if (this.revoking)
204
+ return this.revoking;
205
+ if (this.closing)
206
+ return this.closing;
207
+ this.stop();
208
+ return this.closing = (async () => {
209
+ try {
210
+ await Promise.allSettled([...this.accepted]);
211
+ await this.persistence.close();
212
+ }
213
+ finally {
214
+ await this.storage?.close();
215
+ }
216
+ })();
114
217
  }
115
218
  }
@@ -0,0 +1,5 @@
1
+ /** Social control envelopes do not contribute to message unread counts. */
2
+ export declare function isReadingControl(payload: unknown, appId: string): boolean;
3
+ /** Mirrors the server's voice policy for ordinary and quoted wire envelopes. */
4
+ export declare function messageRequiresPlayback(body: unknown): boolean;
5
+ export declare function messageMentionsProfile(body: unknown, profileId: string): boolean;
@@ -0,0 +1,23 @@
1
+ /** Social control envelopes do not contribute to message unread counts. */
2
+ export function isReadingControl(payload, appId) {
3
+ if (!payload || typeof payload !== "object")
4
+ return false;
5
+ const value = payload;
6
+ if (value.body !== undefined)
7
+ return isReadingControl(value.body, appId);
8
+ return value.kind === "message" && value.content?.appId === appId && (value.content.reaction !== undefined || value.content.recall !== undefined);
9
+ }
10
+ /** Mirrors the server's voice policy for ordinary and quoted wire envelopes. */
11
+ export function messageRequiresPlayback(body) {
12
+ if (!body || typeof body !== "object")
13
+ return false;
14
+ const value = body;
15
+ return value.contentKind === "voice" || value.content?.contentKind === "voice" || [value.content?.voice?.url, value.content?.content?.voice?.url].some(url => typeof url === "string" && url.length > 0);
16
+ }
17
+ export function messageMentionsProfile(body, profileId) {
18
+ if (!body || typeof body !== "object")
19
+ return false;
20
+ const content = body.content;
21
+ const mentions = content?.mentions !== undefined ? content.mentions : content?.content?.mentions;
22
+ return Array.isArray(mentions) && mentions.some(mention => mention?.id === profileId);
23
+ }
@@ -5,6 +5,8 @@ export type RecordCacheOptions<T> = {
5
5
  indexedDB?: IDBFactory;
6
6
  name?: string;
7
7
  onError?: (error: unknown) => void;
8
+ transactionBytes?: number;
9
+ queueBytes?: number;
8
10
  };
9
11
  /** In-memory control-event index backed by bounded asynchronous IndexedDB batches.
10
12
  * Legacy storage is read only during open; the hot path never uses localStorage. */
@@ -23,6 +25,11 @@ export declare class IndexedDbRecordCache<T> {
23
25
  private closing;
24
26
  private initialized;
25
27
  private running?;
28
+ private activeBytes;
29
+ private pendingBytes;
30
+ private activeRecords;
31
+ private transactionBytes;
32
+ private queueBytes;
26
33
  private channel?;
27
34
  private listeners;
28
35
  constructor(options: RecordCacheOptions<T>);
@@ -34,7 +41,9 @@ export declare class IndexedDbRecordCache<T> {
34
41
  subscribe(listener: () => void): () => void;
35
42
  private reload;
36
43
  upsert(incoming: T[]): Promise<void>;
44
+ private bytes;
37
45
  private write;
46
+ private writeBatch;
38
47
  flush(): Promise<void>;
39
48
  private runFlush;
40
49
  close(): Promise<void>;
@@ -17,17 +17,26 @@ export class IndexedDbRecordCache {
17
17
  closing = false;
18
18
  initialized = false;
19
19
  running;
20
+ activeBytes = 0;
21
+ pendingBytes = 0;
22
+ activeRecords = 0;
23
+ transactionBytes;
24
+ queueBytes;
20
25
  channel;
21
26
  listeners = new Set();
22
27
  constructor(options) {
23
28
  this.options = options;
29
+ this.transactionBytes = options.transactionBytes ?? 1_048_576;
30
+ this.queueBytes = options.queueBytes ?? 8_388_608;
31
+ if (!Number.isSafeInteger(this.transactionBytes) || this.transactionBytes < 1 || !Number.isSafeInteger(this.queueBytes) || this.queueBytes < this.transactionBytes)
32
+ throw new Error("INVALID_RECORD_CACHE_BYTE_LIMIT");
24
33
  this.db = new Dexie(options.name ?? "pmate-chat-records", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
25
34
  this.db.version(1).stores({ records: "[scope+id],scope", metadata: "scope" });
26
35
  this.records = this.db.table("records");
27
36
  this.metadata = this.db.table("metadata");
28
37
  this.tasks = new WindowedTasks(16, error => options.onError?.(error));
29
38
  if (typeof BroadcastChannel !== "undefined") {
30
- this.channel = new BroadcastChannel(`pmate-chat-records:${options.scope}`);
39
+ this.channel = new BroadcastChannel(`pmate-chat-records:${options.scope}${this.db.name === "pmate-chat-records" ? "" : `:${this.db.name}`}`);
31
40
  this.channel.onmessage = () => this.tasks.schedule("reload", () => this.reload());
32
41
  }
33
42
  }
@@ -83,30 +92,70 @@ export class IndexedDbRecordCache {
83
92
  await this.ready;
84
93
  if (this.closed || this.closing)
85
94
  throw new Error("RECORD_CACHE_CLOSED");
86
- if (incoming.length + this.pending.size > 4096)
95
+ if (incoming.length > 4096)
87
96
  throw new Error("RECORD_CACHE_BACKPRESSURE");
88
- let changed = false;
97
+ // Plan and validate the whole operation before publishing any in-memory state.
98
+ const staged = new Map();
89
99
  for (const value of incoming) {
90
- const key = this.options.key(value), old = this.values.get(key), next = this.options.merge(old, value);
100
+ const key = this.options.key(value), old = staged.get(key) ?? this.values.get(key);
101
+ const next = this.options.merge(old, value);
91
102
  if (JSON.stringify(old) === JSON.stringify(next))
92
103
  continue;
104
+ if (this.bytes(next) > this.transactionBytes)
105
+ throw new Error("RECORD_CACHE_RECORD_TOO_LARGE");
106
+ staged.set(key, structuredClone(next));
107
+ }
108
+ let nextBytes = this.pendingBytes, nextRecords = this.pending.size;
109
+ for (const [key, value] of staged) {
110
+ const previous = this.pending.get(key);
111
+ nextBytes += this.bytes(value) - (previous === undefined ? 0 : this.bytes(previous));
112
+ if (!this.pending.has(key))
113
+ nextRecords++;
114
+ }
115
+ if (nextRecords + this.activeRecords > 4096 || nextBytes + this.activeBytes > this.queueBytes)
116
+ throw new Error("RECORD_CACHE_BACKPRESSURE");
117
+ let changed = false;
118
+ for (const [key, next] of staged) {
93
119
  this.values.set(key, next);
94
120
  this.pending.set(key, next);
95
121
  changed = true;
96
122
  }
123
+ this.pendingBytes = nextBytes;
97
124
  if (changed)
98
125
  this.snapshotValue = [...this.values.values()];
99
- if (!changed && !this.pending.size)
126
+ if (!changed && !this.pending.size) {
127
+ await this.running;
100
128
  return;
129
+ }
101
130
  const committed = new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
102
131
  this.tasks.schedule("write", () => this.flush());
103
132
  return committed;
104
133
  }
134
+ bytes(value) { return new TextEncoder().encode(JSON.stringify({ scope: this.options.scope, id: this.options.key(value), value })).byteLength; }
105
135
  async write(values) {
136
+ let batch = [], bytes = 0;
137
+ for (const value of values) {
138
+ const size = this.bytes(value);
139
+ if (size > this.transactionBytes)
140
+ throw new Error("RECORD_CACHE_RECORD_TOO_LARGE");
141
+ if (batch.length && (batch.length === 128 || bytes + size > this.transactionBytes)) {
142
+ await this.writeBatch(batch);
143
+ batch = [];
144
+ bytes = 0;
145
+ }
146
+ batch.push(value);
147
+ bytes += size;
148
+ }
149
+ if (batch.length)
150
+ await this.writeBatch(batch);
151
+ }
152
+ async writeBatch(values) {
106
153
  await this.db.transaction("rw", this.records, async () => {
107
154
  const previous = await this.records.bulkGet(values.map(value => [this.options.scope, this.options.key(value)]));
108
155
  const records = values.map((value, index) => ({ scope: this.options.scope, id: this.options.key(value), value: this.options.merge(previous[index]?.value, value) }));
109
156
  const changed = records.filter((row, index) => JSON.stringify(previous[index]?.value) !== JSON.stringify(row.value));
157
+ if (changed.reduce((sum, row) => sum + this.bytes(row.value), 0) > this.transactionBytes)
158
+ throw new Error("RECORD_CACHE_MERGE_TOO_LARGE");
110
159
  if (changed.length)
111
160
  await this.records.bulkPut(changed);
112
161
  });
@@ -126,8 +175,11 @@ export class IndexedDbRecordCache {
126
175
  async runFlush() {
127
176
  const values = [...this.pending.values()], waiters = this.waiters.splice(0);
128
177
  this.pending.clear();
178
+ this.pendingBytes = 0;
129
179
  if (!values.length)
130
180
  return;
181
+ this.activeBytes = values.reduce((sum, value) => sum + this.bytes(value), 0);
182
+ this.activeRecords = values.length;
131
183
  try {
132
184
  for (let offset = 0; offset < values.length; offset += 128)
133
185
  await this.write(values.slice(offset, offset + 128));
@@ -142,9 +194,14 @@ export class IndexedDbRecordCache {
142
194
  const key = this.options.key(value);
143
195
  this.pending.set(key, this.options.merge(value, this.pending.get(key) ?? value));
144
196
  }
197
+ this.pendingBytes = [...this.pending.values()].reduce((sum, value) => sum + this.bytes(value), 0);
145
198
  waiters.forEach(waiter => waiter.reject(error));
146
199
  throw error;
147
200
  }
201
+ finally {
202
+ this.activeBytes = 0;
203
+ this.activeRecords = 0;
204
+ }
148
205
  }
149
206
  async close() {
150
207
  this.closing = true;
@@ -0,0 +1,44 @@
1
+ export type ResponseCacheAccess = () => Promise<{
2
+ version: number;
3
+ allowed: boolean;
4
+ }>;
5
+ export declare function isResponseCacheAuthorityError(error: unknown): boolean;
6
+ export declare function assertResponseCacheAccess(access?: ResponseCacheAccess, expectedVersion?: number): Promise<number | undefined>;
7
+ /** Small response windows, isolated by identity. Epochs fence late writes after
8
+ * access withdrawal. No localStorage or synchronous writes on the read path. */
9
+ export declare class IndexedDbResponseCache<T> {
10
+ private scope;
11
+ private options;
12
+ private db;
13
+ private rows;
14
+ private epochs;
15
+ private pending;
16
+ private tasks;
17
+ private running?;
18
+ private invalidations;
19
+ private closed;
20
+ private closing?;
21
+ constructor(scope: string, options?: {
22
+ indexedDB?: IDBFactory;
23
+ name?: string;
24
+ access?: ResponseCacheAccess;
25
+ });
26
+ /** Resolve shared message-scope authority before opening our transaction.
27
+ * A newer authority version retires response windows exactly once; delayed
28
+ * callers can never roll the authority backwards or delete recovered data. */
29
+ private synchronizeAccess;
30
+ read(key: string): Promise<{
31
+ epoch: number;
32
+ cached: {
33
+ value: T;
34
+ time: number;
35
+ } | undefined;
36
+ }>;
37
+ write(key: string, value: T, epoch: number): Promise<void>;
38
+ /** Idempotent shared-scope retirement: an old cleanup cannot erase windows
39
+ * created after the same authority version was already recovered. */
40
+ retire(version: number): Promise<void>;
41
+ invalidate(): Promise<void>;
42
+ flush(): Promise<void>;
43
+ close(): Promise<void>;
44
+ }