fix(web): replay IndexedDB writes after quota recovery

This commit is contained in:
DarkSky committed 2026-12-02 20:15:38 +09:00
1 parent 65460a7f13
commit 2cbee4060d
4 files changed
+291 -29

No files matched your search

+28 -18
View File
@@ -25,8 +25,8 @@ async function fetchFont(url) {
* The updates and deletions of each workspace go to IndexedDB in call order.
* The changes queued in one task go in one transaction per workspace that
* issues every request at once (`writeDocOpsNow`), so a `flush()` from a
* `pagehide` handler completes while the page unloads. The storage writes a
* failed transaction again.
* `pagehide` handler can commit while the page unloads. A flush also retries
* writes that paused after a quota failure.
*
* @param {string[]} workspaceIds
* @param {{ indexedDB?: IDBFactory, location?: Location, history?: History }} [env]
@@ -34,6 +34,8 @@ async function fetchFont(url) {
export async function openDesktopStore(workspaceIds, env = globalThis) {
const indexedDB = env.indexedDB;
if (!indexedDB || typeof indexedDB.open !== 'function') return null;
/** @type {() => void} */
let markSeeded = () => {};
/** @type {Map<string, ReturnType<typeof createIdbWorkspaceStorage>>} */
const storages = new Map();
/** @type {Map<string, Map<string, Uint8Array[]>>} */
@@ -45,6 +47,7 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
type: 'workspace',
id,
indexedDB,
onDocWriteFailure: () => markSeeded(),
});
storages.set(id, storage);
await storage.open();
@@ -73,8 +76,6 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
const inFlight = new Set();
/** Workspaces that the store held no document of and that no write committed to yet. */
const unseeded = new Set(workspaceIds.filter(id => !frames.get(id)?.size));
/** @type {() => void} */
let markSeeded = () => {};
/** @type {Promise<void>} */
const seeded = unseeded.size
? new Promise(resolve => {
@@ -83,12 +84,18 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
: Promise.resolve();
const writeFailed = error => {
console.error('AFFiNE Desktop could not save a change', error);
if (error?.name !== 'QuotaExceededError') {
console.error('AFFiNE Desktop could not save a change', error);
}
markSeeded();
};
const enqueue = (workspaceId, op) => {
if (!queued.size) queueMicrotask(flush);
if (!queued.size) {
queueMicrotask(() => {
if (queued.size) void flush();
});
}
const ops = queued.get(workspaceId) ?? [];
ops.push(op);
queued.set(workspaceId, ops);
@@ -97,19 +104,22 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
const flush = () => {
const writes = queued;
queued = new Map();
for (const [id, ops] of writes) {
for (const id of new Set([...writes.keys(), ...storages.keys()])) {
const storage = storages.get(id);
const ops = writes.get(id);
let write;
try {
const written = storages
.get(id)
.writeDocOpsNow(ops)
.finally(() => inFlight.delete(written));
inFlight.add(written);
void written.then(() => {
if (unseeded.delete(id) && !unseeded.size) markSeeded();
}, writeFailed);
write = ops ? storage.writeDocOpsNow(ops) : storage.retryPausedWrites();
} catch (error) {
writeFailed(error);
continue;
}
if (!write) continue;
const written = write.finally(() => inFlight.delete(written));
inFlight.add(written);
void written.then(() => {
if (unseeded.delete(id) && !unseeded.size) markSeeded();
}, writeFailed);
}
const flushed = Promise.all(inFlight).then(() => {});
void flushed.catch(() => {});
@@ -143,7 +153,7 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
},
/**
* Resolves when a write to each workspace that the store held no
* document of has committed, or when the desktop runs in memory only.
* document of has committed, or after the first failed write.
*/
seeded,
/** Starts every queued write now. Resolves after every started write commits. */
@@ -173,8 +183,8 @@ export async function startDesktop(
const dark = theme === 'dark' || (theme !== 'light' && prefersDark);
const split = params.get('split');
// Tabs of one origin read the stores and seed the empty workspaces one at a
// time: a tab holds the lock until its seeded workspaces are written, so a
// tab that opens meanwhile reads the seeded content. Without
// time: a tab holds the lock until its seed writes commit or a write fails.
// Later tabs can read any seed that committed. Without
// `navigator.locks`, two seeds merge to the content of one seed.
const mount = async () => {
const store = await openStore(wasm.web_desktop_workspace_ids());
+67 -11
View File
@@ -506,6 +506,7 @@ function bytesEqual(a, b) {
* now?: () => number,
* mergeUpdates?: (updates: Uint8Array[]) => Uint8Array | Promise<Uint8Array>,
* readonlyMode?: boolean,
* onDocWriteFailure?: (error: Error) => void,
* }} options
*/
export function createIdbWorkspaceStorage(options) {
@@ -551,15 +552,16 @@ export function createIdbWorkspaceStorage(options) {
* `writeDocOpsNow` transactions from the oldest one that has not settled,
* in issue order.
* @typedef {{ resolve: () => void, reject: (error: Error) => void }} WriteResult
* @typedef {{ ops: DocOp[], state: 'pending' | 'committed' | 'failed', results: WriteResult[] }} DocWrite
* @typedef {{ ops: DocOp[], state: 'queued' | 'pending' | 'committed' | 'failed', results: WriteResult[] }} DocWrite
* @type {DocWrite[]}
*/
const docWrites = [];
/** Timer of the next attempt of the failed writes, or `null`. */
let retryTimer = null;
/** @type {'idle' | 'waiting' | 'due' | 'reading' | 'ready'} */
/** @type {'idle' | 'waiting' | 'due' | 'reading' | 'ready' | 'paused'} */
let retryState = 'idle';
let delayRetry = false;
let warnedAboutQuota = false;
/** @param {MessageEvent} event */
function handleChannelMessage(event) {
@@ -692,6 +694,7 @@ export function createIdbWorkspaceStorage(options) {
}
retryState = 'idle';
delayRetry = false;
warnedAboutQuota = false;
const error = versionError || new Error('IndexedDB storage was closed');
for (const write of docWrites.splice(0)) {
for (const { reject } of write.results) reject(error);
@@ -865,12 +868,13 @@ export function createIdbWorkspaceStorage(options) {
* supersedes older failed ops for that document. A failed delete retries
* with the updates that committed after it. After a second failure in a
* row the object waits `WRITE_RETRY_MS` before each new attempt. It
* stops after `close()` or a version change.
* stops after `close()` or a version change. When the quota is exceeded,
* it keeps the ops and waits for a new write or an explicit retry.
*
* @param {DocOp[]} ops
* @returns {Promise<void>} Resolves when the ops commit or a later delete
* supersedes them. Rejects if the connection closes before it can confirm
* the write.
* supersedes them. Rejects if storage runs out of space or the connection
* closes before it can confirm the write.
*/
function writeDocOpsNow(ops) {
if (readonlyMode) {
@@ -880,10 +884,21 @@ export function createIdbWorkspaceStorage(options) {
throw new Error('IndexedDB storage is not open');
}
return new Promise((resolve, reject) => {
issueDocWrite(ops, [{ resolve, reject }]);
const results = [{ resolve, reject }];
if (retryState === 'paused') {
docWrites.push({ ops, state: 'queued', results });
settleDocWrites();
} else {
issueDocWrite(ops, results);
}
});
}
/** Starts a paused replay even if the caller has no new ops. */
function retryPausedWrites() {
return retryState === 'paused' ? writeDocOpsNow([]) : null;
}
/** @param {DocOp[]} ops @param {WriteResult[]} results */
function issueDocWrite(ops, results) {
const gen = openGen;
@@ -917,7 +932,30 @@ export function createIdbWorkspaceStorage(options) {
error => {
if (gen !== openGen) return;
write.state = 'failed';
console.error('IndexedDB write failed and is written again', error);
options.onDocWriteFailure?.(error);
if (error?.name === 'QuotaExceededError') {
if (retryTimer !== null) {
clearTimer(retryTimer);
retryTimer = null;
}
retryState = 'paused';
if (!warnedAboutQuota) {
warnedAboutQuota = true;
console.warn(
'IndexedDB could not save the changes because storage is full',
error
);
}
for (const failed of docWrites) {
if (failed.state !== 'failed') continue;
for (const { reject } of failed.results.splice(0)) reject(error);
}
} else {
console.error('IndexedDB write failed and is written again', error);
if (retryState === 'paused') {
for (const { reject } of write.results.splice(0)) reject(error);
}
}
settleDocWrites();
}
);
@@ -1033,6 +1071,7 @@ export function createIdbWorkspaceStorage(options) {
}
retryState = 'idle';
delayRetry = false;
warnedAboutQuota = false;
return;
}
if (
@@ -1041,6 +1080,14 @@ export function createIdbWorkspaceStorage(options) {
) {
return;
}
if (retryState === 'paused') {
if (docWrites.some(write => write.state === 'queued')) {
retryState = 'idle';
delayRetry = false;
rewrite();
}
return;
}
if (retryState === 'ready') {
retryState = 'idle';
delayRetry = true;
@@ -1051,7 +1098,7 @@ export function createIdbWorkspaceStorage(options) {
if (retryState === 'idle' && delayRetry) {
retryState = 'waiting';
retryTimer = setTimer(() => {
if (gen !== openGen) return;
if (gen !== openGen || retryState !== 'waiting') return;
retryTimer = null;
retryState = 'due';
settleDocWrites();
@@ -1067,13 +1114,13 @@ export function createIdbWorkspaceStorage(options) {
);
void readStoredTimes(docIds).then(
() => {
if (gen !== openGen) return;
if (gen !== openGen || retryState !== 'reading') return;
// A write that arrived during the read can fail with a stale clock.
retryState = docWrites.at(-1) === newest ? 'ready' : 'due';
settleDocWrites();
},
() => {
if (gen !== openGen) return;
if (gen !== openGen || retryState !== 'reading') return;
retryState = 'idle';
delayRetry = true;
settleDocWrites();
@@ -1083,13 +1130,21 @@ export function createIdbWorkspaceStorage(options) {
/** Writes the failed ops again, with the updates after each failed delete. */
function rewrite() {
const superseded = new Set(
docWrites
.filter(write => write.state === 'queued')
.flatMap(write =>
write.ops.filter(op => 'delete' in op).map(op => op.docId)
)
);
const deleted = new Set();
const ops = [];
const results = [];
for (const write of docWrites.splice(0)) {
if (write.state === 'failed') {
if (write.state !== 'committed') {
results.push(...write.results);
for (const op of write.ops) {
if (write.state === 'failed' && superseded.has(op.docId)) continue;
if ('delete' in op) deleted.add(op.docId);
ops.push(op);
}
@@ -1844,6 +1899,7 @@ export function createIdbWorkspaceStorage(options) {
pushDocUpdate,
pushDocUpdatesBatch,
writeDocOpsNow,
retryPausedWrites,
getDoc,
getDocRaw,
compactDocWithMerged,
@@ -8,6 +8,7 @@ import {
openDesktopStore,
startDesktop,
} from '../desktop/start.js';
import { openWorkspaceIdb } from '../src/idb-storage.js';
import { createBroadcastBus, createMemoryIdbFactory } from './memory-idb.mjs';
globalThis.BroadcastChannel = createBroadcastBus();
@@ -223,6 +224,116 @@ void test('the desktop store flush resolves after a failed transaction is writte
}
});
for (const recovery of ['transient', 'flush', 'pagehide', 'new write']) {
void test(`the first desktop write failure releases the start lock before recovery by ${recovery}`, async t => {
const idb = globalThis.indexedDB ?? createMemoryIdbFactory();
const workspace = `ws-start-${recovery}`;
const quota = new DOMException('Storage is full', 'QuotaExceededError');
const transient = recovery === 'transient';
const releaseRead = Promise.withResolvers();
const retryRead = Promise.withResolvers();
const warnings = t.mock.method(console, 'warn', () => {});
const errors = t.mock.method(console, 'error', () => {});
let writes = 0;
let locked = false;
let firstFlush;
const locks = {
async request(name, mount) {
assert.equal(name, DESKTOP_START_LOCK);
locked = true;
try {
return await mount();
} finally {
locked = false;
}
},
};
const wasm = {
default() {},
web_desktop_workspace_ids: () => [workspace],
wasm_desktop_main(_dark, _split, _workspace, _doc, store) {
store.pushUpdate(workspace, 'root', Uint8Array.of(1));
firstFlush = store.flush();
},
};
const db = await openWorkspaceIdb(
{ flavour: 'local', type: 'workspace', id: workspace },
{ indexedDB: idb }
);
t.after(() => db.close());
const transaction = db.transaction.bind(db);
t.mock.method(db, 'transaction', (stores, mode) => {
if (mode === 'readwrite' && ++writes === 1 && transient) {
throw new DOMException('Write failed', 'AbortError');
}
const tx = transaction(stores, mode);
if (mode === 'readwrite' && writes === 1) {
tx.commit = () => {
Object.defineProperty(tx, 'error', { value: quota, writable: true });
tx.abort(quota);
};
}
if (mode === 'readonly' && writes === 1 && transient) {
Object.defineProperty(tx, 'oncomplete', {
set(complete) {
Object.defineProperty(tx, 'oncomplete', {
value: async event => {
retryRead.resolve();
await releaseRead.promise;
complete(event);
},
});
},
});
}
return tx;
});
const openStore = ids =>
openDesktopStore(ids, {
indexedDB: {
open() {
const req = { result: db };
queueMicrotask(() => req.onsuccess());
return req;
},
},
});
const store = await startDesktop(wasm, [], '', false, {}, openStore, locks);
assert.equal(locked, false);
assert.equal(writes, 1);
if (transient) {
await retryRead.promise;
releaseRead.resolve();
await firstFlush;
assert.equal(errors.mock.callCount(), 1);
} else {
await assert.rejects(firstFlush, quota);
assert.equal(warnings.mock.callCount(), 1);
assert.equal(errors.mock.callCount(), 0);
if (recovery === 'pagehide') {
const win = new EventTarget();
win.document = new EventTarget();
flushDesktopOnHide({ flush_web_desktop() {} }, store, win);
win.dispatchEvent(new Event('pagehide'));
assert.equal(
writes,
2,
'pagehide starts the transaction synchronously'
);
} else if (recovery === 'new write') {
store.pushUpdate(workspace, 'root', Uint8Array.of(2));
}
await store.flush();
}
assert.equal(writes, 2);
const cold = await openDesktopStore([workspace], { indexedDB: idb });
assert.deepEqual(
cold.docFrames(workspace, 'root').map(bin => [...bin]),
recovery === 'new write' ? [[1], [2]] : [[1]]
);
});
}
void test('the desktop store is seeded once a write to each workspace that it held no document of commits', async () => {
const idb = createMemoryIdbFactory();
const state = async store => {
@@ -1843,6 +1843,91 @@ void test('writeDocOpsNow writes again a failed transaction and the later deleti
const update = (docId, byte) => ({ docId, bin: Uint8Array.of(byte) });
const remove = docId => ({ docId, delete: true });
for (const resume of ['new write', 'explicit retry', 'delete']) {
void test(`quota failures pause without a timer and preserve the frames needed for a ${resume}`, async t => {
const quota = new DOMException('Storage is full', 'QuotaExceededError');
const warnings = t.mock.method(console, 'warn', () => {});
const errors = t.mock.method(console, 'error', () => {});
const failures = [];
const storage = createIdbWorkspaceStorage({
flavour: 'local',
type: 'workspace',
id: `ws-quota-${resume}`,
indexedDB: createIdbTestFactory(),
BroadcastChannelImpl: createBroadcastBus(),
onDocWriteFailure: error => failures.push(error),
setTimeout: () => assert.fail('quota failures must not start a timer'),
});
t.after(() => storage.close());
const db = await storage.open();
const transaction = db.transaction.bind(db);
const batches = [];
let full = true;
t.mock.method(db, 'transaction', (stores, mode) => {
const tx = transaction(stores, mode);
if (mode !== 'readwrite') return tx;
const batch = [];
batches.push(batch);
const updates = tx.objectStore('updates');
const objectStore = tx.objectStore.bind(tx);
const add = updates.add.bind(updates);
updates.add = record => {
batch.push(record.docId);
return add(record);
};
tx.objectStore = name =>
name === 'updates' ? updates : objectStore(name);
if (full) {
tx.commit = () => {
Object.defineProperty(tx, 'error', { value: quota, writable: true });
tx.abort(quota);
};
}
return tx;
});
await assert.rejects(
storage.writeDocOpsNow([update('root', 1), update('large', 2)]),
quota
);
await assert.rejects(storage.retryPausedWrites(), quota);
assert.deepEqual(failures, [quota, quota]);
assert.equal(warnings.mock.callCount(), 1);
assert.equal(errors.mock.callCount(), 0);
assert.equal(await storage.getDocRaw('root'), null);
assert.equal(await storage.getDocRaw('large'), null);
full = false;
if (resume === 'explicit retry') {
const replay = storage.retryPausedWrites();
assert.deepEqual(batches.at(-1), ['root', 'large']);
await replay;
} else {
const replay = storage.writeDocOpsNow([
...(resume === 'delete' ? [remove('large')] : []),
update('root', 3),
]);
assert.deepEqual(
batches.at(-1),
resume === 'delete' ? ['root', 'root'] : ['root', 'large', 'root']
);
await replay;
}
assert.equal(batches.length, 3);
assert.equal(storage.retryPausedWrites(), null);
assert.deepEqual(
(await storage.getDocRaw('root')).updates,
resume === 'explicit retry'
? [Uint8Array.of(1)]
: [Uint8Array.of(1), Uint8Array.of(3)]
);
assert.deepEqual(
(await storage.getDocRaw('large'))?.updates,
resume === 'delete' ? undefined : [Uint8Array.of(2)]
);
});
}
for (const [name, ops, frames] of [
['delete', [remove('note')], [[3], [4]]],
['delete then put', [remove('note'), update('note', 2)], [[2], [3], [4]]],