Something went wrong. Try again.
A live media wall for your Bluesky follows
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405import type { PGlite } from '@electric-sql/pglite';import { PGliteWorker } from '@electric-sql/pglite/worker';import { sanitizeWallSnapshot, type WallSnapshot } from './wall-snapshot.js';
export const THUMBHASH_CACHE_LIMIT = 2000;
export type GraphSnapshot = { follows: string[]; blocks: string[]; syncedAt: number;};
export interface GraphCache { readonly persistent: boolean; load(account: string): Promise<GraphSnapshot | null>; save(account: string, snapshot: GraphSnapshot): Promise<void>; loadWall(account: string): Promise<WallSnapshot | null>; saveWall(account: string, snapshot: WallSnapshot): Promise<void>; clearWall(account: string): Promise<void>; loadThumbhashes(account: string, keys: readonly string[]): Promise<Record<string, Uint8Array>>; loadThumbhash(account: string, key: string): Promise<Uint8Array | null>; saveThumbhash(account: string, key: string, hash: Uint8Array): Promise<void>; close(): Promise<void>;}
function copySnapshot(snapshot: GraphSnapshot): GraphSnapshot { return { follows: [...snapshot.follows], blocks: [...snapshot.blocks], syncedAt: snapshot.syncedAt };}
function copyThumbhash(hash: Uint8Array): Uint8Array { if (hash.length < 5 || hash.length > 64) { throw new RangeError('Thumbhash must contain 5 to 64 bytes'); } return new Uint8Array(hash);}
function wallForAccount(account: string, value: unknown, strict = false): WallSnapshot | null { let reason = 'snapshot belongs to a different account'; const snapshot = sanitizeWallSnapshot( value, Date.now(), (message) => { reason = message; }, strict ); if (snapshot?.moderation.userDid === account) return snapshot; if (strict) throw new TypeError(`Unable to cache the wall: ${reason}`); return null;}
function memoryCache(): GraphCache { const walls = new Map<string, WallSnapshot>(); const snapshots = new Map<string, GraphSnapshot>(); const thumbhashes = new Map<string, Map<string, Uint8Array>>(); let closed = false; const assertOpen = () => { if (closed) throw new Error('Graph cache is closed'); };
return { persistent: false, async load(account) { assertOpen(); const snapshot = snapshots.get(account); return snapshot ? copySnapshot(snapshot) : null; }, async save(account, snapshot) { assertOpen(); snapshots.set(account, copySnapshot(snapshot)); }, async loadWall(account) { assertOpen(); return wallForAccount(account, walls.get(account)); }, async saveWall(account, snapshot) { assertOpen(); const copy = wallForAccount(account, snapshot, true)!; walls.set(account, copy); }, async clearWall(account) { assertOpen(); walls.delete(account); }, async loadThumbhashes(account, keys) { assertOpen(); const entries = thumbhashes.get(account); return Object.fromEntries( keys.slice(0, 300).flatMap((key) => { const hash = entries?.get(key); return hash ? [[key, new Uint8Array(hash)]] : []; }) ); }, async loadThumbhash(account, key) { assertOpen(); const entries = thumbhashes.get(account); const hash = entries?.get(key); if (!hash) return null; entries!.delete(key); entries!.set(key, hash); return new Uint8Array(hash); }, async saveThumbhash(account, key, hash) { assertOpen(); const copy = copyThumbhash(hash); let entries = thumbhashes.get(account); if (!entries) { entries = new Map(); thumbhashes.set(account, entries); } entries.delete(key); entries.set(key, copy); if (entries.size > THUMBHASH_CACHE_LIMIT) { entries.delete(entries.keys().next().value!); } }, async close() { closed = true; snapshots.clear(); thumbhashes.clear(); walls.clear(); } };}
export async function openCache(): Promise<GraphCache> { let worker: Worker | undefined; let db: PGliteWorker | undefined;
try { if ( typeof window === 'undefined' || typeof Worker === 'undefined' || typeof indexedDB === 'undefined' || typeof BroadcastChannel === 'undefined' || !navigator.locks ) { return memoryCache(); } // Avoid starting an IndexedDB database when the origin reports almost no room. const estimate = await navigator.storage?.estimate?.().catch(() => undefined); if ( estimate?.quota !== undefined && estimate.usage !== undefined && estimate.quota - estimate.usage < 16 * 1024 * 1024 ) return memoryCache();
const obsolete = indexedDB.deleteDatabase('/pglite/mural-graph-cache'); obsolete.onerror = () => {}; obsolete.onblocked = () => {}; worker = new Worker(new URL('./cache.worker.ts', import.meta.url), { type: 'module' }); db = new PGliteWorker(worker, { dataDir: 'idb://mural-cache-v2', id: 'mural-cache-v2' });
let timer: ReturnType<typeof setTimeout> | undefined; let onError: ((event: ErrorEvent) => void) | undefined; try { await Promise.race([ db.waitReady, new Promise<never>((_, reject) => { timer = setTimeout( () => reject(new Error('Graph cache initialization timed out')), 30_000 ); onError = () => reject(new Error('Graph cache worker failed')); worker!.addEventListener('error', onError); }) ]); } finally { if (timer !== undefined) clearTimeout(timer); if (onError) worker.removeEventListener('error', onError); } } catch { void db?.close().catch(() => {}); worker?.terminate(); return memoryCache(); }
const cacheWorker = worker; return resilientCache( createPersistentCache(db, () => cacheWorker.terminate()), () => cacheWorker.terminate() );}
export function resilientCache( primary: GraphCache, onFailure: () => void = () => {}, operationTimeoutMs = 10_000): GraphCache { const fallback = memoryCache(); let failed = false; let closed = false; let queue = Promise.resolve(); const fail = () => { if (failed) return; failed = true; void primary.close().catch(() => {}); onFailure(); }; return new Proxy(fallback, { get(target, property) { if (property === 'persistent') return !failed && primary.persistent; if (property === 'close') return () => { if (closed) return queue; closed = true; queue = queue.then(async () => { await fallback.close(); if (!failed) await primary.close(); }); return queue; }; if ( typeof property !== 'string' || !(property in target) || typeof target[property as keyof GraphCache] !== 'function' ) return undefined; return (...args: unknown[]) => { if (closed) return Promise.reject(new Error('Graph cache is closed')); const operation = queue.then(async () => { const local = target[property as keyof GraphCache] as ( ...args: unknown[] ) => Promise<unknown>; if (failed) return local.apply(target, args); let result: unknown; let timer: ReturnType<typeof setTimeout> | undefined; try { const remote = primary[property as keyof GraphCache] as ( ...args: unknown[] ) => Promise<unknown>; result = await Promise.race([ remote.apply(primary, args), new Promise<never>((_, reject) => { timer = setTimeout( () => reject(new Error('Graph cache operation timed out')), operationTimeoutMs ); }) ]); } catch (error) { if (error instanceof TypeError || error instanceof RangeError) throw error; fail(); return local.apply(target, args); } finally { if (timer !== undefined) clearTimeout(timer); } const account = args[0] as string; if (property === 'load' && result) await fallback.save(account, result as GraphSnapshot); else if (property === 'loadWall' && result) await fallback.saveWall(account, result as WallSnapshot); else if (property === 'loadThumbhash' && result) await fallback.saveThumbhash(account, args[1] as string, result as Uint8Array); else if (property === 'loadThumbhashes' && result) { for (const [key, hash] of Object.entries(result)) await fallback.saveThumbhash(account, key, hash as Uint8Array); } else if (property.startsWith('save') || property === 'clearWall') await local.apply(target, args); return result; }); queue = operation.then( () => {}, () => {} ); return operation; }; } });}
export function createPersistentCache( database: Pick<PGlite, 'query' | 'transaction' | 'close'>, onClose: () => void = () => {}): GraphCache { let closing: Promise<void> | undefined; const touched = new Map<string, number>(); const assertOpen = () => { if (closing) throw new Error('Graph cache is closed'); };
return { persistent: true, async load(account) { assertOpen(); const result = await database.query<GraphSnapshot>( `SELECT s.synced_at AS "syncedAt", ARRAY(SELECT subject_did FROM graph_records WHERE account = s.account AND kind = 'follow' ORDER BY position) AS follows, ARRAY(SELECT subject_did FROM graph_records WHERE account = s.account AND kind = 'block' ORDER BY position) AS blocks FROM graph_snapshots s WHERE s.account = $1`, [account] ); return result.rows[0] ?? null; }, async save(account, snapshot) { assertOpen(); const complete = copySnapshot(snapshot); await database.transaction(async (tx) => { await tx.query( `INSERT INTO graph_snapshots (account, synced_at) VALUES ($1, $2) ON CONFLICT (account) DO UPDATE SET synced_at = EXCLUDED.synced_at`, [account, complete.syncedAt] ); await tx.query('DELETE FROM graph_records WHERE account = $1', [account]); for (const [kind, records] of [ ['follow', complete.follows], ['block', complete.blocks] ] as const) { await tx.query( `INSERT INTO graph_records (account, kind, position, subject_did) SELECT $1, $2, position, subject_did FROM unnest($3::text[]) WITH ORDINALITY AS records(subject_did, position)`, [account, kind, records] ); } }); }, async loadWall(account) { assertOpen(); const { rows } = await database.query<{ payload: unknown }>( 'SELECT payload FROM wall_snapshots WHERE account = $1', [account] ); return wallForAccount(account, rows[0]?.payload); }, async saveWall(account, snapshot) { assertOpen(); const copy = wallForAccount(account, snapshot, true)!; await database.query( `INSERT INTO wall_snapshots (account, payload) VALUES ($1, $2::jsonb) ON CONFLICT (account) DO UPDATE SET payload = EXCLUDED.payload WHERE wall_snapshots.payload IS DISTINCT FROM EXCLUDED.payload`, [account, JSON.stringify(copy)] ); }, async clearWall(account) { assertOpen(); await database.query('DELETE FROM wall_snapshots WHERE account = $1', [account]); }, async loadThumbhashes(account, keys) { assertOpen(); if (!keys.length) return {}; const { rows } = await database.query<{ asset_key: string; hash: Uint8Array }>( 'SELECT asset_key, hash FROM asset_thumbhashes WHERE account = $1 AND asset_key = ANY($2::text[])', [account, keys.slice(0, 300)] ); return Object.fromEntries(rows.map((row) => [row.asset_key, new Uint8Array(row.hash)])); }, async loadThumbhash(account, key) { assertOpen(); const { rows } = await database.query<{ hash: Uint8Array }>( `SELECT hash FROM asset_thumbhashes WHERE account = $1 AND asset_key = $2`, [account, key] ); if (!rows[0]) return null; const touchKey = JSON.stringify([account, key]); if (Date.now() - (touched.get(touchKey) ?? 0) >= 5 * 60_000) { await database.query( `UPDATE asset_thumbhashes SET accessed_at = clock_timestamp(), access_order = nextval('asset_thumbhash_access_order') WHERE account = $1 AND asset_key = $2`, [account, key] ); touched.set(touchKey, Date.now()); if (touched.size > 4000) touched.delete(touched.keys().next().value!); } return new Uint8Array(rows[0].hash); }, async saveThumbhash(account, key, hash) { assertOpen(); const copy = copyThumbhash(hash); await database.transaction(async (tx) => { await tx.query( `INSERT INTO asset_thumbhashes (account, asset_key, hash) VALUES ($1, $2, $3) ON CONFLICT (account, asset_key) DO UPDATE SET hash = EXCLUDED.hash, accessed_at = clock_timestamp(), access_order = nextval('asset_thumbhash_access_order')`, [account, key, copy] ); await tx.query( `DELETE FROM asset_thumbhashes WHERE account = $1 AND asset_key IN ( SELECT asset_key FROM asset_thumbhashes WHERE account = $1 ORDER BY access_order DESC OFFSET $2 )`, [account, THUMBHASH_CACHE_LIMIT] ); }); }, close() { closing ??= database.close().finally(onClose); return closing; } };}