Files
AFFiNE/packages/frontend/hosts/web/desktop/start.js
T
DarkSky 12bd597e81 fix(desktop): isolate workspace storage across deletion
Close the database if a blocked IndexedDB open succeeds after rejection.
2026-12-05 11:16:56 +09:00

556 lines
17 KiB
JavaScript

import { createIdbWorkspaceStorage } from '../src/idb-storage.js';
const defaultFonts = [
'Inter-VariableFont_slnt,wght.ttf',
'IBMPlexMono-Regular.ttf',
'IBMPlexMono-Bold.ttf',
'IBMPlexMono-Italic.ttf',
'IBMPlexMono-BoldItalic.ttf',
'NotoSansArabic-Regular.ttf',
'NotoSansHebrew-Regular.ttf',
].map(name => '/assets/fonts/' + name);
const serifFonts = {
serif: '/assets/fonts/SourceSerif4-VariableFont_opsz,wght.ttf',
serifItalic: '/assets/fonts/SourceSerif4-Italic-VariableFont_opsz,wght.ttf',
};
export function desktopFontUrls(manifest, legacyFonts) {
const base = [
'latin',
'mono',
'monoBold',
'monoItalic',
'monoBoldItalic',
'arabic',
'hebrew',
].map(key => manifest?.[key]);
const hasManifest = base.every(url => typeof url === 'string' && url.length);
const urls = hasManifest ? base : [...(legacyFonts ?? defaultFonts)];
for (const [key, fallback] of Object.entries(serifFonts)) {
const url = manifest?.[key];
if (typeof url === 'string' && url.length) {
urls.push(url);
} else if (!hasManifest && legacyFonts == null) {
urls.push(fallback);
}
}
return [...new Set(urls)];
}
async function fetchFont(url) {
const response = await fetch(url);
if (!response.ok)
throw new Error(`Font ${url} returned HTTP ${response.status}`);
return new Uint8Array(await response.arrayBuffer());
}
/**
* Opens the IndexedDB document store of each desktop workspace and reads every
* stored update frame, and the stored media of each workspace that holds a
* document. Returns `null` when the browser gives no IndexedDB, so the desktop
* runs in memory only.
*
* 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
* commit or roll back together, and a `flush()` from a `pagehide` handler can
* commit while the page unloads. After a quota failure, a workspace keeps its
* changes in call order and starts no transaction until a deletion, a
* `retryBlobWrites()`, or a `flush()` writes all of them in one transaction.
*
* @param {string[]} workspaceIds
* @param {{
* indexedDB?: IDBFactory,
* location?: Location,
* history?: History,
* localStorage?: Storage,
* BroadcastChannel?: typeof BroadcastChannel,
* now?: () => number,
* setTimeout?: typeof setTimeout,
* clearTimeout?: typeof clearTimeout,
* }} [env]
*/
export async function openDesktopStore(workspaceIds, env = globalThis) {
const indexedDB = env.indexedDB;
if (!indexedDB || typeof indexedDB.open !== 'function') return null;
/** @type {() => void} */
let markSeeded = () => {};
/** @typedef {{ docId: string, bin: Uint8Array } | { docId: string, delete: true }} DocOp */
/**
* @typedef {{
* id: string,
* storage: ReturnType<typeof createIdbWorkspaceStorage>,
* opening: Promise<void> | null | undefined,
* cancelOpen?: () => void,
* ops: DocOp[],
* blobs: Map<string, Uint8Array>,
* deleted: boolean,
* }} WorkspaceSlot
*/
/** @type {Map<string, WorkspaceSlot>} */
const slots = new Map();
/** @param {WorkspaceSlot} slot */
const isCurrent = slot => !slot.deleted && slots.get(slot.id) === slot;
/** @returns {WorkspaceSlot} */
const getSlot = id => {
const current = slots.get(id);
if (current) return current;
/** @type {WorkspaceSlot} */
const slot = {
id,
storage: createIdbWorkspaceStorage({
flavour: 'local',
type: 'workspace',
id,
indexedDB,
BroadcastChannelImpl: env.BroadcastChannel,
now: env.now,
setTimeout: env.setTimeout,
clearTimeout: env.clearTimeout,
onDocWriteFailure: () => {
if (isCurrent(slot)) markSeeded();
},
}),
// Undefined before the first open and null after the open succeeds.
opening: undefined,
ops: [],
blobs: new Map(),
deleted: false,
};
slots.set(id, slot);
return slot;
};
/** @param {WorkspaceSlot} slot */
const openSlot = slot => {
/** @type {Promise<void>} */
const opening = new Promise((resolve, reject) => {
slot.cancelOpen = resolve;
void slot.storage.open().then(
() => {
if (isCurrent(slot)) {
slot.opening = null;
slot.cancelOpen = undefined;
resolve();
} else {
slot.storage.close();
}
},
error => {
if (isCurrent(slot)) {
slots.delete(slot.id);
slot.cancelOpen = undefined;
slot.storage.close();
reject(error);
}
}
);
});
slot.opening = opening;
return opening;
};
/** @type {Map<string, Map<string, Uint8Array[]>>} */
const frames = new Map();
/** @type {Map<string, Map<string, Uint8Array>>} */
const initialBlobs = new Map();
try {
for (const id of new Set(workspaceIds)) {
const slot = getSlot(id);
await openSlot(slot);
const { storage } = slot;
const docs = 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()
);
}
} catch (error) {
console.error('AFFiNE Desktop keeps this session in memory only', error);
for (const { storage } of slots.values()) storage.close();
return null;
}
/** Workspaces with changes since their last write started. */
/** @type {Set<WorkspaceSlot>} */
const ready = new Set();
/** @type {Set<Promise<void>>} */
const inFlight = new Set();
/** @type {Set<Set<Promise<void>>>} */
const flushes = 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 {Promise<void>} */
const seeded = unseeded.size
? new Promise(resolve => {
markSeeded = resolve;
})
: Promise.resolve();
const writeFailed = error => {
if (error?.name !== 'QuotaExceededError') {
console.error('AFFiNE Desktop could not save a change', error);
}
markSeeded();
};
let flushScheduled = false;
const scheduleFlush = () => {
if (flushScheduled) return;
flushScheduled = true;
queueMicrotask(() => {
flushScheduled = false;
writeWorkspaces(ready);
});
};
/** @param {WorkspaceSlot} slot */
const changed = slot => {
ready.add(slot);
scheduleFlush();
};
const enqueue = (workspaceId, op) => {
const slot = getSlot(workspaceId);
slot.ops.push(op);
changed(slot);
};
const finishSeed = id => {
if (unseeded.delete(id) && !unseeded.size) markSeeded();
};
/** @type {Set<string>} */
const explicitlyRegistered = new Set(workspaceIds);
const isRegisteredWorkspace = id => {
if (explicitlyRegistered.has(id)) return true;
try {
const raw = env.localStorage?.getItem('affine.desktop.workspaceRegistry');
if (!raw) return false;
const entries = JSON.parse(raw);
return Array.isArray(entries) && entries.some(entry => entry?.id === id);
} catch {
return false;
}
};
/**
* Starts one transaction per workspace with its queued media and document
* changes. With `retry`, it also writes the changes that a workspace keeps
* after a quota failure, in the same transaction.
*
* @param {Iterable<WorkspaceSlot>} workspaces
* @param {boolean} [retry]
*/
const writeWorkspaces = (workspaces, retry = false) => {
for (const slot of workspaces) {
ready.delete(slot);
if (!isCurrent(slot)) continue;
const ops = [
...[...slot.blobs].map(([blobKey, data]) => ({ blobKey, data })),
...slot.ops,
];
slot.blobs.clear();
slot.ops.length = 0;
const { id, storage } = slot;
if (slot.opening === undefined && !isRegisteredWorkspace(id)) {
slots.delete(id);
writeFailed(new Error(`Unknown desktop workspace ${id}`));
continue;
}
const writeOps = () => {
if (!isCurrent(slot)) return null;
const sent = ops.length ? storage.writeDocOpsNow(ops) : null;
const replay = retry ? storage.retryPausedWrites() : null;
// A paused workspace keeps `sent` for the replay and rejects it at once.
if (replay && sent) void sent.catch(() => {});
return replay ?? sent;
};
let write;
try {
if (slot.opening === null) {
write = writeOps();
} else if (ops.length) {
write = (slot.opening ?? openSlot(slot)).then(writeOps);
}
} catch (error) {
write = Promise.reject(error);
}
if (!write) continue;
const written = write
.then(
() => {
if (isCurrent(slot)) finishSeed(id);
},
error => {
if (slot.deleted) return;
writeFailed(error);
throw error;
}
)
.finally(() => inFlight.delete(written));
inFlight.add(written);
for (const writes of flushes) writes.add(written);
void written.catch(() => {});
}
};
const flush = () => {
const writes = new Set(inFlight);
flushes.add(writes);
const flushed = (async () => {
try {
writeWorkspaces(slots.values(), true);
while (writes.size) {
const batch = [...writes];
writes.clear();
await Promise.all(batch);
writeWorkspaces(ready);
}
} finally {
flushes.delete(writes);
}
})();
void flushed.catch(() => {});
return flushed;
};
return {
docIds: workspaceId => [...(frames.get(workspaceId)?.keys() ?? [])],
docFrames: (workspaceId, docId) =>
frames.get(workspaceId)?.get(docId) ?? [],
blobIds: workspaceId => [...(initialBlobs.get(workspaceId)?.keys() ?? [])],
blobBytes: (workspaceId, blobId) =>
initialBlobs.get(workspaceId)?.get(blobId),
releaseInitialFrames() {
frames.clear();
initialBlobs.clear();
},
registerWorkspace(workspaceId) {
if (typeof workspaceId === 'string' && workspaceId) {
explicitlyRegistered.add(workspaceId);
}
},
deleteWorkspace(workspaceId) {
if (typeof workspaceId !== 'string' || !workspaceId) return;
explicitlyRegistered.delete(workspaceId);
const slot = slots.get(workspaceId);
if (slot) {
slots.delete(workspaceId);
slot.deleted = true;
ready.delete(slot);
slot.ops.length = 0;
slot.blobs.clear();
slot.storage.close();
slot.cancelOpen?.();
slot.cancelOpen = undefined;
}
frames.delete(workspaceId);
initialBlobs.delete(workspaceId);
finishSeed(workspaceId);
try {
env.localStorage?.removeItem(`affine.desktop.tabs.${workspaceId}`);
env.localStorage?.removeItem(
`affine.desktop.explorerPrefs.${workspaceId}`
);
} catch {
// Ignore unavailable localStorage when clearing deleted workspace state.
}
try {
// IndexedDB queues the next open for this name after this request.
indexedDB.deleteDatabase?.(`local:workspace:${workspaceId}`);
} catch {
// Ignore IDB implementations without deleteDatabase.
}
},
putBlob(workspaceId, blobId, bytes) {
const slot = getSlot(workspaceId);
slot.blobs.set(blobId, bytes);
changed(slot);
},
retryBlobWrites() {
void flush();
},
pushUpdate(workspaceId, docId, bin) {
enqueue(workspaceId, { docId, bin });
},
deleteDoc(workspaceId, docId) {
enqueue(workspaceId, { docId, delete: true });
},
setRoute(workspaceId, docId, tagId, collectionId) {
if (!env.location || !env.history) return;
const url = new URL(env.location.href);
if (
!docId ||
url.searchParams.get('workspace') !== workspaceId ||
url.searchParams.get('doc') !== docId
) {
for (const key of ['mode', 'blockIds', 'elementIds']) {
url.searchParams.delete(key);
}
}
url.searchParams.set('workspace', workspaceId);
for (const key of ['doc', 'tag', 'collection']) {
url.searchParams.delete(key);
}
if (docId) url.searchParams.set('doc', docId);
else if (tagId) url.searchParams.set('tag', tagId);
else if (collectionId) url.searchParams.set('collection', collectionId);
env.history.replaceState(env.history.state, '', url);
},
reportError(message) {
console.error(
'AFFiNE Desktop could not open the stored workspaces',
message
);
markSeeded();
},
/**
* Resolves when a write to each workspace that the store held no
* document of has committed or the workspace has been deleted, or after
* the first failed write.
*/
seeded,
/** Starts queued writes now and waits for writes queued during the flush. */
flush,
};
}
const DOC_MODE_KEY = 'affine:desktop:default-doc-mode';
const THEME_KEY = 'affine:desktop:theme-preference';
function desktopHost(env, params, media) {
const read = key => {
try {
return env.localStorage?.getItem(key);
} catch {
return null;
}
};
const theme = read(THEME_KEY);
const queryTheme = params.get('theme');
const mode = params.get('mode');
const ids = key => [
...new Set(
params
.getAll(key)
.flatMap(value => value.split(','))
.filter(Boolean)
),
];
return {
initialTagId: params.get('tag') || undefined,
initialCollectionId: params.get('collection') || undefined,
initialBlockIds: ids('blockIds'),
initialElementIds: ids('elementIds'),
initialDocMode: mode === 'page' || mode === 'edgeless' ? mode : undefined,
defaultDocMode: read(DOC_MODE_KEY) === 'edgeless' ? 'edgeless' : 'page',
themePreference: ['light', 'dark', 'system'].includes(theme)
? theme
: queryTheme === 'light' || queryTheme === 'dark'
? queryTheme
: 'system',
savePreferences(mode, preference) {
try {
if (mode !== undefined) env.localStorage?.setItem(DOC_MODE_KEY, mode);
if (preference !== undefined) {
env.localStorage?.setItem(THEME_KEY, preference);
}
} catch {
// The mounted desktop keeps its settings when browser storage is unavailable.
}
},
onSplitClosed: () => clearDesktopSplit(env),
watchSystemTheme(callback) {
media?.addEventListener('change', event => callback(event.matches));
},
};
}
export async function startDesktop(
wasm,
fontUrls = desktopFontUrls(),
search,
prefersDark,
preview,
openStoreWithEnv = openDesktopStore,
locks = globalThis.navigator?.locks,
env = globalThis
) {
const [, fonts] = await Promise.all([
wasm.default(),
Promise.all(fontUrls.map(fetchFont)),
]);
for (const bytes of fonts) {
wasm.register_web_desktop_font(bytes);
preview.registerFont(bytes);
}
const params = new URLSearchParams(search);
const split = params.get('split');
const openStore = ids => openStoreWithEnv(ids, env);
// Tabs of one origin read the stores and seed the empty workspaces one at a
// 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());
const media = env.matchMedia?.('(prefers-color-scheme: dark)');
try {
wasm.wasm_desktop_main(
media?.matches ?? prefersDark,
split === 'true' || split === '1',
params.get('workspace') || undefined,
params.get('doc') || undefined,
store ?? undefined,
Date.now(),
desktopHost(env, params, media)
);
} finally {
store?.releaseInitialFrames?.();
}
await store?.seeded;
return store;
};
return typeof locks?.request === 'function'
? locks.request(DESKTOP_START_LOCK, mount)
: mount();
}
/** Removes a closed split from the current URL without adding a history entry. */
export function clearDesktopSplit(env) {
const url = new URL(env.location.href);
if (!url.searchParams.has('split')) return;
url.searchParams.delete('split');
env.history.replaceState(env.history.state, '', url);
}
/** Name of the Web Locks API lock that desktop startup holds. */
export const DESKTOP_START_LOCK = 'affine-desktop:start';
/**
* Writes every queued change of the desktop to IndexedDB before the page is
* hidden or unloaded.
*
* @param {{ flush_web_desktop: () => void }} wasm
* @param {{ flush: () => Promise<void> } | null} store
* @param {Window} win
*/
export function flushDesktopOnHide(wasm, store, win) {
if (!store) return;
const flush = () => {
wasm.flush_web_desktop();
void store.flush();
};
win.addEventListener('pagehide', flush);
win.addEventListener('beforeunload', flush);
win.document.addEventListener('visibilitychange', () => {
if (win.document.visibilityState === 'hidden') flush();
});
}