@pmate/chat-sdk 0.12.0-next.2 → 0.12.0-next.20
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 +54 -3
- package/lib/runtime/chatClient.d.ts +8 -0
- package/lib/runtime/chatClient.js +8 -2
- package/lib/runtime/chatSession.d.ts +69 -7
- package/lib/runtime/chatSession.js +331 -25
- package/lib/runtime/conversationRead.d.ts +13 -0
- package/lib/runtime/conversationRead.js +34 -0
- package/lib/runtime/createChat.d.ts +26 -0
- package/lib/runtime/createChat.js +42 -0
- package/lib/runtime/durableSender.js +4 -1
- package/lib/runtime/index.d.ts +2 -0
- package/lib/runtime/index.js +2 -0
- package/lib/runtime/messageClient.d.ts +22 -5
- package/lib/runtime/messageClient.js +302 -48
- package/lib/runtime/messageReaders.d.ts +8 -1
- package/lib/runtime/messageReaders.js +56 -3
- package/lib/runtime/messageStore.d.ts +23 -1
- package/lib/runtime/messageStore.js +88 -8
- package/lib/runtime/readCounts.d.ts +12 -1
- package/lib/runtime/readCounts.js +66 -6
- package/lib/runtime/readIndex.d.ts +5 -1
- package/lib/runtime/readIndex.js +28 -4
- package/lib/runtime/readingClient.d.ts +4 -0
- package/lib/runtime/readingClient.js +5 -1
- package/lib/runtime/recordCache.d.ts +9 -0
- package/lib/runtime/recordCache.js +62 -5
- package/lib/runtime/responseCache.d.ts +29 -0
- package/lib/runtime/responseCache.js +111 -0
- package/package.json +1 -1
|
@@ -17,17 +17,26 @@ export class IndexedDbRecordCache {
|
|
|
17
17
|
closing = false;
|
|
18
18
|
initialized = false;
|
|
19
19
|
running;
|
|
20
|
+
activeBytes = 0;
|
|
21
|
+
pendingBytes = 0;
|
|
22
|
+
activeRecords = 0;
|
|
23
|
+
transactionBytes;
|
|
24
|
+
queueBytes;
|
|
20
25
|
channel;
|
|
21
26
|
listeners = new Set();
|
|
22
27
|
constructor(options) {
|
|
23
28
|
this.options = options;
|
|
29
|
+
this.transactionBytes = options.transactionBytes ?? 1_048_576;
|
|
30
|
+
this.queueBytes = options.queueBytes ?? 8_388_608;
|
|
31
|
+
if (!Number.isSafeInteger(this.transactionBytes) || this.transactionBytes < 1 || !Number.isSafeInteger(this.queueBytes) || this.queueBytes < this.transactionBytes)
|
|
32
|
+
throw new Error("INVALID_RECORD_CACHE_BYTE_LIMIT");
|
|
24
33
|
this.db = new Dexie(options.name ?? "pmate-chat-records", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
|
|
25
34
|
this.db.version(1).stores({ records: "[scope+id],scope", metadata: "scope" });
|
|
26
35
|
this.records = this.db.table("records");
|
|
27
36
|
this.metadata = this.db.table("metadata");
|
|
28
37
|
this.tasks = new WindowedTasks(16, error => options.onError?.(error));
|
|
29
38
|
if (typeof BroadcastChannel !== "undefined") {
|
|
30
|
-
this.channel = new BroadcastChannel(`pmate-chat-records:${options.scope}`);
|
|
39
|
+
this.channel = new BroadcastChannel(`pmate-chat-records:${options.scope}${this.db.name === "pmate-chat-records" ? "" : `:${this.db.name}`}`);
|
|
31
40
|
this.channel.onmessage = () => this.tasks.schedule("reload", () => this.reload());
|
|
32
41
|
}
|
|
33
42
|
}
|
|
@@ -83,30 +92,70 @@ export class IndexedDbRecordCache {
|
|
|
83
92
|
await this.ready;
|
|
84
93
|
if (this.closed || this.closing)
|
|
85
94
|
throw new Error("RECORD_CACHE_CLOSED");
|
|
86
|
-
if (incoming.length
|
|
95
|
+
if (incoming.length > 4096)
|
|
87
96
|
throw new Error("RECORD_CACHE_BACKPRESSURE");
|
|
88
|
-
|
|
97
|
+
// Plan and validate the whole operation before publishing any in-memory state.
|
|
98
|
+
const staged = new Map();
|
|
89
99
|
for (const value of incoming) {
|
|
90
|
-
const key = this.options.key(value), old =
|
|
100
|
+
const key = this.options.key(value), old = staged.get(key) ?? this.values.get(key);
|
|
101
|
+
const next = this.options.merge(old, value);
|
|
91
102
|
if (JSON.stringify(old) === JSON.stringify(next))
|
|
92
103
|
continue;
|
|
104
|
+
if (this.bytes(next) > this.transactionBytes)
|
|
105
|
+
throw new Error("RECORD_CACHE_RECORD_TOO_LARGE");
|
|
106
|
+
staged.set(key, structuredClone(next));
|
|
107
|
+
}
|
|
108
|
+
let nextBytes = this.pendingBytes, nextRecords = this.pending.size;
|
|
109
|
+
for (const [key, value] of staged) {
|
|
110
|
+
const previous = this.pending.get(key);
|
|
111
|
+
nextBytes += this.bytes(value) - (previous === undefined ? 0 : this.bytes(previous));
|
|
112
|
+
if (!this.pending.has(key))
|
|
113
|
+
nextRecords++;
|
|
114
|
+
}
|
|
115
|
+
if (nextRecords + this.activeRecords > 4096 || nextBytes + this.activeBytes > this.queueBytes)
|
|
116
|
+
throw new Error("RECORD_CACHE_BACKPRESSURE");
|
|
117
|
+
let changed = false;
|
|
118
|
+
for (const [key, next] of staged) {
|
|
93
119
|
this.values.set(key, next);
|
|
94
120
|
this.pending.set(key, next);
|
|
95
121
|
changed = true;
|
|
96
122
|
}
|
|
123
|
+
this.pendingBytes = nextBytes;
|
|
97
124
|
if (changed)
|
|
98
125
|
this.snapshotValue = [...this.values.values()];
|
|
99
|
-
if (!changed && !this.pending.size)
|
|
126
|
+
if (!changed && !this.pending.size) {
|
|
127
|
+
await this.running;
|
|
100
128
|
return;
|
|
129
|
+
}
|
|
101
130
|
const committed = new Promise((resolve, reject) => this.waiters.push({ resolve, reject }));
|
|
102
131
|
this.tasks.schedule("write", () => this.flush());
|
|
103
132
|
return committed;
|
|
104
133
|
}
|
|
134
|
+
bytes(value) { return new TextEncoder().encode(JSON.stringify({ scope: this.options.scope, id: this.options.key(value), value })).byteLength; }
|
|
105
135
|
async write(values) {
|
|
136
|
+
let batch = [], bytes = 0;
|
|
137
|
+
for (const value of values) {
|
|
138
|
+
const size = this.bytes(value);
|
|
139
|
+
if (size > this.transactionBytes)
|
|
140
|
+
throw new Error("RECORD_CACHE_RECORD_TOO_LARGE");
|
|
141
|
+
if (batch.length && (batch.length === 128 || bytes + size > this.transactionBytes)) {
|
|
142
|
+
await this.writeBatch(batch);
|
|
143
|
+
batch = [];
|
|
144
|
+
bytes = 0;
|
|
145
|
+
}
|
|
146
|
+
batch.push(value);
|
|
147
|
+
bytes += size;
|
|
148
|
+
}
|
|
149
|
+
if (batch.length)
|
|
150
|
+
await this.writeBatch(batch);
|
|
151
|
+
}
|
|
152
|
+
async writeBatch(values) {
|
|
106
153
|
await this.db.transaction("rw", this.records, async () => {
|
|
107
154
|
const previous = await this.records.bulkGet(values.map(value => [this.options.scope, this.options.key(value)]));
|
|
108
155
|
const records = values.map((value, index) => ({ scope: this.options.scope, id: this.options.key(value), value: this.options.merge(previous[index]?.value, value) }));
|
|
109
156
|
const changed = records.filter((row, index) => JSON.stringify(previous[index]?.value) !== JSON.stringify(row.value));
|
|
157
|
+
if (changed.reduce((sum, row) => sum + this.bytes(row.value), 0) > this.transactionBytes)
|
|
158
|
+
throw new Error("RECORD_CACHE_MERGE_TOO_LARGE");
|
|
110
159
|
if (changed.length)
|
|
111
160
|
await this.records.bulkPut(changed);
|
|
112
161
|
});
|
|
@@ -126,8 +175,11 @@ export class IndexedDbRecordCache {
|
|
|
126
175
|
async runFlush() {
|
|
127
176
|
const values = [...this.pending.values()], waiters = this.waiters.splice(0);
|
|
128
177
|
this.pending.clear();
|
|
178
|
+
this.pendingBytes = 0;
|
|
129
179
|
if (!values.length)
|
|
130
180
|
return;
|
|
181
|
+
this.activeBytes = values.reduce((sum, value) => sum + this.bytes(value), 0);
|
|
182
|
+
this.activeRecords = values.length;
|
|
131
183
|
try {
|
|
132
184
|
for (let offset = 0; offset < values.length; offset += 128)
|
|
133
185
|
await this.write(values.slice(offset, offset + 128));
|
|
@@ -142,9 +194,14 @@ export class IndexedDbRecordCache {
|
|
|
142
194
|
const key = this.options.key(value);
|
|
143
195
|
this.pending.set(key, this.options.merge(value, this.pending.get(key) ?? value));
|
|
144
196
|
}
|
|
197
|
+
this.pendingBytes = [...this.pending.values()].reduce((sum, value) => sum + this.bytes(value), 0);
|
|
145
198
|
waiters.forEach(waiter => waiter.reject(error));
|
|
146
199
|
throw error;
|
|
147
200
|
}
|
|
201
|
+
finally {
|
|
202
|
+
this.activeBytes = 0;
|
|
203
|
+
this.activeRecords = 0;
|
|
204
|
+
}
|
|
148
205
|
}
|
|
149
206
|
async close() {
|
|
150
207
|
this.closing = true;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Small response windows, isolated by identity. Epochs fence late writes after
|
|
2
|
+
* access withdrawal. No localStorage or synchronous writes on the read path. */
|
|
3
|
+
export declare class IndexedDbResponseCache<T> {
|
|
4
|
+
private scope;
|
|
5
|
+
private db;
|
|
6
|
+
private rows;
|
|
7
|
+
private epochs;
|
|
8
|
+
private pending;
|
|
9
|
+
private tasks;
|
|
10
|
+
private running?;
|
|
11
|
+
private invalidations;
|
|
12
|
+
private closed;
|
|
13
|
+
private closing?;
|
|
14
|
+
constructor(scope: string, options?: {
|
|
15
|
+
indexedDB?: IDBFactory;
|
|
16
|
+
name?: string;
|
|
17
|
+
});
|
|
18
|
+
read(key: string): Promise<{
|
|
19
|
+
epoch: number;
|
|
20
|
+
cached: {
|
|
21
|
+
value: T;
|
|
22
|
+
time: number;
|
|
23
|
+
} | undefined;
|
|
24
|
+
}>;
|
|
25
|
+
write(key: string, value: T, epoch: number): Promise<void>;
|
|
26
|
+
invalidate(): Promise<void>;
|
|
27
|
+
flush(): Promise<void>;
|
|
28
|
+
close(): Promise<void>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Dexie } from "dexie";
|
|
2
|
+
import { WindowedTasks } from "./coalescer.js";
|
|
3
|
+
/** Small response windows, isolated by identity. Epochs fence late writes after
|
|
4
|
+
* access withdrawal. No localStorage or synchronous writes on the read path. */
|
|
5
|
+
export class IndexedDbResponseCache {
|
|
6
|
+
scope;
|
|
7
|
+
db;
|
|
8
|
+
rows;
|
|
9
|
+
epochs;
|
|
10
|
+
pending = [];
|
|
11
|
+
tasks = new WindowedTasks(16, () => { });
|
|
12
|
+
running;
|
|
13
|
+
invalidations = new Set();
|
|
14
|
+
closed = false;
|
|
15
|
+
closing;
|
|
16
|
+
constructor(scope, options = {}) {
|
|
17
|
+
this.scope = scope;
|
|
18
|
+
this.db = new Dexie(options.name ?? "pmate-chat-response-windows", { indexedDB: options.indexedDB ?? globalThis.indexedDB, IDBKeyRange: globalThis.IDBKeyRange });
|
|
19
|
+
this.db.version(1).stores({ windows: "[scope+key],scope", epochs: "scope" });
|
|
20
|
+
this.rows = this.db.table("windows");
|
|
21
|
+
this.epochs = this.db.table("epochs");
|
|
22
|
+
}
|
|
23
|
+
async read(key) {
|
|
24
|
+
if (this.closed)
|
|
25
|
+
throw new Error("RESPONSE_CACHE_CLOSED");
|
|
26
|
+
return this.db.transaction("r", this.rows, this.epochs, async () => {
|
|
27
|
+
const epoch = (await this.epochs.get(this.scope))?.epoch ?? 0;
|
|
28
|
+
const row = await this.rows.get([this.scope, key]);
|
|
29
|
+
return { epoch, cached: row?.epoch === epoch ? { value: row.value, time: row.time } : undefined };
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
write(key, value, epoch) {
|
|
33
|
+
if (this.closed)
|
|
34
|
+
return Promise.reject(new Error("RESPONSE_CACHE_CLOSED"));
|
|
35
|
+
const copy = structuredClone(value), bytes = new TextEncoder().encode(JSON.stringify(copy)).byteLength;
|
|
36
|
+
// Count in-flight data as well as queued data; requests cannot create an
|
|
37
|
+
// unbounded backlog while IndexedDB is blocked by another tab.
|
|
38
|
+
if (bytes > 65536 || this.pending.length >= 128 || this.pending.reduce((n, w) => n + w.row.bytes, 0) + bytes > 1048576)
|
|
39
|
+
return Promise.reject(new Error("RESPONSE_CACHE_BACKPRESSURE"));
|
|
40
|
+
const promise = new Promise((resolve, reject) => this.pending.push({ row: { scope: this.scope, key, epoch, time: Date.now(), bytes, value: copy }, resolve, reject }));
|
|
41
|
+
this.tasks.schedule("write", () => this.flush());
|
|
42
|
+
return promise;
|
|
43
|
+
}
|
|
44
|
+
invalidate() {
|
|
45
|
+
if (this.closed)
|
|
46
|
+
return Promise.reject(new Error("RESPONSE_CACHE_CLOSED"));
|
|
47
|
+
const task = (async () => {
|
|
48
|
+
await this.db.transaction("rw", this.rows, this.epochs, async () => {
|
|
49
|
+
const epoch = ((await this.epochs.get(this.scope))?.epoch ?? 0) + 1;
|
|
50
|
+
await this.epochs.put({ scope: this.scope, epoch });
|
|
51
|
+
await this.rows.where("scope").equals(this.scope).delete();
|
|
52
|
+
});
|
|
53
|
+
})();
|
|
54
|
+
this.invalidations.add(task);
|
|
55
|
+
return task.finally(() => this.invalidations.delete(task));
|
|
56
|
+
}
|
|
57
|
+
async flush() {
|
|
58
|
+
if (this.running) {
|
|
59
|
+
await this.running;
|
|
60
|
+
if (this.pending.length)
|
|
61
|
+
return this.flush();
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const batch = [...this.pending];
|
|
65
|
+
if (!batch.length)
|
|
66
|
+
return;
|
|
67
|
+
const task = (async () => {
|
|
68
|
+
try {
|
|
69
|
+
const accepted = await this.db.transaction("rw", this.rows, this.epochs, async () => {
|
|
70
|
+
const epoch = (await this.epochs.get(this.scope))?.epoch ?? 0;
|
|
71
|
+
const valid = batch.filter(write => write.row.epoch === epoch);
|
|
72
|
+
const unique = new Map(valid.map(write => [write.row.key, write.row]));
|
|
73
|
+
await this.rows.bulkPut([...unique.values()]);
|
|
74
|
+
const stored = await this.rows.where("scope").equals(this.scope).toArray();
|
|
75
|
+
stored.sort((a, b) => b.time - a.time || a.key.localeCompare(b.key));
|
|
76
|
+
let bytes = 0;
|
|
77
|
+
const evicted = [];
|
|
78
|
+
stored.forEach((row, index) => { bytes += row.bytes; if (index >= 256 || bytes > 1048576)
|
|
79
|
+
evicted.push([this.scope, row.key]); });
|
|
80
|
+
await this.rows.bulkDelete(evicted);
|
|
81
|
+
return new Set(valid);
|
|
82
|
+
});
|
|
83
|
+
batch.forEach(write => accepted.has(write) ? write.resolve() : write.reject(new Error("RESPONSE_CACHE_INVALIDATED")));
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
batch.forEach(write => write.reject(error));
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
finally {
|
|
90
|
+
this.pending.splice(0, batch.length);
|
|
91
|
+
}
|
|
92
|
+
})().finally(() => { if (this.running === task)
|
|
93
|
+
this.running = undefined; });
|
|
94
|
+
this.running = task;
|
|
95
|
+
return task;
|
|
96
|
+
}
|
|
97
|
+
close() {
|
|
98
|
+
if (this.closing)
|
|
99
|
+
return this.closing;
|
|
100
|
+
this.closed = true;
|
|
101
|
+
this.tasks.close();
|
|
102
|
+
return this.closing = (async () => {
|
|
103
|
+
try {
|
|
104
|
+
await Promise.all([this.flush(), ...this.invalidations]);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
this.db.close();
|
|
108
|
+
}
|
|
109
|
+
})();
|
|
110
|
+
}
|
|
111
|
+
}
|
package/package.json
CHANGED