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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231 | /**
* Raw-envelope LRU cache for the public feed (docs/PROTOCOL.md §6 re-seed
* contract, deferred from M4): verified feed envelopes (0x10 docs and their
* referenced 0x11 blocks) are cached VERBATIM so a later visit can re-deposit
* them byte-identically — server-side SHA-256 dedup makes a re-deposit free
* and re-arms the mailbox TTL, which is what keeps a shard alive between
* author visits.
*
* Storage: one IndexedDB store keyed by cid string. Envelopes are ≤64 KB by
* construction (one mailbox frame each); the whole cache is size-bounded to
* ~5 MB with LRU eviction by lastUsed — OWN envelopes (my posts/likes) are
* evicted only after every foreign one is gone, because "own docs always"
* re-seeding depends on them. Everything is best-effort: a browser without
* IndexedDB (or a private-mode failure) degrades to a no-op cache and only
* costs re-seeding, never reading.
*/
import { nsDb } from "../config";
export interface CachedEnvelope {
/** The envelope's cid string — the store key and dedup identity. */
cid: string;
kind: "doc" | "block";
shard: string;
stripe: number;
/** Doc ts (blocks inherit the referencing doc's ts) — drives the 24 h age gate. */
ts: number;
own: boolean;
size: number;
lastUsed: number;
raw: Uint8Array;
/** For docs: root cids of the 0x11 blocks the doc references (images). */
blockCids?: string[];
/**
* P1 activities: the activity's `end` ts (joins inherit their activity's).
* Re-seeding skips docs whose exp lies >24 h in the past, so expired
* activities age out of the public window instead of living forever.
*/
exp?: number;
}
const DB_NAME = nsDb("feed-cache");
const STORE = "env";
const MAX_TOTAL_BYTES = 5 * 1024 * 1024;
let dbPromise: Promise<IDBDatabase | null> | null = null;
/**
* Running total of cached `size` bytes, so cachePut can decide whether eviction
* is needed WITHOUT a full-store getAll() on every write. null = unknown (boot,
* or after a delete): recomputed once via a cursor, then maintained
* incrementally. Best-effort (single tab); a desync just recomputes.
*/
let totalBytes: number | null = null;
/** One-time (per unknown state) size sum via a cursor — no raw copies retained. */
function ensureTotal(db: IDBDatabase): Promise<void> {
if (totalBytes !== null) return Promise.resolve();
return new Promise((resolve) => {
try {
const tx = db.transaction(STORE, "readonly");
let sum = 0;
const req = tx.objectStore(STORE).openCursor();
req.onsuccess = () => {
const cur = req.result;
if (cur) {
sum += (cur.value as CachedEnvelope).size ?? 0;
cur.continue();
} else {
totalBytes = sum;
resolve();
}
};
req.onerror = () => resolve();
} catch {
resolve();
}
});
}
function openDb(): Promise<IDBDatabase | null> {
if (dbPromise) return dbPromise;
dbPromise = new Promise((resolve) => {
try {
const req = indexedDB.open(DB_NAME, 1);
req.onupgradeneeded = () => {
const db = req.result;
if (!db.objectStoreNames.contains(STORE)) {
const store = db.createObjectStore(STORE, { keyPath: "cid" });
store.createIndex("shard", "shard");
store.createIndex("lastUsed", "lastUsed");
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => resolve(null);
req.onblocked = () => resolve(null);
} catch {
resolve(null);
}
});
return dbPromise;
}
function txDone(tx: IDBTransaction): Promise<void> {
return new Promise((resolve, reject) => {
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error ?? new Error("tx failed"));
tx.onabort = () => reject(tx.error ?? new Error("tx aborted"));
});
}
function reqResult<T>(req: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error ?? new Error("req failed"));
});
}
/** Store envelopes (upsert by cid), then evict LRU down to the size budget. */
export async function cachePut(entries: CachedEnvelope[]): Promise<void> {
if (entries.length === 0) return;
const db = await openDb();
if (!db) return;
try {
await ensureTotal(db); // one-time size sum; then maintained incrementally
const tx = db.transaction(STORE, "readwrite");
const store = tx.objectStore(STORE);
for (const e of entries) {
if (e.raw.length > 65_536) continue; // envelopes are one mailbox frame
// count() is a keys-only request (no raw copy) — a re-put of the same cid
// is byte-identical (cid = content hash), so only NEW cids grow the total.
const cReq = store.count(e.cid);
cReq.onsuccess = () => {
const existed = cReq.result > 0;
store.put(e);
if (!existed && totalBytes !== null) totalBytes += e.size;
};
}
await txDone(tx);
if (totalBytes === null || totalBytes > MAX_TOTAL_BYTES) await evictOverBudget(db);
} catch {
// best-effort cache — quota/private-mode failures cost only re-seeding
totalBytes = null; // a failed write may have left the counter out of sync
}
}
/** Bump lastUsed on a set of cids (a read = a use, for LRU purposes). */
export async function cacheTouch(cids: string[]): Promise<void> {
if (cids.length === 0) return;
const db = await openDb();
if (!db) return;
try {
const tx = db.transaction(STORE, "readwrite");
const store = tx.objectStore(STORE);
const now = Date.now();
for (const cid of cids) {
const req = store.get(cid);
req.onsuccess = () => {
const e = req.result as CachedEnvelope | undefined;
if (e) {
e.lastUsed = now;
store.put(e);
}
};
}
await txDone(tx);
} catch {}
}
export async function cacheGet(cid: string): Promise<CachedEnvelope | null> {
const db = await openDb();
if (!db) return null;
try {
const tx = db.transaction(STORE, "readonly");
const e = await reqResult(tx.objectStore(STORE).get(cid));
return (e as CachedEnvelope | undefined) ?? null;
} catch {
return null;
}
}
/** All cached DOC envelopes of one shard (blocks are fetched by cid). */
export async function cacheDocsOf(shard: string): Promise<CachedEnvelope[]> {
const db = await openDb();
if (!db) return [];
try {
const tx = db.transaction(STORE, "readonly");
const all = await reqResult(tx.objectStore(STORE).index("shard").getAll(shard));
return (all as CachedEnvelope[]).filter((e) => e.kind === "doc");
} catch {
return [];
}
}
/** Remove one envelope (e.g. a locally-deleted own post + its blocks). */
export async function cacheDelete(cids: string[]): Promise<void> {
if (cids.length === 0) return;
const db = await openDb();
if (!db) return;
try {
const tx = db.transaction(STORE, "readwrite");
for (const cid of cids) tx.objectStore(STORE).delete(cid);
await txDone(tx);
totalBytes = null; // sizes of the deleted rows are unknown here — recompute
} catch {}
}
/** Evict least-recently-used entries until under budget; own entries last. */
async function evictOverBudget(db: IDBDatabase): Promise<void> {
try {
const tx = db.transaction(STORE, "readonly");
const all = (await reqResult(tx.objectStore(STORE).getAll())) as CachedEnvelope[];
let total = 0;
for (const e of all) total += e.size;
if (total <= MAX_TOTAL_BYTES) return;
// foreign before own, stalest first inside each class
const order = [...all].sort((a, b) => Number(a.own) - Number(b.own) || a.lastUsed - b.lastUsed);
const victims: string[] = [];
for (const e of order) {
if (total <= MAX_TOTAL_BYTES) break;
victims.push(e.cid);
total -= e.size;
}
const wtx = db.transaction(STORE, "readwrite");
for (const cid of victims) wtx.objectStore(STORE).delete(cid);
await txDone(wtx);
totalBytes = total; // authoritative post-eviction total (survivors' bytes)
} catch {
totalBytes = null;
}
}
|