1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
|
import type { StoredChunk } from "@dispatch/wire";
import type {
ConversationCacheIndexEntry,
ConversationChunkStore,
} from "../../features/conversation-cache";
const DEFAULT_DB_NAME = "dispatch-chunk-cache";
const DB_VERSION = 1;
const CHUNKS_STORE = "chunks";
const META_STORE = "meta";
interface ChunkRecord {
conversationId: string;
seq: number;
role: StoredChunk["role"];
chunk: StoredChunk["chunk"];
}
interface MetaRecord {
conversationId: string;
lastAccess: number;
}
export interface CreateIdbChunkStoreOptions {
indexedDB?: IDBFactory;
dbName?: string;
}
function requestToPromise<T>(req: IDBRequest<T>): Promise<T> {
return new Promise<T>((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function txComplete(tx: IDBTransaction): Promise<void> {
return new Promise<void>((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
tx.onabort = () => reject(tx.error);
});
}
function openDb(idb: IDBFactory, dbName: string): Promise<IDBDatabase> {
return new Promise<IDBDatabase>((resolve, reject) => {
const req = idb.open(dbName, DB_VERSION);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains(CHUNKS_STORE)) {
const store = db.createObjectStore(CHUNKS_STORE, {
keyPath: ["conversationId", "seq"],
});
store.createIndex("byConversation", "conversationId");
}
if (!db.objectStoreNames.contains(META_STORE)) {
db.createObjectStore(META_STORE, { keyPath: "conversationId" });
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
function keyRangeFor(conversationId: string): IDBKeyRange {
const lower: [string, number] = [conversationId, 0];
const upper: [string, number] = [conversationId, Number.POSITIVE_INFINITY];
return IDBKeyRange.bound(lower, upper);
}
function chunksToStoredChunks(records: ChunkRecord[]): StoredChunk[] {
return records.map((r) => ({ seq: r.seq, role: r.role, chunk: r.chunk }));
}
export function createIdbChunkStore(opts?: CreateIdbChunkStoreOptions): ConversationChunkStore {
const idb = opts?.indexedDB ?? globalThis.indexedDB;
const dbName = opts?.dbName ?? DEFAULT_DB_NAME;
let dbPromise: Promise<IDBDatabase> | null = null;
function getDb(): Promise<IDBDatabase> {
if (dbPromise === null) {
dbPromise = openDb(idb, dbName);
}
return dbPromise;
}
return {
async load(conversationId: string): Promise<readonly StoredChunk[]> {
const db = await getDb();
const tx = db.transaction(CHUNKS_STORE, "readonly");
const store = tx.objectStore(CHUNKS_STORE);
const range = keyRangeFor(conversationId);
const records = await requestToPromise<ChunkRecord[]>(store.getAll(range));
await txComplete(tx);
records.sort((a, b) => a.seq - b.seq);
return chunksToStoredChunks(records);
},
async append(conversationId: string, chunks: readonly StoredChunk[]): Promise<void> {
if (chunks.length === 0) return;
const db = await getDb();
const tx = db.transaction([CHUNKS_STORE, META_STORE], "readwrite");
const chunkStore = tx.objectStore(CHUNKS_STORE);
const metaStore = tx.objectStore(META_STORE);
for (const c of chunks) {
chunkStore.put({
conversationId,
seq: c.seq,
role: c.role,
chunk: c.chunk,
} satisfies ChunkRecord);
}
metaStore.put({
conversationId,
lastAccess: Date.now(),
} satisfies MetaRecord);
await txComplete(tx);
},
async delete(conversationId: string): Promise<void> {
const db = await getDb();
const tx = db.transaction([CHUNKS_STORE, META_STORE], "readwrite");
const chunkStore = tx.objectStore(CHUNKS_STORE);
const metaStore = tx.objectStore(META_STORE);
chunkStore.delete(keyRangeFor(conversationId));
metaStore.delete(conversationId);
await txComplete(tx);
},
async index(): Promise<readonly ConversationCacheIndexEntry[]> {
const db = await getDb();
const tx = db.transaction([CHUNKS_STORE, META_STORE], "readonly");
const chunkStore = tx.objectStore(CHUNKS_STORE);
const metaStore = tx.objectStore(META_STORE);
const allChunks = await requestToPromise<ChunkRecord[]>(chunkStore.getAll());
const allMeta = await requestToPromise<MetaRecord[]>(metaStore.getAll());
await txComplete(tx);
const metaMap = new Map<string, number>();
for (const m of allMeta) {
metaMap.set(m.conversationId, m.lastAccess);
}
const grouped = new Map<string, { chunkCount: number; maxSeq: number }>();
for (const r of allChunks) {
const existing = grouped.get(r.conversationId);
if (existing === undefined) {
grouped.set(r.conversationId, { chunkCount: 1, maxSeq: r.seq });
} else {
existing.chunkCount++;
if (r.seq > existing.maxSeq) {
existing.maxSeq = r.seq;
}
}
}
const result: ConversationCacheIndexEntry[] = [];
for (const [conversationId, stats] of grouped) {
const lastAccess = metaMap.get(conversationId);
result.push({
conversationId,
chunkCount: stats.chunkCount,
maxSeq: stats.maxSeq,
...(lastAccess !== undefined ? { lastAccess } : {}),
});
}
return result;
},
};
}
|