@pmate/chat-sdk 0.12.0-next.92 → 0.12.0-next.94
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 +20 -0
- package/lib/runtime/chatSession.js +6 -2
- package/lib/runtime/createChat.js +5 -1
- package/lib/runtime/inboxClient.d.ts +9 -0
- package/lib/runtime/inboxClient.js +81 -10
- package/lib/runtime/inboxProjections.d.ts +47 -0
- package/lib/runtime/inboxProjections.js +9 -0
- package/lib/runtime/inboxReceipts.d.ts +25 -0
- package/lib/runtime/inboxReceipts.js +84 -0
- package/lib/runtime/inboxStore.d.ts +23 -0
- package/lib/runtime/inboxStore.js +144 -13
- package/lib/runtime/inboxTransport.js +12 -1
- package/lib/runtime/index.d.ts +2 -0
- package/lib/runtime/index.js +2 -0
- package/lib/runtime/messageReaders.d.ts +2 -0
- package/lib/runtime/messageReaders.js +9 -1
- package/lib/runtime/readCounts.d.ts +4 -0
- package/lib/runtime/readCounts.js +26 -1
- package/lib/runtime/readingClient.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -353,3 +353,23 @@ permission errors and unknown delivery outcomes retain the original identity;
|
|
|
353
353
|
they must never create a second group. Durable creation retries reuse the same
|
|
354
354
|
creation command. Server-side conditional appends enforce uniqueness across Hub
|
|
355
355
|
instances. Deploy that server contract before enabling Team-free group lookup.
|
|
356
|
+
|
|
357
|
+
### Inbox receipt projection
|
|
358
|
+
|
|
359
|
+
In Inbox mode, peer counts and reader pages are built from author-private receipt
|
|
360
|
+
facts instead of a separate reading service. This removes transient mismatches
|
|
361
|
+
between message delivery and receipt queries. Enable the server's receipt
|
|
362
|
+
projection before adopting this SDK version.
|
|
363
|
+
|
|
364
|
+
`InboxClient.receipts` hydrates once from normalized IndexedDB rows and serves
|
|
365
|
+
viewport counts/readers from memory. `ChatSession` selects it automatically when
|
|
366
|
+
`inbox` is supplied; no counts, readers or subscription HTTP calls run in that
|
|
367
|
+
mode. Receipt-only updates preserve message references. A warm older cache fills
|
|
368
|
+
only receipt facts through the projection bootstrap; a fresh full Inbox replay
|
|
369
|
+
needs no second receipt download. Independent projection versions and atomic
|
|
370
|
+
state/cursor commits preserve message caches during receipt upgrades.
|
|
371
|
+
|
|
372
|
+
Empty ten-second checks and duplicate notifications do not open a projection
|
|
373
|
+
write transaction. Received receipt batches insert only new keys in one bulk
|
|
374
|
+
write. Own viewport read observations are coalesced over 100ms before their
|
|
375
|
+
pending intents become durable; callers resolve after commit.
|
|
@@ -89,9 +89,11 @@ export class ChatSession {
|
|
|
89
89
|
throw new Error("REACH_HANDLER_UNAVAILABLE");
|
|
90
90
|
} });
|
|
91
91
|
this.reading = new ReadingClient({ ...options.reading, teamId: scope.teamId, storageScope: JSON.stringify([scope.accountId]), migrateLegacy: true, metadataOnly: true });
|
|
92
|
-
this.readers = new MessageReadersClient({ appId: scope.appId, profileId: scope.profileId, token: options.reading.sessionToken, scope, access: () => this.messages.scopeAccess(), onError: options.onError, hubHttpUrl: options.reading.hubHttpUrl, fetch: options.reading.fetch });
|
|
92
|
+
this.readers = new MessageReadersClient({ local: options.inbox?.receipts, appId: scope.appId, profileId: scope.profileId, token: options.reading.sessionToken, scope, access: () => this.messages.scopeAccess(), onError: options.onError, hubHttpUrl: options.reading.hubHttpUrl, fetch: options.reading.fetch });
|
|
93
93
|
if (options.loadGroup) {
|
|
94
94
|
this.groups = new GroupClient({ local: !!options.inbox, scope, access: () => this.messages.scopeAccess(), load: options.loadGroup, onError: options.onError, onDenied: async (error, _threadId, signal) => {
|
|
95
|
+
if (isScopedGroupDenial(error))
|
|
96
|
+
return true;
|
|
95
97
|
if (error?.status === 403 && options.messages.transport.authorizeScope) {
|
|
96
98
|
try {
|
|
97
99
|
await options.messages.transport.authorizeScope(signal ?? new AbortController().signal);
|
|
@@ -674,6 +676,8 @@ export class ChatSession {
|
|
|
674
676
|
throw new Error("Reading reach identity mismatch");
|
|
675
677
|
return "handled";
|
|
676
678
|
}
|
|
679
|
+
if (this.options.inbox && event.eventType === "social.readCountsChanged")
|
|
680
|
+
return "handled";
|
|
677
681
|
if (event.eventType === "social.readCountsChanged") {
|
|
678
682
|
if (typeof event.payload.threadId !== "string" || !Number.isSafeInteger(event.payload.revision) || Number(event.payload.revision) < 0)
|
|
679
683
|
throw new Error("INVALID_READ_COUNTS_EVENT");
|
|
@@ -733,7 +737,7 @@ export class ChatSession {
|
|
|
733
737
|
this.countClosings.add(closing);
|
|
734
738
|
}
|
|
735
739
|
const scope = this.options.messages.scope;
|
|
736
|
-
const client = new ReadCountsClient({ appId: scope.appId, profileId: scope.profileId, scope, access: () => this.messages.scopeAccess(), token: this.options.reading.sessionToken, clientInstanceId: receiver, hubHttpUrl: this.options.reading.hubHttpUrl, fetch: this.options.reading.fetch,
|
|
740
|
+
const client = new ReadCountsClient({ local: this.options.inbox?.receipts, appId: scope.appId, profileId: scope.profileId, scope, access: () => this.messages.scopeAccess(), token: this.options.reading.sessionToken, clientInstanceId: receiver, hubHttpUrl: this.options.reading.hubHttpUrl, fetch: this.options.reading.fetch,
|
|
737
741
|
onChange: value => { if (!this.closed && this.counts === client)
|
|
738
742
|
this.publishCounts(value); },
|
|
739
743
|
onError: error => {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { scopedGroupDenial } from "./groupDenial.js";
|
|
1
2
|
import { IndexedDbDiscussionStore } from "./messageDiscussionStore.js";
|
|
2
3
|
import { mergeStoredMessage } from "./messageStore.js";
|
|
3
4
|
import { messageThreadRoot } from "./messageThread.js";
|
|
@@ -53,8 +54,11 @@ export function createChatSession(options) {
|
|
|
53
54
|
loadGroup: async (groupId, signal) => {
|
|
54
55
|
if (options.inbox) {
|
|
55
56
|
const group = await options.inbox.store.group(groupId, teamId);
|
|
56
|
-
if (group)
|
|
57
|
+
if (group) {
|
|
58
|
+
if (group.status !== "dissolved" && !group.members?.includes(profileId))
|
|
59
|
+
throw scopedGroupDenial(Object.assign(new Error("GROUP_ACCESS_DENIED"), { status: 403 }));
|
|
57
60
|
return group;
|
|
61
|
+
}
|
|
58
62
|
if (options.inbox.offlineMode() || isOffline())
|
|
59
63
|
throw new Error("GROUP_METADATA_OFFLINE");
|
|
60
64
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { InboxReceipts } from "./inboxReceipts.js";
|
|
1
2
|
import { IndexedDbInbox, type InboxScope, type InboxEvent } from "./inboxStore.js";
|
|
2
3
|
export type InboxProgress = {
|
|
3
4
|
stage: "loading" | "syncing" | "ready" | "offline" | "error";
|
|
@@ -21,6 +22,11 @@ export type InboxClientOptions = InboxScope & {
|
|
|
21
22
|
* One persisted lease owns live/check traffic across tabs and team sessions. */
|
|
22
23
|
export declare class InboxClient {
|
|
23
24
|
private options;
|
|
25
|
+
readonly receipts: InboxReceipts;
|
|
26
|
+
private receiptTail;
|
|
27
|
+
private queueReceipts;
|
|
28
|
+
private receiptsHydrated;
|
|
29
|
+
private receiptMemorySeq;
|
|
24
30
|
readonly store: IndexedDbInbox;
|
|
25
31
|
private closed;
|
|
26
32
|
private controller;
|
|
@@ -49,6 +55,9 @@ export declare class InboxClient {
|
|
|
49
55
|
subscribe(listener: (threads: readonly string[]) => void): () => void;
|
|
50
56
|
private publish;
|
|
51
57
|
private notify;
|
|
58
|
+
private committed;
|
|
59
|
+
private hydrateReceipts;
|
|
60
|
+
private completeReceipts;
|
|
52
61
|
private credentials;
|
|
53
62
|
private request;
|
|
54
63
|
start(): Promise<void>;
|
|
@@ -1,9 +1,15 @@
|
|
|
1
|
+
import { InboxReceipts } from "./inboxReceipts.js";
|
|
1
2
|
import { IndexedDbInbox, inboxSequence } from "./inboxStore.js";
|
|
2
3
|
import { isOffline } from "./connectivity.js";
|
|
3
4
|
/** Push full facts normally; range catch-up repairs gaps and silent push loss.
|
|
4
5
|
* One persisted lease owns live/check traffic across tabs and team sessions. */
|
|
5
6
|
export class InboxClient {
|
|
6
7
|
options;
|
|
8
|
+
receipts;
|
|
9
|
+
receiptTail = Promise.resolve();
|
|
10
|
+
queueReceipts(task) { const run = this.receiptTail.then(task); this.receiptTail = run.catch(() => { }); return run; }
|
|
11
|
+
receiptsHydrated = false;
|
|
12
|
+
receiptMemorySeq = "0";
|
|
7
13
|
store;
|
|
8
14
|
closed = false;
|
|
9
15
|
controller = new AbortController();
|
|
@@ -27,11 +33,27 @@ export class InboxClient {
|
|
|
27
33
|
constructor(options) {
|
|
28
34
|
this.options = options;
|
|
29
35
|
this.store = options.store ?? new IndexedDbInbox(options);
|
|
36
|
+
this.receipts = new InboxReceipts(options.appId, options.profileId);
|
|
30
37
|
if (typeof BroadcastChannel !== "undefined" && typeof window !== "undefined") {
|
|
31
38
|
this.channel = new BroadcastChannel(`pmate-inbox:${this.store.owner}`);
|
|
32
|
-
this.channel.onmessage = event => {
|
|
33
|
-
|
|
34
|
-
|
|
39
|
+
this.channel.onmessage = event => {
|
|
40
|
+
if (Array.isArray(event.data?.threads))
|
|
41
|
+
this.notify(event.data.threads, false);
|
|
42
|
+
if (Array.isArray(event.data?.events)) {
|
|
43
|
+
const events = event.data.events;
|
|
44
|
+
void this.queueReceipts(() => {
|
|
45
|
+
if (this.receiptsHydrated)
|
|
46
|
+
this.receipts.apply(events, event.data.receiptsReady ?? undefined);
|
|
47
|
+
if (events.length) {
|
|
48
|
+
const seq = events.at(-1).inboxSeq;
|
|
49
|
+
if (inboxSequence(seq) > inboxSequence(this.receiptMemorySeq))
|
|
50
|
+
this.receiptMemorySeq = seq;
|
|
51
|
+
}
|
|
52
|
+
}).catch(error => this.failed(error));
|
|
53
|
+
if (this.initializedOnce)
|
|
54
|
+
this.eventListeners.forEach(listener => listener(events));
|
|
55
|
+
}
|
|
56
|
+
};
|
|
35
57
|
}
|
|
36
58
|
}
|
|
37
59
|
snapshot = () => this.progress;
|
|
@@ -51,6 +73,41 @@ export class InboxClient {
|
|
|
51
73
|
notify(threads, broadcast = true) { if (this.closed)
|
|
52
74
|
return; this.options.onChange?.(threads); this.listeners.forEach(listener => listener(threads)); if (broadcast)
|
|
53
75
|
this.channel?.postMessage({ threads }); }
|
|
76
|
+
committed(events, after, seq) {
|
|
77
|
+
return this.queueReceipts(() => {
|
|
78
|
+
const fresh = events.filter(event => inboxSequence(event.inboxSeq) > inboxSequence(after));
|
|
79
|
+
if (this.receiptsHydrated)
|
|
80
|
+
this.receipts.apply(fresh);
|
|
81
|
+
if (this.receiptsHydrated && inboxSequence(seq) > inboxSequence(this.receiptMemorySeq))
|
|
82
|
+
this.receiptMemorySeq = seq;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
hydrateReceipts() {
|
|
86
|
+
return this.queueReceipts(async () => {
|
|
87
|
+
const snapshot = await this.store.receiptSnapshot();
|
|
88
|
+
this.receipts.hydrate(snapshot.rows, snapshot.projection?.status === "ready", snapshot.assignments);
|
|
89
|
+
this.receiptMemorySeq = snapshot.cursor?.seq ?? "0";
|
|
90
|
+
this.receiptsHydrated = true;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
async completeReceipts() {
|
|
94
|
+
let projection = await this.store.projection("receipts");
|
|
95
|
+
if (projection?.status === "ready")
|
|
96
|
+
return;
|
|
97
|
+
do {
|
|
98
|
+
const params = { projection: "receipts", afterSeq: projection?.baselineAfterSeq ?? "0", limit: "500" };
|
|
99
|
+
if (projection?.baselineThroughSeq)
|
|
100
|
+
params.throughSeq = projection.baselineThroughSeq;
|
|
101
|
+
const page = await this.request("bootstrap", params);
|
|
102
|
+
await this.store.importReceiptBaseline(page);
|
|
103
|
+
await this.queueReceipts(() => { if (this.receiptsHydrated)
|
|
104
|
+
this.receipts.apply(page.events, !page.hasMore); });
|
|
105
|
+
this.channel?.postMessage({ events: page.events, receiptsReady: !page.hasMore });
|
|
106
|
+
projection = await this.store.projection("receipts");
|
|
107
|
+
} while (!this.closed && projection?.status !== "ready");
|
|
108
|
+
if (!this.closed)
|
|
109
|
+
await this.hydrateReceipts();
|
|
110
|
+
}
|
|
54
111
|
async credentials() { const token = await this.options.getToken?.() ?? this.options.sessionToken; if (!token)
|
|
55
112
|
throw new Error("INBOX_CREDENTIALS_UNAVAILABLE"); return token; }
|
|
56
113
|
async request(action, params = {}, signal) {
|
|
@@ -111,11 +168,18 @@ export class InboxClient {
|
|
|
111
168
|
throw new Error("INBOX_OFFLINE");
|
|
112
169
|
const wasReady = this.progress.stage === "ready";
|
|
113
170
|
let cursor = await this.store.cursor(), initial;
|
|
171
|
+
if (cursor) {
|
|
172
|
+
await this.store.prepareProjections();
|
|
173
|
+
if (!this.receiptsHydrated || this.receiptMemorySeq !== cursor.seq)
|
|
174
|
+
await this.hydrateReceipts();
|
|
175
|
+
}
|
|
114
176
|
if (cursor)
|
|
115
177
|
initial = await this.request("check", { afterSeq: cursor.seq, epoch: cursor.epoch });
|
|
116
178
|
if (!cursor || initial?.resetRequired) {
|
|
117
179
|
const bootstrap = await this.request("bootstrap");
|
|
118
180
|
cursor = await this.store.bootstrap(bootstrap, cursor ?? null);
|
|
181
|
+
this.receiptsHydrated = false;
|
|
182
|
+
this.receipts.clear();
|
|
119
183
|
this.notify([]);
|
|
120
184
|
initial = undefined;
|
|
121
185
|
const start = inboxSequence(cursor.seq), target = inboxSequence(bootstrap.headSeq) > start ? inboxSequence(bootstrap.headSeq) : start;
|
|
@@ -124,8 +188,9 @@ export class InboxClient {
|
|
|
124
188
|
const page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
|
|
125
189
|
const previous = cursor.seq, applied = await this.store.apply(page);
|
|
126
190
|
cursor = applied.cursor;
|
|
127
|
-
if (cursor.seq !== previous)
|
|
191
|
+
if (cursor.seq !== previous && applied.threads.length)
|
|
128
192
|
this.notify(applied.threads);
|
|
193
|
+
await this.committed(page.events, previous, cursor.seq);
|
|
129
194
|
this.facts(page.events, previous);
|
|
130
195
|
const processed = inboxSequence(cursor.seq) - start, total = target - start;
|
|
131
196
|
this.publish({ stage: "syncing", percent: total === 0n ? 99 : Number(processed * 9900n / total) / 100, processed: processed.toString(), total: total.toString() });
|
|
@@ -139,8 +204,9 @@ export class InboxClient {
|
|
|
139
204
|
do {
|
|
140
205
|
const previous = cursor.seq, applied = await this.store.apply(page);
|
|
141
206
|
cursor = applied.cursor;
|
|
142
|
-
if (cursor.seq !== previous)
|
|
207
|
+
if (cursor.seq !== previous && applied.threads.length)
|
|
143
208
|
this.notify(applied.threads);
|
|
209
|
+
await this.committed(page.events, previous, cursor.seq);
|
|
144
210
|
this.facts(page.events, previous);
|
|
145
211
|
const processed = inboxSequence(cursor.seq) - start, total = target - start;
|
|
146
212
|
if (total > 0n || !wasReady)
|
|
@@ -149,10 +215,14 @@ export class InboxClient {
|
|
|
149
215
|
break;
|
|
150
216
|
page = await this.request("events", { afterSeq: cursor.seq, throughSeq: target.toString(), epoch: cursor.epoch });
|
|
151
217
|
} while (!this.closed);
|
|
218
|
+
await this.completeReceipts();
|
|
219
|
+
if (!this.receiptsHydrated)
|
|
220
|
+
await this.hydrateReceipts();
|
|
152
221
|
if (!this.closed && (!wasReady || target > start)) {
|
|
153
222
|
this.initializedOnce = true;
|
|
154
223
|
this.publish({ stage: "ready", percent: 100, processed: (target - start).toString(), total: (target - start).toString() });
|
|
155
|
-
|
|
224
|
+
if (!wasReady)
|
|
225
|
+
this.notify([]);
|
|
156
226
|
}
|
|
157
227
|
}
|
|
158
228
|
async tick(check = true) {
|
|
@@ -213,9 +283,9 @@ export class InboxClient {
|
|
|
213
283
|
}
|
|
214
284
|
try {
|
|
215
285
|
const previous = (await this.store.cursor())?.seq ?? "0", applied = await this.store.apply(page);
|
|
216
|
-
if (applied.threads.length)
|
|
217
|
-
|
|
218
|
-
|
|
286
|
+
if (applied.threads.length && applied.cursor.seq !== previous)
|
|
287
|
+
this.notify(applied.threads);
|
|
288
|
+
await this.committed(page.events, previous, applied.cursor.seq);
|
|
219
289
|
this.facts(page.events, previous);
|
|
220
290
|
}
|
|
221
291
|
catch (error) {
|
|
@@ -256,8 +326,9 @@ export class InboxClient {
|
|
|
256
326
|
if (typeof document !== "undefined")
|
|
257
327
|
document.removeEventListener("visibilitychange", this.wake);
|
|
258
328
|
}
|
|
259
|
-
await Promise.allSettled([this.running, this.liveTask]);
|
|
329
|
+
await Promise.allSettled([this.running, this.liveTask, this.receiptTail]);
|
|
260
330
|
await this.store.releaseLease(this.token);
|
|
331
|
+
this.receipts.clear();
|
|
261
332
|
this.channel?.close();
|
|
262
333
|
this.eventListeners.clear();
|
|
263
334
|
this.listeners.clear();
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Wire compatibility is independent of each local materialization. */
|
|
2
|
+
export declare const INBOX_PROTOCOL_VERSION = 1;
|
|
3
|
+
export declare const INBOX_PROJECTION_VERSIONS: {
|
|
4
|
+
readonly messages: 1;
|
|
5
|
+
readonly reading: 1;
|
|
6
|
+
readonly receipts: 1;
|
|
7
|
+
};
|
|
8
|
+
export type InboxProjectionName = keyof typeof INBOX_PROJECTION_VERSIONS;
|
|
9
|
+
export type InboxProjectionState = {
|
|
10
|
+
owner: string;
|
|
11
|
+
name: InboxProjectionName;
|
|
12
|
+
version: number;
|
|
13
|
+
epoch: string;
|
|
14
|
+
appliedInboxSeq: string;
|
|
15
|
+
status: "ready" | "rebuilding";
|
|
16
|
+
baselineThroughSeq?: string;
|
|
17
|
+
baselineAfterSeq?: string;
|
|
18
|
+
liveInboxSeq?: string;
|
|
19
|
+
};
|
|
20
|
+
export type InboxReceipt = {
|
|
21
|
+
version: 1;
|
|
22
|
+
authorProfileId: string;
|
|
23
|
+
readerProfileId: string;
|
|
24
|
+
threadId: string;
|
|
25
|
+
messageIds: string[];
|
|
26
|
+
sourceId: string;
|
|
27
|
+
sourceAcceptedAt: number;
|
|
28
|
+
};
|
|
29
|
+
export type InboxReceiptRow = {
|
|
30
|
+
owner: string;
|
|
31
|
+
thread: string;
|
|
32
|
+
messageId: string;
|
|
33
|
+
readerId: string;
|
|
34
|
+
};
|
|
35
|
+
export type InboxReceiptBaseline = {
|
|
36
|
+
epoch: string;
|
|
37
|
+
appId: string;
|
|
38
|
+
profileId: string;
|
|
39
|
+
projection: "receipts";
|
|
40
|
+
version: number;
|
|
41
|
+
ready: boolean;
|
|
42
|
+
throughSeq: string;
|
|
43
|
+
nextSeq: string;
|
|
44
|
+
hasMore: boolean;
|
|
45
|
+
events: import("./inboxStore.js").InboxEvent[];
|
|
46
|
+
};
|
|
47
|
+
export declare function validateInboxReceipt(value: unknown, profile: string): InboxReceipt;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Wire compatibility is independent of each local materialization. */
|
|
2
|
+
export const INBOX_PROTOCOL_VERSION = 1;
|
|
3
|
+
export const INBOX_PROJECTION_VERSIONS = { messages: 1, reading: 1, receipts: 1 };
|
|
4
|
+
export function validateInboxReceipt(value, profile) {
|
|
5
|
+
const receipt = value;
|
|
6
|
+
if (!receipt || receipt.version !== 1 || receipt.authorProfileId !== profile || typeof receipt.readerProfileId !== "string" || !receipt.readerProfileId || receipt.readerProfileId === profile || typeof receipt.threadId !== "string" || !receipt.threadId || !Array.isArray(receipt.messageIds) || receipt.messageIds.length > 200 || receipt.messageIds.some(id => typeof id !== "string" || !id || id.length > 512) || typeof receipt.sourceId !== "string" || !receipt.sourceId || !Number.isSafeInteger(receipt.sourceAcceptedAt) || receipt.sourceAcceptedAt < 0)
|
|
7
|
+
throw new Error("INVALID_INBOX_RECEIPT");
|
|
8
|
+
return receipt;
|
|
9
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type InboxReceiptRow } from "./inboxProjections.js";
|
|
2
|
+
import type { InboxEvent } from "./inboxStore.js";
|
|
3
|
+
import type { ReadCountsResult } from "./readCounts.js";
|
|
4
|
+
import type { MessageReadersPage, MessageReadersQuery } from "./messageReaders.js";
|
|
5
|
+
/** Durable facts are hydrated once; viewport queries never access IndexedDB. */
|
|
6
|
+
export declare class InboxReceipts {
|
|
7
|
+
private appId;
|
|
8
|
+
private profileId;
|
|
9
|
+
private readers;
|
|
10
|
+
private aliases;
|
|
11
|
+
private revision;
|
|
12
|
+
private ready;
|
|
13
|
+
private listeners;
|
|
14
|
+
constructor(appId: string, profileId: string);
|
|
15
|
+
subscribe(listener: (threads: readonly string[]) => void): () => void;
|
|
16
|
+
private add;
|
|
17
|
+
hydrate(rows: readonly InboxReceiptRow[], ready: boolean, assignments?: readonly {
|
|
18
|
+
value: Record<string, any>;
|
|
19
|
+
}[]): void;
|
|
20
|
+
apply(events: readonly InboxEvent[], ready?: boolean): void;
|
|
21
|
+
counts(threadId: string, messageIds: readonly string[]): ReadCountsResult | undefined;
|
|
22
|
+
page(query: MessageReadersQuery): MessageReadersPage;
|
|
23
|
+
private messageReaders;
|
|
24
|
+
clear(): void;
|
|
25
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { validateInboxReceipt } from "./inboxProjections.js";
|
|
2
|
+
/** Durable facts are hydrated once; viewport queries never access IndexedDB. */
|
|
3
|
+
export class InboxReceipts {
|
|
4
|
+
appId;
|
|
5
|
+
profileId;
|
|
6
|
+
readers = new Map();
|
|
7
|
+
aliases = new Map();
|
|
8
|
+
revision = 0;
|
|
9
|
+
ready = false;
|
|
10
|
+
listeners = new Set();
|
|
11
|
+
constructor(appId, profileId) {
|
|
12
|
+
this.appId = appId;
|
|
13
|
+
this.profileId = profileId;
|
|
14
|
+
}
|
|
15
|
+
subscribe(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
|
16
|
+
add(row) {
|
|
17
|
+
let thread = this.readers.get(row.thread);
|
|
18
|
+
if (!thread)
|
|
19
|
+
this.readers.set(row.thread, thread = new Map());
|
|
20
|
+
let ids = thread.get(row.messageId);
|
|
21
|
+
if (!ids)
|
|
22
|
+
thread.set(row.messageId, ids = new Set());
|
|
23
|
+
if (ids.has(row.readerId))
|
|
24
|
+
return false;
|
|
25
|
+
ids.add(row.readerId);
|
|
26
|
+
this.revision++;
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
hydrate(rows, ready, assignments = []) {
|
|
30
|
+
this.aliases.clear();
|
|
31
|
+
for (const { value } of assignments)
|
|
32
|
+
this.aliases.set(value.sourceThreadId, value.threadId);
|
|
33
|
+
this.readers.clear();
|
|
34
|
+
this.revision++;
|
|
35
|
+
for (const row of rows)
|
|
36
|
+
this.add(row);
|
|
37
|
+
this.ready = ready;
|
|
38
|
+
this.listeners.forEach(listener => listener([]));
|
|
39
|
+
}
|
|
40
|
+
apply(events, ready = this.ready) {
|
|
41
|
+
const changed = new Set(), becameReady = ready && !this.ready;
|
|
42
|
+
for (const event of events) {
|
|
43
|
+
if (event.kind === "threadAssigned") {
|
|
44
|
+
this.aliases.set(event.fact.sourceThreadId, event.fact.threadId);
|
|
45
|
+
changed.add(event.fact.threadId);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (event.kind !== "readingUpdated" || event.fact.receiptOnly !== true)
|
|
49
|
+
continue;
|
|
50
|
+
const receipt = validateInboxReceipt(event.fact.receipt, this.profileId);
|
|
51
|
+
for (const messageId of receipt.messageIds)
|
|
52
|
+
if (this.add({ thread: receipt.threadId, messageId, readerId: receipt.readerProfileId }))
|
|
53
|
+
changed.add(this.aliases.get(receipt.threadId) ?? receipt.threadId);
|
|
54
|
+
}
|
|
55
|
+
this.ready = ready;
|
|
56
|
+
if (this.ready && (becameReady || changed.size))
|
|
57
|
+
this.listeners.forEach(listener => listener(becameReady ? [] : [...changed]));
|
|
58
|
+
}
|
|
59
|
+
counts(threadId, messageIds) {
|
|
60
|
+
if (!this.ready)
|
|
61
|
+
return;
|
|
62
|
+
return { appId: this.appId, threadId, revision: this.revision, counts: Object.fromEntries(messageIds.map(id => [id, this.messageReaders(threadId, id).size])) };
|
|
63
|
+
}
|
|
64
|
+
page(query) {
|
|
65
|
+
if (!this.ready)
|
|
66
|
+
throw new Error("INBOX_RECEIPTS_NOT_READY");
|
|
67
|
+
const limit = query.limit ?? 50;
|
|
68
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || (query.revision !== undefined && (!Number.isSafeInteger(query.revision) || query.revision < 0)))
|
|
69
|
+
throw new Error("INVALID_MESSAGE_READERS_QUERY");
|
|
70
|
+
const ids = [...this.messageReaders(query.threadId, query.messageId)].sort();
|
|
71
|
+
const resetRequired = query.revision !== undefined && query.revision !== this.revision;
|
|
72
|
+
const remaining = ids.filter(id => resetRequired || !query.afterProfileId || id > query.afterProfileId), profileIds = remaining.slice(0, limit);
|
|
73
|
+
return { appId: this.appId, threadId: query.threadId, messageId: query.messageId, revision: this.revision, total: ids.length, profileIds, nextAfter: remaining.length > limit ? profileIds.at(-1) : null, resetRequired };
|
|
74
|
+
}
|
|
75
|
+
messageReaders(threadId, messageId) {
|
|
76
|
+
const result = new Set(this.readers.get(threadId)?.get(messageId));
|
|
77
|
+
for (const [source, target] of this.aliases)
|
|
78
|
+
if (target === threadId)
|
|
79
|
+
for (const reader of this.readers.get(source)?.get(messageId) ?? [])
|
|
80
|
+
result.add(reader);
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
clear() { this.aliases.clear(); this.readers.clear(); this.ready = false; this.revision++; this.listeners.forEach(listener => listener([])); }
|
|
84
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type InboxProjectionName, type InboxProjectionState, type InboxReceiptRow, type InboxReceiptBaseline } from "./inboxProjections.js";
|
|
1
2
|
import { Dexie, type Table } from "dexie";
|
|
2
3
|
import { type ReadSnapshot } from "./readIndex.js";
|
|
3
4
|
import type { MessageThreadSummary } from "./socialReadClient.js";
|
|
@@ -32,6 +33,12 @@ export type InboxBootstrap = {
|
|
|
32
33
|
startSeq: string;
|
|
33
34
|
headSeq: string;
|
|
34
35
|
windowStart: number;
|
|
36
|
+
projections?: {
|
|
37
|
+
receipts?: {
|
|
38
|
+
version: number;
|
|
39
|
+
ready: boolean;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
35
42
|
basis: {
|
|
36
43
|
id: string;
|
|
37
44
|
kind: string;
|
|
@@ -108,6 +115,8 @@ export declare class IndexedDbInbox {
|
|
|
108
115
|
readonly explicit: Table<ExplicitRow, [string, string, string]>;
|
|
109
116
|
readonly threads: Table<ThreadRow, [string, string]>;
|
|
110
117
|
readonly leases: Table<InboxLease, string>;
|
|
118
|
+
readonly projections: Table<InboxProjectionState, [string, InboxProjectionName]>;
|
|
119
|
+
readonly receipts: Table<InboxReceiptRow, [string, string, string, string]>;
|
|
111
120
|
constructor(scope: InboxScope, options?: {
|
|
112
121
|
indexedDB?: IDBFactory;
|
|
113
122
|
name?: string;
|
|
@@ -127,7 +136,20 @@ export declare class IndexedDbInbox {
|
|
|
127
136
|
windowStart: number;
|
|
128
137
|
};
|
|
129
138
|
threads: string[];
|
|
139
|
+
receiptThreads: string[];
|
|
140
|
+
}>;
|
|
141
|
+
/** Upgrade the receipt projection without touching message rows or scroll state. */
|
|
142
|
+
prepareProjections(): Promise<void>;
|
|
143
|
+
receiptSnapshot(): Promise<{
|
|
144
|
+
cursor: InboxCursor | undefined;
|
|
145
|
+
projection: InboxProjectionState | undefined;
|
|
146
|
+
rows: InboxReceiptRow[];
|
|
147
|
+
assignments: FactRow[];
|
|
130
148
|
}>;
|
|
149
|
+
projection(name: InboxProjectionName): import("dexie").PromiseExtended<InboxProjectionState | undefined>;
|
|
150
|
+
private checkpointProjections;
|
|
151
|
+
private writeReceipts;
|
|
152
|
+
importReceiptBaseline(page: InboxReceiptBaseline): Promise<string[]>;
|
|
131
153
|
private applyFact;
|
|
132
154
|
readingSnapshot(): Promise<ReadSnapshot>;
|
|
133
155
|
threadMessages(thread: string): Promise<{
|
|
@@ -187,6 +209,7 @@ export declare class IndexedDbInbox {
|
|
|
187
209
|
items: MessageThreadSummary[];
|
|
188
210
|
revision: number;
|
|
189
211
|
}>;
|
|
212
|
+
conversationGroup(thread: string, teamId: string): Promise<import("./socialReadClient.js").SocialGroup | undefined>;
|
|
190
213
|
group(groupId: string, teamId: string): Promise<import("./socialReadClient.js").SocialGroup | undefined>;
|
|
191
214
|
private annotatedBody;
|
|
192
215
|
close(): void;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { INBOX_PROJECTION_VERSIONS, validateInboxReceipt } from "./inboxProjections.js";
|
|
1
2
|
import { Dexie } from "dexie";
|
|
2
3
|
import { messageRequiresPlayback, isReadingControl } from "./readingContent.js";
|
|
3
4
|
import { messageThreadRoot } from "./messageThread.js";
|
|
@@ -24,6 +25,8 @@ export class IndexedDbInbox {
|
|
|
24
25
|
explicit;
|
|
25
26
|
threads;
|
|
26
27
|
leases;
|
|
28
|
+
projections;
|
|
29
|
+
receipts;
|
|
27
30
|
constructor(scope, options = {}) {
|
|
28
31
|
this.scope = scope;
|
|
29
32
|
this.owner = JSON.stringify([scope.accountId, scope.appId, scope.profileId]);
|
|
@@ -31,6 +34,9 @@ export class IndexedDbInbox {
|
|
|
31
34
|
this.db.version(1).stores({ cursors: "owner", messages: "[owner+thread+id],[owner+thread+seq],[owner+thread+time+id],[owner+thread],owner", facts: "[owner+kind+id],[owner+kind],[owner+thread],owner", positions: "[owner+thread+root],[owner+thread],owner", explicit: "[owner+thread+id],[owner+thread],owner", threads: "[owner+id],owner" });
|
|
32
35
|
this.db.version(2).stores({ leases: "owner" });
|
|
33
36
|
this.db.version(3).stores({ messages: "[owner+thread+id],[owner+thread+seq],[owner+thread+time+id],[owner+thread+changeSeq+id],[owner+thread],owner" });
|
|
37
|
+
this.db.version(4).stores({ projections: "[owner+name],owner", receipts: "[owner+thread+messageId+readerId],[owner+thread+messageId],[owner+thread],owner" });
|
|
38
|
+
this.projections = this.db.table("projections");
|
|
39
|
+
this.receipts = this.db.table("receipts");
|
|
34
40
|
this.cursors = this.db.table("cursors");
|
|
35
41
|
this.messages = this.db.table("messages");
|
|
36
42
|
this.facts = this.db.table("facts");
|
|
@@ -39,13 +45,15 @@ export class IndexedDbInbox {
|
|
|
39
45
|
this.threads = this.db.table("threads");
|
|
40
46
|
this.leases = this.db.table("leases");
|
|
41
47
|
}
|
|
42
|
-
tables() { return [this.cursors, this.messages, this.facts, this.positions, this.explicit, this.threads]; }
|
|
48
|
+
tables() { return [this.cursors, this.messages, this.facts, this.positions, this.explicit, this.threads, this.projections, this.receipts]; }
|
|
43
49
|
cursor() { return this.cursors.get(this.owner); }
|
|
44
50
|
claimLease(token, now = Date.now()) {
|
|
45
51
|
return this.db.transaction("rw", this.leases, async () => {
|
|
46
52
|
const old = await this.leases.get(this.owner);
|
|
47
53
|
if (old && old.token !== token && old.expiresAt > now)
|
|
48
54
|
return false;
|
|
55
|
+
if (old?.token === token && old.expiresAt > now + 15000)
|
|
56
|
+
return true;
|
|
49
57
|
await this.leases.put({ owner: this.owner, token, expiresAt: now + 30000 });
|
|
50
58
|
return true;
|
|
51
59
|
});
|
|
@@ -71,7 +79,7 @@ export class IndexedDbInbox {
|
|
|
71
79
|
// A reset rebuilds current state, while older message cache stays available.
|
|
72
80
|
const old = await this.messages.where("owner").equals(this.owner).toArray();
|
|
73
81
|
await this.messages.bulkDelete(old.filter(row => row.acceptedAt >= input.windowStart).map(row => [row.owner, row.thread, row.id]));
|
|
74
|
-
for (const table of [this.facts, this.positions, this.explicit, this.threads])
|
|
82
|
+
for (const table of [this.facts, this.positions, this.explicit, this.threads, this.projections, this.receipts])
|
|
75
83
|
await table.where("owner").equals(this.owner).delete();
|
|
76
84
|
for (const item of [...input.basis].sort((a, b) => inboxSequence(a.inboxSeq) < inboxSequence(b.inboxSeq) ? -1 : 1)) {
|
|
77
85
|
if (inboxSequence(item.inboxSeq) >= start)
|
|
@@ -79,7 +87,10 @@ export class IndexedDbInbox {
|
|
|
79
87
|
await this.applyFact({ inboxSeq: item.inboxSeq, sourceId: item.id, acceptedAt: input.windowStart - 1, kind: item.kind, fact: item.fact }, input.windowStart, true);
|
|
80
88
|
}
|
|
81
89
|
const cursor = { owner: this.owner, epoch: input.epoch, seq: (start - 1n).toString(), windowStart: input.windowStart, initialized: false };
|
|
90
|
+
if (input.projections?.receipts?.version === INBOX_PROJECTION_VERSIONS.receipts && input.projections.receipts.ready)
|
|
91
|
+
await this.projections.put({ owner: this.owner, name: "receipts", version: INBOX_PROJECTION_VERSIONS.receipts, epoch: cursor.epoch, appliedInboxSeq: cursor.seq, liveInboxSeq: cursor.seq, status: "ready" });
|
|
82
92
|
await this.cursors.put(cursor);
|
|
93
|
+
await this.checkpointProjections(cursor);
|
|
83
94
|
return cursor;
|
|
84
95
|
});
|
|
85
96
|
}
|
|
@@ -91,12 +102,15 @@ export class IndexedDbInbox {
|
|
|
91
102
|
throw new Error("INBOX_RESET_REQUIRED");
|
|
92
103
|
if (next > head || !Array.isArray(page.events))
|
|
93
104
|
throw new Error("INVALID_INBOX_PAGE");
|
|
105
|
+
const known = await this.cursor();
|
|
106
|
+
if (known?.epoch === page.epoch && known.initialized && next <= inboxSequence(known.seq) && page.events.every(event => inboxSequence(event.inboxSeq) <= inboxSequence(known.seq)))
|
|
107
|
+
return { cursor: known, threads: [], receiptThreads: [] };
|
|
94
108
|
return this.db.transaction("rw", this.tables(), async () => {
|
|
95
109
|
const cursor = await this.cursor();
|
|
96
110
|
if (!cursor || cursor.epoch !== page.epoch)
|
|
97
111
|
throw new Error("INBOX_RESET_REQUIRED");
|
|
98
112
|
let sequence = inboxSequence(cursor.seq);
|
|
99
|
-
const changed = new Set();
|
|
113
|
+
const changed = new Set(), receiptEvents = [];
|
|
100
114
|
for (const event of page.events) {
|
|
101
115
|
const incoming = inboxSequence(event.inboxSeq);
|
|
102
116
|
if (incoming <= sequence)
|
|
@@ -105,16 +119,116 @@ export class IndexedDbInbox {
|
|
|
105
119
|
throw new Error("INBOX_SEQUENCE_GAP");
|
|
106
120
|
if (!Number.isSafeInteger(event.acceptedAt) || event.acceptedAt < 0 || !event.sourceId)
|
|
107
121
|
throw new Error("INVALID_INBOX_EVENT");
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
122
|
+
if (event.kind === "readingUpdated" && event.fact.receiptOnly === true)
|
|
123
|
+
receiptEvents.push(event);
|
|
124
|
+
else {
|
|
125
|
+
const thread = await this.applyFact(event, cursor.windowStart, false);
|
|
126
|
+
if (thread)
|
|
127
|
+
changed.add(thread);
|
|
128
|
+
}
|
|
111
129
|
sequence = incoming;
|
|
112
130
|
}
|
|
113
131
|
if (next > sequence)
|
|
114
132
|
throw new Error("INBOX_SEQUENCE_GAP");
|
|
115
133
|
const updated = { ...cursor, seq: sequence.toString(), initialized: cursor.initialized || sequence >= head };
|
|
116
|
-
await this.
|
|
117
|
-
|
|
134
|
+
const receiptThreads = await this.writeReceipts(receiptEvents);
|
|
135
|
+
// Empty checks and duplicate pushes do not take write locks on projections.
|
|
136
|
+
if (updated.seq !== cursor.seq || updated.initialized !== cursor.initialized) {
|
|
137
|
+
await this.cursors.put(updated);
|
|
138
|
+
await this.checkpointProjections(updated);
|
|
139
|
+
}
|
|
140
|
+
return { cursor: updated, threads: [...changed], receiptThreads };
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/** Upgrade the receipt projection without touching message rows or scroll state. */
|
|
144
|
+
async prepareProjections() {
|
|
145
|
+
const cursor = await this.cursor();
|
|
146
|
+
if (!cursor)
|
|
147
|
+
return;
|
|
148
|
+
const current = await this.projections.bulkGet(["messages", "reading", "receipts"].map(name => [this.owner, name]));
|
|
149
|
+
if (current.every(row => row !== undefined && row.version === INBOX_PROJECTION_VERSIONS[row.name] && row.epoch === cursor.epoch))
|
|
150
|
+
return;
|
|
151
|
+
await this.db.transaction("rw", this.cursors, this.projections, this.receipts, async () => {
|
|
152
|
+
const latest = await this.cursor();
|
|
153
|
+
if (!latest || latest.epoch !== cursor.epoch)
|
|
154
|
+
throw new Error("INBOX_RESET_REQUIRED");
|
|
155
|
+
for (const name of ["messages", "reading", "receipts"]) {
|
|
156
|
+
const old = await this.projection(name), version = INBOX_PROJECTION_VERSIONS[name];
|
|
157
|
+
if (old?.version === version && old.epoch === cursor.epoch)
|
|
158
|
+
continue;
|
|
159
|
+
if (name !== "receipts" && old)
|
|
160
|
+
throw new Error(`INBOX_PROJECTION_MIGRATION_REQUIRED:${name}`);
|
|
161
|
+
if (name === "receipts")
|
|
162
|
+
await this.receipts.where("owner").equals(this.owner).delete();
|
|
163
|
+
await this.projections.put({ owner: this.owner, name, version, epoch: cursor.epoch, appliedInboxSeq: name === "receipts" ? "0" : latest.seq, liveInboxSeq: latest.seq, status: name === "receipts" ? "rebuilding" : "ready" });
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
async receiptSnapshot() {
|
|
168
|
+
return this.db.transaction("r", this.cursors, this.projections, this.receipts, this.facts, async () => ({ cursor: await this.cursor(), projection: await this.projection("receipts"), rows: await this.receipts.where("owner").equals(this.owner).toArray(), assignments: await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray() }));
|
|
169
|
+
}
|
|
170
|
+
projection(name) { return this.projections.get([this.owner, name]); }
|
|
171
|
+
async checkpointProjections(cursor) {
|
|
172
|
+
const names = Object.keys(INBOX_PROJECTION_VERSIONS);
|
|
173
|
+
const old = await this.projections.bulkGet(names.map(name => [this.owner, name]));
|
|
174
|
+
const rows = names.map((name, index) => {
|
|
175
|
+
const current = old[index], version = INBOX_PROJECTION_VERSIONS[name];
|
|
176
|
+
if (current && current.version !== version)
|
|
177
|
+
throw new Error(`INBOX_PROJECTION_REBUILD_REQUIRED:${name}`);
|
|
178
|
+
if (name === "receipts")
|
|
179
|
+
return current ? { ...current, liveInboxSeq: cursor.seq, ...(current.status === "ready" ? { appliedInboxSeq: inboxSequence(current.appliedInboxSeq) > inboxSequence(cursor.seq) ? current.appliedInboxSeq : cursor.seq } : {}) } : { owner: this.owner, name, version, epoch: cursor.epoch, appliedInboxSeq: "0", liveInboxSeq: cursor.seq, status: "rebuilding" };
|
|
180
|
+
return { owner: this.owner, name, version, epoch: cursor.epoch, appliedInboxSeq: cursor.seq, status: "ready" };
|
|
181
|
+
});
|
|
182
|
+
await this.projections.bulkPut(rows);
|
|
183
|
+
}
|
|
184
|
+
async writeReceipts(events) {
|
|
185
|
+
if (!events.length)
|
|
186
|
+
return [];
|
|
187
|
+
const records = new Map(), threads = new Set();
|
|
188
|
+
for (const event of events) {
|
|
189
|
+
if (event.kind !== "readingUpdated" || event.fact.appId !== this.scope.appId || event.fact.profileId !== this.scope.profileId || event.fact.receiptOnly !== true)
|
|
190
|
+
throw new Error("INVALID_INBOX_RECEIPT_ENVELOPE");
|
|
191
|
+
const receipt = validateInboxReceipt(event.fact.receipt, this.scope.profileId);
|
|
192
|
+
if (event.fact.threadId !== receipt.threadId || event.fact.readThroughSeq !== 0 || !Array.isArray(event.fact.explicitReadMessageIds) || event.fact.explicitReadMessageIds.length !== 0 || event.fact.threadRootId !== undefined)
|
|
193
|
+
throw new Error("INVALID_INBOX_RECEIPT_ENVELOPE");
|
|
194
|
+
threads.add(receipt.threadId);
|
|
195
|
+
for (const messageId of receipt.messageIds) {
|
|
196
|
+
const row = { owner: this.owner, thread: receipt.threadId, messageId, readerId: receipt.readerProfileId };
|
|
197
|
+
records.set(JSON.stringify([row.thread, row.messageId, row.readerId]), row);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const rows = [...records.values()], old = await this.receipts.bulkGet(rows.map(row => [row.owner, row.thread, row.messageId, row.readerId]));
|
|
201
|
+
const fresh = rows.filter((_, index) => !old[index]);
|
|
202
|
+
if (fresh.length)
|
|
203
|
+
await this.receipts.bulkPut(fresh);
|
|
204
|
+
return [...threads];
|
|
205
|
+
}
|
|
206
|
+
async importReceiptBaseline(page) {
|
|
207
|
+
this.identity(page);
|
|
208
|
+
const through = inboxSequence(page.throughSeq), next = inboxSequence(page.nextSeq);
|
|
209
|
+
if (!Array.isArray(page.events) || typeof page.hasMore !== "boolean" || (!page.hasMore && next !== through) || page.projection !== "receipts" || page.version !== INBOX_PROJECTION_VERSIONS.receipts || next > through || !page.ready)
|
|
210
|
+
throw new Error("INBOX_RECEIPTS_NOT_READY");
|
|
211
|
+
return this.db.transaction("rw", this.cursors, this.projections, this.receipts, async () => {
|
|
212
|
+
const cursor = await this.cursor();
|
|
213
|
+
if (!cursor || cursor.epoch !== page.epoch)
|
|
214
|
+
throw new Error("INBOX_RESET_REQUIRED");
|
|
215
|
+
const old = await this.projection("receipts");
|
|
216
|
+
if (old?.status === "ready" && old.version === page.version)
|
|
217
|
+
return [];
|
|
218
|
+
if (old?.baselineThroughSeq !== undefined && old.baselineThroughSeq !== page.throughSeq)
|
|
219
|
+
throw new Error("INBOX_RECEIPT_BASELINE_CHANGED");
|
|
220
|
+
let after = inboxSequence(old?.baselineAfterSeq ?? "0");
|
|
221
|
+
for (const event of page.events) {
|
|
222
|
+
const seq = inboxSequence(event.inboxSeq);
|
|
223
|
+
if (seq <= after || seq > through)
|
|
224
|
+
throw new Error("INVALID_INBOX_RECEIPT_BASELINE");
|
|
225
|
+
after = seq;
|
|
226
|
+
}
|
|
227
|
+
if (next < after || next < inboxSequence(old?.baselineAfterSeq ?? "0") || (page.hasMore && next <= inboxSequence(old?.baselineAfterSeq ?? "0")))
|
|
228
|
+
throw new Error("INVALID_INBOX_RECEIPT_BASELINE");
|
|
229
|
+
const changed = await this.writeReceipts(page.events);
|
|
230
|
+
await this.projections.put({ owner: this.owner, name: "receipts", version: page.version, epoch: page.epoch, appliedInboxSeq: page.hasMore ? next.toString() : (inboxSequence(cursor.seq) > through ? cursor.seq : page.throughSeq), liveInboxSeq: cursor.seq, status: page.hasMore ? "rebuilding" : "ready", baselineThroughSeq: page.throughSeq, baselineAfterSeq: next.toString() });
|
|
231
|
+
return changed;
|
|
118
232
|
});
|
|
119
233
|
}
|
|
120
234
|
async applyFact(event, windowStart, basis) {
|
|
@@ -134,11 +248,14 @@ export class IndexedDbInbox {
|
|
|
134
248
|
await this.facts.put({ owner, kind: "groupControl", id: message.messageId, thread, value: data });
|
|
135
249
|
await this.facts.put({ owner, kind: "structure", id: thread, thread, value: { seq: event.inboxSeq } });
|
|
136
250
|
}
|
|
137
|
-
|
|
251
|
+
const sourceAcceptedAt = data.sourceAcceptedAt ?? event.acceptedAt;
|
|
252
|
+
if (!Number.isSafeInteger(sourceAcceptedAt) || sourceAcceptedAt < 0)
|
|
253
|
+
throw new Error("INVALID_INBOX_SOURCE_TIME");
|
|
254
|
+
if (basis || sourceAcceptedAt < windowStart)
|
|
138
255
|
return thread;
|
|
139
256
|
const root = messageThreadRoot(message.body) ?? "";
|
|
140
257
|
const recalls = await this.facts.get([owner, "recall", JSON.stringify([thread, message.messageId])]);
|
|
141
|
-
await this.messages.put({ owner, thread, id: message.messageId, acceptedAt:
|
|
258
|
+
await this.messages.put({ owner, thread, id: message.messageId, acceptedAt: sourceAcceptedAt, time: message.serverCreatedAt, seq: message.seq, changeSeq: event.inboxSeq.padStart(19, "0"), root, recalled: recalls?.value.from === message.from, value: message });
|
|
142
259
|
const target = body?.kind === "recall" ? body.targetMessageId : body?.kind === "message" && body.content?.appId === this.scope.appId ? body.content?.recall?.messageId : undefined;
|
|
143
260
|
if (typeof target === "string") {
|
|
144
261
|
const key = JSON.stringify([thread, target]);
|
|
@@ -150,13 +267,21 @@ export class IndexedDbInbox {
|
|
|
150
267
|
return thread;
|
|
151
268
|
}
|
|
152
269
|
case "readingUpdated": {
|
|
270
|
+
if (data.receiptOnly === true) {
|
|
271
|
+
await this.writeReceipts([event]);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
153
274
|
if (data.profileId !== this.scope.profileId || !data.threadId || !Number.isSafeInteger(data.readThroughSeq) || data.readThroughSeq < 0 || !Array.isArray(data.explicitReadMessageIds))
|
|
154
275
|
throw new Error("INVALID_INBOX_READING");
|
|
155
276
|
const thread = data.threadId, root = data.threadRootId ?? "", old = await this.positions.get([owner, thread, root]);
|
|
156
277
|
if (!old || data.readThroughSeq > old.seq)
|
|
157
278
|
await this.positions.put({ owner, thread, root, seq: data.readThroughSeq, messageId: data.readThroughMessageId });
|
|
158
|
-
if (data.explicitReadMessageIds.length)
|
|
159
|
-
|
|
279
|
+
if (data.explicitReadMessageIds.length) {
|
|
280
|
+
const rows = [...new Set(data.explicitReadMessageIds)].map(id => ({ owner, thread, id })), old = await this.explicit.bulkGet(rows.map(row => [owner, thread, row.id]));
|
|
281
|
+
const fresh = rows.filter((_, index) => !old[index]);
|
|
282
|
+
if (fresh.length)
|
|
283
|
+
await this.explicit.bulkPut(fresh);
|
|
284
|
+
}
|
|
160
285
|
return thread;
|
|
161
286
|
}
|
|
162
287
|
case "threadAssigned": {
|
|
@@ -209,7 +334,7 @@ export class IndexedDbInbox {
|
|
|
209
334
|
async readingSnapshot() {
|
|
210
335
|
return this.db.transaction("r", this.tables(), async () => {
|
|
211
336
|
const cursor = await this.cursor(), owner = this.owner;
|
|
212
|
-
const [threads, rows, positions, explicit, facts] = await Promise.all([this.threads.where("owner").equals(owner).toArray(), this.messages.where("owner").equals(owner).toArray(), this.positions.where("owner").equals(owner).toArray(), this.explicit.where("owner").equals(owner).toArray(), this.facts.where("owner").
|
|
337
|
+
const [threads, rows, positions, explicit, facts] = await Promise.all([this.threads.where("owner").equals(owner).toArray(), this.messages.where("owner").equals(owner).toArray(), this.positions.where("owner").equals(owner).toArray(), this.explicit.where("owner").equals(owner).toArray(), this.facts.where("[owner+kind]").anyOf([[owner, "threadAssigned"], [owner, "groupControl"]]).toArray()]);
|
|
213
338
|
const byThread = new Map(threads.map(thread => [thread.id, { id: thread.id, kind: thread.kind, teamId: thread.teamId, messages: [], readThroughSeq: 0, explicitReadMessageIds: [], preservedReadMessageIds: [], messageThreadReadThrough: {} }]));
|
|
214
339
|
for (const position of positions) {
|
|
215
340
|
const thread = byThread.get(position.thread);
|
|
@@ -324,6 +449,12 @@ export class IndexedDbInbox {
|
|
|
324
449
|
return { items, revision: Number(cursor?.seq ?? "0") };
|
|
325
450
|
});
|
|
326
451
|
}
|
|
452
|
+
async conversationGroup(thread, teamId) {
|
|
453
|
+
const assignments = (await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray()).filter(row => row.value.threadId === thread);
|
|
454
|
+
const records = await this.threads.bulkGet([thread, ...assignments.map(row => row.value.sourceThreadId)].map(source => [this.owner, source]));
|
|
455
|
+
const group = records.find(row => row?.kind === "group");
|
|
456
|
+
return group ? this.group(group.targetId, teamId) : undefined;
|
|
457
|
+
}
|
|
327
458
|
async group(groupId, teamId) {
|
|
328
459
|
const assignments = await this.facts.where("[owner+kind]").equals([this.owner, "threadAssigned"]).toArray();
|
|
329
460
|
const controls = (await this.facts.where("[owner+kind]").equals([this.owner, "groupControl"]).toArray()).map(row => {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { scopedGroupDenial } from "./groupDenial.js";
|
|
1
2
|
import { inboxSequence } from "./inboxStore.js";
|
|
2
3
|
import { messageThreadRoot } from "./messageThread.js";
|
|
3
4
|
const encode = (cursor) => `ib1:${encodeURIComponent(JSON.stringify(cursor))}`;
|
|
@@ -19,7 +20,17 @@ const cached = (message) => ({ ...message, id: message.messageId, timestamp: mes
|
|
|
19
20
|
export function inboxMessageTransport(inbox, team, root) {
|
|
20
21
|
const db = inbox.store;
|
|
21
22
|
const read = (run) => db.db.transaction("r", [db.cursors, db.messages, db.facts, db.threads], run);
|
|
23
|
+
const authorized = async (thread) => {
|
|
24
|
+
const group = await db.conversationGroup(thread, team);
|
|
25
|
+
if (group?.status === "dissolved")
|
|
26
|
+
return false;
|
|
27
|
+
if (group && !group.members?.includes(db.scope.profileId))
|
|
28
|
+
throw scopedGroupDenial(Object.assign(new Error("GROUP_ACCESS_DENIED"), { status: 403, threadId: thread }));
|
|
29
|
+
return true;
|
|
30
|
+
};
|
|
22
31
|
const rows = async (thread) => {
|
|
32
|
+
if (!await authorized(thread))
|
|
33
|
+
return [];
|
|
23
34
|
const messages = await db.conversationMessages(thread, team);
|
|
24
35
|
const byId = new Map(messages.map(message => [message.messageId, message]));
|
|
25
36
|
return messages.filter(message => {
|
|
@@ -47,7 +58,7 @@ export function inboxMessageTransport(inbox, team, root) {
|
|
|
47
58
|
changes: (thread, after, signal) => read(async () => {
|
|
48
59
|
signal.throwIfAborted();
|
|
49
60
|
const current = await metadata(thread), cursor = decode(after);
|
|
50
|
-
if (!valid(cursor, current) || await db.structureSequence(thread) > inboxSequence(cursor.seq))
|
|
61
|
+
if (!await authorized(thread) || !valid(cursor, current) || await db.structureSequence(thread) > inboxSequence(cursor.seq))
|
|
51
62
|
return { messages: [], checkpoint: encode(current), resetRequired: true };
|
|
52
63
|
const changed = await db.conversationChanges(thread, team, cursor.seq, cursor.id ?? "\uffff");
|
|
53
64
|
const selected = changed.slice(0, 100), hasMore = changed.length > selected.length;
|
package/lib/runtime/index.d.ts
CHANGED
package/lib/runtime/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { InboxReceipts } from "./inboxReceipts.js";
|
|
1
2
|
import { type ResponseCacheAccess } from "./responseCache.js";
|
|
2
3
|
import { type MessageScope } from "./messageStore.js";
|
|
3
4
|
export type MessageReadersPage = {
|
|
@@ -18,6 +19,7 @@ export type MessageReadersQuery = {
|
|
|
18
19
|
limit?: number;
|
|
19
20
|
};
|
|
20
21
|
export type MessageReadersOptions = {
|
|
22
|
+
local?: InboxReceipts;
|
|
21
23
|
appId: string;
|
|
22
24
|
profileId: string;
|
|
23
25
|
token: string;
|
|
@@ -20,7 +20,7 @@ export class MessageReadersClient {
|
|
|
20
20
|
generation = 0;
|
|
21
21
|
constructor(options) {
|
|
22
22
|
this.options = { ...options };
|
|
23
|
-
if (options.scope) {
|
|
23
|
+
if (options.scope && !options.local) {
|
|
24
24
|
if (options.scope.appId !== options.appId || options.scope.profileId !== options.profileId)
|
|
25
25
|
throw new Error("MESSAGE_READERS_SCOPE_MISMATCH");
|
|
26
26
|
this.cache = new IndexedDbResponseCache(messageScopeKey(options.scope), { access: options.access });
|
|
@@ -31,6 +31,14 @@ export class MessageReadersClient {
|
|
|
31
31
|
return Promise.reject(new Error("MESSAGE_READERS_CLOSED"));
|
|
32
32
|
if (signal?.aborted)
|
|
33
33
|
return Promise.reject(signal.reason);
|
|
34
|
+
if (this.options.local) {
|
|
35
|
+
try {
|
|
36
|
+
return Promise.resolve(this.options.local.page(query));
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
return Promise.reject(error);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
34
42
|
const input = { ...query, limit: query.limit ?? 50 };
|
|
35
43
|
if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100 || (input.revision !== undefined && (!Number.isSafeInteger(input.revision) || input.revision < 0)))
|
|
36
44
|
return Promise.reject(new Error("INVALID_MESSAGE_READERS_QUERY"));
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { InboxReceipts } from "./inboxReceipts.js";
|
|
1
2
|
import { type ResponseCacheAccess } from "./responseCache.js";
|
|
2
3
|
import { type MessageScope } from "./messageStore.js";
|
|
3
4
|
export type ReadCountsResult = {
|
|
@@ -7,6 +8,7 @@ export type ReadCountsResult = {
|
|
|
7
8
|
counts: Record<string, number>;
|
|
8
9
|
};
|
|
9
10
|
export type ReadCountsOptions = {
|
|
11
|
+
local?: InboxReceipts;
|
|
10
12
|
appId: string;
|
|
11
13
|
profileId: string;
|
|
12
14
|
token: string;
|
|
@@ -21,6 +23,8 @@ export type ReadCountsOptions = {
|
|
|
21
23
|
/** One active conversation; fixed event window, bounded batches, no count polling. */
|
|
22
24
|
export declare class ReadCountsClient {
|
|
23
25
|
private options;
|
|
26
|
+
private offLocal?;
|
|
27
|
+
private publishLocal;
|
|
24
28
|
private thread?;
|
|
25
29
|
private ids;
|
|
26
30
|
private timer?;
|
|
@@ -41,6 +41,12 @@ function nextSubscriptionSequence() { subscriptionSequence = Math.max(Date.now()
|
|
|
41
41
|
/** One active conversation; fixed event window, bounded batches, no count polling. */
|
|
42
42
|
export class ReadCountsClient {
|
|
43
43
|
options;
|
|
44
|
+
offLocal;
|
|
45
|
+
publishLocal() { if (this.thread) {
|
|
46
|
+
const result = this.options.local?.counts(this.thread, this.ids);
|
|
47
|
+
if (result)
|
|
48
|
+
this.publish(result);
|
|
49
|
+
} }
|
|
44
50
|
thread;
|
|
45
51
|
ids = [];
|
|
46
52
|
timer;
|
|
@@ -71,6 +77,11 @@ export class ReadCountsClient {
|
|
|
71
77
|
force = false;
|
|
72
78
|
constructor(options) {
|
|
73
79
|
this.options = options;
|
|
80
|
+
if (options.local) {
|
|
81
|
+
this.offLocal = options.local.subscribe(threads => { if (!threads.length || this.thread && threads.includes(this.thread))
|
|
82
|
+
this.publishLocal(); });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
74
85
|
if (options.scope) {
|
|
75
86
|
if (options.scope.appId !== options.appId || options.scope.profileId !== options.profileId)
|
|
76
87
|
throw new Error("READ_COUNTS_SCOPE_MISMATCH");
|
|
@@ -165,6 +176,12 @@ export class ReadCountsClient {
|
|
|
165
176
|
if (this.closed)
|
|
166
177
|
return;
|
|
167
178
|
const ids = [...new Set(messageIds)].slice(-100);
|
|
179
|
+
if (this.options.local) {
|
|
180
|
+
this.thread = threadId;
|
|
181
|
+
this.ids = ids;
|
|
182
|
+
this.publishLocal();
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
168
185
|
if (this.thread === threadId) {
|
|
169
186
|
if (JSON.stringify(ids) !== JSON.stringify(this.ids)) {
|
|
170
187
|
this.ids = ids;
|
|
@@ -201,6 +218,8 @@ export class ReadCountsClient {
|
|
|
201
218
|
this.schedule(0);
|
|
202
219
|
}
|
|
203
220
|
changed(threadId, revision) {
|
|
221
|
+
if (this.options.local)
|
|
222
|
+
return;
|
|
204
223
|
if (!Number.isSafeInteger(revision) || revision < 0)
|
|
205
224
|
throw new Error("INVALID_READ_COUNTS_EVENT");
|
|
206
225
|
if (threadId !== this.thread || revision <= this.revision || this.closed)
|
|
@@ -209,6 +228,10 @@ export class ReadCountsClient {
|
|
|
209
228
|
this.schedule(3000);
|
|
210
229
|
}
|
|
211
230
|
reconnect() {
|
|
231
|
+
if (this.options.local) {
|
|
232
|
+
this.publishLocal();
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
212
235
|
if (!this.thread || this.closed)
|
|
213
236
|
return;
|
|
214
237
|
this.force = true;
|
|
@@ -317,7 +340,9 @@ export class ReadCountsClient {
|
|
|
317
340
|
clearTimeout(this.timer);
|
|
318
341
|
clearInterval(this.heartbeat);
|
|
319
342
|
this.controller?.abort();
|
|
320
|
-
|
|
343
|
+
this.offLocal?.();
|
|
344
|
+
this.offLocal = undefined;
|
|
345
|
+
if (old && !this.options.local)
|
|
321
346
|
void this.subscription(old, true).catch(() => { });
|
|
322
347
|
this.thread = undefined;
|
|
323
348
|
return this.closing = this.cache?.close().catch(error => this.report(error, "cache.close")) ?? Promise.resolve();
|
|
@@ -33,7 +33,7 @@ export class ReadingClient {
|
|
|
33
33
|
throw new Error("INVALID_READ_TEAM");
|
|
34
34
|
const storage = options.persistence ?? (this.storage = new IndexedDbReadIndex(globalThis.indexedDB, "pmate-social-read-index", options.storageScope, options.migrateLegacy, options.metadataOnly));
|
|
35
35
|
this.backing = storage;
|
|
36
|
-
this.persistence = new BatchedReadIndex(storage);
|
|
36
|
+
this.persistence = new BatchedReadIndex(storage, options.inbox ? 100 : 16);
|
|
37
37
|
this.tasks = new WindowedTasks(1000, error => this.failed(error));
|
|
38
38
|
this.sync = new ReadSyncClient({ ...options, persistence: this.persistence, onChange: state => this.publish(state) });
|
|
39
39
|
if (options.inbox)
|
package/package.json
CHANGED