@pmate/chat-sdk 0.13.0-profile.1 → 0.13.0-profile.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/lib/profile.d.ts +4 -1
- package/lib/profile.js +4 -1
- package/lib/runtime/profileChat.d.ts +118 -1
- package/lib/runtime/profileChat.js +98 -30
- package/lib/runtime/profileCommitQueue.d.ts +2 -1
- package/lib/runtime/profileCommitQueue.js +26 -7
- package/lib/runtime/profileCoordinator.d.ts +19 -19
- package/lib/runtime/profileCoordinator.js +127 -94
- package/lib/runtime/profileDatabase.d.ts +7 -7
- package/lib/runtime/profileDatabase.js +57 -42
- package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
- package/lib/runtime/profileGenerationBuilder.js +60 -26
- package/lib/runtime/profileInboxFeed.d.ts +1 -0
- package/lib/runtime/profileInboxFeed.js +12 -2
- package/lib/runtime/profileLegacyInbox.d.ts +8 -0
- package/lib/runtime/profileLegacyInbox.js +114 -0
- package/lib/runtime/profileLegacyOutbox.d.ts +7 -0
- package/lib/runtime/profileLegacyOutbox.js +106 -0
- package/lib/runtime/profileLegacyReading.d.ts +7 -0
- package/lib/runtime/profileLegacyReading.js +110 -0
- package/lib/runtime/profileMemoryStore.d.ts +22 -2
- package/lib/runtime/profileMemoryStore.js +140 -12
- package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
- package/lib/runtime/profileOutboxDispatcher.js +41 -5
- package/lib/runtime/profileOwner.d.ts +11 -6
- package/lib/runtime/profileOwner.js +71 -46
- package/lib/runtime/profileProjection.d.ts +54 -5
- package/lib/runtime/profileProjection.js +336 -51
- package/lib/runtime/profileReadingIndex.d.ts +1 -0
- package/lib/runtime/profileReadingIndex.js +17 -1
- package/lib/runtime/profileStoreTypes.d.ts +15 -9
- package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +10 -26
- package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +55 -102
- package/lib/runtime/profileWorkerHost.d.ts +4 -6
- package/lib/runtime/profileWorkerHost.js +58 -21
- package/package.json +2 -2
|
@@ -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. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
1
2
|
import { inboxSequence } from "./inboxStore.js";
|
|
2
3
|
/** The existing Inbox HTTP/live protocol, with no raw event cache. Each page is
|
|
3
4
|
* backpressured by durable owner commits; long requests never hold its queue. */
|
|
@@ -27,6 +28,8 @@ export class ProfileInboxFeed {
|
|
|
27
28
|
catch { }
|
|
28
29
|
}
|
|
29
30
|
async request(action, params = {}) {
|
|
31
|
+
if (!this.options.owner.active)
|
|
32
|
+
throw Error("PROFILE_OWNER_UNAVAILABLE");
|
|
30
33
|
const identity = this.options.owner.identity;
|
|
31
34
|
const query = new URLSearchParams({ appId: identity.appId, profileId: identity.profileId, ...params });
|
|
32
35
|
const response = await (this.options.fetch ?? fetch)(`${this.options.hubHttpUrl.replace(/\/$/, "")}/api/social/inbox/${action}?${query}`, {
|
|
@@ -46,6 +49,8 @@ export class ProfileInboxFeed {
|
|
|
46
49
|
synchronize() {
|
|
47
50
|
if (this.closed)
|
|
48
51
|
return Promise.reject(Error("INBOX_CLIENT_CLOSED"));
|
|
52
|
+
if (!this.options.owner.active)
|
|
53
|
+
return Promise.reject(Error("PROFILE_OWNER_UNAVAILABLE"));
|
|
49
54
|
if (this.running)
|
|
50
55
|
return this.running;
|
|
51
56
|
const task = this.catchUp().catch(error => { this.progress("error"); throw error; });
|
|
@@ -110,7 +115,7 @@ export class ProfileInboxFeed {
|
|
|
110
115
|
}
|
|
111
116
|
async rebuild() {
|
|
112
117
|
const bootstrap = await this.request("bootstrap");
|
|
113
|
-
const pending = (await this.options.owner.pendingGenerations()).find(build => build.epoch === bootstrap.epoch);
|
|
118
|
+
const pending = (await this.options.owner.pendingGenerations()).find(build => build.epoch === bootstrap.epoch && build.projectionVersion === PROFILE_PROJECTION_VERSION);
|
|
114
119
|
const generation = pending?.generation ?? await this.options.owner.beginGeneration(bootstrap);
|
|
115
120
|
const build = await this.options.owner.generationProgress(generation);
|
|
116
121
|
this.building = { generation, epoch: build.epoch, target: build.throughSeq ?? bootstrap.headSeq };
|
|
@@ -139,9 +144,10 @@ export class ProfileInboxFeed {
|
|
|
139
144
|
this.building = undefined;
|
|
140
145
|
}
|
|
141
146
|
async catchUp() {
|
|
147
|
+
await this.options.prepare?.();
|
|
142
148
|
if (this.building)
|
|
143
149
|
await this.resumeBuild();
|
|
144
|
-
if (this.options.owner.current.epoch === "uninitialized")
|
|
150
|
+
if (this.options.owner.current.epoch === "uninitialized" || this.options.owner.current.projectionVersion !== PROFILE_PROJECTION_VERSION)
|
|
145
151
|
await this.rebuild();
|
|
146
152
|
let current = this.options.owner.current;
|
|
147
153
|
let page = await this.request("check", { afterSeq: current.committedSeq, epoch: current.epoch });
|
|
@@ -172,6 +178,10 @@ export class ProfileInboxFeed {
|
|
|
172
178
|
async tick() {
|
|
173
179
|
if (this.closed)
|
|
174
180
|
return;
|
|
181
|
+
if (!this.options.owner.active) {
|
|
182
|
+
this.streamController?.abort();
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
175
185
|
await this.synchronize();
|
|
176
186
|
if (this.options.live === false || this.liveTask)
|
|
177
187
|
return;
|
|
@@ -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,114 @@
|
|
|
1
|
+
import { PROFILE_PROJECTION_VERSION } from "./profileMemoryStore.js";
|
|
2
|
+
import { inboxSequence } from "./inboxStore.js";
|
|
3
|
+
export async function openLegacyDatabase(factory, name) {
|
|
4
|
+
return new Promise((resolve, reject) => {
|
|
5
|
+
let fresh = false;
|
|
6
|
+
const request = factory.open(name);
|
|
7
|
+
request.onupgradeneeded = event => {
|
|
8
|
+
if (event.oldVersion === 0) {
|
|
9
|
+
fresh = true;
|
|
10
|
+
request.transaction.abort();
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
request.onerror = event => { event.preventDefault(); fresh ? resolve(undefined) : reject(request.error); };
|
|
14
|
+
request.onsuccess = () => resolve(request.result);
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
async function capture(database, owner) {
|
|
18
|
+
const names = ["cursors", "messages", "facts", "positions", "explicit", "receipts", "projections"].filter(name => database.objectStoreNames.contains(name));
|
|
19
|
+
if (!names.includes("cursors"))
|
|
20
|
+
return { messages: [], facts: [], positions: [], explicit: [], receipts: [], projections: [] };
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
const transaction = database.transaction(names, "readonly");
|
|
23
|
+
const result = {};
|
|
24
|
+
transaction.oncomplete = () => resolve({ messages: [], facts: [], positions: [], explicit: [], receipts: [], projections: [], ...result });
|
|
25
|
+
transaction.onerror = () => reject(transaction.error);
|
|
26
|
+
transaction.onabort = () => reject(transaction.error ?? Error("LEGACY_INBOX_CAPTURE_ABORTED"));
|
|
27
|
+
for (const name of names) {
|
|
28
|
+
const store = transaction.objectStore(name);
|
|
29
|
+
const request = name === "cursors" ? store.get(owner) : store.index("owner").getAll(IDBKeyRange.only(owner));
|
|
30
|
+
request.onsuccess = () => { result[name === "cursors" ? "cursor" : name] = request.result; };
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** One-time materialization migration. Source data is read consistently and
|
|
35
|
+
* retained; the old cursor becomes active only with the complete new view. */
|
|
36
|
+
export async function migrateLegacyInbox(owner, options = {}) {
|
|
37
|
+
if (owner.current.epoch !== "uninitialized")
|
|
38
|
+
return false;
|
|
39
|
+
const database = await openLegacyDatabase(options.indexedDB ?? globalThis.indexedDB, options.name ?? "pmate-chat-inbox-v1");
|
|
40
|
+
if (!database)
|
|
41
|
+
return false;
|
|
42
|
+
const identity = owner.identity, key = JSON.stringify([identity.accountId, identity.appId, identity.profileId]);
|
|
43
|
+
let rows;
|
|
44
|
+
try {
|
|
45
|
+
rows = await capture(database, key);
|
|
46
|
+
}
|
|
47
|
+
finally {
|
|
48
|
+
database.close();
|
|
49
|
+
}
|
|
50
|
+
const cursor = rows.cursor;
|
|
51
|
+
if (!cursor?.initialized || !cursor.epoch)
|
|
52
|
+
return false;
|
|
53
|
+
const seq = inboxSequence(cursor.seq);
|
|
54
|
+
const generation = `legacy-inbox:v${PROFILE_PROJECTION_VERSION}:${JSON.stringify([cursor.epoch, cursor.seq])}`;
|
|
55
|
+
await owner.beginGeneration({ ...identity, epoch: cursor.epoch, startSeq: (seq + 1n).toString(), headSeq: cursor.seq,
|
|
56
|
+
windowStart: cursor.windowStart, basis: [] }, generation);
|
|
57
|
+
if ((await owner.generationProgress(generation)).status === "validated") {
|
|
58
|
+
await owner.activateGeneration(generation);
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
let pending = [], bytes = 0;
|
|
62
|
+
const flush = async () => { if (pending.length) {
|
|
63
|
+
await owner.appendGeneration(generation, pending);
|
|
64
|
+
pending = [];
|
|
65
|
+
bytes = 0;
|
|
66
|
+
} };
|
|
67
|
+
const push = async (operation) => {
|
|
68
|
+
const size = new TextEncoder().encode(JSON.stringify(operation)).byteLength;
|
|
69
|
+
if (pending.length && (pending.length >= 200 || bytes + size > 512 * 1024))
|
|
70
|
+
await flush();
|
|
71
|
+
pending.push(operation);
|
|
72
|
+
bytes += size;
|
|
73
|
+
};
|
|
74
|
+
const restore = (kind, fact, sourceId, acceptedAt = cursor.windowStart) => ({ type: "restoreEvent", event: { inboxSeq: "0", sourceId, acceptedAt, kind, fact: { appId: identity.appId, ...fact } } });
|
|
75
|
+
// Set readiness before importing messages: each new own message receives its
|
|
76
|
+
// already-known receipt status without a final whole-history rewrite.
|
|
77
|
+
const receiptsReady = rows.projections.some(row => row.name === "receipts" && row.epoch === cursor.epoch && row.status === "ready" && inboxSequence(row.appliedInboxSeq) >= seq);
|
|
78
|
+
if (receiptsReady)
|
|
79
|
+
await push({ type: "receiptsReady" });
|
|
80
|
+
for (const row of rows.facts)
|
|
81
|
+
if (row.kind === "groupControl")
|
|
82
|
+
await push(restore("messageAdded", row.value, row.id));
|
|
83
|
+
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));
|
|
84
|
+
for (const row of rows.messages) {
|
|
85
|
+
if (!row.value.seq) {
|
|
86
|
+
const body = row.value.body;
|
|
87
|
+
if (body?.kind === "contact" && body.action === "friendRequest")
|
|
88
|
+
await push({ type: "restoreInvitation", message: row.value, acceptedAt: row.acceptedAt, recalled: row.recalled });
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const body = row.value.body;
|
|
92
|
+
const value = row.root ? { ...row.value, body: { ...body, content: { ...body?.content, threadRootId: row.root } } } : row.value;
|
|
93
|
+
await push({ ...restore("messageAdded", { ...value, sourceAcceptedAt: row.acceptedAt }, row.id, row.acceptedAt), recalled: row.recalled });
|
|
94
|
+
}
|
|
95
|
+
for (const row of rows.positions)
|
|
96
|
+
await push(restore("readingUpdated", { profileId: identity.profileId, threadId: row.thread,
|
|
97
|
+
...(row.root ? { threadRootId: row.root } : {}), readThroughSeq: row.seq, readThroughMessageId: row.messageId, explicitReadMessageIds: [] }, `position:${row.thread}:${row.root}`));
|
|
98
|
+
const roots = new Map(rows.messages.map(row => [JSON.stringify([row.value.threadId, row.id]), row.root]));
|
|
99
|
+
for (const row of rows.explicit) {
|
|
100
|
+
const root = roots.get(JSON.stringify([row.thread, row.id]));
|
|
101
|
+
await push(restore("readingUpdated", { profileId: identity.profileId, threadId: row.thread, ...(root ? { threadRootId: root } : {}),
|
|
102
|
+
readThroughSeq: 0, explicitReadMessageIds: [row.id] }, `explicit:${row.id}`));
|
|
103
|
+
}
|
|
104
|
+
for (const row of rows.facts)
|
|
105
|
+
if (["threadOrganized", "threadAssigned", "relationshipUpdated"].includes(row.kind))
|
|
106
|
+
await push(restore(row.kind, row.value, row.id));
|
|
107
|
+
for (const row of rows.receipts)
|
|
108
|
+
await push({ type: "restoreReceipt", data: { appId: identity.appId, profileId: identity.profileId,
|
|
109
|
+
threadId: row.thread, readThroughSeq: 0, explicitReadMessageIds: [], receipt: { version: 1, authorProfileId: identity.profileId,
|
|
110
|
+
readerProfileId: row.readerId, threadId: row.thread, messageIds: [row.messageId], sourceId: `legacy-receipt:${row.messageId}:${row.readerId}`, sourceAcceptedAt: 0 } } });
|
|
111
|
+
await flush();
|
|
112
|
+
await owner.activateGeneration(generation);
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ProfileCurrentState, ProfileMessage, ProfileThread, ProfileWindow } from "./profileStoreTypes.js";
|
|
2
2
|
import type { ChatMessage } from "../chatTypes.js";
|
|
3
|
-
export declare const PROFILE_PROTOCOL_VERSION =
|
|
4
|
-
export declare const PROFILE_PROJECTION_VERSION =
|
|
3
|
+
export declare const PROFILE_PROTOCOL_VERSION = 2;
|
|
4
|
+
export declare const PROFILE_PROJECTION_VERSION = 2;
|
|
5
5
|
export type ProfileSnapshot = {
|
|
6
6
|
current: ProfileCurrentState;
|
|
7
7
|
threads: ProfileThread[];
|
|
@@ -24,6 +24,15 @@ export type ProfileDelta = {
|
|
|
24
24
|
export declare class ProfileMemoryStore {
|
|
25
25
|
private onError;
|
|
26
26
|
private profileId;
|
|
27
|
+
private windowRows;
|
|
28
|
+
private messageWindows;
|
|
29
|
+
private windowPages;
|
|
30
|
+
private windowAccess;
|
|
31
|
+
private windowIds;
|
|
32
|
+
private windowListeners;
|
|
33
|
+
private windowListListeners;
|
|
34
|
+
private dirtyWindows;
|
|
35
|
+
private readonly emptyWindowIds;
|
|
27
36
|
private current?;
|
|
28
37
|
private entities;
|
|
29
38
|
private threads;
|
|
@@ -47,6 +56,9 @@ export declare class ProfileMemoryStore {
|
|
|
47
56
|
};
|
|
48
57
|
getThread(threadId: string): ProfileThread | undefined;
|
|
49
58
|
getMessage(messageId: string): ProfileMessage | undefined;
|
|
59
|
+
getAccessRevision(): number;
|
|
60
|
+
isTeamAvailable(teamId: string | undefined): boolean;
|
|
61
|
+
isThreadAvailable(threadId: string): boolean;
|
|
50
62
|
getPresentedMessage(messageId: string): Readonly<{
|
|
51
63
|
id: string;
|
|
52
64
|
threadId: string;
|
|
@@ -105,6 +117,14 @@ export declare class ProfileMemoryStore {
|
|
|
105
117
|
subscribeThreadList: (listener: () => void) => () => void;
|
|
106
118
|
subscribeMessages(listener: (messages: readonly ProfileMessage[]) => void): () => void;
|
|
107
119
|
subscribeThread(threadId: string, listener: () => void): () => void;
|
|
120
|
+
private windowKey;
|
|
121
|
+
private installWindow;
|
|
122
|
+
getWindowIds(threadId: string): readonly string[];
|
|
123
|
+
findMessageWindow(threadId: string, messageId: string): string | undefined;
|
|
124
|
+
readPresentedWindow(threadId: string, windowId: string): readonly ChatMessage[];
|
|
125
|
+
subscribeWindow(threadId: string, windowId: string, listener: () => void): () => void;
|
|
126
|
+
subscribeWindowList(threadId: string, listener: () => void): () => void;
|
|
127
|
+
private subscribeKey;
|
|
108
128
|
restore(snapshot: ProfileSnapshot): void;
|
|
109
129
|
apply(delta: ProfileDelta): void;
|
|
110
130
|
private indexMessage;
|