mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-06 11:42:26 +03:00
feat(web): scope cloud IndexedDB by account and load documents on demand
- Give a cloud space with an account a database of its own for each canonical server origin and user. Local spaces keep the 0.27.5 name `local:${type}:${id}`. The canonical origin rejects a URL with a user name or password.
- Keep `local_seq` acknowledgements in `peerClocks` for each account. The pushed watermark moves only across a gap-free run of acknowledgements.
- Add `getTier1DocsRaw`, `getDocsByIdsRaw`, and `listDocIds`. Key cursors find the records. A cold read reads no other page frames and no blob bytes. Key cursors also read the stored times of all documents. A write of an unloaded page then sorts after its stored updates.
- Add the `lazyTier1` mode to `openDesktopStore`, with `loadDocFrames`, `loadBlob`, and `listStoredDocIds`. These reads apply the changes that have not committed yet on top of the stored data. The storage reports each committed op in the `complete` event of its write transaction.
- Add `createReplicatorLease`. It elects one replicator tab per database with the Web Locks API. Without that API, it uses a heartbeat lease on a `BroadcastChannel`, then a single tab. The lock holder answers lease probes and leads after the lease tab yields. A lease candidate withdraws for a lower tab ID.
- Post a `changes` message with document and blob IDs after each committed write, compaction, blob change, and watermark move. Add `deleteBlob`.
This commit is contained in:
1 parent
8bc35f30e4
commit
3268dcd7e1
4 files changed
+2617
-56
No files matched your search
@@ -51,6 +51,14 @@ async function fetchFont(url) {
|
||||
* document. Returns `null` when the browser gives no IndexedDB, so the desktop
|
||||
* runs in memory only.
|
||||
*
|
||||
* With `lazyTier1`, the store reads at startup only the frames that the first
|
||||
* screen needs (`getTier1DocsRaw`): the workspace root, the `db$*` and
|
||||
* `userdata$*` tables, and the documents of `initialDocIdsByWorkspace`. It
|
||||
* reads no media at startup. `loadDocFrames`, `loadBlob`, and
|
||||
* `listStoredDocIds` read the other documents and media on demand, in both
|
||||
* modes. They apply the changes that this store holds and that have not
|
||||
* committed yet on top of the stored data, so a read never loses a change.
|
||||
*
|
||||
* The media, updates, and deletions queued in one task go to IndexedDB in one
|
||||
* transaction per workspace that issues every request at once
|
||||
* (`writeDocOpsNow`), so media and the document updates that refer to it
|
||||
@@ -69,6 +77,8 @@ async function fetchFont(url) {
|
||||
* now?: () => number,
|
||||
* setTimeout?: typeof setTimeout,
|
||||
* clearTimeout?: typeof clearTimeout,
|
||||
* lazyTier1?: boolean,
|
||||
* initialDocIdsByWorkspace?: Record<string, string[]>,
|
||||
* }} [env]
|
||||
*/
|
||||
export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
@@ -77,6 +87,15 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
/** @type {() => void} */
|
||||
let markSeeded = () => {};
|
||||
/** @typedef {{ docId: string, bin: Uint8Array } | { docId: string, delete: true }} DocOp */
|
||||
/** @typedef {{ blobKey: string, data: Uint8Array }} BlobOp */
|
||||
/**
|
||||
* A change of a workspace from the call that queued it until it and every
|
||||
* earlier change commit. `committed` turns true in the `complete` event of
|
||||
* the transaction that writes the change, or when a later committed change
|
||||
* replaces it.
|
||||
*
|
||||
* @typedef {{ op: DocOp | BlobOp, committed: boolean }} PendingChange
|
||||
*/
|
||||
/**
|
||||
* @typedef {{
|
||||
* id: string,
|
||||
@@ -84,7 +103,8 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
* opening: Promise<void> | null | undefined,
|
||||
* cancelOpen?: () => void,
|
||||
* ops: DocOp[],
|
||||
* blobs: Map<string, Uint8Array>,
|
||||
* blobs: Map<string, BlobOp>,
|
||||
* pending: PendingChange[],
|
||||
* deleted: boolean,
|
||||
* }} WorkspaceSlot
|
||||
*/
|
||||
@@ -113,11 +133,13 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
onDocWriteFailure: () => {
|
||||
if (isCurrent(slot)) markSeeded();
|
||||
},
|
||||
onDocOpsCommitted: ops => commitPending(slot, ops),
|
||||
}),
|
||||
// Undefined before the first open and null after the open succeeds.
|
||||
opening: undefined,
|
||||
ops: [],
|
||||
blobs: new Map(),
|
||||
pending: [],
|
||||
deleted: false,
|
||||
};
|
||||
slots.set(id, slot);
|
||||
@@ -157,17 +179,22 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
const frames = new Map();
|
||||
/** @type {Map<string, Map<string, Uint8Array>>} */
|
||||
const initialBlobs = new Map();
|
||||
const lazy = env.lazyTier1 === true;
|
||||
try {
|
||||
for (const id of new Set(workspaceIds)) {
|
||||
const slot = getSlot(id);
|
||||
await openSlot(slot);
|
||||
const { storage } = slot;
|
||||
const docs = await storage.getAllDocsRaw();
|
||||
const docs = lazy
|
||||
? await storage.getTier1DocsRaw({
|
||||
includeDocIds: env.initialDocIdsByWorkspace?.[id] ?? [],
|
||||
})
|
||||
: await storage.getAllDocsRaw();
|
||||
frames.set(id, docs);
|
||||
// No document of an empty workspace refers to the stored media.
|
||||
initialBlobs.set(
|
||||
id,
|
||||
docs.size ? await storage.getAllBlobsRaw() : new Map()
|
||||
!lazy && docs.size ? await storage.getAllBlobsRaw() : new Map()
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -218,9 +245,90 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
const enqueue = (workspaceId, op) => {
|
||||
const slot = getSlot(workspaceId);
|
||||
slot.ops.push(op);
|
||||
slot.pending.push({ op, committed: false });
|
||||
changed(slot);
|
||||
};
|
||||
|
||||
/**
|
||||
* Marks the changes of `ops` committed, with each earlier change that a
|
||||
* committed deletion of its document or a committed blob of its key
|
||||
* replaces, and drops the committed changes at the start of the list. The
|
||||
* storage calls it in the `complete` event of the write transaction, so a
|
||||
* read transaction that completes later sees each change that it marks.
|
||||
*
|
||||
* @param {WorkspaceSlot} slot
|
||||
* @param {Array<DocOp | BlobOp>} ops
|
||||
*/
|
||||
const commitPending = (slot, ops) => {
|
||||
const sent = new Set(ops);
|
||||
for (const [index, change] of slot.pending.entries()) {
|
||||
if (!sent.has(change.op)) continue;
|
||||
change.committed = true;
|
||||
const { op } = change;
|
||||
if (!('delete' in op) && !('blobKey' in op)) continue;
|
||||
for (const earlier of slot.pending.slice(0, index)) {
|
||||
if (
|
||||
'blobKey' in op
|
||||
? 'blobKey' in earlier.op && earlier.op.blobKey === op.blobKey
|
||||
: 'docId' in earlier.op && earlier.op.docId === op.docId
|
||||
) {
|
||||
earlier.committed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let start = 0;
|
||||
while (slot.pending[start]?.committed) start += 1;
|
||||
slot.pending.splice(0, start);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads stored data with `read` and returns it with the changes that were
|
||||
* pending when the read completed. A write transaction that completes
|
||||
* before the read transaction completes started before it, so its changes
|
||||
* are in the stored data and are marked committed.
|
||||
*
|
||||
* A workspace that this store has not opened has no data to read.
|
||||
*
|
||||
* @template T
|
||||
* @param {string} workspaceId
|
||||
* @param {(storage: WorkspaceSlot['storage']) => Promise<T>} read
|
||||
* @returns {Promise<{ stored: T | null, pending: PendingChange[] }>}
|
||||
*/
|
||||
const readWithPending = async (workspaceId, read) => {
|
||||
const slot = slots.get(workspaceId);
|
||||
if (!slot) return { stored: null, pending: [] };
|
||||
const stored = await read(slot.storage);
|
||||
return { stored, pending: slot.pending.slice() };
|
||||
};
|
||||
|
||||
/**
|
||||
* Applies the pending changes of a document to its stored frames. Without
|
||||
* an uncommitted deletion, the uncommitted updates follow the stored
|
||||
* frames. A failed deletion is written again with the updates that
|
||||
* committed after it, so from the first uncommitted deletion on, every
|
||||
* change of the document applies to empty frames.
|
||||
*
|
||||
* @param {PendingChange[]} pending
|
||||
* @param {string} docId
|
||||
* @param {Uint8Array[]} stored
|
||||
* @returns {Uint8Array[]}
|
||||
*/
|
||||
const applyPending = (pending, docId, stored) => {
|
||||
const changes = pending.filter(
|
||||
change => 'docId' in change.op && change.op.docId === docId
|
||||
);
|
||||
const start = changes.findIndex(
|
||||
change => !change.committed && 'delete' in change.op
|
||||
);
|
||||
let frames = start < 0 ? [...stored] : [];
|
||||
for (const [index, { op, committed }] of changes.entries()) {
|
||||
if (start < 0 ? committed : index < start) continue;
|
||||
if ('delete' in op) frames = [];
|
||||
else if ('bin' in op) frames.push(op.bin);
|
||||
}
|
||||
return frames;
|
||||
};
|
||||
|
||||
const finishSeed = id => {
|
||||
if (unseeded.delete(id) && !unseeded.size) markSeeded();
|
||||
};
|
||||
@@ -251,10 +359,7 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
ready.delete(slot);
|
||||
if (!isCurrent(slot)) continue;
|
||||
|
||||
const ops = [
|
||||
...[...slot.blobs].map(([blobKey, data]) => ({ blobKey, data })),
|
||||
...slot.ops,
|
||||
];
|
||||
const ops = [...slot.blobs.values(), ...slot.ops];
|
||||
slot.blobs.clear();
|
||||
slot.ops.length = 0;
|
||||
const { id, storage } = slot;
|
||||
@@ -347,6 +452,7 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
ready.delete(slot);
|
||||
slot.ops.length = 0;
|
||||
slot.blobs.clear();
|
||||
slot.pending.length = 0;
|
||||
slot.storage.close();
|
||||
slot.cancelOpen?.();
|
||||
slot.cancelOpen = undefined;
|
||||
@@ -371,9 +477,74 @@ export async function openDesktopStore(workspaceIds, env = globalThis) {
|
||||
},
|
||||
putBlob(workspaceId, blobId, bytes) {
|
||||
const slot = getSlot(workspaceId);
|
||||
slot.blobs.set(blobId, bytes);
|
||||
const replaced = slot.blobs.get(blobId);
|
||||
const op = { blobKey: blobId, data: bytes };
|
||||
slot.blobs.set(blobId, op);
|
||||
// The replaced bytes were never sent, so they never commit.
|
||||
const stale = slot.pending.find(change => change.op === replaced);
|
||||
if (stale) stale.committed = true;
|
||||
slot.pending.push({ op, committed: false });
|
||||
changed(slot);
|
||||
},
|
||||
/**
|
||||
* Reads the frames of one document: the stored frames with the changes
|
||||
* that have not committed (`applyPending`).
|
||||
*
|
||||
* @param {string} workspaceId
|
||||
* @param {string} docId
|
||||
* @returns {Promise<Uint8Array[]>}
|
||||
*/
|
||||
async loadDocFrames(workspaceId, docId) {
|
||||
const { stored, pending } = await readWithPending(workspaceId, storage =>
|
||||
storage.getDocsByIdsRaw([docId])
|
||||
);
|
||||
return applyPending(pending, docId, stored?.get(docId) ?? []);
|
||||
},
|
||||
/**
|
||||
* Reads the bytes of one blob: the newest uncommitted bytes, else the
|
||||
* stored bytes, else `null` for a missing or deleted blob.
|
||||
*
|
||||
* @param {string} workspaceId
|
||||
* @param {string} blobId
|
||||
* @returns {Promise<Uint8Array | null>}
|
||||
*/
|
||||
async loadBlob(workspaceId, blobId) {
|
||||
const { stored, pending } = await readWithPending(workspaceId, storage =>
|
||||
storage.getBlob(blobId)
|
||||
);
|
||||
const change = pending.findLast(
|
||||
({ op, committed }) =>
|
||||
!committed && 'blobKey' in op && op.blobKey === blobId
|
||||
);
|
||||
if (change && 'data' in change.op) return change.op.data;
|
||||
return stored?.data ?? null;
|
||||
},
|
||||
/**
|
||||
* Lists the documents of a workspace from stored keys, with the changes
|
||||
* that have not committed (`applyPending`). It reads no frames.
|
||||
*
|
||||
* @param {string} workspaceId
|
||||
* @returns {Promise<string[]>}
|
||||
*/
|
||||
async listStoredDocIds(workspaceId) {
|
||||
const { stored, pending } = await readWithPending(workspaceId, storage =>
|
||||
storage.listDocIds()
|
||||
);
|
||||
const storedIds = new Set(stored);
|
||||
const ids = new Set(stored);
|
||||
const marker = [new Uint8Array(0)];
|
||||
for (const { op } of pending) {
|
||||
if (!('docId' in op)) continue;
|
||||
const frames = applyPending(
|
||||
pending,
|
||||
op.docId,
|
||||
storedIds.has(op.docId) ? marker : []
|
||||
);
|
||||
if (frames.length) ids.add(op.docId);
|
||||
else ids.delete(op.docId);
|
||||
}
|
||||
return [...ids];
|
||||
},
|
||||
retryBlobWrites() {
|
||||
void flush();
|
||||
},
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1740,3 +1740,504 @@ void test('desktop releases the start lock when the last workspace awaiting a se
|
||||
assert.equal(released, true);
|
||||
assert.equal(await started, store);
|
||||
});
|
||||
|
||||
/**
|
||||
* Adds a key cursor to the `updatedAt` index of `snapshots` of the in-memory
|
||||
* IndexedDB double, which has none. The cursor walks the index keys in
|
||||
* order. It reads the records with the `getAll` that the double had before
|
||||
* other test wrappers, so read counters do not see it.
|
||||
*/
|
||||
function withSnapshotTimeCursor(factory) {
|
||||
const patched = new WeakSet();
|
||||
const patchDb = db => {
|
||||
if (patched.has(db)) return;
|
||||
patched.add(db);
|
||||
const transaction = db.transaction.bind(db);
|
||||
db.transaction = (names, mode) => {
|
||||
const tx = transaction(names, mode);
|
||||
const objectStore = tx.objectStore.bind(tx);
|
||||
tx.objectStore = storeName => {
|
||||
const store = objectStore(storeName);
|
||||
if (storeName !== 'snapshots') return store;
|
||||
const getAll = store.getAll.bind(store);
|
||||
const index = store.index.bind(store);
|
||||
store.index = indexName => {
|
||||
const found = index(indexName);
|
||||
if (indexName !== 'updatedAt') return found;
|
||||
return {
|
||||
...found,
|
||||
openKeyCursor() {
|
||||
const req = { result: null, onsuccess: null, onerror: null };
|
||||
const all = getAll();
|
||||
all.onsuccess = () => {
|
||||
const entries = all.result
|
||||
.map(value => ({
|
||||
key: value.updatedAt,
|
||||
primaryKey: value.docId,
|
||||
}))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
+a.key - +b.key || (a.primaryKey < b.primaryKey ? -1 : 1)
|
||||
);
|
||||
for (const entry of entries) {
|
||||
req.result = { ...entry, continue() {} };
|
||||
req.onsuccess?.();
|
||||
}
|
||||
req.result = null;
|
||||
req.onsuccess?.();
|
||||
};
|
||||
return req;
|
||||
},
|
||||
};
|
||||
};
|
||||
return store;
|
||||
};
|
||||
return tx;
|
||||
};
|
||||
};
|
||||
return {
|
||||
...factory,
|
||||
open(name, version) {
|
||||
const req = factory.open(name, version);
|
||||
return new Proxy(req, {
|
||||
get(target, prop) {
|
||||
const value = Reflect.get(target, prop);
|
||||
if (prop === 'result' && value) patchDb(value);
|
||||
return value;
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the store of workspace `id` and records each request that reads
|
||||
* stored values, by store name and key. Key cursors are not recorded.
|
||||
*/
|
||||
async function recordDesktopValueReads(t, indexedDB, id) {
|
||||
const db = await openWorkspaceIdb(
|
||||
{ flavour: 'local', type: 'workspace', id },
|
||||
{ indexedDB }
|
||||
);
|
||||
t.after(() => db.close());
|
||||
const reads = [];
|
||||
const transaction = db.transaction.bind(db);
|
||||
t.mock.method(db, 'transaction', (stores, mode) => {
|
||||
const tx = transaction(stores, mode);
|
||||
const objectStore = tx.objectStore.bind(tx);
|
||||
tx.objectStore = name => {
|
||||
const store = objectStore(name);
|
||||
for (const method of ['get', 'getAll']) {
|
||||
const read = store[method].bind(store);
|
||||
store[method] = key => {
|
||||
reads.push({ store: name, method, key });
|
||||
return read(key);
|
||||
};
|
||||
}
|
||||
return store;
|
||||
};
|
||||
return tx;
|
||||
});
|
||||
return {
|
||||
reads,
|
||||
indexedDB: {
|
||||
open(name, version) {
|
||||
if (name !== `local:workspace:${id}`) {
|
||||
return indexedDB.open(name, version);
|
||||
}
|
||||
const req = { result: db };
|
||||
queueMicrotask(() => req.onsuccess());
|
||||
return req;
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps an IndexedDB factory so that a read-only transaction runs its
|
||||
* requests only after every `readwrite` transaction created before it
|
||||
* completes, as browsers order transactions with overlapping scopes. The
|
||||
* in-memory double runs read-only requests at once.
|
||||
*/
|
||||
function orderTransactions(indexedDB) {
|
||||
let writes = Promise.resolve();
|
||||
const wrapDb = db =>
|
||||
new Proxy(db, {
|
||||
get(target, prop) {
|
||||
if (prop !== 'transaction') return Reflect.get(target, prop);
|
||||
return (names, mode) => {
|
||||
if (mode === 'readwrite') {
|
||||
const tx = target.transaction(names, mode);
|
||||
let settle;
|
||||
writes = Promise.all([writes, new Promise(r => (settle = r))]);
|
||||
return new Proxy(tx, {
|
||||
set(txTarget, key, value) {
|
||||
if (key === 'oncomplete' || key === 'onabort') {
|
||||
txTarget[key] = event => {
|
||||
settle();
|
||||
value?.(event);
|
||||
};
|
||||
return true;
|
||||
}
|
||||
return Reflect.set(txTarget, key, value);
|
||||
},
|
||||
});
|
||||
}
|
||||
/** @type {IDBTransaction | null} */
|
||||
let real = null;
|
||||
const queued = [];
|
||||
const proxyTx = {
|
||||
error: null,
|
||||
oncomplete: null,
|
||||
onabort: null,
|
||||
commit() {},
|
||||
objectStore: name => {
|
||||
const request = (call, args) => {
|
||||
const req = {
|
||||
result: undefined,
|
||||
error: null,
|
||||
onsuccess: null,
|
||||
onerror: null,
|
||||
};
|
||||
const run = () => {
|
||||
const store = real.objectStore(name);
|
||||
const r = call(store)(...args);
|
||||
r.onsuccess = event => {
|
||||
req.result = r.result;
|
||||
req.onsuccess?.(event);
|
||||
};
|
||||
r.onerror = event => {
|
||||
req.error = r.error;
|
||||
req.onerror?.(event);
|
||||
};
|
||||
};
|
||||
if (real) run();
|
||||
else queued.push(run);
|
||||
return req;
|
||||
};
|
||||
return {
|
||||
get: (...args) => request(store => store.get.bind(store), args),
|
||||
getAll: (...args) =>
|
||||
request(store => store.getAll.bind(store), args),
|
||||
openKeyCursor: (...args) =>
|
||||
request(store => store.openKeyCursor.bind(store), args),
|
||||
index: indexName => ({
|
||||
getAll: (...args) =>
|
||||
request(store => {
|
||||
const index = store.index(indexName);
|
||||
return index.getAll.bind(index);
|
||||
}, args),
|
||||
openKeyCursor: (...args) =>
|
||||
request(store => {
|
||||
const index = store.index(indexName);
|
||||
return index.openKeyCursor.bind(index);
|
||||
}, args),
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
void writes.then(() => {
|
||||
real = target.transaction(names, mode);
|
||||
real.oncomplete = event => proxyTx.oncomplete?.(event);
|
||||
real.onabort = event => {
|
||||
proxyTx.error = real.error;
|
||||
proxyTx.onabort?.(event);
|
||||
};
|
||||
for (const run of queued.splice(0)) run();
|
||||
});
|
||||
return proxyTx;
|
||||
};
|
||||
},
|
||||
});
|
||||
return {
|
||||
open(name, version) {
|
||||
const req = indexedDB.open(name, version);
|
||||
return new Proxy(req, {
|
||||
get(target, prop) {
|
||||
const value = Reflect.get(target, prop);
|
||||
return prop === 'result' && value ? wrapDb(value) : value;
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
void test('a lazy desktop store of a 1,000-page workspace with 50 blobs reads only the first-screen documents at startup and loads pages, media, and IDs on demand with uncommitted changes', async t => {
|
||||
const memory = withSnapshotTimeCursor(createMemoryIdbFactory());
|
||||
const seed = await openDesktopStore(['ws'], { indexedDB: memory });
|
||||
for (const docId of [
|
||||
'ws',
|
||||
'db$docProperties',
|
||||
'userdata$alice$ws$favorite',
|
||||
]) {
|
||||
seed.pushUpdate('ws', docId, Uint8Array.of(1));
|
||||
}
|
||||
for (let i = 0; i < 1000; i += 1) {
|
||||
seed.pushUpdate('ws', `page-${i}`, Uint8Array.of(10, i & 0xff));
|
||||
}
|
||||
for (let i = 0; i < 50; i += 1) {
|
||||
const bytes = new Uint8Array(256 * 1024);
|
||||
bytes[0] = i;
|
||||
seed.putBlob('ws', `blob-${i}`, bytes);
|
||||
}
|
||||
await seed.flush();
|
||||
|
||||
const { reads, indexedDB } = await recordDesktopValueReads(t, memory, 'ws');
|
||||
const store = await openDesktopStore(['ws'], {
|
||||
indexedDB: orderTransactions(indexedDB),
|
||||
lazyTier1: true,
|
||||
initialDocIdsByWorkspace: { ws: ['page-3'] },
|
||||
});
|
||||
const firstScreen = [
|
||||
'db$docProperties',
|
||||
'page-3',
|
||||
'userdata$alice$ws$favorite',
|
||||
'ws',
|
||||
];
|
||||
assert.deepEqual(store.docIds('ws').sort(), firstScreen);
|
||||
assert.deepEqual(store.docFrames('ws', 'page-3'), [Uint8Array.of(10, 3)]);
|
||||
assert.deepEqual(store.blobIds('ws'), []);
|
||||
const docOf = read => (read.store === 'updates' ? read.key[0] : read.key);
|
||||
const frameReads = reads.filter(
|
||||
read => read.store === 'updates' || read.store === 'snapshots'
|
||||
);
|
||||
assert.deepEqual(
|
||||
frameReads.filter(read => !firstScreen.includes(docOf(read))),
|
||||
[]
|
||||
);
|
||||
assert.deepEqual(
|
||||
reads.filter(
|
||||
read =>
|
||||
read.store === 'blobData' ||
|
||||
(read.method === 'getAll' && read.store !== 'clocks')
|
||||
),
|
||||
[]
|
||||
);
|
||||
console.log(
|
||||
`lazy desktop cold start of 1,003 documents and 50 blobs: ${frameReads.length} frame reads, 0 reads of other pages, 0 blob reads`
|
||||
);
|
||||
|
||||
assert.deepEqual(await store.loadDocFrames('ws', 'page-900'), [
|
||||
Uint8Array.of(10, 900 & 0xff),
|
||||
]);
|
||||
assert.equal((await store.loadBlob('ws', 'blob-7'))[0], 7);
|
||||
assert.equal(await store.loadBlob('ws', 'missing'), null);
|
||||
assert.equal(await store.loadBlob('other', 'blob-7'), null);
|
||||
assert.deepEqual(await store.loadDocFrames('other', 'page-1'), []);
|
||||
reads.length = 0;
|
||||
assert.equal((await store.listStoredDocIds('ws')).length, 1003);
|
||||
assert.deepEqual(reads, []);
|
||||
|
||||
store.pushUpdate('ws', 'page-900', Uint8Array.of(20));
|
||||
store.deleteDoc('ws', 'page-901');
|
||||
store.pushUpdate('ws', 'page-new', Uint8Array.of(21));
|
||||
store.putBlob('ws', 'blob-7', Uint8Array.of(77));
|
||||
const [page900, page901, ids, blob7] = await Promise.all([
|
||||
store.loadDocFrames('ws', 'page-900'),
|
||||
store.loadDocFrames('ws', 'page-901'),
|
||||
store.listStoredDocIds('ws'),
|
||||
store.loadBlob('ws', 'blob-7'),
|
||||
]);
|
||||
assert.deepEqual(page900, [Uint8Array.of(10, 900 & 0xff), Uint8Array.of(20)]);
|
||||
assert.deepEqual(page901, []);
|
||||
assert.ok(ids.includes('page-new') && !ids.includes('page-901'));
|
||||
assert.equal(ids.length, 1003);
|
||||
assert.deepEqual(blob7, Uint8Array.of(77));
|
||||
|
||||
await store.flush();
|
||||
assert.deepEqual(await store.loadDocFrames('ws', 'page-900'), [
|
||||
Uint8Array.of(10, 900 & 0xff),
|
||||
Uint8Array.of(20),
|
||||
]);
|
||||
assert.deepEqual(await store.loadDocFrames('ws', 'page-new'), [
|
||||
Uint8Array.of(21),
|
||||
]);
|
||||
});
|
||||
|
||||
void test('the desktop store reads a change that a quota failure holds back until a later write commits it', async t => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(console, 'error', () => {});
|
||||
const indexedDB = createMemoryIdbFactory();
|
||||
let limit = 0;
|
||||
const { store, quota } = await openQuotaLimitedDesktop(
|
||||
t,
|
||||
indexedDB,
|
||||
['ws'],
|
||||
'ws',
|
||||
() => limit
|
||||
);
|
||||
store.pushUpdate('ws', 'page', Uint8Array.of(1));
|
||||
store.putBlob('ws', 'img', Uint8Array.of(2));
|
||||
await assert.rejects(store.flush(), quota);
|
||||
assert.deepEqual(await store.loadDocFrames('ws', 'page'), [Uint8Array.of(1)]);
|
||||
assert.deepEqual(await store.loadBlob('ws', 'img'), Uint8Array.of(2));
|
||||
assert.deepEqual(await store.listStoredDocIds('ws'), ['page']);
|
||||
|
||||
limit = Infinity;
|
||||
await store.flush();
|
||||
assert.deepEqual(await store.loadDocFrames('ws', 'page'), [Uint8Array.of(1)]);
|
||||
const cold = await openDesktopStore(['ws'], { indexedDB });
|
||||
assert.deepEqual(cold.docFrames('ws', 'page'), [Uint8Array.of(1)]);
|
||||
assert.deepEqual(await cold.loadBlob('ws', 'img'), Uint8Array.of(2));
|
||||
});
|
||||
|
||||
void test('a deletion that commits before a read does not erase the frames that another connection writes after it', async () => {
|
||||
const memory = createMemoryIdbFactory();
|
||||
const indexedDB = orderTransactions(memory);
|
||||
const store = await openDesktopStore(['ws'], { indexedDB });
|
||||
store.pushUpdate('ws', 'page', Uint8Array.of(1));
|
||||
await store.flush();
|
||||
const other = createIdbWorkspaceStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id: 'ws',
|
||||
indexedDB,
|
||||
now: () => Date.UTC(2030, 0, 1),
|
||||
});
|
||||
await other.open();
|
||||
|
||||
store.deleteDoc('ws', 'page');
|
||||
// Start the deletion transaction, then the read, then the remote write.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
const read = store.loadDocFrames('ws', 'page');
|
||||
const remote = other.writeDocOpsNow([
|
||||
{ docId: 'page', bin: Uint8Array.of(9) },
|
||||
]);
|
||||
assert.deepEqual(await read, [Uint8Array.of(9)]);
|
||||
await remote;
|
||||
assert.deepEqual(await store.loadDocFrames('ws', 'page'), [Uint8Array.of(9)]);
|
||||
assert.deepEqual(await store.listStoredDocIds('ws'), ['page']);
|
||||
other.close();
|
||||
});
|
||||
|
||||
void test('during pagehide a lazy desktop store starts at once the write of a page that it did not load and of a new page, after the stored updates', async t => {
|
||||
const indexedDB = withSnapshotTimeCursor(createMemoryIdbFactory());
|
||||
const db = await openWorkspaceIdb(
|
||||
{ flavour: 'local', type: 'workspace', id: 'ws-clock' },
|
||||
{ indexedDB }
|
||||
);
|
||||
t.after(() => db.close());
|
||||
const seed = db.transaction(['updates', 'clocks'], 'readwrite');
|
||||
seed.objectStore('updates').put({
|
||||
docId: 'page',
|
||||
bin: Uint8Array.of(1),
|
||||
createdAt: new Date(5000),
|
||||
});
|
||||
seed.objectStore('clocks').put({ docId: 'page', timestamp: new Date(5000) });
|
||||
seed.commit();
|
||||
await new Promise(resolve => (seed.oncomplete = resolve));
|
||||
const transaction = db.transaction.bind(db);
|
||||
let writes = 0;
|
||||
t.mock.method(db, 'transaction', (stores, mode) => {
|
||||
if (mode === 'readwrite') writes += 1;
|
||||
return transaction(stores, mode);
|
||||
});
|
||||
|
||||
for (const lazyTier1 of [true, false]) {
|
||||
const store = await openDesktopStore(['ws-clock'], {
|
||||
indexedDB: {
|
||||
open() {
|
||||
const req = { result: db };
|
||||
queueMicrotask(() => req.onsuccess());
|
||||
return req;
|
||||
},
|
||||
},
|
||||
lazyTier1,
|
||||
now: () => 4000,
|
||||
});
|
||||
const listeners = new Map();
|
||||
const win = {
|
||||
addEventListener: (type, listener) => listeners.set(type, listener),
|
||||
document: { addEventListener() {}, visibilityState: 'visible' },
|
||||
};
|
||||
flushDesktopOnHide({ flush_web_desktop() {} }, store, win);
|
||||
store.pushUpdate('ws-clock', 'page', Uint8Array.of(lazyTier1 ? 2 : 3));
|
||||
store.pushUpdate('ws-clock', `new-${lazyTier1}`, Uint8Array.of(4));
|
||||
const before = writes;
|
||||
listeners.get('pagehide')();
|
||||
assert.equal(writes, before + 1, `lazyTier1 ${lazyTier1}`);
|
||||
await store.flush();
|
||||
}
|
||||
const storage = createIdbWorkspaceStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id: 'ws-clock',
|
||||
indexedDB,
|
||||
});
|
||||
const raw = await storage.getDocRaw('page');
|
||||
assert.deepEqual(raw.updates, [
|
||||
Uint8Array.of(1),
|
||||
Uint8Array.of(2),
|
||||
Uint8Array.of(3),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
raw.updateTimes.map(time => time.getTime()),
|
||||
[5000, 5001, 5002]
|
||||
);
|
||||
assert.deepEqual(await storage.getDocTimestamps(new Date(5000)), {
|
||||
page: new Date(5002),
|
||||
});
|
||||
for (const docId of ['new-true', 'new-false']) {
|
||||
assert.deepEqual((await storage.getDocRaw(docId)).updates, [
|
||||
Uint8Array.of(4),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
void test('a lazy desktop store writes a page that it did not load after a stored update or snapshot time that a slow clock left above the clock record', async () => {
|
||||
const indexedDB = withSnapshotTimeCursor(createMemoryIdbFactory());
|
||||
const db = await openWorkspaceIdb(
|
||||
{ flavour: 'local', type: 'workspace', id: 'ws-skew' },
|
||||
{ indexedDB }
|
||||
);
|
||||
// Another connection wrote at 9000, then one with a slow clock moved the
|
||||
// clock records back to 5001.
|
||||
const seed = db.transaction(['updates', 'snapshots', 'clocks'], 'readwrite');
|
||||
seed.objectStore('updates').put({
|
||||
docId: 'by-update',
|
||||
bin: Uint8Array.of(1),
|
||||
createdAt: new Date(9000),
|
||||
});
|
||||
seed.objectStore('snapshots').put({
|
||||
docId: 'by-snapshot',
|
||||
bin: Uint8Array.of(1),
|
||||
createdAt: new Date(9000),
|
||||
updatedAt: new Date(9000),
|
||||
});
|
||||
for (const docId of ['by-update', 'by-snapshot']) {
|
||||
seed.objectStore('updates').put({
|
||||
docId,
|
||||
bin: Uint8Array.of(2),
|
||||
createdAt: new Date(5001),
|
||||
});
|
||||
seed.objectStore('clocks').put({ docId, timestamp: new Date(5001) });
|
||||
}
|
||||
seed.commit();
|
||||
await new Promise(resolve => (seed.oncomplete = resolve));
|
||||
|
||||
const store = await openDesktopStore(['ws-skew'], {
|
||||
indexedDB,
|
||||
lazyTier1: true,
|
||||
now: () => 4000,
|
||||
});
|
||||
assert.deepEqual(store.docIds('ws-skew'), []);
|
||||
store.pushUpdate('ws-skew', 'by-update', Uint8Array.of(3));
|
||||
store.pushUpdate('ws-skew', 'by-snapshot', Uint8Array.of(3));
|
||||
await store.flush();
|
||||
const storage = createIdbWorkspaceStorage({
|
||||
flavour: 'local',
|
||||
type: 'workspace',
|
||||
id: 'ws-skew',
|
||||
indexedDB,
|
||||
});
|
||||
assert.deepEqual(
|
||||
Object.keys(await storage.getDocTimestamps(new Date(9000))).sort(),
|
||||
['by-snapshot', 'by-update']
|
||||
);
|
||||
assert.deepEqual((await storage.getDocRaw('by-update')).updates, [
|
||||
Uint8Array.of(2),
|
||||
Uint8Array.of(1),
|
||||
Uint8Array.of(3),
|
||||
]);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user