@pmate/chat-sdk 0.12.0-next.95 → 0.13.0-profile.0
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/framework.d.ts +2 -0
- package/lib/framework.js +2 -0
- package/lib/messageView.d.ts +5 -0
- package/lib/messageView.js +2 -2
- package/lib/profile.d.ts +14 -0
- package/lib/profile.js +10 -0
- package/lib/profileWorker.d.ts +1 -0
- package/lib/profileWorker.js +3 -0
- package/lib/runtime/inboxClient.d.ts +3 -1
- package/lib/runtime/inboxClient.js +19 -1
- package/lib/runtime/profileChat.d.ts +135 -0
- package/lib/runtime/profileChat.js +299 -0
- package/lib/runtime/profileCommitQueue.d.ts +38 -0
- package/lib/runtime/profileCommitQueue.js +101 -0
- package/lib/runtime/profileCoordinator.d.ts +46 -0
- package/lib/runtime/profileCoordinator.js +135 -0
- package/lib/runtime/profileDatabase.d.ts +42 -0
- package/lib/runtime/profileDatabase.js +164 -0
- package/lib/runtime/profileGenerationBuilder.d.ts +18 -0
- package/lib/runtime/profileGenerationBuilder.js +112 -0
- package/lib/runtime/profileInboxFeed.d.ts +38 -0
- package/lib/runtime/profileInboxFeed.js +240 -0
- package/lib/runtime/profileMemoryStore.d.ts +113 -0
- package/lib/runtime/profileMemoryStore.js +259 -0
- package/lib/runtime/profileOutboxDispatcher.d.ts +31 -0
- package/lib/runtime/profileOutboxDispatcher.js +106 -0
- package/lib/runtime/profileOwner.d.ts +57 -0
- package/lib/runtime/profileOwner.js +202 -0
- package/lib/runtime/profileProjection.d.ts +77 -0
- package/lib/runtime/profileProjection.js +625 -0
- package/lib/runtime/profileReadingIndex.d.ts +17 -0
- package/lib/runtime/profileReadingIndex.js +99 -0
- package/lib/runtime/profileReplica.d.ts +59 -0
- package/lib/runtime/profileReplica.js +236 -0
- package/lib/runtime/profileStoreTypes.d.ts +163 -0
- package/lib/runtime/profileStoreTypes.js +1 -0
- package/lib/runtime/profileWindows.d.ts +38 -0
- package/lib/runtime/profileWindows.js +175 -0
- package/lib/runtime/profileWorkerHost.d.ts +33 -0
- package/lib/runtime/profileWorkerHost.js +156 -0
- package/package.json +11 -1
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** A fixed acceptance window with one durable commit in flight. Failed batches
|
|
2
|
+
* stay at the head: later commands cannot pass a failed Inbox cursor update. */
|
|
3
|
+
export class ProfileCommitQueue {
|
|
4
|
+
entries = [];
|
|
5
|
+
bytes = 0;
|
|
6
|
+
timer;
|
|
7
|
+
running;
|
|
8
|
+
closed = false;
|
|
9
|
+
retryAt = 0;
|
|
10
|
+
urgent = false;
|
|
11
|
+
retryBatch;
|
|
12
|
+
options;
|
|
13
|
+
constructor(options) {
|
|
14
|
+
this.options = { commit: options.commit, onError: options.onError,
|
|
15
|
+
windowMs: options.windowMs ?? 200, maxEvents: options.maxEvents ?? 200, maxBytes: options.maxBytes ?? 512 * 1024,
|
|
16
|
+
capacityEvents: options.capacityEvents ?? 2000, capacityBytes: options.capacityBytes ?? 8 * 1024 * 1024,
|
|
17
|
+
retryMs: options.retryMs ?? 10000 };
|
|
18
|
+
for (const key of ["windowMs", "maxEvents", "maxBytes", "capacityEvents", "capacityBytes", "retryMs"]) {
|
|
19
|
+
if (!Number.isSafeInteger(this.options[key]) || this.options[key] < 1)
|
|
20
|
+
throw new Error("INVALID_COMMIT_QUEUE_OPTIONS");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
get pending() { return { events: this.entries.length, bytes: this.bytes }; }
|
|
24
|
+
/** Admission is synchronous; callers pause their source on backpressure.
|
|
25
|
+
* A single oversized event is admitted only into an otherwise empty queue. */
|
|
26
|
+
enqueue(event, bytes, immediate = false, barrier = false) {
|
|
27
|
+
if (this.closed)
|
|
28
|
+
throw new Error("PROFILE_COMMIT_QUEUE_CLOSED");
|
|
29
|
+
if (!Number.isSafeInteger(bytes) || bytes < 0)
|
|
30
|
+
throw new Error("INVALID_COMMIT_EVENT_SIZE");
|
|
31
|
+
if (this.entries.length >= this.options.capacityEvents ||
|
|
32
|
+
this.entries.length > 0 && this.bytes + bytes > this.options.capacityBytes)
|
|
33
|
+
throw new Error("PROFILE_COMMIT_BACKPRESSURE");
|
|
34
|
+
const completion = new Promise(resolve => this.entries.push({ event, bytes, accepted: Date.now(), resolve, barrier }));
|
|
35
|
+
this.bytes += bytes;
|
|
36
|
+
this.urgent ||= immediate;
|
|
37
|
+
this.schedule();
|
|
38
|
+
return completion;
|
|
39
|
+
}
|
|
40
|
+
/** Expedite accepted commands without bypassing a failed batch's retry delay. */
|
|
41
|
+
flush() {
|
|
42
|
+
this.urgent = true;
|
|
43
|
+
this.schedule();
|
|
44
|
+
}
|
|
45
|
+
schedule() {
|
|
46
|
+
if (this.closed || this.running || !this.entries.length)
|
|
47
|
+
return;
|
|
48
|
+
clearTimeout(this.timer);
|
|
49
|
+
const now = Date.now();
|
|
50
|
+
const full = this.entries.length >= this.options.maxEvents || this.bytes >= this.options.maxBytes;
|
|
51
|
+
const due = Math.max(this.retryAt, this.urgent || full ? now : this.entries[0].accepted + this.options.windowMs);
|
|
52
|
+
this.timer = setTimeout(() => { this.timer = undefined; void this.run(); }, Math.max(0, due - now));
|
|
53
|
+
}
|
|
54
|
+
async run() {
|
|
55
|
+
if (this.closed || this.running || !this.entries.length)
|
|
56
|
+
return;
|
|
57
|
+
let batch = this.retryBatch;
|
|
58
|
+
if (!batch) {
|
|
59
|
+
let count = 0, bytes = 0;
|
|
60
|
+
for (const entry of this.entries) {
|
|
61
|
+
if (count && (entry.barrier || this.entries[0].barrier || count >= this.options.maxEvents || bytes + entry.bytes > this.options.maxBytes))
|
|
62
|
+
break;
|
|
63
|
+
count++;
|
|
64
|
+
bytes += entry.bytes;
|
|
65
|
+
}
|
|
66
|
+
batch = this.entries.slice(0, count);
|
|
67
|
+
}
|
|
68
|
+
const count = batch.length, bytes = batch.reduce((total, entry) => total + entry.bytes, 0);
|
|
69
|
+
this.urgent = false;
|
|
70
|
+
const task = Promise.resolve().then(() => this.options.commit(batch.map(entry => entry.event)));
|
|
71
|
+
this.running = task;
|
|
72
|
+
try {
|
|
73
|
+
await task;
|
|
74
|
+
this.entries.splice(0, count);
|
|
75
|
+
this.bytes -= bytes;
|
|
76
|
+
this.retryAt = 0;
|
|
77
|
+
this.retryBatch = undefined;
|
|
78
|
+
batch.forEach(entry => entry.resolve());
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
this.retryBatch = batch;
|
|
82
|
+
this.retryAt = Date.now() + this.options.retryMs;
|
|
83
|
+
try {
|
|
84
|
+
this.options.onError?.(error);
|
|
85
|
+
}
|
|
86
|
+
catch { /* Reporting cannot stop recovery. */ }
|
|
87
|
+
}
|
|
88
|
+
finally {
|
|
89
|
+
this.running = undefined;
|
|
90
|
+
this.schedule();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Never silently discard accepted non-durable commands. The owner must drain
|
|
94
|
+
* before closing; an interrupted process recovers remote inputs by cursor. */
|
|
95
|
+
close() {
|
|
96
|
+
if (this.entries.length || this.running)
|
|
97
|
+
throw new Error("PROFILE_COMMIT_QUEUE_NOT_DRAINED");
|
|
98
|
+
this.closed = true;
|
|
99
|
+
clearTimeout(this.timer);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { ProfileReplica, type ProfileMessagePort } from "./profileReplica.js";
|
|
2
|
+
import { type ProfileWorkerConfiguration } from "./profileWorkerHost.js";
|
|
3
|
+
import type { ProfileOperation } from "./profileProjection.js";
|
|
4
|
+
type WorkerHandle = ProfileMessagePort & {
|
|
5
|
+
terminate(): void;
|
|
6
|
+
};
|
|
7
|
+
export type ProfileCoordinatorOptions = {
|
|
8
|
+
configuration: ProfileWorkerConfiguration;
|
|
9
|
+
createWorker: () => WorkerHandle;
|
|
10
|
+
channel?: (name: string) => ProfileMessagePort & {
|
|
11
|
+
close(): void;
|
|
12
|
+
};
|
|
13
|
+
onError?: (error: unknown) => void;
|
|
14
|
+
onProgress?: (progress: unknown) => void;
|
|
15
|
+
requestTimeoutMs?: number;
|
|
16
|
+
retryMs?: number;
|
|
17
|
+
};
|
|
18
|
+
/** A WebView owns a stable memory replica, not necessarily the writer Worker.
|
|
19
|
+
* Every context may acquire an expired lease; fencing decides the sole writer. */
|
|
20
|
+
export declare class ProfileCoordinator {
|
|
21
|
+
private options;
|
|
22
|
+
readonly replica: ProfileReplica;
|
|
23
|
+
private channel;
|
|
24
|
+
private worker?;
|
|
25
|
+
private host?;
|
|
26
|
+
private acquiring?;
|
|
27
|
+
private timer?;
|
|
28
|
+
private closed;
|
|
29
|
+
private needsOwner;
|
|
30
|
+
private starting?;
|
|
31
|
+
get identity(): import("./inboxStore.js").InboxScope;
|
|
32
|
+
get memory(): import("./profileMemoryStore.js").ProfileMemoryStore;
|
|
33
|
+
submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
|
|
34
|
+
synchronize(): Promise<void>;
|
|
35
|
+
waitForCommand(id: string): Promise<void>;
|
|
36
|
+
voiceAttachment(id: string): Promise<Blob | null>;
|
|
37
|
+
constructor(options: ProfileCoordinatorOptions);
|
|
38
|
+
private report;
|
|
39
|
+
private workerMessage;
|
|
40
|
+
start(): Promise<void>;
|
|
41
|
+
private initialize;
|
|
42
|
+
private acquire;
|
|
43
|
+
updateToken(token: string): Promise<void>;
|
|
44
|
+
close(): Promise<void>;
|
|
45
|
+
}
|
|
46
|
+
export {};
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { ProfileReplica } from "./profileReplica.js";
|
|
2
|
+
import { openProfileWorker, profileChannelName } from "./profileWorkerHost.js";
|
|
3
|
+
/** A WebView owns a stable memory replica, not necessarily the writer Worker.
|
|
4
|
+
* Every context may acquire an expired lease; fencing decides the sole writer. */
|
|
5
|
+
export class ProfileCoordinator {
|
|
6
|
+
options;
|
|
7
|
+
replica;
|
|
8
|
+
channel;
|
|
9
|
+
worker;
|
|
10
|
+
host;
|
|
11
|
+
acquiring;
|
|
12
|
+
timer;
|
|
13
|
+
closed = false;
|
|
14
|
+
needsOwner = false;
|
|
15
|
+
starting;
|
|
16
|
+
get identity() { return this.options.configuration.identity; }
|
|
17
|
+
get memory() { return this.replica.memory; }
|
|
18
|
+
submit(operation, immediate = false) { return this.replica.submit(operation, immediate); }
|
|
19
|
+
synchronize() { return this.replica.synchronize(); }
|
|
20
|
+
waitForCommand(id) { return this.replica.waitForCommand(id); }
|
|
21
|
+
voiceAttachment(id) { return this.replica.voiceAttachment(id); }
|
|
22
|
+
constructor(options) {
|
|
23
|
+
this.options = options;
|
|
24
|
+
const scope = profileChannelName(options.configuration.identity);
|
|
25
|
+
this.channel = options.channel?.(scope) ?? new BroadcastChannel(scope);
|
|
26
|
+
this.channel.addEventListener("message", this.workerMessage);
|
|
27
|
+
this.replica = new ProfileReplica(this.channel, scope, error => {
|
|
28
|
+
this.report(error);
|
|
29
|
+
if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
|
|
30
|
+
this.needsOwner = true;
|
|
31
|
+
void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
|
|
32
|
+
}
|
|
33
|
+
}, options.requestTimeoutMs ?? 5000, options.configuration.identity.profileId);
|
|
34
|
+
}
|
|
35
|
+
report(error) { try {
|
|
36
|
+
this.options.onError?.(error);
|
|
37
|
+
}
|
|
38
|
+
catch { } }
|
|
39
|
+
workerMessage = (event) => {
|
|
40
|
+
if (event.data?.profileControl === "progress") {
|
|
41
|
+
try {
|
|
42
|
+
this.options.onProgress?.(event.data.progress);
|
|
43
|
+
}
|
|
44
|
+
catch { }
|
|
45
|
+
}
|
|
46
|
+
if (event.data?.profileControl === "error")
|
|
47
|
+
this.report(Error(event.data.error));
|
|
48
|
+
};
|
|
49
|
+
start() {
|
|
50
|
+
if (this.starting)
|
|
51
|
+
return this.starting;
|
|
52
|
+
const task = this.initialize().catch(error => { this.starting = undefined; throw error; });
|
|
53
|
+
this.starting = task;
|
|
54
|
+
return task;
|
|
55
|
+
}
|
|
56
|
+
async initialize() {
|
|
57
|
+
await this.acquire();
|
|
58
|
+
await this.replica.start(false);
|
|
59
|
+
if (!this.timer)
|
|
60
|
+
this.timer = setInterval(() => {
|
|
61
|
+
void this.replica.check().catch(error => {
|
|
62
|
+
this.report(error);
|
|
63
|
+
if (["PROFILE_OWNER_TIMEOUT", "PROFILE_OWNER_UNAVAILABLE"].includes(error?.message)) {
|
|
64
|
+
this.needsOwner = true;
|
|
65
|
+
void this.acquire().then(() => this.replica.repair()).catch(failure => this.report(failure));
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}, this.options.retryMs ?? 10000);
|
|
69
|
+
}
|
|
70
|
+
acquire() {
|
|
71
|
+
if (this.closed)
|
|
72
|
+
return Promise.reject(Error("PROFILE_COORDINATOR_CLOSED"));
|
|
73
|
+
if (this.acquiring)
|
|
74
|
+
return this.acquiring;
|
|
75
|
+
if (this.host && !this.needsOwner)
|
|
76
|
+
return Promise.resolve();
|
|
77
|
+
const task = (async () => {
|
|
78
|
+
if (this.worker) {
|
|
79
|
+
this.worker.removeEventListener("message", this.workerMessage);
|
|
80
|
+
this.worker.terminate();
|
|
81
|
+
this.worker = undefined;
|
|
82
|
+
this.host = undefined;
|
|
83
|
+
}
|
|
84
|
+
const worker = this.options.createWorker();
|
|
85
|
+
worker.addEventListener("message", this.workerMessage);
|
|
86
|
+
try {
|
|
87
|
+
const host = await openProfileWorker(worker, this.options.configuration);
|
|
88
|
+
if (this.closed) {
|
|
89
|
+
await host.close();
|
|
90
|
+
worker.terminate();
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
this.worker = worker;
|
|
94
|
+
this.host = host;
|
|
95
|
+
this.needsOwner = false;
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
worker.removeEventListener("message", this.workerMessage);
|
|
99
|
+
worker.terminate();
|
|
100
|
+
if (error?.message !== "PROFILE_OWNER_UNAVAILABLE")
|
|
101
|
+
throw error;
|
|
102
|
+
// Another healthy writer serves this replica through the shared channel.
|
|
103
|
+
this.needsOwner = false;
|
|
104
|
+
}
|
|
105
|
+
})();
|
|
106
|
+
this.acquiring = task;
|
|
107
|
+
void task.finally(() => { if (this.acquiring === task)
|
|
108
|
+
this.acquiring = undefined; }).catch(() => { });
|
|
109
|
+
return task;
|
|
110
|
+
}
|
|
111
|
+
async updateToken(token) {
|
|
112
|
+
const configuration = this.options.configuration;
|
|
113
|
+
if (!configuration.network)
|
|
114
|
+
return;
|
|
115
|
+
configuration.network = { ...configuration.network, token };
|
|
116
|
+
await this.host?.update(configuration);
|
|
117
|
+
}
|
|
118
|
+
async close() {
|
|
119
|
+
this.closed = true;
|
|
120
|
+
clearInterval(this.timer);
|
|
121
|
+
this.replica.close();
|
|
122
|
+
this.channel.removeEventListener("message", this.workerMessage);
|
|
123
|
+
this.channel.close();
|
|
124
|
+
await this.acquiring;
|
|
125
|
+
try {
|
|
126
|
+
await this.host?.close();
|
|
127
|
+
}
|
|
128
|
+
finally {
|
|
129
|
+
this.worker?.removeEventListener("message", this.workerMessage);
|
|
130
|
+
this.worker?.terminate();
|
|
131
|
+
this.worker = undefined;
|
|
132
|
+
this.host = undefined;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import Dexie, { type Table } from "dexie";
|
|
2
|
+
import type { ProfileCurrentState, ProfileGenerationState, ProfileIdentity, ProfileMessage, ProfileOutboxCommand, ProfileStateRecord, ProfileThread, ProfileWindow, ProfileWriteBatch, ProfileWriterLease } from "./profileStoreTypes.js";
|
|
3
|
+
export declare function profileDatabaseName(identity: ProfileIdentity): string;
|
|
4
|
+
/** One Profile, five stores, one transaction boundary. No page-facing read API:
|
|
5
|
+
* restoration is explicit and normal queries belong to the in-memory view. */
|
|
6
|
+
export declare class ProfileDatabase extends Dexie {
|
|
7
|
+
readonly identity: ProfileIdentity;
|
|
8
|
+
threads: Table<ProfileThread, [string, string]>;
|
|
9
|
+
windows: Table<ProfileWindow, [string, string, string]>;
|
|
10
|
+
messages: Table<ProfileMessage, [string, string]>;
|
|
11
|
+
inboxState: Table<ProfileStateRecord, string>;
|
|
12
|
+
outbox: Table<ProfileOutboxCommand, string>;
|
|
13
|
+
constructor(identity: ProfileIdentity, options?: {
|
|
14
|
+
indexedDB?: IDBFactory;
|
|
15
|
+
name?: string;
|
|
16
|
+
});
|
|
17
|
+
claimWriter(ownerId: string, now?: number, ttlMs?: number): Promise<ProfileWriterLease | undefined>;
|
|
18
|
+
private assertWriter;
|
|
19
|
+
releaseWriter(ownerId: string, fence: number): Promise<void>;
|
|
20
|
+
initialize(ownerId: string, fence: number, state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
|
|
21
|
+
commit(batch: ProfileWriteBatch): Promise<ProfileCurrentState>;
|
|
22
|
+
/** Restore from one consistent transaction, never mix data across a switch. */
|
|
23
|
+
restore(): Promise<{
|
|
24
|
+
current: ProfileCurrentState | undefined;
|
|
25
|
+
threads: ProfileThread[];
|
|
26
|
+
windows: ProfileWindow[];
|
|
27
|
+
messages: ProfileMessage[];
|
|
28
|
+
outbox: ProfileOutboxCommand[];
|
|
29
|
+
}>;
|
|
30
|
+
saveGeneration(ownerId: string, fence: number, build: ProfileGenerationState, rows: {
|
|
31
|
+
threads?: ProfileThread[];
|
|
32
|
+
windows?: ProfileWindow[];
|
|
33
|
+
messages?: ProfileMessage[];
|
|
34
|
+
}): Promise<void>;
|
|
35
|
+
restoreGeneration(generation: string): Promise<{
|
|
36
|
+
build: ProfileGenerationState | undefined;
|
|
37
|
+
threads: ProfileThread[];
|
|
38
|
+
windows: ProfileWindow[];
|
|
39
|
+
messages: ProfileMessage[];
|
|
40
|
+
}>;
|
|
41
|
+
activateGeneration(ownerId: string, fence: number, generation: string, expectedRevision: number): Promise<ProfileCurrentState>;
|
|
42
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import Dexie, {} from "dexie";
|
|
2
|
+
import { inboxSequence } from "./inboxStore.js";
|
|
3
|
+
export function profileDatabaseName(identity) {
|
|
4
|
+
return `pmate-chat:${[identity.accountId, identity.appId, identity.profileId].map(encodeURIComponent).join(":")}`;
|
|
5
|
+
}
|
|
6
|
+
/** One Profile, five stores, one transaction boundary. No page-facing read API:
|
|
7
|
+
* restoration is explicit and normal queries belong to the in-memory view. */
|
|
8
|
+
export class ProfileDatabase extends Dexie {
|
|
9
|
+
identity;
|
|
10
|
+
threads;
|
|
11
|
+
windows;
|
|
12
|
+
messages;
|
|
13
|
+
inboxState;
|
|
14
|
+
outbox;
|
|
15
|
+
constructor(identity, options = {}) {
|
|
16
|
+
super(options.name ?? profileDatabaseName(identity), { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
|
|
17
|
+
this.identity = identity;
|
|
18
|
+
this.version(1).stores({
|
|
19
|
+
threads: "[generation+threadId],generation,[generation+parentThreadId]",
|
|
20
|
+
windows: "[generation+threadId+windowId],generation,[generation+threadId+firstOrderKey],[generation+threadId+sequence]",
|
|
21
|
+
messages: "[generation+messageId],generation,[generation+threadId+orderKey],[generation+sourceThreadId+sourceSeq+messageId]",
|
|
22
|
+
inboxState: "key",
|
|
23
|
+
outbox: "commandId,[state+createdAt],threadId,messageId",
|
|
24
|
+
});
|
|
25
|
+
this.on("versionchange", () => { this.close(); return false; });
|
|
26
|
+
}
|
|
27
|
+
async claimWriter(ownerId, now = Date.now(), ttlMs = 30000) {
|
|
28
|
+
if (!ownerId || !Number.isSafeInteger(ttlMs) || ttlMs < 1)
|
|
29
|
+
throw Error("INVALID_PROFILE_LEASE");
|
|
30
|
+
return this.transaction("rw", this.inboxState, async () => {
|
|
31
|
+
const old = await this.inboxState.get("lease");
|
|
32
|
+
if (old && old.ownerId !== ownerId && old.expiresAt > now)
|
|
33
|
+
return undefined;
|
|
34
|
+
const fence = old ? old.ownerId === ownerId && old.expiresAt > now ? old.fence : old.fence + 1 : 1;
|
|
35
|
+
if (!Number.isSafeInteger(fence))
|
|
36
|
+
throw Error("PROFILE_FENCE_EXHAUSTED");
|
|
37
|
+
const lease = { key: "lease", ownerId, fence, expiresAt: now + ttlMs };
|
|
38
|
+
await this.inboxState.put(lease);
|
|
39
|
+
return lease;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
async assertWriter(ownerId, fence) {
|
|
43
|
+
const lease = await this.inboxState.get("lease");
|
|
44
|
+
if (!lease || lease.ownerId !== ownerId || lease.fence !== fence || lease.expiresAt <= Date.now())
|
|
45
|
+
throw Error("PROFILE_WRITER_FENCED");
|
|
46
|
+
}
|
|
47
|
+
async releaseWriter(ownerId, fence) {
|
|
48
|
+
await this.transaction("rw", this.inboxState, async () => {
|
|
49
|
+
const lease = await this.inboxState.get("lease");
|
|
50
|
+
// Keep the counter: deleting it would allow a stale producer to reuse fence 1.
|
|
51
|
+
if (lease?.ownerId === ownerId && lease.fence === fence)
|
|
52
|
+
await this.inboxState.put({ ...lease, expiresAt: 0 });
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
async initialize(ownerId, fence, state) {
|
|
56
|
+
inboxSequence(state.committedSeq);
|
|
57
|
+
return this.transaction("rw", this.inboxState, async () => {
|
|
58
|
+
await this.assertWriter(ownerId, fence);
|
|
59
|
+
const previous = await this.inboxState.get("current");
|
|
60
|
+
if (previous)
|
|
61
|
+
return previous;
|
|
62
|
+
const current = { ...state, key: "current", commitRevision: 0 };
|
|
63
|
+
await this.inboxState.put(current);
|
|
64
|
+
return current;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async commit(batch) {
|
|
68
|
+
inboxSequence(batch.committedSeq);
|
|
69
|
+
for (const row of [...batch.threads ?? [], ...batch.windows ?? [], ...batch.messages ?? []]) {
|
|
70
|
+
if (row.generation !== batch.generation)
|
|
71
|
+
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
72
|
+
}
|
|
73
|
+
return this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
|
|
74
|
+
await this.assertWriter(batch.ownerId, batch.fence);
|
|
75
|
+
const current = await this.inboxState.get("current");
|
|
76
|
+
if (!current || current.activeGeneration !== batch.generation || current.epoch !== batch.epoch)
|
|
77
|
+
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
78
|
+
if (current.commitRevision !== batch.expectedRevision)
|
|
79
|
+
throw Error("PROFILE_REVISION_CONFLICT");
|
|
80
|
+
if (inboxSequence(batch.committedSeq) < inboxSequence(current.committedSeq))
|
|
81
|
+
throw Error("PROFILE_CURSOR_REGRESSION");
|
|
82
|
+
const changed = [batch.threads, batch.windows, batch.messages, batch.outbox, batch.deleteMessages, batch.deleteWindows, batch.deleteOutbox].some(rows => rows?.length);
|
|
83
|
+
if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady))
|
|
84
|
+
return current;
|
|
85
|
+
if (batch.messages?.length)
|
|
86
|
+
await this.messages.bulkPut(batch.messages);
|
|
87
|
+
if (batch.windows?.length)
|
|
88
|
+
await this.windows.bulkPut(batch.windows);
|
|
89
|
+
if (batch.threads?.length)
|
|
90
|
+
await this.threads.bulkPut(batch.threads);
|
|
91
|
+
if (batch.outbox?.length)
|
|
92
|
+
await this.outbox.bulkPut(batch.outbox);
|
|
93
|
+
if (batch.deleteMessages?.length)
|
|
94
|
+
await this.messages.bulkDelete(batch.deleteMessages.map(id => [batch.generation, id]));
|
|
95
|
+
if (batch.deleteWindows?.length)
|
|
96
|
+
await this.windows.bulkDelete(batch.deleteWindows.map(([thread, id]) => [batch.generation, thread, id]));
|
|
97
|
+
if (batch.deleteOutbox?.length)
|
|
98
|
+
await this.outbox.bulkDelete(batch.deleteOutbox);
|
|
99
|
+
if (!Number.isSafeInteger(current.commitRevision + 1))
|
|
100
|
+
throw Error("PROFILE_REVISION_EXHAUSTED");
|
|
101
|
+
const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
|
|
102
|
+
await this.inboxState.put(next);
|
|
103
|
+
return next;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/** Restore from one consistent transaction, never mix data across a switch. */
|
|
107
|
+
async restore() {
|
|
108
|
+
return this.transaction("r", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
|
|
109
|
+
const current = await this.inboxState.get("current");
|
|
110
|
+
const generation = current?.activeGeneration;
|
|
111
|
+
return { current,
|
|
112
|
+
threads: generation ? await this.threads.where("generation").equals(generation).toArray() : [],
|
|
113
|
+
windows: generation ? await this.windows.where("generation").equals(generation).toArray() : [],
|
|
114
|
+
messages: generation ? await this.messages.where("generation").equals(generation).toArray() : [],
|
|
115
|
+
outbox: await this.outbox.toArray(),
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
async saveGeneration(ownerId, fence, build, rows) {
|
|
120
|
+
inboxSequence(build.committedSeq);
|
|
121
|
+
for (const row of [...rows.threads ?? [], ...rows.windows ?? [], ...rows.messages ?? []])
|
|
122
|
+
if (row.generation !== build.generation)
|
|
123
|
+
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
124
|
+
if (build.key !== `build:${build.generation}`)
|
|
125
|
+
throw Error("PROFILE_GENERATION_MISMATCH");
|
|
126
|
+
await this.transaction("rw", [this.threads, this.windows, this.messages, this.inboxState], async () => {
|
|
127
|
+
await this.assertWriter(ownerId, fence);
|
|
128
|
+
const current = await this.inboxState.get("current");
|
|
129
|
+
if (current?.activeGeneration === build.generation)
|
|
130
|
+
throw Error("PROFILE_BUILD_IS_ACTIVE");
|
|
131
|
+
if (rows.messages?.length)
|
|
132
|
+
await this.messages.bulkPut(rows.messages);
|
|
133
|
+
if (rows.windows?.length)
|
|
134
|
+
await this.windows.bulkPut(rows.windows);
|
|
135
|
+
if (rows.threads?.length)
|
|
136
|
+
await this.threads.bulkPut(rows.threads);
|
|
137
|
+
await this.inboxState.put(build);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
async restoreGeneration(generation) {
|
|
141
|
+
return this.transaction("r", [this.threads, this.windows, this.messages, this.inboxState], async () => ({
|
|
142
|
+
build: await this.inboxState.get(`build:${generation}`),
|
|
143
|
+
threads: await this.threads.where("generation").equals(generation).toArray(),
|
|
144
|
+
windows: await this.windows.where("generation").equals(generation).toArray(),
|
|
145
|
+
messages: await this.messages.where("generation").equals(generation).toArray(),
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
async activateGeneration(ownerId, fence, generation, expectedRevision) {
|
|
149
|
+
return this.transaction("rw", this.inboxState, async () => {
|
|
150
|
+
await this.assertWriter(ownerId, fence);
|
|
151
|
+
const current = await this.inboxState.get("current");
|
|
152
|
+
const build = await this.inboxState.get(`build:${generation}`);
|
|
153
|
+
if (!current || current.commitRevision !== expectedRevision || build?.sourceRevision !== expectedRevision)
|
|
154
|
+
throw Error("PROFILE_REVISION_CONFLICT");
|
|
155
|
+
if (build.status !== "validated")
|
|
156
|
+
throw Error("PROFILE_BUILD_NOT_VALIDATED");
|
|
157
|
+
const next = { key: "current", activeGeneration: generation, epoch: build.epoch,
|
|
158
|
+
committedSeq: build.committedSeq, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
|
|
159
|
+
await this.inboxState.put({ ...build, status: "active" });
|
|
160
|
+
await this.inboxState.put(next);
|
|
161
|
+
return next;
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ProfileDatabase } from "./profileDatabase.js";
|
|
2
|
+
import { ProfileProjection, type ProfileOperation } from "./profileProjection.js";
|
|
3
|
+
import { type InboxBootstrap } from "./inboxStore.js";
|
|
4
|
+
import type { ProfileGenerationState, ProfileWriterLease } from "./profileStoreTypes.js";
|
|
5
|
+
/** Called only by the owner's serial commit queue. Network catch-up happens
|
|
6
|
+
* outside this class; each staged page is one bounded local transaction. */
|
|
7
|
+
export declare class ProfileGenerationBuilder {
|
|
8
|
+
private database;
|
|
9
|
+
private lease;
|
|
10
|
+
private cache;
|
|
11
|
+
constructor(database: ProfileDatabase, lease: () => ProfileWriterLease);
|
|
12
|
+
private persist;
|
|
13
|
+
private load;
|
|
14
|
+
begin(generation: string, bootstrap: InboxBootstrap, sourceRevision: number): Promise<void>;
|
|
15
|
+
append(generation: string, events: readonly ProfileOperation[]): Promise<void>;
|
|
16
|
+
progress(generation: string): Promise<ProfileGenerationState>;
|
|
17
|
+
activate(generation: string, active: ProfileProjection): Promise<ProfileProjection>;
|
|
18
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { ProfileDatabase } from "./profileDatabase.js";
|
|
2
|
+
import { ProfileProjection } from "./profileProjection.js";
|
|
3
|
+
import { ProfileMemoryStore } from "./profileMemoryStore.js";
|
|
4
|
+
import { inboxSequence } from "./inboxStore.js";
|
|
5
|
+
/** Called only by the owner's serial commit queue. Network catch-up happens
|
|
6
|
+
* outside this class; each staged page is one bounded local transaction. */
|
|
7
|
+
export class ProfileGenerationBuilder {
|
|
8
|
+
database;
|
|
9
|
+
lease;
|
|
10
|
+
cache = new Map();
|
|
11
|
+
constructor(database, lease) {
|
|
12
|
+
this.database = database;
|
|
13
|
+
this.lease = lease;
|
|
14
|
+
}
|
|
15
|
+
async persist(build, projection, events) {
|
|
16
|
+
const prepared = projection.prepare(events);
|
|
17
|
+
const next = { ...build, committedSeq: prepared.current.committedSeq, buildRevision: prepared.current.commitRevision, receiptsReady: prepared.current.receiptsReady };
|
|
18
|
+
const lease = this.lease();
|
|
19
|
+
await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
|
|
20
|
+
projection.accept(prepared);
|
|
21
|
+
this.cache.set(build.generation, { build: next, projection });
|
|
22
|
+
return { build: next, projection };
|
|
23
|
+
}
|
|
24
|
+
async load(generation) {
|
|
25
|
+
const cached = this.cache.get(generation);
|
|
26
|
+
if (cached)
|
|
27
|
+
return cached;
|
|
28
|
+
const saved = await this.database.restoreGeneration(generation);
|
|
29
|
+
if (!saved.build)
|
|
30
|
+
throw Error("PROFILE_BUILD_NOT_FOUND");
|
|
31
|
+
const current = { key: "current", activeGeneration: generation, epoch: saved.build.epoch,
|
|
32
|
+
committedSeq: saved.build.committedSeq, projectionVersion: saved.build.projectionVersion, commitRevision: saved.build.buildRevision ?? 0, receiptsReady: saved.build.receiptsReady };
|
|
33
|
+
const projection = new ProfileProjection(this.database.identity, { ...saved, current }, saved.build.windowStart ?? 0);
|
|
34
|
+
const result = { build: saved.build, projection };
|
|
35
|
+
this.cache.set(generation, result);
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
async begin(generation, bootstrap, sourceRevision) {
|
|
39
|
+
const start = inboxSequence(bootstrap.startSeq), head = inboxSequence(bootstrap.headSeq);
|
|
40
|
+
if (start < 1n || start > head + 1n || !bootstrap.epoch || !Number.isSafeInteger(bootstrap.windowStart))
|
|
41
|
+
throw Error("INVALID_INBOX_BOOTSTRAP");
|
|
42
|
+
const saved = await this.database.restoreGeneration(generation);
|
|
43
|
+
if (saved.build) {
|
|
44
|
+
if (saved.build.epoch !== bootstrap.epoch || saved.build.throughSeq !== bootstrap.headSeq || saved.build.windowStart !== bootstrap.windowStart)
|
|
45
|
+
throw Error("PROFILE_BUILD_ID_COLLISION");
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const build = { key: `build:${generation}`, generation, epoch: bootstrap.epoch,
|
|
49
|
+
committedSeq: (start - 1n).toString(), projectionVersion: 1, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
|
|
50
|
+
windowStart: bootstrap.windowStart, buildRevision: 0 };
|
|
51
|
+
const projection = new ProfileProjection(this.database.identity, { current: { key: "current", activeGeneration: generation,
|
|
52
|
+
epoch: build.epoch, committedSeq: build.committedSeq, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
|
|
53
|
+
const prepared = projection.prepareBasis(bootstrap), lease = this.lease();
|
|
54
|
+
const next = { ...build, buildRevision: prepared.current.commitRevision };
|
|
55
|
+
await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
|
|
56
|
+
projection.accept(prepared);
|
|
57
|
+
this.cache.set(generation, { build: next, projection });
|
|
58
|
+
}
|
|
59
|
+
async append(generation, events) {
|
|
60
|
+
const { build, projection } = await this.load(generation);
|
|
61
|
+
if (build.status !== "building")
|
|
62
|
+
throw Error("PROFILE_BUILD_NOT_WRITABLE");
|
|
63
|
+
await this.persist(build, projection, events);
|
|
64
|
+
}
|
|
65
|
+
async progress(generation) { return (await this.load(generation)).build; }
|
|
66
|
+
async activate(generation, active) {
|
|
67
|
+
let { build, projection } = await this.load(generation);
|
|
68
|
+
if (inboxSequence(build.committedSeq) < inboxSequence(build.throughSeq ?? "0"))
|
|
69
|
+
throw Error("PROFILE_BUILD_INCOMPLETE");
|
|
70
|
+
const operations = [];
|
|
71
|
+
// Keep locally accepted work that arrived while the replacement was built.
|
|
72
|
+
// Already-replayed server messages win by their stable message identity.
|
|
73
|
+
for (const message of active.messages.values()) {
|
|
74
|
+
if (message.sourceSeq || projection.messages.has(message.messageId))
|
|
75
|
+
continue;
|
|
76
|
+
const thread = projection.threads.get(message.threadId);
|
|
77
|
+
if (thread?.status !== "ready")
|
|
78
|
+
continue;
|
|
79
|
+
const pending = active.outbox.get(message.messageId);
|
|
80
|
+
const pendingPayload = pending?.payload;
|
|
81
|
+
const wire = pendingPayload?.message ?? pending?.payload ?? { hash: message.messageId, t: message.orderKey[0],
|
|
82
|
+
from: message.from, to: thread.internal?.targetId ?? "", opcode: 1, kind: 1, body: message.content, recipients: message.recipients };
|
|
83
|
+
const command = pending ?? { commandId: message.messageId, messageId: message.messageId, kind: "message",
|
|
84
|
+
threadId: message.threadId, createdAt: wire.t, payload: wire, state: "pending", attempts: 0 };
|
|
85
|
+
operations.push({ type: "send", threadId: message.threadId, message: wire, command });
|
|
86
|
+
if (!pending)
|
|
87
|
+
operations.push({ type: "commandResult", commandId: message.messageId, state: "confirmed" });
|
|
88
|
+
}
|
|
89
|
+
for (const thread of active.threads.values()) {
|
|
90
|
+
if (!projection.threads.has(thread.threadId))
|
|
91
|
+
continue;
|
|
92
|
+
for (const source of thread.readingSources) {
|
|
93
|
+
if (!source.pendingReadThroughSeq && !source.pendingExplicitReadMessageIds?.length)
|
|
94
|
+
continue;
|
|
95
|
+
operations.push({ type: "restoreReading", data: { appId: this.database.identity.appId, profileId: this.database.identity.profileId,
|
|
96
|
+
threadId: source.sourceThreadId, threadRootId: thread.rootMessageId,
|
|
97
|
+
readThroughSeq: source.pendingReadThroughSeq ?? 0, explicitReadMessageIds: source.pendingExplicitReadMessageIds ?? [] } });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (operations.length)
|
|
101
|
+
({ build, projection } = await this.persist(build, projection, operations));
|
|
102
|
+
const snapshot = projection.snapshot();
|
|
103
|
+
new ProfileMemoryStore().restore(snapshot);
|
|
104
|
+
const lease = this.lease();
|
|
105
|
+
const validated = { ...build, status: "validated", sourceRevision: active.current.commitRevision };
|
|
106
|
+
await this.database.saveGeneration(lease.ownerId, lease.fence, validated, {});
|
|
107
|
+
const current = await this.database.activateGeneration(lease.ownerId, lease.fence, generation, active.current.commitRevision);
|
|
108
|
+
const result = new ProfileProjection(this.database.identity, { ...snapshot, current, outbox: [...active.outbox.values()] }, build.windowStart ?? 0);
|
|
109
|
+
this.cache.delete(generation);
|
|
110
|
+
return result;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { ProfileOwner } from "./profileOwner.js";
|
|
2
|
+
import type { InboxProgress } from "./inboxClient.js";
|
|
3
|
+
export type ProfileInboxFeedOptions = {
|
|
4
|
+
owner: ProfileOwner;
|
|
5
|
+
hubHttpUrl: string;
|
|
6
|
+
getToken: () => string | Promise<string>;
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
onError?: (error: unknown) => void;
|
|
9
|
+
onProgress?: (progress: InboxProgress) => void;
|
|
10
|
+
live?: boolean;
|
|
11
|
+
};
|
|
12
|
+
/** The existing Inbox HTTP/live protocol, with no raw event cache. Each page is
|
|
13
|
+
* backpressured by durable owner commits; long requests never hold its queue. */
|
|
14
|
+
export declare class ProfileInboxFeed {
|
|
15
|
+
private options;
|
|
16
|
+
private controller;
|
|
17
|
+
private streamController?;
|
|
18
|
+
private running?;
|
|
19
|
+
private liveTask?;
|
|
20
|
+
private timer?;
|
|
21
|
+
private closed;
|
|
22
|
+
private building?;
|
|
23
|
+
constructor(options: ProfileInboxFeedOptions);
|
|
24
|
+
private report;
|
|
25
|
+
private progress;
|
|
26
|
+
private request;
|
|
27
|
+
start(): Promise<void>;
|
|
28
|
+
synchronize(): Promise<void>;
|
|
29
|
+
private validate;
|
|
30
|
+
private commit;
|
|
31
|
+
private completeReceipts;
|
|
32
|
+
private rebuild;
|
|
33
|
+
private resumeBuild;
|
|
34
|
+
private catchUp;
|
|
35
|
+
private tick;
|
|
36
|
+
private listen;
|
|
37
|
+
close(): Promise<void>;
|
|
38
|
+
}
|