@pmate/chat-sdk 0.13.0-profile.0 → 0.13.0-profile.2
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/lib/profile.d.ts +4 -1
- package/lib/profile.js +4 -1
- package/lib/runtime/profileChat.d.ts +5 -0
- package/lib/runtime/profileChat.js +63 -19
- package/lib/runtime/profileCoordinator.js +6 -1
- package/lib/runtime/profileDatabase.js +4 -3
- package/lib/runtime/profileGenerationBuilder.js +38 -4
- package/lib/runtime/profileInboxFeed.d.ts +1 -0
- package/lib/runtime/profileInboxFeed.js +1 -0
- package/lib/runtime/profileLegacyInbox.d.ts +8 -0
- package/lib/runtime/profileLegacyInbox.js +109 -0
- package/lib/runtime/profileLegacyOutbox.d.ts +7 -0
- package/lib/runtime/profileLegacyOutbox.js +106 -0
- package/lib/runtime/profileLegacyReading.d.ts +7 -0
- package/lib/runtime/profileLegacyReading.js +110 -0
- package/lib/runtime/profileMemoryStore.d.ts +2 -0
- package/lib/runtime/profileMemoryStore.js +6 -0
- package/lib/runtime/profileOutboxDispatcher.js +2 -0
- package/lib/runtime/profileOwner.d.ts +5 -1
- package/lib/runtime/profileOwner.js +25 -1
- package/lib/runtime/profileProjection.d.ts +20 -0
- package/lib/runtime/profileProjection.js +76 -7
- package/lib/runtime/profileReadingIndex.d.ts +1 -0
- package/lib/runtime/profileReadingIndex.js +16 -0
- package/lib/runtime/profileReplica.d.ts +1 -0
- package/lib/runtime/profileReplica.js +7 -0
- package/lib/runtime/profileStoreTypes.d.ts +7 -0
- package/lib/runtime/profileWorkerHost.js +9 -1
- package/package.json +1 -1
package/lib/profile.d.ts
CHANGED
|
@@ -7,7 +7,10 @@ export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
|
7
7
|
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
|
8
8
|
export { ProfileInboxFeed } from "./runtime/profileInboxFeed.js";
|
|
9
9
|
export { ProfileOutboxDispatcher } from "./runtime/profileOutboxDispatcher.js";
|
|
10
|
-
export {
|
|
10
|
+
export { migrateLegacyInbox } from "./runtime/profileLegacyInbox.js";
|
|
11
|
+
export { migrateLegacyOutbox } from "./runtime/profileLegacyOutbox.js";
|
|
12
|
+
export { migrateLegacyReading } from "./runtime/profileLegacyReading.js";
|
|
13
|
+
export { createProfileChat, getProfileChatRuntime, handleProfileChatReach, revokeProfileChatAccess } from "./runtime/profileChat.js";
|
|
11
14
|
export type { ProfileChatHost } from "./runtime/profileChat.js";
|
|
12
15
|
export type { ProfileWorkerConfiguration } from "./runtime/profileWorkerHost.js";
|
|
13
16
|
export type { ProfileSnapshot, ProfileDelta } from "./runtime/profileMemoryStore.js";
|
package/lib/profile.js
CHANGED
|
@@ -7,4 +7,7 @@ export { profileDiscussionId } from "./runtime/profileProjection.js";
|
|
|
7
7
|
export { ProfileCoordinator } from "./runtime/profileCoordinator.js";
|
|
8
8
|
export { ProfileInboxFeed } from "./runtime/profileInboxFeed.js";
|
|
9
9
|
export { ProfileOutboxDispatcher } from "./runtime/profileOutboxDispatcher.js";
|
|
10
|
-
export {
|
|
10
|
+
export { migrateLegacyInbox } from "./runtime/profileLegacyInbox.js";
|
|
11
|
+
export { migrateLegacyOutbox } from "./runtime/profileLegacyOutbox.js";
|
|
12
|
+
export { migrateLegacyReading } from "./runtime/profileLegacyReading.js";
|
|
13
|
+
export { createProfileChat, getProfileChatRuntime, handleProfileChatReach, revokeProfileChatAccess } from "./runtime/profileChat.js";
|
|
@@ -4,6 +4,7 @@ import type { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
|
4
4
|
import { type ProfileOperation } from "./profileProjection.js";
|
|
5
5
|
import type { ProfileIdentity } from "./profileStoreTypes.js";
|
|
6
6
|
import { type ChatRuntimeMessage } from "./protocol.js";
|
|
7
|
+
import type { OnlineReachEvent } from "./reach.js";
|
|
7
8
|
export type ProfileChatHost = {
|
|
8
9
|
identity: ProfileIdentity;
|
|
9
10
|
memory: ProfileMemoryStore;
|
|
@@ -15,6 +16,8 @@ export type ProfileChatHost = {
|
|
|
15
16
|
};
|
|
16
17
|
export declare function getProfileChatRuntime(chat: Chat): ProfileChat;
|
|
17
18
|
export declare function createProfileChat(host: ProfileChatHost, teamId: string): Chat;
|
|
19
|
+
export declare function handleProfileChatReach(chat: Chat, event: OnlineReachEvent): "handled" | undefined;
|
|
20
|
+
export declare function revokeProfileChatAccess(chat: Chat): Promise<void>;
|
|
18
21
|
/** Product-facing Chat adapter over prepared Profile views. No legacy Session,
|
|
19
22
|
* second outbox, reading persistence or per-team message database is created. */
|
|
20
23
|
export declare class ProfileChat implements Chat {
|
|
@@ -22,11 +25,13 @@ export declare class ProfileChat implements Chat {
|
|
|
22
25
|
readonly teamId: string;
|
|
23
26
|
private discussion?;
|
|
24
27
|
private views;
|
|
28
|
+
private preparedInputs;
|
|
25
29
|
private limits;
|
|
26
30
|
private listening;
|
|
27
31
|
private listListeners;
|
|
28
32
|
private offs;
|
|
29
33
|
private offList;
|
|
34
|
+
private readyWaiters;
|
|
30
35
|
private closed;
|
|
31
36
|
private summary;
|
|
32
37
|
constructor(host: ProfileChatHost, teamId: string, discussion?: {
|
|
@@ -5,6 +5,7 @@ import { createRuntimeMsg } from "./protocol.js";
|
|
|
5
5
|
import { outgoingContent } from "./outgoingContent.js";
|
|
6
6
|
import { dmThreadId, groupThreadId } from "./thread.js";
|
|
7
7
|
import { createUniqueGroup } from "./groupIdentity.js";
|
|
8
|
+
import { messageThreadRoot } from "./messageThread.js";
|
|
8
9
|
const sessions = new WeakMap();
|
|
9
10
|
export function getProfileChatRuntime(chat) {
|
|
10
11
|
const session = sessions.get(chat);
|
|
@@ -13,6 +14,19 @@ export function getProfileChatRuntime(chat) {
|
|
|
13
14
|
return session;
|
|
14
15
|
}
|
|
15
16
|
export function createProfileChat(host, teamId) { return new ProfileChat(host, teamId); }
|
|
17
|
+
export function handleProfileChatReach(chat, event) {
|
|
18
|
+
if (!["social.readCountsChanged", "social.readStateChanged"].includes(event.eventType))
|
|
19
|
+
return;
|
|
20
|
+
const { identity } = getProfileChatRuntime(chat).host;
|
|
21
|
+
if (event.appId !== identity.appId)
|
|
22
|
+
throw Error("UNEXPECTED_READING_APPLICATION");
|
|
23
|
+
if (event.eventType === "social.readStateChanged" && event.payload.profileId !== identity.profileId)
|
|
24
|
+
throw Error("Reading reach identity mismatch");
|
|
25
|
+
// Inbox owns the ordered receipt stream. Reach is only a hint and must not
|
|
26
|
+
// create another reading store or apply facts outside that stream.
|
|
27
|
+
return "handled";
|
|
28
|
+
}
|
|
29
|
+
export function revokeProfileChatAccess(chat) { return getProfileChatRuntime(chat).revokeAccess(); }
|
|
16
30
|
/** Product-facing Chat adapter over prepared Profile views. No legacy Session,
|
|
17
31
|
* second outbox, reading persistence or per-team message database is created. */
|
|
18
32
|
export class ProfileChat {
|
|
@@ -20,11 +34,13 @@ export class ProfileChat {
|
|
|
20
34
|
teamId;
|
|
21
35
|
discussion;
|
|
22
36
|
views = new Map();
|
|
37
|
+
preparedInputs = new Map();
|
|
23
38
|
limits = new Map();
|
|
24
39
|
listening = new Map();
|
|
25
40
|
listListeners = new Set();
|
|
26
41
|
offs = new Map();
|
|
27
42
|
offList;
|
|
43
|
+
readyWaiters = new Set();
|
|
28
44
|
closed = false;
|
|
29
45
|
summary = { threads: [], unreadMessageCount: undefined, badgeCount: undefined, connection: "connecting" };
|
|
30
46
|
constructor(host, teamId, discussion) {
|
|
@@ -83,6 +99,11 @@ export class ProfileChat {
|
|
|
83
99
|
pages.unshift(page);
|
|
84
100
|
anchor = page[0]?.id;
|
|
85
101
|
}
|
|
102
|
+
const inputs = this.preparedInputs.get(id);
|
|
103
|
+
if (inputs && inputs.thread === thread && inputs.parent === parent && inputs.pages.length === pages.length &&
|
|
104
|
+
pages.every((page, index) => page === inputs.pages[index]))
|
|
105
|
+
return this.snapshot(id);
|
|
106
|
+
this.preparedInputs.set(id, { thread, parent, pages });
|
|
86
107
|
const messages = pages.length === 1 ? pages[0] : pages.flat();
|
|
87
108
|
const group = this.group(parent);
|
|
88
109
|
const counts = {};
|
|
@@ -114,15 +135,37 @@ export class ProfileChat {
|
|
|
114
135
|
for (const listener of this.listListeners)
|
|
115
136
|
listener(this.summary);
|
|
116
137
|
}
|
|
117
|
-
async start() {
|
|
138
|
+
async start() {
|
|
139
|
+
this.assertOpen();
|
|
140
|
+
await this.host.start();
|
|
141
|
+
this.assertOpen();
|
|
142
|
+
if (this.host.memory.getStatus().phase !== "ready")
|
|
143
|
+
await new Promise((resolve, reject) => {
|
|
144
|
+
const cancel = () => { off(); this.readyWaiters.delete(cancel); reject(new ChatError("closed", "Chat session closed")); };
|
|
145
|
+
const check = () => {
|
|
146
|
+
if (this.host.memory.getStatus().phase !== "ready")
|
|
147
|
+
return;
|
|
148
|
+
off();
|
|
149
|
+
this.readyWaiters.delete(cancel);
|
|
150
|
+
resolve();
|
|
151
|
+
};
|
|
152
|
+
const off = this.host.memory.subscribeThreadList(check);
|
|
153
|
+
this.readyWaiters.add(cancel);
|
|
154
|
+
check();
|
|
155
|
+
});
|
|
156
|
+
this.assertOpen();
|
|
157
|
+
this.prepareSummary();
|
|
158
|
+
}
|
|
118
159
|
initialize() { return this.start(); }
|
|
119
160
|
async close() { if (this.closed)
|
|
120
|
-
return; this.closed = true;
|
|
161
|
+
return; this.closed = true; for (const cancel of this.readyWaiters)
|
|
162
|
+
cancel(); this.offList(); for (const off of this.offs.values())
|
|
121
163
|
off(); this.offs.clear(); this.listening.clear(); this.listListeners.clear(); }
|
|
122
164
|
async resolveThreadId(target, options = {}) {
|
|
123
165
|
this.assertOpen();
|
|
124
166
|
options.signal?.throwIfAborted();
|
|
125
|
-
await this.
|
|
167
|
+
await this.start();
|
|
168
|
+
options.signal?.throwIfAborted();
|
|
126
169
|
const kind = target.groupId !== undefined ? "group" : "dm", targetId = target.groupId ?? target.peerId;
|
|
127
170
|
if (this.discussion)
|
|
128
171
|
return this.discussion.parentId;
|
|
@@ -134,7 +177,16 @@ export class ProfileChat {
|
|
|
134
177
|
return id;
|
|
135
178
|
}
|
|
136
179
|
async getThread(id, options = {}) { this.assertOpen(); options.signal?.throwIfAborted(); return this.prepare(id); }
|
|
137
|
-
async loadEarlier(id, options = {}) {
|
|
180
|
+
async loadEarlier(id, options = {}) {
|
|
181
|
+
this.assertOpen();
|
|
182
|
+
options.signal?.throwIfAborted();
|
|
183
|
+
this.limits.set(id, (this.limits.get(id) ?? 128) + 128);
|
|
184
|
+
const previous = this.views.get(id), value = this.prepare(id);
|
|
185
|
+
if (previous !== value)
|
|
186
|
+
for (const listener of this.listening.get(id) ?? [])
|
|
187
|
+
listener(value);
|
|
188
|
+
return value;
|
|
189
|
+
}
|
|
138
190
|
async refreshThread(id, options = {}) { options.signal?.throwIfAborted(); await this.host.synchronize(); return this.getThread(id, options); }
|
|
139
191
|
subscribeThread(id, listener, _options = {}) {
|
|
140
192
|
this.assertOpen();
|
|
@@ -173,8 +225,10 @@ export class ProfileChat {
|
|
|
173
225
|
}
|
|
174
226
|
async sendPrepared(threadId, wire, options = {}, voiceBlob) {
|
|
175
227
|
this.assertOpen();
|
|
176
|
-
|
|
177
|
-
|
|
228
|
+
const root = messageThreadRoot(wire.body);
|
|
229
|
+
const destination = this.discussion ? this.key(threadId) : root ? profileDiscussionId(threadId, root) : threadId;
|
|
230
|
+
await this.host.submit({ type: "send", threadId: destination, parentThreadId: this.discussion?.parentId ?? (root ? threadId : undefined), message: wire, command: {
|
|
231
|
+
commandId: wire.hash, messageId: wire.hash, kind: "message", threadId: destination, createdAt: wire.t,
|
|
178
232
|
payload: voiceBlob ? { message: wire, voiceBlob } : wire, state: "pending", attempts: 0,
|
|
179
233
|
} }, true);
|
|
180
234
|
if (options.waitFor === "delivered")
|
|
@@ -204,20 +258,10 @@ export class ProfileChat {
|
|
|
204
258
|
return this.host.submit({ type: "observe", threadId: this.key(id), messageIds: ids, policy: event, commandId: crypto.randomUUID(), createdAt: Date.now() }, event === "played");
|
|
205
259
|
}
|
|
206
260
|
async markRead(id) {
|
|
207
|
-
|
|
208
|
-
if (!thread)
|
|
261
|
+
if (!this.thread(id))
|
|
209
262
|
return;
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
let anchor;
|
|
213
|
-
for (;;) {
|
|
214
|
-
const page = this.host.memory.readPage(this.key(id), anchor, 1000);
|
|
215
|
-
ids.push(...page.map(row => row.messageId));
|
|
216
|
-
if (page.length < 1000)
|
|
217
|
-
break;
|
|
218
|
-
anchor = page[0].messageId;
|
|
219
|
-
}
|
|
220
|
-
await this.observeMessages(id, ids, "visible");
|
|
263
|
+
await this.host.submit({ type: "observe", threadId: this.key(id), messageIds: [], allVisible: true,
|
|
264
|
+
policy: "visible", commandId: crypto.randomUUID(), createdAt: Date.now() });
|
|
221
265
|
}
|
|
222
266
|
async getReaders(id, messageId, options = {}) {
|
|
223
267
|
options.signal?.throwIfAborted();
|
|
@@ -113,7 +113,12 @@ export class ProfileCoordinator {
|
|
|
113
113
|
if (!configuration.network)
|
|
114
114
|
return;
|
|
115
115
|
configuration.network = { ...configuration.network, token };
|
|
116
|
-
|
|
116
|
+
if (this.host)
|
|
117
|
+
await this.host.update(configuration);
|
|
118
|
+
else if (this.starting) {
|
|
119
|
+
await this.starting;
|
|
120
|
+
await this.replica.updateCredentials(token);
|
|
121
|
+
}
|
|
117
122
|
}
|
|
118
123
|
async close() {
|
|
119
124
|
this.closed = true;
|
|
@@ -80,7 +80,8 @@ export class ProfileDatabase extends Dexie {
|
|
|
80
80
|
if (inboxSequence(batch.committedSeq) < inboxSequence(current.committedSeq))
|
|
81
81
|
throw Error("PROFILE_CURSOR_REGRESSION");
|
|
82
82
|
const changed = [batch.threads, batch.windows, batch.messages, batch.outbox, batch.deleteMessages, batch.deleteWindows, batch.deleteOutbox].some(rows => rows?.length);
|
|
83
|
-
|
|
83
|
+
const localMigrations = batch.localMigrations ? [...new Set([...(current.localMigrations ?? []), ...batch.localMigrations])] : current.localMigrations;
|
|
84
|
+
if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations))
|
|
84
85
|
return current;
|
|
85
86
|
if (batch.messages?.length)
|
|
86
87
|
await this.messages.bulkPut(batch.messages);
|
|
@@ -98,7 +99,7 @@ export class ProfileDatabase extends Dexie {
|
|
|
98
99
|
await this.outbox.bulkDelete(batch.deleteOutbox);
|
|
99
100
|
if (!Number.isSafeInteger(current.commitRevision + 1))
|
|
100
101
|
throw Error("PROFILE_REVISION_EXHAUSTED");
|
|
101
|
-
const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
|
|
102
|
+
const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
|
|
102
103
|
await this.inboxState.put(next);
|
|
103
104
|
return next;
|
|
104
105
|
});
|
|
@@ -154,7 +155,7 @@ export class ProfileDatabase extends Dexie {
|
|
|
154
155
|
throw Error("PROFILE_REVISION_CONFLICT");
|
|
155
156
|
if (build.status !== "validated")
|
|
156
157
|
throw Error("PROFILE_BUILD_NOT_VALIDATED");
|
|
157
|
-
const next = { key: "current", activeGeneration: generation, epoch: build.epoch,
|
|
158
|
+
const next = { ...current, key: "current", activeGeneration: generation, epoch: build.epoch,
|
|
158
159
|
committedSeq: build.committedSeq, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
|
|
159
160
|
await this.inboxState.put({ ...build, status: "active" });
|
|
160
161
|
await this.inboxState.put(next);
|
|
@@ -68,25 +68,40 @@ export class ProfileGenerationBuilder {
|
|
|
68
68
|
if (inboxSequence(build.committedSeq) < inboxSequence(build.throughSeq ?? "0"))
|
|
69
69
|
throw Error("PROFILE_BUILD_INCOMPLETE");
|
|
70
70
|
const operations = [];
|
|
71
|
+
const registered = new Set();
|
|
71
72
|
// Keep locally accepted work that arrived while the replacement was built.
|
|
72
73
|
// Already-replayed server messages win by their stable message identity.
|
|
73
74
|
for (const message of active.messages.values()) {
|
|
74
75
|
if (message.sourceSeq || projection.messages.has(message.messageId))
|
|
75
76
|
continue;
|
|
76
|
-
const thread = projection.threads.get(message.threadId);
|
|
77
|
+
const thread = projection.threads.get(message.threadId) ?? active.threads.get(message.threadId);
|
|
77
78
|
if (thread?.status !== "ready")
|
|
78
79
|
continue;
|
|
80
|
+
const parent = thread.parentThreadId ? active.threads.get(thread.parentThreadId) : thread;
|
|
81
|
+
if (!parent || parent.status !== "ready")
|
|
82
|
+
continue;
|
|
83
|
+
if (!projection.threads.has(parent.threadId) && !registered.has(parent.threadId)) {
|
|
84
|
+
if (!parent.teamId || !parent.internal?.targetId)
|
|
85
|
+
continue;
|
|
86
|
+
operations.push({ type: "register", threadId: parent.threadId, kind: parent.kind === "dm" ? "dm" : "group",
|
|
87
|
+
targetId: parent.internal.targetId, teamId: parent.teamId, title: parent.title });
|
|
88
|
+
registered.add(parent.threadId);
|
|
89
|
+
}
|
|
79
90
|
const pending = active.outbox.get(message.messageId);
|
|
80
91
|
const pendingPayload = pending?.payload;
|
|
81
92
|
const wire = pendingPayload?.message ?? pending?.payload ?? { hash: message.messageId, t: message.orderKey[0],
|
|
82
93
|
from: message.from, to: thread.internal?.targetId ?? "", opcode: 1, kind: 1, body: message.content, recipients: message.recipients };
|
|
83
94
|
const command = pending ?? { commandId: message.messageId, messageId: message.messageId, kind: "message",
|
|
84
95
|
threadId: message.threadId, createdAt: wire.t, payload: wire, state: "pending", attempts: 0 };
|
|
85
|
-
operations.push({ type: "send", threadId: message.threadId, message: wire, command });
|
|
96
|
+
operations.push({ type: "send", threadId: message.threadId, parentThreadId: thread.parentThreadId, message: wire, command, preserveWire: true });
|
|
86
97
|
if (!pending)
|
|
87
98
|
operations.push({ type: "commandResult", commandId: message.messageId, state: "confirmed" });
|
|
88
99
|
}
|
|
89
100
|
for (const thread of active.threads.values()) {
|
|
101
|
+
for (const [messageId, intents] of Object.entries(thread.internal?.pendingReadingIntents ?? {})) {
|
|
102
|
+
for (const intent of intents)
|
|
103
|
+
operations.push({ type: "restoreReadingIntent", threadId: thread.threadId, messageId, ...intent, defer: true });
|
|
104
|
+
}
|
|
90
105
|
if (!projection.threads.has(thread.threadId))
|
|
91
106
|
continue;
|
|
92
107
|
for (const source of thread.readingSources) {
|
|
@@ -97,8 +112,27 @@ export class ProfileGenerationBuilder {
|
|
|
97
112
|
readThroughSeq: source.pendingReadThroughSeq ?? 0, explicitReadMessageIds: source.pendingExplicitReadMessageIds ?? [] } });
|
|
98
113
|
}
|
|
99
114
|
}
|
|
100
|
-
|
|
101
|
-
(
|
|
115
|
+
for (const command of active.outbox.values())
|
|
116
|
+
if (command.kind !== "message")
|
|
117
|
+
operations.push({ type: "restoreReadingCommand", command });
|
|
118
|
+
let batch = [], bytes = 0;
|
|
119
|
+
const flush = async () => {
|
|
120
|
+
if (!batch.length)
|
|
121
|
+
return;
|
|
122
|
+
const saved = await this.persist(build, projection, batch);
|
|
123
|
+
build = saved.build;
|
|
124
|
+
projection = saved.projection;
|
|
125
|
+
batch = [];
|
|
126
|
+
bytes = 0;
|
|
127
|
+
};
|
|
128
|
+
for (const operation of operations) {
|
|
129
|
+
const size = new TextEncoder().encode(JSON.stringify(operation)).byteLength;
|
|
130
|
+
if (batch.length && (batch.length >= 200 || bytes + size > 512 * 1024))
|
|
131
|
+
await flush();
|
|
132
|
+
batch.push(operation);
|
|
133
|
+
bytes += size;
|
|
134
|
+
}
|
|
135
|
+
await flush();
|
|
102
136
|
const snapshot = projection.snapshot();
|
|
103
137
|
new ProfileMemoryStore().restore(snapshot);
|
|
104
138
|
const lease = this.lease();
|
|
@@ -8,6 +8,7 @@ export type ProfileInboxFeedOptions = {
|
|
|
8
8
|
onError?: (error: unknown) => void;
|
|
9
9
|
onProgress?: (progress: InboxProgress) => void;
|
|
10
10
|
live?: boolean;
|
|
11
|
+
prepare?: () => Promise<unknown>;
|
|
11
12
|
};
|
|
12
13
|
/** The existing Inbox HTTP/live protocol, with no raw event cache. Each page is
|
|
13
14
|
* backpressured by durable owner commits; long requests never hold its queue. */
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ProfileOwner } from "./profileOwner.js";
|
|
2
|
+
export declare function openLegacyDatabase(factory: IDBFactory, name: string): Promise<IDBDatabase | undefined>;
|
|
3
|
+
/** One-time materialization migration. Source data is read consistently and
|
|
4
|
+
* retained; the old cursor becomes active only with the complete new view. */
|
|
5
|
+
export declare function migrateLegacyInbox(owner: ProfileOwner, options?: {
|
|
6
|
+
indexedDB?: IDBFactory;
|
|
7
|
+
name?: string;
|
|
8
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { inboxSequence } from "./inboxStore.js";
|
|
2
|
+
export async function openLegacyDatabase(factory, name) {
|
|
3
|
+
return new Promise((resolve, reject) => {
|
|
4
|
+
let fresh = false;
|
|
5
|
+
const request = factory.open(name);
|
|
6
|
+
request.onupgradeneeded = event => {
|
|
7
|
+
if (event.oldVersion === 0) {
|
|
8
|
+
fresh = true;
|
|
9
|
+
request.transaction.abort();
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
request.onerror = event => { event.preventDefault(); fresh ? resolve(undefined) : reject(request.error); };
|
|
13
|
+
request.onsuccess = () => resolve(request.result);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
async function capture(database, owner) {
|
|
17
|
+
const names = ["cursors", "messages", "facts", "positions", "explicit", "receipts", "projections"].filter(name => database.objectStoreNames.contains(name));
|
|
18
|
+
if (!names.includes("cursors"))
|
|
19
|
+
return { messages: [], facts: [], positions: [], explicit: [], receipts: [], projections: [] };
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
const transaction = database.transaction(names, "readonly");
|
|
22
|
+
const result = {};
|
|
23
|
+
transaction.oncomplete = () => resolve({ messages: [], facts: [], positions: [], explicit: [], receipts: [], projections: [], ...result });
|
|
24
|
+
transaction.onerror = () => reject(transaction.error);
|
|
25
|
+
transaction.onabort = () => reject(transaction.error ?? Error("LEGACY_INBOX_CAPTURE_ABORTED"));
|
|
26
|
+
for (const name of names) {
|
|
27
|
+
const store = transaction.objectStore(name);
|
|
28
|
+
const request = name === "cursors" ? store.get(owner) : store.index("owner").getAll(IDBKeyRange.only(owner));
|
|
29
|
+
request.onsuccess = () => { result[name === "cursors" ? "cursor" : name] = request.result; };
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/** One-time materialization migration. Source data is read consistently and
|
|
34
|
+
* retained; the old cursor becomes active only with the complete new view. */
|
|
35
|
+
export async function migrateLegacyInbox(owner, options = {}) {
|
|
36
|
+
if (owner.current.epoch !== "uninitialized")
|
|
37
|
+
return false;
|
|
38
|
+
const database = await openLegacyDatabase(options.indexedDB ?? globalThis.indexedDB, options.name ?? "pmate-chat-inbox-v1");
|
|
39
|
+
if (!database)
|
|
40
|
+
return false;
|
|
41
|
+
const identity = owner.identity, key = JSON.stringify([identity.accountId, identity.appId, identity.profileId]);
|
|
42
|
+
let rows;
|
|
43
|
+
try {
|
|
44
|
+
rows = await capture(database, key);
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
database.close();
|
|
48
|
+
}
|
|
49
|
+
const cursor = rows.cursor;
|
|
50
|
+
if (!cursor?.initialized || !cursor.epoch)
|
|
51
|
+
return false;
|
|
52
|
+
const seq = inboxSequence(cursor.seq);
|
|
53
|
+
const generation = `legacy-inbox:${JSON.stringify([cursor.epoch, cursor.seq])}`;
|
|
54
|
+
await owner.beginGeneration({ ...identity, epoch: cursor.epoch, startSeq: (seq + 1n).toString(), headSeq: cursor.seq,
|
|
55
|
+
windowStart: cursor.windowStart, basis: [] }, generation);
|
|
56
|
+
if ((await owner.generationProgress(generation)).status === "validated") {
|
|
57
|
+
await owner.activateGeneration(generation);
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
let pending = [], bytes = 0;
|
|
61
|
+
const flush = async () => { if (pending.length) {
|
|
62
|
+
await owner.appendGeneration(generation, pending);
|
|
63
|
+
pending = [];
|
|
64
|
+
bytes = 0;
|
|
65
|
+
} };
|
|
66
|
+
const push = async (operation) => {
|
|
67
|
+
const size = new TextEncoder().encode(JSON.stringify(operation)).byteLength;
|
|
68
|
+
if (pending.length && (pending.length >= 200 || bytes + size > 512 * 1024))
|
|
69
|
+
await flush();
|
|
70
|
+
pending.push(operation);
|
|
71
|
+
bytes += size;
|
|
72
|
+
};
|
|
73
|
+
const restore = (kind, fact, sourceId, acceptedAt = cursor.windowStart) => ({ type: "restoreEvent", event: { inboxSeq: "0", sourceId, acceptedAt, kind, fact: { appId: identity.appId, ...fact } } });
|
|
74
|
+
// Set readiness before importing messages: each new own message receives its
|
|
75
|
+
// already-known receipt status without a final whole-history rewrite.
|
|
76
|
+
const receiptsReady = rows.projections.some(row => row.name === "receipts" && row.epoch === cursor.epoch && row.status === "ready" && inboxSequence(row.appliedInboxSeq) >= seq);
|
|
77
|
+
if (receiptsReady)
|
|
78
|
+
await push({ type: "receiptsReady" });
|
|
79
|
+
for (const row of rows.facts)
|
|
80
|
+
if (row.kind === "groupControl")
|
|
81
|
+
await push(restore("messageAdded", row.value, row.id));
|
|
82
|
+
rows.messages.sort((a, b) => a.value.serverCreatedAt - b.value.serverCreatedAt || a.value.threadId.localeCompare(b.value.threadId) || (a.value.seq ?? 0) - (b.value.seq ?? 0) || a.id.localeCompare(b.id));
|
|
83
|
+
for (const row of rows.messages) {
|
|
84
|
+
if (!row.value.seq)
|
|
85
|
+
continue;
|
|
86
|
+
const body = row.value.body;
|
|
87
|
+
const value = row.root ? { ...row.value, body: { ...body, content: { ...body?.content, threadRootId: row.root } } } : row.value;
|
|
88
|
+
await push({ ...restore("messageAdded", { ...value, sourceAcceptedAt: row.acceptedAt }, row.id, row.acceptedAt), recalled: row.recalled });
|
|
89
|
+
}
|
|
90
|
+
for (const row of rows.positions)
|
|
91
|
+
await push(restore("readingUpdated", { profileId: identity.profileId, threadId: row.thread,
|
|
92
|
+
...(row.root ? { threadRootId: row.root } : {}), readThroughSeq: row.seq, readThroughMessageId: row.messageId, explicitReadMessageIds: [] }, `position:${row.thread}:${row.root}`));
|
|
93
|
+
const roots = new Map(rows.messages.map(row => [JSON.stringify([row.value.threadId, row.id]), row.root]));
|
|
94
|
+
for (const row of rows.explicit) {
|
|
95
|
+
const root = roots.get(JSON.stringify([row.thread, row.id]));
|
|
96
|
+
await push(restore("readingUpdated", { profileId: identity.profileId, threadId: row.thread, ...(root ? { threadRootId: root } : {}),
|
|
97
|
+
readThroughSeq: 0, explicitReadMessageIds: [row.id] }, `explicit:${row.id}`));
|
|
98
|
+
}
|
|
99
|
+
for (const row of rows.facts)
|
|
100
|
+
if (["threadOrganized", "threadAssigned", "relationshipUpdated"].includes(row.kind))
|
|
101
|
+
await push(restore(row.kind, row.value, row.id));
|
|
102
|
+
for (const row of rows.receipts)
|
|
103
|
+
await push({ type: "restoreReceipt", data: { appId: identity.appId, profileId: identity.profileId,
|
|
104
|
+
threadId: row.thread, readThroughSeq: 0, explicitReadMessageIds: [], receipt: { version: 1, authorProfileId: identity.profileId,
|
|
105
|
+
readerProfileId: row.readerId, threadId: row.thread, messageIds: [row.messageId], sourceId: `legacy-receipt:${row.messageId}:${row.readerId}`, sourceAcceptedAt: 0 } } });
|
|
106
|
+
await flush();
|
|
107
|
+
await owner.activateGeneration(generation);
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ProfileOwner } from "./profileOwner.js";
|
|
2
|
+
/** Imports exact durable wires; no sender or legacy database upgrade is opened.
|
|
3
|
+
* The completion marker is committed after every admitted command is durable. */
|
|
4
|
+
export declare function migrateLegacyOutbox(owner: ProfileOwner, options?: {
|
|
5
|
+
indexedDB?: IDBFactory;
|
|
6
|
+
name?: string;
|
|
7
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { openLegacyDatabase } from "./profileLegacyInbox.js";
|
|
2
|
+
import { profileDiscussionId } from "./profileProjection.js";
|
|
3
|
+
import { messageThreadRoot } from "./messageThread.js";
|
|
4
|
+
import { dmThreadId, groupThreadId } from "./thread.js";
|
|
5
|
+
const migration = "legacy-outbox-v1";
|
|
6
|
+
async function capture(database, prefix) {
|
|
7
|
+
const messages = database.objectStoreNames.contains("outgoingMessages") ? "outgoingMessages" : "outbox";
|
|
8
|
+
if (!database.objectStoreNames.contains(messages))
|
|
9
|
+
return { messages: [], attachments: [], epochs: [] };
|
|
10
|
+
const names = [messages, "outgoingAttachments", "scopeEpochs"].filter(name => database.objectStoreNames.contains(name));
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
const transaction = database.transaction(names, "readonly"), range = IDBKeyRange.bound(prefix, `${prefix}\uffff`);
|
|
13
|
+
const result = { messages: [], attachments: [], epochs: [] };
|
|
14
|
+
transaction.oncomplete = () => resolve(result);
|
|
15
|
+
transaction.onerror = () => reject(transaction.error);
|
|
16
|
+
transaction.onabort = () => reject(transaction.error ?? Error("LEGACY_OUTBOX_CAPTURE_ABORTED"));
|
|
17
|
+
for (const name of names) {
|
|
18
|
+
const store = transaction.objectStore(name);
|
|
19
|
+
if (name !== "scopeEpochs" && !store.indexNames.contains("scope")) {
|
|
20
|
+
transaction.abort();
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const request = (name === "scopeEpochs" ? store : store.index("scope")).getAll(range);
|
|
24
|
+
request.onsuccess = () => {
|
|
25
|
+
if (name === messages)
|
|
26
|
+
result.messages = request.result;
|
|
27
|
+
else if (name === "scopeEpochs")
|
|
28
|
+
result.epochs = request.result;
|
|
29
|
+
else
|
|
30
|
+
result.attachments = request.result;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
/** Imports exact durable wires; no sender or legacy database upgrade is opened.
|
|
36
|
+
* The completion marker is committed after every admitted command is durable. */
|
|
37
|
+
export async function migrateLegacyOutbox(owner, options = {}) {
|
|
38
|
+
if (owner.current.localMigrations?.includes(migration))
|
|
39
|
+
return false;
|
|
40
|
+
const identity = owner.identity;
|
|
41
|
+
const prefix = `${JSON.stringify([identity.appId, identity.accountId, identity.profileId]).slice(0, -1)},`;
|
|
42
|
+
const database = await openLegacyDatabase(options.indexedDB ?? globalThis.indexedDB, options.name ?? "pmate-chat-outbox");
|
|
43
|
+
let rows = { messages: [], attachments: [], epochs: [] };
|
|
44
|
+
if (database) {
|
|
45
|
+
try {
|
|
46
|
+
rows = await capture(database, prefix);
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
database.close();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
const epochs = new Map(rows.epochs.map(row => [row.scope, row.version]));
|
|
53
|
+
const attachments = new Map(rows.attachments.map(row => [JSON.stringify([row.scope, row.hash]), row]));
|
|
54
|
+
const operations = [];
|
|
55
|
+
const add = (operation, bytes = 0) => operations.push({ operation, bytes: bytes + new TextEncoder().encode(JSON.stringify(operation)).byteLength });
|
|
56
|
+
for (const row of rows.messages) {
|
|
57
|
+
if (row.confirmed || (row.accessVersion ?? 0) !== (epochs.get(row.scope) ?? 0))
|
|
58
|
+
continue;
|
|
59
|
+
const scope = JSON.parse(row.scope);
|
|
60
|
+
if (scope.length !== 4 || scope[0] !== identity.appId || scope[1] !== identity.accountId || scope[2] !== identity.profileId || typeof scope[3] !== "string" || !scope[3])
|
|
61
|
+
throw Error("LEGACY_OUTBOX_SCOPE_MISMATCH");
|
|
62
|
+
const teamId = scope[3], wire = row.message;
|
|
63
|
+
if (!wire || wire.hash !== row.hash || wire.from !== identity.profileId || !wire.to || !Number.isSafeInteger(wire.t))
|
|
64
|
+
throw Error("LEGACY_OUTBOX_MESSAGE_MISMATCH");
|
|
65
|
+
const body = wire.body;
|
|
66
|
+
const content = body.content ?? body.payload;
|
|
67
|
+
if (content?.appId !== identity.appId || content.teamId !== teamId)
|
|
68
|
+
throw Error("LEGACY_OUTBOX_SCOPE_MISMATCH");
|
|
69
|
+
const kind = body.threadKind === "group" || body.kind === "group" || body.content?.groupId ? "group" : "dm";
|
|
70
|
+
const parent = kind === "group" ? groupThreadId(identity.appId, wire.to, teamId) : dmThreadId(identity.appId, identity.profileId, wire.to, teamId);
|
|
71
|
+
if (row.threadId !== parent)
|
|
72
|
+
throw Error("LEGACY_OUTBOX_THREAD_MISMATCH");
|
|
73
|
+
if (owner.memory.getThread(parent)?.status === "unavailable")
|
|
74
|
+
continue;
|
|
75
|
+
const root = messageThreadRoot(wire.body), threadId = root ? profileDiscussionId(parent, root) : parent;
|
|
76
|
+
let voiceBlob = row.voiceBlob ?? (row.voiceData ? new Blob([row.voiceData.bytes], { type: row.voiceData.type }) : undefined);
|
|
77
|
+
if (row.voiceAttachment) {
|
|
78
|
+
const attachment = attachments.get(JSON.stringify([row.scope, row.hash]));
|
|
79
|
+
if (!attachment || attachment.accessVersion !== (row.accessVersion ?? 0) || attachment.size !== row.voiceAttachment.size || attachment.type !== row.voiceAttachment.type ||
|
|
80
|
+
(attachment.bytes?.byteLength ?? attachment.blob?.size) !== attachment.size)
|
|
81
|
+
throw Error("LEGACY_VOICE_ATTACHMENT_UNAVAILABLE");
|
|
82
|
+
voiceBlob = attachment.blob ?? new Blob([attachment.bytes], { type: attachment.type });
|
|
83
|
+
}
|
|
84
|
+
add({ type: "register", threadId: parent, kind, targetId: wire.to, teamId });
|
|
85
|
+
add({ type: "send", threadId, ...(root ? { parentThreadId: parent } : {}), message: wire, preserveWire: true,
|
|
86
|
+
command: { commandId: row.hash, messageId: row.hash, kind: "message", threadId, createdAt: wire.t,
|
|
87
|
+
payload: voiceBlob ? { message: wire, voiceBlob } : wire, state: row.status === "failed" ? "failed" : "pending", attempts: 0 } }, voiceBlob?.size);
|
|
88
|
+
}
|
|
89
|
+
// Await bounded groups so a large old queue cannot bypass owner backpressure.
|
|
90
|
+
let pending = [], bytes = 0;
|
|
91
|
+
const flush = async () => { if (pending.length) {
|
|
92
|
+
owner.flush();
|
|
93
|
+
await Promise.all(pending);
|
|
94
|
+
pending = [];
|
|
95
|
+
bytes = 0;
|
|
96
|
+
} };
|
|
97
|
+
for (const item of operations) {
|
|
98
|
+
if (pending.length && (pending.length >= 200 || bytes + item.bytes > 512 * 1024))
|
|
99
|
+
await flush();
|
|
100
|
+
pending.push(owner.enqueue(item.operation, item.bytes));
|
|
101
|
+
bytes += item.bytes;
|
|
102
|
+
}
|
|
103
|
+
await flush();
|
|
104
|
+
await owner.enqueue({ type: "migrationCompleted", id: migration }, 100, true);
|
|
105
|
+
return rows.messages.length > 0;
|
|
106
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ProfileOwner } from "./profileOwner.js";
|
|
2
|
+
/** Pending operations preserve their server idempotency keys. Unresolved
|
|
3
|
+
* observations remain durable Thread facts until a source message arrives. */
|
|
4
|
+
export declare function migrateLegacyReading(owner: ProfileOwner, options?: {
|
|
5
|
+
indexedDB?: IDBFactory;
|
|
6
|
+
name?: string;
|
|
7
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { openLegacyDatabase } from "./profileLegacyInbox.js";
|
|
2
|
+
const migration = "legacy-reading-v1";
|
|
3
|
+
async function capture(database, appId, profileId, accountId) {
|
|
4
|
+
const name = database.objectStoreNames.contains("readingProfiles") ? "readingProfiles" : "profiles";
|
|
5
|
+
if (!database.objectStoreNames.contains(name))
|
|
6
|
+
return;
|
|
7
|
+
const names = [name, ...(database.objectStoreNames.contains("readBatches") ? ["readBatches"] : [])];
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
const transaction = database.transaction(names, "readonly"), store = transaction.objectStore(name);
|
|
10
|
+
let state;
|
|
11
|
+
transaction.oncomplete = () => resolve(state);
|
|
12
|
+
transaction.onerror = () => reject(transaction.error);
|
|
13
|
+
transaction.onabort = () => reject(transaction.error ?? Error("LEGACY_READING_CAPTURE_ABORTED"));
|
|
14
|
+
const storageScope = JSON.stringify([accountId]), key = [appId, profileId, storageScope];
|
|
15
|
+
const accept = (value, sourceKey) => {
|
|
16
|
+
state = value;
|
|
17
|
+
if (!value || !names.includes("readBatches"))
|
|
18
|
+
return;
|
|
19
|
+
const owner = JSON.stringify(sourceKey), journal = transaction.objectStore("readBatches");
|
|
20
|
+
const active = journal.get([owner, "active"]);
|
|
21
|
+
active.onsuccess = () => {
|
|
22
|
+
if (!active.result?.active)
|
|
23
|
+
return;
|
|
24
|
+
const progress = active.result.active;
|
|
25
|
+
if (typeof progress.id !== "string" || !Number.isSafeInteger(progress.total) || progress.total < 1 || !Number.isSafeInteger(progress.next) || progress.next < 0 || progress.next > progress.total) {
|
|
26
|
+
transaction.abort();
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const plan = journal.get([owner, `${progress.id}:plan`]);
|
|
30
|
+
plan.onsuccess = () => {
|
|
31
|
+
if (!plan.result?.plan?.header || JSON.stringify(plan.result.plan.profileKey) !== JSON.stringify(sourceKey)) {
|
|
32
|
+
transaction.abort();
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
state = plan.result.plan.header;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const scoped = store.get(key);
|
|
40
|
+
scoped.onsuccess = () => {
|
|
41
|
+
if (scoped.result) {
|
|
42
|
+
accept(scoped.result, key);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const marker = store.get([appId, profileId, "legacy-owner-v1"]);
|
|
46
|
+
marker.onsuccess = () => {
|
|
47
|
+
// An unscoped legacy record is usable only with its existing account claim.
|
|
48
|
+
if (marker.result?.legacyOwner !== storageScope)
|
|
49
|
+
return;
|
|
50
|
+
const legacy = store.get([appId, profileId]);
|
|
51
|
+
legacy.onsuccess = () => accept(legacy.result, [appId, profileId]);
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/** Pending operations preserve their server idempotency keys. Unresolved
|
|
57
|
+
* observations remain durable Thread facts until a source message arrives. */
|
|
58
|
+
export async function migrateLegacyReading(owner, options = {}) {
|
|
59
|
+
if (owner.current.localMigrations?.includes(migration))
|
|
60
|
+
return false;
|
|
61
|
+
const database = await openLegacyDatabase(options.indexedDB ?? globalThis.indexedDB, options.name ?? "pmate-social-read-index");
|
|
62
|
+
let state;
|
|
63
|
+
if (database) {
|
|
64
|
+
try {
|
|
65
|
+
state = await capture(database, owner.identity.appId, owner.identity.profileId, owner.identity.accountId);
|
|
66
|
+
}
|
|
67
|
+
finally {
|
|
68
|
+
database.close();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
const operations = [];
|
|
72
|
+
if (state) {
|
|
73
|
+
if (state.schemaVersion !== 1 || state.appId !== owner.identity.appId || state.profileId !== owner.identity.profileId || !Array.isArray(state.pending))
|
|
74
|
+
throw Error("LEGACY_READING_IDENTITY_MISMATCH");
|
|
75
|
+
for (const operation of state.pending) {
|
|
76
|
+
if (!operation.operationId || !operation.threadId || !Number.isSafeInteger(operation.readThroughSeq) || operation.readThroughSeq < 0 ||
|
|
77
|
+
!Array.isArray(operation.explicitReadMessageIds) || operation.explicitReadMessageIds.some(id => typeof id !== "string" || !id))
|
|
78
|
+
throw Error("INVALID_LEGACY_READING_COMMAND");
|
|
79
|
+
if (owner.memory.getThread(operation.threadId)?.status === "unavailable")
|
|
80
|
+
continue;
|
|
81
|
+
operations.push({ type: "restoreReadingCommand", command: { commandId: operation.operationId, kind: operation.explicitReadMessageIds.length ? "played" : "reading",
|
|
82
|
+
threadId: operation.threadId, createdAt: Date.now(), payload: { ...operation, appId: owner.identity.appId, profileId: owner.identity.profileId }, state: "pending", attempts: 0 } });
|
|
83
|
+
}
|
|
84
|
+
for (const intent of state.observedReadIntents ?? []) {
|
|
85
|
+
if (!intent.operationId || !intent.threadId || !intent.messageId || !["visible", "explicit"].includes(intent.readPolicy))
|
|
86
|
+
throw Error("INVALID_LEGACY_READING_INTENT");
|
|
87
|
+
if (owner.memory.getThread(intent.threadId)?.status === "unavailable")
|
|
88
|
+
continue;
|
|
89
|
+
operations.push({ type: "restoreReadingIntent", threadId: intent.threadId, messageId: intent.messageId, commandId: intent.operationId,
|
|
90
|
+
policy: intent.readPolicy === "explicit" ? "played" : "visible", createdAt: Date.now() });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
let pending = [], bytes = 0;
|
|
94
|
+
const flush = async () => { if (pending.length) {
|
|
95
|
+
owner.flush();
|
|
96
|
+
await Promise.all(pending);
|
|
97
|
+
pending = [];
|
|
98
|
+
bytes = 0;
|
|
99
|
+
} };
|
|
100
|
+
for (const operation of operations) {
|
|
101
|
+
const size = new TextEncoder().encode(JSON.stringify(operation)).byteLength;
|
|
102
|
+
if (pending.length && (pending.length >= 200 || bytes + size > 512 * 1024))
|
|
103
|
+
await flush();
|
|
104
|
+
pending.push(owner.enqueue(operation, size));
|
|
105
|
+
bytes += size;
|
|
106
|
+
}
|
|
107
|
+
await flush();
|
|
108
|
+
await owner.enqueue({ type: "migrationCompleted", id: migration }, 100, true);
|
|
109
|
+
return Boolean(state);
|
|
110
|
+
}
|
|
@@ -30,6 +30,7 @@ export declare class ProfileMemoryStore {
|
|
|
30
30
|
private directories;
|
|
31
31
|
private listeners;
|
|
32
32
|
private listListeners;
|
|
33
|
+
private messageListeners;
|
|
33
34
|
private list;
|
|
34
35
|
private pageCache;
|
|
35
36
|
private epochs;
|
|
@@ -102,6 +103,7 @@ export declare class ProfileMemoryStore {
|
|
|
102
103
|
}> | undefined;
|
|
103
104
|
getThreadList: () => readonly ProfileThread[];
|
|
104
105
|
subscribeThreadList: (listener: () => void) => () => void;
|
|
106
|
+
subscribeMessages(listener: (messages: readonly ProfileMessage[]) => void): () => void;
|
|
105
107
|
subscribeThread(threadId: string, listener: () => void): () => void;
|
|
106
108
|
restore(snapshot: ProfileSnapshot): void;
|
|
107
109
|
apply(delta: ProfileDelta): void;
|
|
@@ -14,6 +14,7 @@ export class ProfileMemoryStore {
|
|
|
14
14
|
directories = new Map();
|
|
15
15
|
listeners = new Map();
|
|
16
16
|
listListeners = new Set();
|
|
17
|
+
messageListeners = new Set();
|
|
17
18
|
list = [];
|
|
18
19
|
pageCache = new Map();
|
|
19
20
|
epochs = new Map();
|
|
@@ -40,6 +41,7 @@ export class ProfileMemoryStore {
|
|
|
40
41
|
getPresentedMessage(messageId) { return this.presented.get(messageId); }
|
|
41
42
|
getThreadList = () => this.list;
|
|
42
43
|
subscribeThreadList = (listener) => { this.listListeners.add(listener); return () => { this.listListeners.delete(listener); }; };
|
|
44
|
+
subscribeMessages(listener) { this.messageListeners.add(listener); return () => { this.messageListeners.delete(listener); }; }
|
|
43
45
|
subscribeThread(threadId, listener) {
|
|
44
46
|
let listeners = this.listeners.get(threadId);
|
|
45
47
|
if (!listeners) {
|
|
@@ -119,6 +121,7 @@ export class ProfileMemoryStore {
|
|
|
119
121
|
}
|
|
120
122
|
}
|
|
121
123
|
const affected = new Set(delta.threads.map(row => row.threadId));
|
|
124
|
+
const added = delta.messages.filter(row => !this.entities.has(row.messageId));
|
|
122
125
|
const previousThreads = new Map(delta.threads.map(row => [row.threadId, this.threads.get(row.threadId)]));
|
|
123
126
|
for (const message of delta.messages) {
|
|
124
127
|
const previous = this.entities.get(message.messageId);
|
|
@@ -183,6 +186,9 @@ export class ProfileMemoryStore {
|
|
|
183
186
|
}
|
|
184
187
|
}
|
|
185
188
|
this.publish(affected, delta.threads.length > 0);
|
|
189
|
+
if (added.length)
|
|
190
|
+
for (const listener of this.messageListeners)
|
|
191
|
+
this.notify(() => listener(added));
|
|
186
192
|
}
|
|
187
193
|
indexMessage(message) {
|
|
188
194
|
const index = this.readingIndices.get(message.threadId) ?? new ProfileReadingIndex();
|
|
@@ -49,6 +49,8 @@ export class ProfileOutboxDispatcher {
|
|
|
49
49
|
// Refresh from committed memory after each ACK so work accepted during a
|
|
50
50
|
// network wait is picked up without waiting for another ten-second tick.
|
|
51
51
|
while (!this.closed && owner.active) {
|
|
52
|
+
if (owner.memory.getStatus().phase !== "ready")
|
|
53
|
+
return;
|
|
52
54
|
const command = owner.commands().sort((a, b) => a.createdAt - b.createdAt || a.commandId.localeCompare(b.commandId))[0];
|
|
53
55
|
if (!command)
|
|
54
56
|
return;
|
|
@@ -27,6 +27,7 @@ export declare class ProfileOwner {
|
|
|
27
27
|
private closed;
|
|
28
28
|
private committedListeners;
|
|
29
29
|
private synchronizer;
|
|
30
|
+
private credentialUpdater;
|
|
30
31
|
private constructor();
|
|
31
32
|
static open(options: ProfileOwnerOptions): Promise<ProfileOwner>;
|
|
32
33
|
get current(): import("./profileStoreTypes.js").ProfileCurrentState;
|
|
@@ -40,15 +41,18 @@ export declare class ProfileOwner {
|
|
|
40
41
|
commands(): import("./profileStoreTypes.js").ProfileOutboxCommand[];
|
|
41
42
|
subscribeCommitted(listener: (delta: ProfileDelta) => void): () => void;
|
|
42
43
|
setSynchronizer(synchronize: () => Promise<void>): void;
|
|
44
|
+
setCredentialUpdater(update: (token: string) => void): void;
|
|
45
|
+
updateCredentials(token: string): void;
|
|
43
46
|
synchronize(): Promise<void>;
|
|
44
47
|
waitForCommand(commandId: string, signal: AbortSignal): Promise<void>;
|
|
45
48
|
enqueue(event: ProfileOperation, bytes: number, immediate?: boolean): Promise<void>;
|
|
46
49
|
flush(): void;
|
|
47
|
-
beginGeneration(bootstrap: InboxBootstrap, generation?:
|
|
50
|
+
beginGeneration(bootstrap: InboxBootstrap, generation?: string): Promise<string>;
|
|
48
51
|
appendGeneration(generation: string, events: ProfileOperation[]): Promise<void>;
|
|
49
52
|
generationProgress(generation: string): Promise<ProfileGenerationState>;
|
|
50
53
|
pendingGenerations(): Promise<ProfileGenerationState[]>;
|
|
51
54
|
activateGeneration(generation: string): Promise<void>;
|
|
55
|
+
private materializeReadingIntents;
|
|
52
56
|
private report;
|
|
53
57
|
private renew;
|
|
54
58
|
private notify;
|
|
@@ -17,6 +17,7 @@ export class ProfileOwner {
|
|
|
17
17
|
closed = false;
|
|
18
18
|
committedListeners = new Set();
|
|
19
19
|
synchronizer = () => Promise.resolve();
|
|
20
|
+
credentialUpdater = () => { throw Error("PROFILE_NETWORK_UNAVAILABLE"); };
|
|
20
21
|
constructor(options) {
|
|
21
22
|
this.options = options;
|
|
22
23
|
this.memory = new ProfileMemoryStore(options.onError, options.database.identity.profileId);
|
|
@@ -41,6 +42,7 @@ export class ProfileOwner {
|
|
|
41
42
|
owner.queue = new ProfileCommitQueue({ commit: events => owner.commit(events), windowMs: options.windowMs,
|
|
42
43
|
retryMs: options.retryMs, onError: error => owner.report(error) });
|
|
43
44
|
owner.timer = setInterval(() => { void owner.renew(); }, 10000);
|
|
45
|
+
await owner.materializeReadingIntents();
|
|
44
46
|
return owner;
|
|
45
47
|
}
|
|
46
48
|
catch (error) {
|
|
@@ -56,6 +58,8 @@ export class ProfileOwner {
|
|
|
56
58
|
commands() { return [...this.projection.outbox.values()]; }
|
|
57
59
|
subscribeCommitted(listener) { this.committedListeners.add(listener); return () => { this.committedListeners.delete(listener); }; }
|
|
58
60
|
setSynchronizer(synchronize) { this.synchronizer = synchronize; }
|
|
61
|
+
setCredentialUpdater(update) { this.credentialUpdater = update; }
|
|
62
|
+
updateCredentials(token) { this.credentialUpdater(token); }
|
|
59
63
|
synchronize() { return this.synchronizer(); }
|
|
60
64
|
waitForCommand(commandId, signal) {
|
|
61
65
|
return new Promise((resolve, reject) => {
|
|
@@ -106,6 +110,26 @@ export class ProfileOwner {
|
|
|
106
110
|
if (this.closed || this.lost)
|
|
107
111
|
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
108
112
|
await this.queue.enqueue({ ownerType: "activate", generation }, 128, true, true);
|
|
113
|
+
await this.materializeReadingIntents();
|
|
114
|
+
}
|
|
115
|
+
async materializeReadingIntents() {
|
|
116
|
+
let pending = [];
|
|
117
|
+
const flush = async () => { if (pending.length) {
|
|
118
|
+
this.queue.flush();
|
|
119
|
+
await Promise.all(pending);
|
|
120
|
+
pending = [];
|
|
121
|
+
} };
|
|
122
|
+
for (const thread of this.projection.threads.values())
|
|
123
|
+
for (const [messageId, intents] of Object.entries(thread.internal?.pendingReadingIntents ?? {})) {
|
|
124
|
+
if (!this.projection.messages.get(messageId)?.sourceSeq)
|
|
125
|
+
continue;
|
|
126
|
+
for (const intent of intents) {
|
|
127
|
+
if (pending.length >= 200)
|
|
128
|
+
await flush();
|
|
129
|
+
pending.push(this.enqueue({ type: "restoreReadingIntent", threadId: thread.threadId, messageId, ...intent }, 256));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
await flush();
|
|
109
133
|
}
|
|
110
134
|
report(error) {
|
|
111
135
|
if (error?.message === "PROFILE_WRITER_FENCED")
|
|
@@ -172,7 +196,7 @@ export class ProfileOwner {
|
|
|
172
196
|
const prepared = this.projection.prepare(events);
|
|
173
197
|
const committed = await this.options.database.commit({ ...prepared, ownerId: this.lease.ownerId, fence: this.lease.fence,
|
|
174
198
|
generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
|
|
175
|
-
committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady });
|
|
199
|
+
committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations });
|
|
176
200
|
if (committed.commitRevision === fromRevision)
|
|
177
201
|
return;
|
|
178
202
|
prepared.current = committed;
|
|
@@ -6,6 +6,24 @@ import type { ProfileCurrentState, ProfileIdentity, ProfileMessage, ProfileOutbo
|
|
|
6
6
|
import type { ChatRuntimeMessage } from "./protocol.js";
|
|
7
7
|
export declare const profileDiscussionId: (parent: string, root: string) => string;
|
|
8
8
|
export type ProfileLocalOperation = {
|
|
9
|
+
type: "migrationCompleted";
|
|
10
|
+
id: string;
|
|
11
|
+
} | {
|
|
12
|
+
type: "restoreReadingCommand";
|
|
13
|
+
command: ProfileOutboxCommand;
|
|
14
|
+
} | {
|
|
15
|
+
type: "restoreReadingIntent";
|
|
16
|
+
threadId: string;
|
|
17
|
+
messageId: string;
|
|
18
|
+
commandId: string;
|
|
19
|
+
policy: "visible" | "played";
|
|
20
|
+
createdAt: number;
|
|
21
|
+
defer?: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
type: "restoreEvent";
|
|
24
|
+
event: InboxEvent;
|
|
25
|
+
recalled?: boolean;
|
|
26
|
+
} | {
|
|
9
27
|
type: "register";
|
|
10
28
|
threadId: string;
|
|
11
29
|
kind: "group" | "dm";
|
|
@@ -21,6 +39,7 @@ export type ProfileLocalOperation = {
|
|
|
21
39
|
parentThreadId?: string;
|
|
22
40
|
message: ChatRuntimeMessage;
|
|
23
41
|
command: ProfileOutboxCommand;
|
|
42
|
+
preserveWire?: boolean;
|
|
24
43
|
} | {
|
|
25
44
|
type: "commandPayload";
|
|
26
45
|
commandId: string;
|
|
@@ -29,6 +48,7 @@ export type ProfileLocalOperation = {
|
|
|
29
48
|
type: "observe";
|
|
30
49
|
threadId: string;
|
|
31
50
|
messageIds: string[];
|
|
51
|
+
allVisible?: boolean;
|
|
32
52
|
policy: "visible" | "played";
|
|
33
53
|
commandId: string;
|
|
34
54
|
createdAt: number;
|
|
@@ -117,6 +117,7 @@ class ProfileProjectionDraft {
|
|
|
117
117
|
seq;
|
|
118
118
|
revision;
|
|
119
119
|
receiptsReady;
|
|
120
|
+
localMigrations;
|
|
120
121
|
constructor(base) {
|
|
121
122
|
this.base = base;
|
|
122
123
|
this.seq = inboxSequence(base.current.committedSeq);
|
|
@@ -285,6 +286,30 @@ class ProfileProjectionDraft {
|
|
|
285
286
|
this.seq = seq;
|
|
286
287
|
}
|
|
287
288
|
local(operation) {
|
|
289
|
+
if (operation.type === "restoreReadingCommand") {
|
|
290
|
+
const command = operation.command, data = command.payload;
|
|
291
|
+
if (!["reading", "played"].includes(command.kind) || !command.commandId || data.appId !== this.base.identity.appId || data.profileId !== this.base.identity.profileId)
|
|
292
|
+
throw Error("INVALID_READING_COMMAND");
|
|
293
|
+
this.reading({ inboxSeq: "0", sourceId: command.commandId, acceptedAt: command.createdAt, kind: "readingUpdated", fact: data }, false);
|
|
294
|
+
if (!this.outbox.has(command.commandId) && !this.base.outbox.has(command.commandId))
|
|
295
|
+
this.outbox.set(command.commandId, command);
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
if (operation.type === "restoreReadingIntent") {
|
|
299
|
+
this.restoreReadingIntent(operation);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (operation.type === "migrationCompleted") {
|
|
303
|
+
this.localMigrations = [...new Set([...(this.localMigrations ?? this.base.current.localMigrations ?? []), operation.id])];
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (operation.type === "restoreEvent") {
|
|
307
|
+
this.event(operation.event, true);
|
|
308
|
+
const message = operation.recalled && this.message(operation.event.fact.messageId);
|
|
309
|
+
if (message && !message.recalled)
|
|
310
|
+
this.setMessage({ ...message, recalled: true });
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
288
313
|
if (operation.type === "commandPayload") {
|
|
289
314
|
const command = this.outbox.get(operation.commandId) ?? this.base.outbox.get(operation.commandId);
|
|
290
315
|
if (!command || command.kind !== "message" || operation.message.hash !== command.messageId || operation.message.from !== this.base.identity.profileId)
|
|
@@ -350,7 +375,7 @@ class ProfileProjectionDraft {
|
|
|
350
375
|
const reaction = body?.kind === "message" ? body.content?.reaction : undefined;
|
|
351
376
|
const recall = body?.kind === "recall" ? body.targetMessageId : body?.content?.recall?.messageId;
|
|
352
377
|
if (reaction || recall || body?.kind === "group") {
|
|
353
|
-
if (reaction) {
|
|
378
|
+
if (reaction && !operation.preserveWire) {
|
|
354
379
|
const target = this.message(reaction.messageId), key = JSON.stringify(["reaction", wire.from, reaction.emojiId]);
|
|
355
380
|
const previous = target?.controlVersions[key];
|
|
356
381
|
const floor = typeof previous === "string" ? JSON.parse(previous)[0] : 0;
|
|
@@ -368,7 +393,7 @@ class ProfileProjectionDraft {
|
|
|
368
393
|
const message = { generation: this.base.current.activeGeneration, messageId: wire.hash,
|
|
369
394
|
sourceThreadId: thread.parentThreadId ?? thread.threadId, threadId: thread.threadId,
|
|
370
395
|
orderKey: [wire.t, thread.parentThreadId ?? thread.threadId, Number.MAX_SAFE_INTEGER, wire.hash], from: wire.from,
|
|
371
|
-
recipients: wire.recipients, content: wire.body, attachmentRefs: [], reactions: [], sendStatus: "sending",
|
|
396
|
+
recipients: wire.recipients, content: wire.body, attachmentRefs: [], reactions: [], sendStatus: command.state === "failed" ? "failed" : "sending",
|
|
372
397
|
readPolicy: messageRequiresPlayback(wire.body) ? "explicit" : "visible", readBy: [], receiptStatus: "unknown",
|
|
373
398
|
explicitReadingFacts: [], controlVersions: {}, revision: this.revision };
|
|
374
399
|
message.presentation = projectMessageContent({ id: wire.hash, messageId: wire.hash, threadId: thread.threadId,
|
|
@@ -396,7 +421,9 @@ class ProfileProjectionDraft {
|
|
|
396
421
|
if (!thread || thread.status !== "ready")
|
|
397
422
|
throw Error("PROFILE_THREAD_NOT_READY");
|
|
398
423
|
const grouped = new Map();
|
|
399
|
-
|
|
424
|
+
const ids = operation.allVisible && operation.policy === "visible"
|
|
425
|
+
? this.readingIndex(thread.threadId).latestVisible().map(ref => ref.messageId) : operation.messageIds;
|
|
426
|
+
for (const id of new Set(ids)) {
|
|
400
427
|
const message = this.message(id);
|
|
401
428
|
if (!message || message.threadId !== thread.threadId || message.readPolicy === "discussion" || this.read(message))
|
|
402
429
|
continue;
|
|
@@ -483,6 +510,43 @@ class ProfileProjectionDraft {
|
|
|
483
510
|
const saved = entry;
|
|
484
511
|
this.control(parent.threadId, saved.wire, saved.reaction, saved.recall);
|
|
485
512
|
}
|
|
513
|
+
for (const origin of new Set([source.threadId, parent.threadId])) {
|
|
514
|
+
const intents = this.thread(origin)?.internal?.pendingReadingIntents?.[wire.messageId] ?? [];
|
|
515
|
+
for (const intent of intents)
|
|
516
|
+
this.restoreReadingIntent({ type: "restoreReadingIntent", threadId: origin, messageId: wire.messageId, ...intent });
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
restoreReadingIntent(operation) {
|
|
520
|
+
const source = this.ensure(operation.threadId), message = this.message(operation.messageId);
|
|
521
|
+
const thread = message && this.thread(message.threadId);
|
|
522
|
+
const canonical = source.internal?.assignments?.[source.threadId] ?? source.threadId;
|
|
523
|
+
const known = message && message.sourceSeq && (message.sourceThreadId === source.threadId || (thread?.parentThreadId ?? thread?.threadId) === canonical);
|
|
524
|
+
const intents = { ...source.internal?.pendingReadingIntents }, previous = intents[operation.messageId] ?? [];
|
|
525
|
+
if (!known || operation.defer) {
|
|
526
|
+
if (!previous.some(intent => intent.commandId === operation.commandId)) {
|
|
527
|
+
intents[operation.messageId] = [...previous, { commandId: operation.commandId, policy: operation.policy, createdAt: operation.createdAt }];
|
|
528
|
+
this.putThread({ ...source, internal: { ...source.internal, pendingReadingIntents: intents } });
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
else if (previous.some(intent => intent.commandId === operation.commandId)) {
|
|
532
|
+
const remaining = previous.filter(intent => intent.commandId !== operation.commandId);
|
|
533
|
+
if (remaining.length)
|
|
534
|
+
intents[operation.messageId] = remaining;
|
|
535
|
+
else
|
|
536
|
+
delete intents[operation.messageId];
|
|
537
|
+
this.putThread({ ...source, internal: { ...source.internal, pendingReadingIntents: intents } });
|
|
538
|
+
}
|
|
539
|
+
if (!known || message.from === this.base.identity.profileId || message.recalled || message.readPolicy === "discussion" ||
|
|
540
|
+
(operation.policy === "played") !== (message.readPolicy === "explicit"))
|
|
541
|
+
return;
|
|
542
|
+
const values = operation.policy === "played" ? { readThroughSeq: 0, explicitReadMessageIds: [message.messageId] }
|
|
543
|
+
: { readThroughSeq: message.sourceSeq, readThroughMessageId: message.messageId, explicitReadMessageIds: [] };
|
|
544
|
+
const fact = eventForLocalReading(this.base.identity, message.sourceThreadId, thread?.rootMessageId, values).fact;
|
|
545
|
+
if (operation.defer)
|
|
546
|
+
this.reading({ inboxSeq: "0", sourceId: operation.commandId, acceptedAt: operation.createdAt, kind: "readingUpdated", fact }, false);
|
|
547
|
+
else
|
|
548
|
+
this.local({ type: "restoreReadingCommand", command: { commandId: operation.commandId, kind: operation.policy === "played" ? "played" : "reading",
|
|
549
|
+
threadId: message.threadId, createdAt: operation.createdAt, payload: fact, state: "pending", attempts: 0 } });
|
|
486
550
|
}
|
|
487
551
|
control(threadId, wire, reaction, recall) {
|
|
488
552
|
const targetId = recall ?? reaction?.messageId;
|
|
@@ -522,7 +586,10 @@ class ProfileProjectionDraft {
|
|
|
522
586
|
reading(event, confirmed = true) {
|
|
523
587
|
const data = event.fact;
|
|
524
588
|
if (data.receiptOnly === true) {
|
|
525
|
-
const receipt = validateInboxReceipt(data, this.base.identity.profileId);
|
|
589
|
+
const receipt = validateInboxReceipt(data.receipt, this.base.identity.profileId);
|
|
590
|
+
if (data.appId !== this.base.identity.appId || data.profileId !== this.base.identity.profileId || data.threadId !== receipt.threadId ||
|
|
591
|
+
data.readThroughSeq !== 0 || !Array.isArray(data.explicitReadMessageIds) || data.explicitReadMessageIds.length || data.threadRootId !== undefined)
|
|
592
|
+
throw Error("INVALID_INBOX_RECEIPT_ENVELOPE");
|
|
526
593
|
for (const id of receipt.messageIds) {
|
|
527
594
|
const message = this.message(id);
|
|
528
595
|
if (message && message.from !== this.base.identity.profileId)
|
|
@@ -541,8 +608,9 @@ class ProfileProjectionDraft {
|
|
|
541
608
|
}
|
|
542
609
|
if (data.profileId !== this.base.identity.profileId || !data.threadId || !Number.isSafeInteger(data.readThroughSeq) || data.readThroughSeq < 0 || !Array.isArray(data.explicitReadMessageIds))
|
|
543
610
|
throw Error("INVALID_INBOX_READING");
|
|
544
|
-
const
|
|
545
|
-
const
|
|
611
|
+
const canonical = this.thread(data.threadId)?.internal?.assignments?.[data.threadId] ?? data.threadId;
|
|
612
|
+
const id = data.threadRootId ? profileDiscussionId(canonical, data.threadRootId) : canonical;
|
|
613
|
+
const thread = this.ensure(id, data.threadRootId ? "discussion" : "group", data.threadRootId ? { parentThreadId: canonical, rootMessageId: data.threadRootId } : {});
|
|
546
614
|
if (thread.parentThreadId)
|
|
547
615
|
this.ensure(thread.parentThreadId);
|
|
548
616
|
const sourceId = data.threadId, previous = this.source(thread, sourceId);
|
|
@@ -614,7 +682,8 @@ class ProfileProjectionDraft {
|
|
|
614
682
|
this.ensure(data.threadId, "dm", { teamId: data.teamId });
|
|
615
683
|
}
|
|
616
684
|
finish() {
|
|
617
|
-
return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady
|
|
685
|
+
return { current: { ...this.base.current, committedSeq: this.seq.toString(), commitRevision: this.revision, receiptsReady: this.receiptsReady,
|
|
686
|
+
localMigrations: this.localMigrations ?? this.base.current.localMigrations },
|
|
618
687
|
threads: [...this.threads.values()], windows: [...this.windows.values()], messages: [...this.messages.values()], readingIndices: this.readingIndices,
|
|
619
688
|
outbox: [...this.outbox.values()].filter(command => !this.deleteOutbox.has(command.commandId)), deleteOutbox: [...this.deleteOutbox] };
|
|
620
689
|
}
|
|
@@ -13,5 +13,6 @@ export declare class ProfileReadingIndex {
|
|
|
13
13
|
upsert(message: ProfileMessage, profileId: string, source?: ProfileReadingSource): void;
|
|
14
14
|
summary(positions: readonly ProfileReadingSource[]): Summary;
|
|
15
15
|
visibleBetween(sourceId: string, low: number, high: number): ProfileMessageRef[];
|
|
16
|
+
latestVisible(): ProfileMessageRef[];
|
|
16
17
|
}
|
|
17
18
|
export {};
|
|
@@ -64,6 +64,13 @@ function between(root, low, high, result) {
|
|
|
64
64
|
if (root.seq <= high)
|
|
65
65
|
between(root.right, low, high, result);
|
|
66
66
|
}
|
|
67
|
+
function lastVisible(root) {
|
|
68
|
+
if (!root?.visible.unread)
|
|
69
|
+
return;
|
|
70
|
+
if (root.right?.visible.unread)
|
|
71
|
+
return lastVisible(root.right);
|
|
72
|
+
return root.explicit ? lastVisible(root.left) : root.ref;
|
|
73
|
+
}
|
|
67
74
|
/** Persistent per-source range trees. Cursor advances aggregate whole ranges;
|
|
68
75
|
* they neither scan history nor rewrite a read flag on each Message. */
|
|
69
76
|
export class ProfileReadingIndex {
|
|
@@ -96,4 +103,13 @@ export class ProfileReadingIndex {
|
|
|
96
103
|
between(this.sources.get(sourceId), low, high, result);
|
|
97
104
|
return result;
|
|
98
105
|
}
|
|
106
|
+
latestVisible() {
|
|
107
|
+
const result = [];
|
|
108
|
+
for (const root of this.sources.values()) {
|
|
109
|
+
const ref = lastVisible(root);
|
|
110
|
+
if (ref)
|
|
111
|
+
result.push(ref);
|
|
112
|
+
}
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
99
115
|
}
|
|
@@ -47,6 +47,7 @@ export declare class ProfileReplica {
|
|
|
47
47
|
repair(): Promise<void>;
|
|
48
48
|
submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
|
|
49
49
|
synchronize(): Promise<void>;
|
|
50
|
+
updateCredentials(token: string): Promise<void>;
|
|
50
51
|
waitForCommand(commandId: string): Promise<void>;
|
|
51
52
|
voiceAttachment(messageId: string): Promise<Blob | null>;
|
|
52
53
|
getStatus(): {
|
|
@@ -62,6 +62,12 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
|
|
|
62
62
|
await owner.synchronize();
|
|
63
63
|
result = null;
|
|
64
64
|
}
|
|
65
|
+
else if (request.action === "credentials") {
|
|
66
|
+
if (typeof request.token !== "string" || !request.token || request.token.length > 65536)
|
|
67
|
+
throw Error("INVALID_PROFILE_CREDENTIALS");
|
|
68
|
+
owner.updateCredentials(request.token);
|
|
69
|
+
result = null;
|
|
70
|
+
}
|
|
65
71
|
else if (request.action === "waitCommand") {
|
|
66
72
|
if (typeof request.commandId !== "string" || !request.commandId)
|
|
67
73
|
throw Error("INVALID_PROFILE_COMMAND");
|
|
@@ -220,6 +226,7 @@ export class ProfileReplica {
|
|
|
220
226
|
return this.request("operation", { operation, bytes: new TextEncoder().encode(JSON.stringify(operation)).byteLength + binaryBytes, immediate });
|
|
221
227
|
}
|
|
222
228
|
synchronize() { return this.request("synchronize"); }
|
|
229
|
+
updateCredentials(token) { return this.request("credentials", { token }); }
|
|
223
230
|
waitForCommand(commandId) { return this.request("waitCommand", { commandId }); }
|
|
224
231
|
voiceAttachment(messageId) { return this.request("voiceAttachment", { commandId: messageId }); }
|
|
225
232
|
getStatus() { return { ...this.memory.getStatus(), error: this.lastError }; }
|
|
@@ -48,6 +48,11 @@ export type ProfileThread = {
|
|
|
48
48
|
pendingControls?: Record<string, unknown[]>;
|
|
49
49
|
messageRoots?: Record<string, string>;
|
|
50
50
|
pendingReceipts?: Record<string, string[]>;
|
|
51
|
+
pendingReadingIntents?: Record<string, {
|
|
52
|
+
commandId: string;
|
|
53
|
+
policy: "visible" | "played";
|
|
54
|
+
createdAt: number;
|
|
55
|
+
}[]>;
|
|
51
56
|
participantCounts?: Record<string, number>;
|
|
52
57
|
};
|
|
53
58
|
};
|
|
@@ -113,6 +118,7 @@ export type ProfileCurrentState = {
|
|
|
113
118
|
projectionVersion: number;
|
|
114
119
|
commitRevision: number;
|
|
115
120
|
receiptsReady?: boolean;
|
|
121
|
+
localMigrations?: string[];
|
|
116
122
|
};
|
|
117
123
|
export type ProfileWriterLease = {
|
|
118
124
|
key: "lease";
|
|
@@ -153,6 +159,7 @@ export type ProfileWriteBatch = {
|
|
|
153
159
|
epoch: string;
|
|
154
160
|
committedSeq: string;
|
|
155
161
|
receiptsReady?: boolean;
|
|
162
|
+
localMigrations?: string[];
|
|
156
163
|
threads?: ProfileThread[];
|
|
157
164
|
windows?: ProfileWindow[];
|
|
158
165
|
messages?: ProfileMessage[];
|
|
@@ -5,6 +5,9 @@ import { PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
|
|
|
5
5
|
import { ProfileInboxFeed } from "./profileInboxFeed.js";
|
|
6
6
|
import { ProfileOutboxDispatcher } from "./profileOutboxDispatcher.js";
|
|
7
7
|
import { ChatClient } from "./chatClient.js";
|
|
8
|
+
import { migrateLegacyInbox } from "./profileLegacyInbox.js";
|
|
9
|
+
import { migrateLegacyOutbox } from "./profileLegacyOutbox.js";
|
|
10
|
+
import { migrateLegacyReading } from "./profileLegacyReading.js";
|
|
8
11
|
export const profileChannelName = (identity) => `pmate-profile:${JSON.stringify([identity.accountId, identity.appId, identity.profileId])}`;
|
|
9
12
|
/** Installs the SDK host in a Dedicated Worker, not on the rendering thread.
|
|
10
13
|
* Identity cannot change within a host; a Profile switch creates another host. */
|
|
@@ -62,10 +65,15 @@ export function installProfileWorker(port, options = {}) {
|
|
|
62
65
|
const report = (error) => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_NETWORK_FAILED" });
|
|
63
66
|
const endpoint = network.hubHttpUrl.replace(/\/$/, "").replace(/^ws/, "http");
|
|
64
67
|
const token = () => network.token;
|
|
68
|
+
owner.setCredentialUpdater(value => { network = { ...network, token: value }; });
|
|
65
69
|
connection = new ChatClient({ appId: config.identity.appId, profileId: config.identity.profileId,
|
|
66
70
|
hubUrl: endpoint.replace(/^http/, "ws"), fetchImpl: options.fetch, getToken: async () => token(),
|
|
67
71
|
session: { token: token(), identity: { accountId: config.identity.accountId, app: config.identity.appId, profileId: config.identity.profileId } } });
|
|
68
|
-
feed = new ProfileInboxFeed({ owner, hubHttpUrl: endpoint, getToken: token, fetch: options.fetch, onError: report,
|
|
72
|
+
feed = new ProfileInboxFeed({ owner, hubHttpUrl: endpoint, getToken: token, fetch: options.fetch, onError: report, prepare: async () => {
|
|
73
|
+
await migrateLegacyInbox(owner);
|
|
74
|
+
await migrateLegacyOutbox(owner);
|
|
75
|
+
await migrateLegacyReading(owner);
|
|
76
|
+
},
|
|
69
77
|
onProgress: progress => { const message = { profileControl: "progress", progress }; port.postMessage(message); channel?.postMessage(message); } });
|
|
70
78
|
owner.setSynchronizer(() => feed.synchronize());
|
|
71
79
|
dispatcher = new ProfileOutboxDispatcher({ owner, hubHttpUrl: endpoint, getToken: token, fetch: options.fetch,
|
package/package.json
CHANGED