From 9dade085a4ee8d9f3ce683b9180c687943ce757f Mon Sep 17 00:00:00 2001 From: bubulux Date: Fri, 4 Dec 2026 18:03:43 +0100 Subject: [PATCH 1/2] A write names the files it changed; the Studio reads those, not the root (#599) After every write the Worker told the root's room `changed`, and every open Studio read the whole root again (list and bin, about 1,200 D1 rows for a project of 110 files), the saving window twice. With editors saving every 400 to 700 ms that came to 4.4 million rows read in a day by one person. - Worker: a write that changed nothing but some files' own records names them, `{ type: "changed", files }` (PUT /api/files/:id, property values, a canvas's render, a photo and its images; at most 16, one root). A changed property definition, a new file others already point at, and every wider route stay unnamed. - Studio: `loadFiles` reads named files one by one and puts them into the root's list; reads of a root run one after the other, a waiting root read answers every call, and a heard change is skipped when a read that began after it covers it (the window's own change no longer reads twice). - Autosaves, renames, bodies, new files, values and the import's preview step read their file instead of the root. Co-Authored-By: Claude Fable 5.2 --- apps/studio/src/api.ts | 2 + apps/studio/src/apps/CanvasApp.tsx | 4 +- apps/studio/src/apps/DevicesApp.tsx | 2 +- apps/studio/src/apps/LayoutsApp.tsx | 2 +- apps/studio/src/apps/PresetsApp.tsx | 4 +- apps/studio/src/apps/TimelineApp.tsx | 2 +- apps/studio/src/ext/flows/FlowsApp.tsx | 2 +- apps/studio/src/ext/hardware/RemotesApp.tsx | 2 +- apps/studio/src/files.ts | 112 +++++++++++++++++--- apps/studio/src/media.ts | 2 +- apps/studio/src/props.ts | 6 +- apps/studio/src/shots/doc.ts | 5 +- apps/worker/src/canvas.ts | 3 +- apps/worker/src/files.ts | 13 +++ apps/worker/src/index.ts | 17 ++- apps/worker/src/live.ts | 19 ++-- apps/worker/src/photos.ts | 8 +- apps/worker/src/properties.ts | 4 +- apps/worker/test/routes/projects.test.ts | 34 +++++- docs/api.md | 2 +- docs/features/files.md | 2 +- 21 files changed, 196 insertions(+), 51 deletions(-) diff --git a/apps/studio/src/api.ts b/apps/studio/src/api.ts index 9d31f59f..aec269c8 100644 --- a/apps/studio/src/api.ts +++ b/apps/studio/src/api.ts @@ -108,6 +108,8 @@ export const fetchFiles = (r: Root) => get<{ files: FileRec[] }>(`/api/files?${r export const putValues = (id: string, values: Record) => send<{ values: Record }>("PUT", `/api/files/${id}/properties`, { values }).then((x) => x.values); /** The same values on many files (bulk edit). */ export const setValuesOn = (ids: string[], values: Record) => send("POST", "/api/properties/set", { ids, values }); +/** One file as the root's list gives it: with its body, references and values. */ +export const fetchFile = (id: string) => get<{ file: FileRec }>(`/api/files/${id}`).then((x) => x.file); export const fetchBin = (r: Root) => get<{ files: FileRec[] }>(`/api/files?${rootQuery(r)}&bin=1`).then((x) => x.files); /** Make an internal file a file of its root (one-way): at the top level, or in a container. */ export const releaseFile = (id: string, container: string | null = null) => send<{ file: FileRec }>("POST", `/api/files/${id}/release`, { container }).then((x) => x.file); diff --git a/apps/studio/src/apps/CanvasApp.tsx b/apps/studio/src/apps/CanvasApp.tsx index 5a286cc0..6894256b 100644 --- a/apps/studio/src/apps/CanvasApp.tsx +++ b/apps/studio/src/apps/CanvasApp.tsx @@ -11,7 +11,7 @@ import type { FileRec } from "../api"; import { CanvasEditor, type Draft, type PlaceablePhoto } from "../canvas/CanvasEditor"; import { pictureOf, rectOf, type BasePhoto } from "../canvas/geometry"; import { renderCanvas } from "../canvas/render"; -import { loadRoot, useRoot } from "../files"; +import { loadFiles, useRoot } from "../files"; import { toastError } from "../hosts"; import { imageUrl } from "../media"; import { presetsIn } from "../optics"; @@ -213,7 +213,7 @@ export function Editing({ file, files, projectId, me, nameOf, active, hosted, li setStatus(pending.current ? "waiting" : "saved"); // Too large to go whole over the live socket: viewers read it again now. if (sock.current?.readyState === WebSocket.OPEN && JSON.stringify(b).length > MAX_SEND - 100) sock.current.send(JSON.stringify({ type: "saved" })); - void loadRoot({ project: projectId }); + void loadFiles({ project: projectId }, [file.id]); } catch (e) { setStatus("failed"); if (e instanceof api.ApiError && e.status === 423) { held.current = false; void take(); } else toastError(e); diff --git a/apps/studio/src/apps/DevicesApp.tsx b/apps/studio/src/apps/DevicesApp.tsx index 27404da3..e1b9734d 100644 --- a/apps/studio/src/apps/DevicesApp.tsx +++ b/apps/studio/src/apps/DevicesApp.tsx @@ -149,7 +149,7 @@ const layoutName = (id: string | undefined, layouts: FileRec[]) => (id === "came function PhoneCard({ d, devices, layouts, connected }: { d: FileRec; devices: FileRec[]; layouts: FileRec[]; connected: boolean }) { const b = d.body as unknown as DeviceBody; const [name, setName] = useState(d.name); - const save = (change: Partial) => void api.putFile(d.id, { body: { ...b, ...change } }).then(() => store.loadRoot("home"), toastError); + const save = (change: Partial) => void api.putFile(d.id, { body: { ...b, ...change } }).then(() => store.loadFiles("home", [d.id]), toastError); const offered: [string, string, IconName][] = [...CORE_TABS, ...phoneTabs().filter((t) => extensionOn(t.extension)).map((t): [string, string, IconName] => [t.id, t.label, t.icon])]; const tabs = b.tabs.filter((t) => t !== "setup"); // Tabs of an extension the project has off stay in the choice, unseen. diff --git a/apps/studio/src/apps/LayoutsApp.tsx b/apps/studio/src/apps/LayoutsApp.tsx index a6b3ffb5..3bf39f87 100644 --- a/apps/studio/src/apps/LayoutsApp.tsx +++ b/apps/studio/src/apps/LayoutsApp.tsx @@ -74,7 +74,7 @@ function Editor({ id, file, layouts, devices, onPick, projectId }: { id: string; const save = async () => { pending.current = null; if (!file || layoutError(latest.current as unknown as Record)) return; - try { await api.putFile(file.id, { body: latest.current }); setStatus("saved"); void store.loadRoot("home"); } + try { await api.putFile(file.id, { body: latest.current }); setStatus("saved"); void store.loadFiles("home", [file.id]); } catch (e) { toastError(e); } }; useEffect(() => () => { if (pending.current) { clearTimeout(pending.current); void save(); } }, []); diff --git a/apps/studio/src/apps/PresetsApp.tsx b/apps/studio/src/apps/PresetsApp.tsx index 1ee06aa1..9fe8cd2a 100644 --- a/apps/studio/src/apps/PresetsApp.tsx +++ b/apps/studio/src/apps/PresetsApp.tsx @@ -5,7 +5,7 @@ import { useEffect, useMemo, useState } from "preact/hooks"; import { Badge, Button, EmptyState, FormField, Icon, NumberInput, SidebarNav, Switch, Table, TextInput, BrowserLayout, Toolbar, ToolbarSpacer, StatusBar, cx } from "@openclapper/design"; import { opticsView } from "@openclapper/fov-math"; import { focalsOf, type PresetBody } from "@openclapper/model"; -import { bin, loadRoot, useRoot } from "../files"; +import { bin, loadFiles, useRoot } from "../files"; import * as api from "../api"; import { confirm, toast, toastError } from "../hosts"; import { presetsIn, usedFocals, type Preset } from "../optics"; @@ -54,7 +54,7 @@ function PresetPage({ p, used, onDuplicate, onGone }: { p: Preset; used: Set(null); useEffect(() => setName(p.name), [p.name]); const save = async (change: { name?: string; body?: PresetBody }) => { - try { await api.putFile(p.id, change); } catch (e) { toastError(e); } finally { await loadRoot({ project: p.file.project_id! }); } + try { await api.putFile(p.id, change); } catch (e) { toastError(e); } finally { await loadFiles({ project: p.file.project_id! }, [p.id]); } }; const b = p.body; const focals = focalsOf(b.lenses); diff --git a/apps/studio/src/apps/TimelineApp.tsx b/apps/studio/src/apps/TimelineApp.tsx index a77d231a..b61ebb22 100644 --- a/apps/studio/src/apps/TimelineApp.tsx +++ b/apps/studio/src/apps/TimelineApp.tsx @@ -125,7 +125,7 @@ function Cut({ f, files, bin, projectId, active, startAt, setRoute }: { f: FileR try { await api.putFileLocked(f.id, { body: b, refs: timelineRefs(b) }, lock.holder); setStatus(pending.current ? "waiting" : "saved"); - void store.loadRoot({ project: projectId }); + void store.loadFiles({ project: projectId }, [f.id]); } catch (e) { setStatus("failed"); if (e instanceof api.ApiError && e.status === 423) lock.lost(); else toastError(e); diff --git a/apps/studio/src/ext/flows/FlowsApp.tsx b/apps/studio/src/ext/flows/FlowsApp.tsx index a2188d73..c8d9359f 100644 --- a/apps/studio/src/ext/flows/FlowsApp.tsx +++ b/apps/studio/src/ext/flows/FlowsApp.tsx @@ -118,7 +118,7 @@ function FlowEditor({ f, projectId, active, list, onNew, onGone }: { f: FileRec; try { const rec = await api.putFileLocked(f.id, { body: latest.current as unknown as Record }, lock.holder); setStatus(pending.current ? "waiting" : "saved"); - void store.loadRoot({ project: projectId }); + void store.loadFiles({ project: projectId }, [f.id]); return rec.updated_at ?? null; } catch (e) { setStatus("failed"); diff --git a/apps/studio/src/ext/hardware/RemotesApp.tsx b/apps/studio/src/ext/hardware/RemotesApp.tsx index 00995a7b..ee17149a 100644 --- a/apps/studio/src/ext/hardware/RemotesApp.tsx +++ b/apps/studio/src/ext/hardware/RemotesApp.tsx @@ -138,7 +138,7 @@ function Editor({ file, devices, onGone }: { file: FileRec; devices: FileRec[]; const save = async () => { pending.current = null; if (remoteError(latest.current)) return; - try { await api.putFile(file.id, { body: latest.current }); setStatus("saved"); void store.loadRoot("home"); } catch (e) { toastError(e); } + try { await api.putFile(file.id, { body: latest.current }); setStatus("saved"); void store.loadFiles("home", [file.id]); } catch (e) { toastError(e); } }; useEffect(() => () => { if (pending.current) { clearTimeout(pending.current); void save(); } }, []); const change = (next: RemoteBody) => { diff --git a/apps/studio/src/files.ts b/apps/studio/src/files.ts index effa35cd..69692984 100644 --- a/apps/studio/src/files.ts +++ b/apps/studio/src/files.ts @@ -5,8 +5,9 @@ import type { FileRec, Root } from "./api"; /** * The files of a root, one copy for every window (docs/rewrite/07-organisation.md): the Files app, * the desktop's icons, the taskbar's pins and the recycle bin all read this store, so a change in - * one shows in all. A change goes to the server first and the root is read again; nothing is - * guessed locally. + * one shows in all. A change goes to the server first and what it changed is read again: the one + * file when only its own record changed, else the root; nothing is guessed locally (#599: reading + * the root after every save cost a project's worth of database rows each time). */ export interface RootFiles { files: FileRec[] | null; bin: FileRec[] | null; error: string | null } const EMPTY: RootFiles = { files: null, bin: null, error: null }; @@ -19,15 +20,73 @@ const put = (r: Root, change: Partial) => { roots.set(rootKey(r), { . export const getRoot = (r: Root): RootFiles => roots.get(rootKey(r)) ?? EMPTY; -/** Read a root's live files and its bin again. */ -export async function loadRoot(r: Root): Promise { +// Reads of one root run one after the other, so what a later read found is never replaced by an earlier one's +// answer. `rootAt` and `fileAt`: when the last read of the root, or of one file, began; a change heard before that +// is in what it read. +interface Reads { line: Promise; waiting: Promise | null; rootAt: number; fileAt: Map } +const reads = new Map(); +let account = 0; +function readsOf(key: string): Reads { + let x = reads.get(key); + if (!x) reads.set(key, x = { line: Promise.resolve(), waiting: null, rootAt: 0, fileAt: new Map() }); + return x; +} +function inLine(key: string, run: () => Promise): Promise { + const x = readsOf(key); + return x.line = x.line.then(run, run); +} + +async function readRoot(r: Root): Promise { + const x = readsOf(rootKey(r)), mine = account; + x.rootAt = performance.now(); + x.fileAt.clear(); try { const [files, bin] = await Promise.all([api.fetchFiles(r), api.fetchBin(r)]); - put(r, { files, bin, error: null }); - } catch (e) { put(r, { error: (e as Error).message }); } + if (mine === account) put(r, { files, bin, error: null }); + } catch (e) { if (mine === account) put(r, { error: (e as Error).message }); } } + +/** Read a root's live files and its bin again. A read that waits for its turn answers every call until it starts. */ +export function loadRoot(r: Root): Promise { + const x = readsOf(rootKey(r)); + return x.waiting ??= inLine(rootKey(r), () => { x.waiting = null; return readRoot(r); }); +} + +/** More files than this are not read one by one: the root is read once. */ +const ONE_BY_ONE = 16; +// As the server lists them: by name without case (ASCII's only, as SQLite's NOCASE), then by id. +const fold = (s: string) => s.replace(/[A-Z]+/g, (c) => c.toLowerCase()); +const inOrder = (a: FileRec, b: FileRec) => { const x = fold(a.name), y = fold(b.name); return x < y ? -1 : x > y ? 1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0; }; + +/** + * Read these files again and put them into the root's list (#599): for a change of nothing but their own records + * (a body, a name, values, a photo's images). Anything it cannot place (a file that left the list, a file not + * found, another root's) reads the root instead. + */ +export function loadFiles(r: Root, ids: readonly string[]): Promise { + const key = rootKey(r), want = [...new Set(ids)]; + if (!want.length) return Promise.resolve(); + if (want.length > ONE_BY_ONE || !roots.get(key)?.files) return loadRoot(r); + return inLine(key, async () => { + const x = readsOf(key), mine = account, at = performance.now(); + for (const id of want) x.fileAt.set(id, at); + try { + const fresh = await Promise.all(want.map((id) => api.fetchFile(id))); + const cur = roots.get(key)?.files; + if (mine !== account) return; + if (!cur) throw new Error("the root is not read yet"); + const listed = new Set(cur.map((f) => f.id)); + // A binned file that was not listed changed nothing here (a photo's image arriving for a copy in the bin). + const live = fresh.filter((f) => !f.deleted_at || listed.has(f.id)); + if (live.some((f) => f.deleted_at || rootKey(rootOf(f)) !== key)) throw new Error("not a file of this list any more"); + const got = new Map(live.map((f) => [f.id, f])); + put(r, { files: [...cur.filter((f) => !got.has(f.id)), ...live].sort(inOrder), error: null }); + } catch { await readRoot(r); } + }); +} + /** Forget everything (another account signed in). */ -export function clearFiles() { roots.clear(); for (const k of [...watches.keys()]) { const w = watches.get(k)!; w.users = 0; clearTimeout(w.retry); clearTimeout(w.soon); w.ws?.close(); watches.delete(k); } notify(); } +export function clearFiles() { account++; reads.clear(); roots.clear(); for (const k of [...watches.keys()]) { const w = watches.get(k)!; w.users = 0; clearTimeout(w.retry); clearTimeout(w.soon); w.ws?.close(); watches.delete(k); } notify(); } /** The root a file belongs to. */ export const rootOf = (f: Pick): Root => (f.project_id ? { project: f.project_id } : "home"); @@ -36,15 +95,19 @@ export const rootOf = (f: Pick): Root => (f.project_id ? async function change(r: Root, run: () => Promise): Promise { try { return await run(); } finally { await loadRoot(r); } } +/** The same for a change of one file's own record (its name, its body, making it): that file is read again. */ +async function changeOne(r: Root, id: string, run: () => Promise): Promise { + try { return await run(); } finally { await loadFiles(r, [id]); } +} export const create = (r: Root, type: string, more: { id?: string; name?: string; container?: string | null; body?: Record; refs?: { kind: string; to: string }[] } = {}) => { const { id = crypto.randomUUID(), ...rest } = more; - return change(r, () => api.createFile(r, id, { type, ...rest })); + return changeOne(r, id, () => api.createFile(r, id, { type, ...rest })); }; /** Rename a file; `holder`: the edit lock this window holds on it (a flow or shot open for editing), else it counts as someone else. */ -export const rename = (f: FileRec, name: string, holder?: string) => change(rootOf(f), () => (holder ? api.putFileLocked(f.id, { name }, holder) : api.putFile(f.id, { name }))); +export const rename = (f: FileRec, name: string, holder?: string) => changeOne(rootOf(f), f.id, () => (holder ? api.putFileLocked(f.id, { name }, holder) : api.putFile(f.id, { name }))); /** Save a file's body (a collection's colour or order); the type's rules are checked by the server. */ -export const saveBody = (f: FileRec, body: Record) => change(rootOf(f), () => api.putFile(f.id, { body })); +export const saveBody = (f: FileRec, body: Record) => changeOne(rootOf(f), f.id, () => api.putFile(f.id, { body })); export const move = (r: Root, ids: string[], container: string | null) => change(r, () => api.moveFiles(ids, container)); export const bin = (r: Root, ids: string[]) => change(r, () => api.binFiles(ids)); export const restore = (r: Root, ids: string[]) => change(r, () => api.restoreFiles(ids)); @@ -54,14 +117,26 @@ export const duplicate = (f: FileRec, more: { name?: string; container?: string // ---------- Live: a root on screen reads itself again when its files changed elsewhere (#426) ---------- // One socket per root while some window shows it (`/api/live/root`, the root's room in the Worker): every write that -// changed a file of the root, from any client (a phone's upload too), says `changed`, and the root is read again -// (once for a burst). After a drop it reconnects and reads the root again, for what it missed meanwhile. -const watches = new Map; soon?: ReturnType }>(); +// changed a file of the root, from any client (a phone's upload too), says `changed`: with the files it names, when +// only their own records changed (#599), and those are read again; without, the root is (once for a burst). A change +// this window made itself is heard too, and skipped when the read after it already began. After a drop it reconnects +// and reads the root again, for what it missed meanwhile. +interface Watch { users: number; ws: WebSocket | null; retry?: ReturnType; soon?: ReturnType; /** Heard and not read yet: the whole root (when), files (each when). */ root: number | null; files: Map } +const watches = new Map(); +/** Reads what a root's socket said changed, unless a read that began after it was said has it already. */ +function readHeard(r: Root, w: Watch) { + const x = readsOf(rootKey(r)); + const root = w.root !== null && w.root >= x.rootAt; + const files = [...w.files].filter(([id, at]) => at >= Math.max(x.rootAt, x.fileAt.get(id) ?? 0)).map(([id]) => id); + w.root = null; w.files.clear(); + if (root) void loadRoot(r); + else if (files.length) void loadFiles(r, files); +} function watch(r: Root): () => void { const key = rootKey(r); let w = watches.get(key); if (w) { w.users++; return () => unwatch(key); } - w = { users: 1, ws: null }; + w = { users: 1, ws: null, root: null, files: new Map() }; watches.set(key, w); const entry = w; const open = (again: boolean) => { @@ -71,9 +146,14 @@ function watch(r: Root): () => void { entry.ws = ws; ws.onopen = () => { if (again) void loadRoot(r); }; ws.onmessage = (e) => { - if (!String(e.data).includes("\"changed\"")) return; + let m: { type?: unknown; files?: unknown }; + try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; } + if (m.type !== "changed") return; + const at = performance.now(); + if (Array.isArray(m.files)) { for (const id of m.files) if (typeof id === "string") entry.files.set(id, at); } + else entry.root = at; clearTimeout(entry.soon); - entry.soon = setTimeout(() => void loadRoot(r), 250); + entry.soon = setTimeout(() => readHeard(r, entry), 250); }; ws.onclose = () => { if (entry.ws === ws) entry.ws = null; if (entry.users > 0) entry.retry = setTimeout(() => open(true), 3000); }; }; diff --git a/apps/studio/src/media.ts b/apps/studio/src/media.ts index 1fc01715..e297c335 100644 --- a/apps/studio/src/media.ts +++ b/apps/studio/src/media.ts @@ -116,7 +116,7 @@ async function run(j: Job): Promise { j.step = 1; } if (j.step === 1) { await putImage(j.id, "thumbnail", await derive(bmp, THUMB, 0.8)); j.step = 2; } - if (j.step === 2) { await putImage(j.id, "preview", await derive(bmp, PREVIEW, 0.86)); j.step = 3; j.state = "preview"; notify(); void store.loadRoot(j.root); } + if (j.step === 2) { await putImage(j.id, "preview", await derive(bmp, PREVIEW, 0.86)); j.step = 3; j.state = "preview"; notify(); void store.loadFiles(j.root, [j.id]); } if (j.step === 3) { await putImage(j.id, "original", j.file); j.step = 4; } } finally { bmp.close(); } } diff --git a/apps/studio/src/props.ts b/apps/studio/src/props.ts index e431d3b7..238dd00a 100644 --- a/apps/studio/src/props.ts +++ b/apps/studio/src/props.ts @@ -1,7 +1,7 @@ import { defaultPattern, optionId, STARTERS, type PropertyDef } from "@openclapper/model"; import * as api from "./api"; import type { FileRec } from "./api"; -import { create, fixedFolder, loadRoot, saveBody, useRoot } from "./files"; +import { create, fixedFolder, loadFiles, loadRoot, saveBody, useRoot } from "./files"; /** * The project's property catalogue and naming patterns in the Studio (docs/features/properties.md): @@ -63,8 +63,8 @@ export async function savePattern(projectId: string, files: readonly FileRec[] | else await create({ project: projectId }, "naming", { name: `Names of ${type}`, container: settingsOf(files), body }); } -/** Sets property values on one file or many; the store reads the project again. */ +/** Sets property values on one file or many; the store reads those files again (the project, when they are many). */ export async function setValues(projectId: string, ids: string[], values: Record) { try { if (ids.length === 1) await api.putValues(ids[0], values); else await api.setValuesOn(ids, values); } - finally { await loadRoot({ project: projectId }); } + finally { await loadFiles({ project: projectId }, ids); } } diff --git a/apps/studio/src/shots/doc.ts b/apps/studio/src/shots/doc.ts index abee206b..9b822daa 100644 --- a/apps/studio/src/shots/doc.ts +++ b/apps/studio/src/shots/doc.ts @@ -7,7 +7,7 @@ import { useEffect, useRef, useState } from "preact/hooks"; import type { Progression } from "@openclapper/model"; import * as api from "../api"; import type { FileRec } from "../api"; -import { loadRoot } from "../files"; +import { loadFiles } from "../files"; import { toastError } from "../hosts"; import type { EditLock, LiveDoc } from "../lock"; import { itemsOf, overlayOf, progressionBody, type Item } from "./progression"; @@ -48,7 +48,8 @@ function useSaved(f: FileRec | undefined, read: (f: FileRec) => D, write: (d: if (!d || !at || (l && !l.held())) return; try { await (l ? api.putFileLocked(at.id, write(d), l.holder) : api.putFile(at.id, write(d))); } catch (e) { if (l && e instanceof api.ApiError && e.status === 423) l.lost(); else toastError(e); } - finally { await loadRoot({ project: at.project_id! }); } + // A save changes the file, and the file it is internal to (its parent's "changed"). + finally { await loadFiles({ project: at.project_id! }, [at.id, ...(at.internal_of ? [at.internal_of] : [])]); } }; useEffect(() => () => { if (pending.current) { clearTimeout(pending.current); void save(); } }, [f?.id]); const change = (next: D | ((d: D) => D)) => { diff --git a/apps/worker/src/canvas.ts b/apps/worker/src/canvas.ts index c41823ec..3bb02f60 100644 --- a/apps/worker/src/canvas.ts +++ b/apps/worker/src/canvas.ts @@ -6,7 +6,7 @@ import { tellRoom } from "./live.ts"; import { assertUuid, HttpError, json, readJson, type Router } from "@openclapper/service-kit"; import { fileType, presetChangeError, type CanvasBody, type FrameValues, type PresetBody } from "@openclapper/model"; -import { accessFile, fileOut } from "./files.ts"; +import { accessFile, changedOnly, fileOut } from "./files.ts"; import { assertBodySize, preconditionFailed, sniffImageType } from "./images.ts"; import type { Ctx, Env } from "./index.ts"; @@ -168,6 +168,7 @@ export function registerCanvasRoutes(r: Router) { env.DB.prepare("INSERT OR REPLACE INTO renders (file_id, part, type, bytes, at) VALUES (?1, ?2, ?3, ?4, ?5)").bind(f.id, part, type, bytes.byteLength, at), env.DB.prepare("UPDATE files SET updated_at = ?2 WHERE id = ?1").bind(f.id, at), ]); + changedOnly(ctx, f.id); return json({ file: await fileOut(env, f.id) }, 201); }); diff --git a/apps/worker/src/files.ts b/apps/worker/src/files.ts index 029a7222..e0e6b486 100644 --- a/apps/worker/src/files.ts +++ b/apps/worker/src/files.ts @@ -201,6 +201,16 @@ export async function fileOut(env: Env, id: string) { return { ...toApi(f, true), refs: await refsOf(env, f) }; } +/** + * Says a write changed nothing but these files' own records, so a root's watchers read those files instead of the + * whole root (#599). Not for a write that changes what other files show: their place, their values, a reference of + * theirs that is missing or back. + */ +export const changedOnly = (ctx: Ctx, ...ids: string[]) => { for (const id of ids) ctx.only?.add(id); }; + +/** Whether a file points at this id: making a file others already point at changes them too (their reference is no longer missing). */ +export const pointedAt = async (env: Env, id: string) => !!(await env.DB.prepare("SELECT 1 FROM refs WHERE to_file = ?1 LIMIT 1").bind(id).first()); + /** The statements that replace a file's own references (everything but what property values keep). */ function writeRefs(env: Env, id: string, refs: Ref[]): D1PreparedStatement[] { const stmts = [env.DB.prepare("DELETE FROM refs WHERE from_file = ?1 AND kind != 'property'").bind(id)]; @@ -466,6 +476,9 @@ export function registerFileRoutes(r: Router) { // Whoever watches a lockable file hears at once that it was saved (#426: from any client, the device's too). if (stored && t.lockable) await tellRoom(env, fid, { type: "saved" }); if (underParent) await tellRoom(env, parent!.id, { type: "saved" }); + // The root's watchers read this file only, unless the write reached others: a definition's values, references to a new file. + const refitted = t.type === "property" && !!stored && !!save; + if (!refitted && (stored || !(await pointedAt(env, fid)))) changedOnly(ctx, fid, ...(underParent ? [parent!.id] : [])); return json({ file: await fileOut(env, fid) }, stored ? 200 : 201); }); diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index 9f45dd0e..e18743e1 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -3,7 +3,7 @@ * Every request except signing in needs a user: a session from the auth provider * (`@openclapper/auth-provider`, first-party.ts by default). The routes are in routes.ts. */ -import { rootChanged } from "./live.ts"; +import { MAX_NAMED, rootChanged } from "./live.ts"; import { provider } from "@openclapper/auth-provider"; import { HttpError, json } from "@openclapper/service-kit"; import { purgeExpired } from "./files.ts"; @@ -37,6 +37,11 @@ export interface Ctx { tenant: Tenant; /** The roots this request may change, noted by the access checks (tenancy.ts `touch`). */ touched?: Set; + /** + * The files a write changed, when it changed nothing but their own records (files.ts `changedOnly`): the root's + * room then names them, and its watchers read those files instead of the whole root (#599). + */ + only?: Set; } /** A session, everywhere: local development signs in too (dev@localhost, `make init`), so it behaves like production. */ @@ -67,12 +72,14 @@ export default { if (!(await provider.allow(identity, capability, env))) throw new HttpError(403, "not allowed for this account"); } const tenant = await loadTenant(env, identity.userId); - const touched = new Set(); - const res = await router.handle(request.method, url.pathname, { request, env, url, identity, tenant, touched }); + const touched = new Set(), only = new Set(); + const res = await router.handle(request.method, url.pathname, { request, env, url, identity, tenant, touched, only }); // A write that went through: the roots it changed hear it, so open clients read them again (#426). Taking or - // renewing an edit lock is not a change of the files. + // renewing an edit lock is not a change of the files. A write that named the files it changed (one root's, a + // few) is told with them (#599). if (request.method !== "GET" && request.method !== "HEAD" && res.status < 400 && touched.size && !url.pathname.endsWith("/lock")) { - await Promise.all([...touched].map((root) => rootChanged(env, root))); + const files = touched.size === 1 && only.size > 0 && only.size <= MAX_NAMED ? [...only] : null; + await Promise.all([...touched].map((root) => rootChanged(env, root, files))); } return res; } catch (err) { diff --git a/apps/worker/src/live.ts b/apps/worker/src/live.ts index 0439f89d..1f192051 100644 --- a/apps/worker/src/live.ts +++ b/apps/worker/src/live.ts @@ -36,7 +36,8 @@ const readHolder = (v: string | null) => { export function registerLiveRoutes(r: Router) { /** * A root's live socket (#426): `?project_id=` or `?home=1`. It hears `changed` whenever a write changed a file of - * the root, from any client, so open file lists read it again instead of waiting for a reload. + * the root, from any client, so open file lists read it again instead of waiting for a reload. With `files` (ids) + * nothing but those files' own records changed, and reading them is enough (#599). */ r.on("GET", "/api/live/root", async (ctx) => { const { env, request, url, tenant } = ctx; @@ -78,10 +79,16 @@ export async function tellRoom(env: Env, fileId: string, msg: { type: "lock"; by } catch (e) { console.warn("live: room not told", fileId, e); } } -/** A root's files changed (#426): its room ("root:" or "root:home:") tells every open client. */ -export async function rootChanged(env: Env, root: string) { +/** More changed files than this are not named: the watchers read the root once instead of that many files. */ +export const MAX_NAMED = 16; + +/** + * A root's files changed (#426): its room ("root:" or "root:home:") tells every open client. + * `files`: the only files whose records changed, when the write knows that (#599); null: anything may have. + */ +export async function rootChanged(env: Env, root: string, files: string[] | null = null) { try { - await env.CANVAS_LIVE.get(env.CANVAS_LIVE.idFromName(`root:${root}`)).fetch(new Request("https://room/notify", { method: "POST", body: JSON.stringify({ type: "changed" }) })); + await env.CANVAS_LIVE.get(env.CANVAS_LIVE.idFromName(`root:${root}`)).fetch(new Request("https://room/notify", { method: "POST", body: JSON.stringify({ type: "changed", ...(files ? { files } : {}) }) })); } catch (e) { console.warn("live: root not told", root, e); } } @@ -132,8 +139,8 @@ export class CanvasRoom extends DurableObject { } /** From the lock routes and saves: every socket hears who edits now; a lock's end is watched with an alarm. */ - private async notify(m: { file: string; type: string; by?: string | null; until?: string | null; holder?: string }): Promise { - if (m.type === "saved" || m.type === "changed") { this.sendAll({ type: m.type }); return new Response(null, { status: 204 }); } + private async notify(m: { file: string; type: string; by?: string | null; until?: string | null; holder?: string; files?: string[] }): Promise { + if (m.type === "saved" || m.type === "changed") { this.sendAll({ type: m.type, ...(m.files ? { files: m.files } : {}) }); return new Response(null, { status: 204 }); } await this.ctx.storage.put("file", m.file); this.sendAll({ type: "editor", by: m.by ?? null, ...(m.by && m.until ? { until: m.until } : {}), ...(m.by && m.holder ? { holder: m.holder } : {}) }); if (m.by && m.until) { await this.ctx.storage.put("lock", { by: m.by, until: m.until }); await this.ctx.storage.setAlarm(new Date(m.until).getTime() + 1000); } diff --git a/apps/worker/src/photos.ts b/apps/worker/src/photos.ts index cfc61564..ebbcb050 100644 --- a/apps/worker/src/photos.ts +++ b/apps/worker/src/photos.ts @@ -1,7 +1,7 @@ import { photoAov } from "@openclapper/fov-math"; import { MAX_FILE_NAME, captureFrameError, fileType, placementError } from "@openclapper/model"; import { assertUuid, HttpError, json, readJson, type Router } from "@openclapper/service-kit"; -import { accessFile, fileOut } from "./files.ts"; +import { accessFile, changedOnly, fileOut, pointedAt } from "./files.ts"; import { assertBodySize, imageExt, preconditionFailed, sniffImageType, type ImageType } from "./images.ts"; import type { Ctx, Env } from "./index.ts"; import { nextName } from "./properties.ts"; @@ -104,6 +104,7 @@ export function registerPhotoRoutes(r: Router) { if (existing) { await accessFile(ctx, pid, "editor"); if (existing.type !== "photo") throw new HttpError(409, "this id is another file's"); + changedOnly(ctx, pid); return json({ file: await fileOut(env, pid) }); } const projectId = assertUuid(b.project_id, "project_id"); @@ -133,6 +134,7 @@ export function registerPhotoRoutes(r: Router) { env.DB.prepare("INSERT INTO photos (file_id, object_id, origin, media_type, taken_at, width, height, aov_horizontal, aov_vertical, aov_source, device_id, frame) VALUES (?1, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)") .bind(pid, b.origin, mediaType, taken, width, height, aov?.horizontal ?? null, aov?.vertical ?? null, aov?.source ?? null, deviceId, frame), ]); + if (!(await pointedAt(env, pid))) changedOnly(ctx, pid); return json({ file: await fileOut(env, pid) }, 201); }); @@ -148,7 +150,7 @@ export function registerPhotoRoutes(r: Router) { const file = await accessFile(ctx, pid, "editor"); const photo = file.type === "photo" ? await photoRow(env, pid) : null; if (!photo) throw new HttpError(404, "photo not found"); - if (photo[`${which}_bytes`] !== null) return json({ file: await fileOut(env, pid), already: true }); + if (photo[`${which}_bytes`] !== null) { changedOnly(ctx, pid); return json({ file: await fileOut(env, pid), already: true }); } assertBodySize(request, LIMIT[which].bytes); const bytes = new Uint8Array(await request.arrayBuffer()); if (bytes.byteLength === 0) throw new HttpError(400, "the image is empty"); @@ -159,6 +161,8 @@ export function registerPhotoRoutes(r: Router) { // Every photo that shares the image gets it; a second upload racing this one finds it stored. const set = which === "original" ? "original_bytes = ?2, media_type = ?3" : `${which}_bytes = ?2, ${which}_type = ?3`; await env.DB.prepare(`UPDATE photos SET ${set} WHERE object_id = ?1 AND ${which}_bytes IS NULL`).bind(photo.object_id, bytes.byteLength, type).run(); + const sharing = await env.DB.prepare("SELECT file_id FROM photos WHERE object_id = ?1").bind(photo.object_id).all<{ file_id: string }>(); + changedOnly(ctx, ...sharing.results.map((r) => r.file_id)); return json({ file: await fileOut(env, pid) }, 201); }); diff --git a/apps/worker/src/properties.ts b/apps/worker/src/properties.ts index 70da9801..206f1983 100644 --- a/apps/worker/src/properties.ts +++ b/apps/worker/src/properties.ts @@ -12,7 +12,7 @@ import { attachedTo, defaultPattern, fileType, filesNamed, fitValue, isEmptyValue, MAX_BULK, patternProblems, renderName, valueError, valueText, type PropertyDef, } from "@openclapper/model"; -import { accessFile } from "./files.ts"; +import { accessFile, changedOnly } from "./files.ts"; import type { Ctx, Env } from "./index.ts"; interface Def { id: string; name: string; def: PropertyDef; deleted: boolean } @@ -196,6 +196,8 @@ async function setValues(ctx: Ctx, ids: string[], change: Change) { stmts.push(...propertyRefs(env, f.id), env.DB.prepare("UPDATE files SET updated_at = ?2 WHERE id = ?1").bind(f.id, at)); } await env.DB.batch(stmts); + // Values are the file's own: its watchers read the files that got them. + changedOnly(ctx, ...ids); const after = await valuesOf(env, ids); return Object.fromEntries(ids.map((id) => [id, after.get(id) ?? {}])); } diff --git a/apps/worker/test/routes/projects.test.ts b/apps/worker/test/routes/projects.test.ts index 9ac64b12..35d73df0 100644 --- a/apps/worker/test/routes/projects.test.ts +++ b/apps/worker/test/routes/projects.test.ts @@ -50,15 +50,43 @@ describe("a root's live room (#426)", () => { await ok(api(u.token, "PUT", `/api/projects/${id}`, { name: `L ${id}` }), 201); const watch = (token: string) => api(token, "GET", `/api/live/root?project_id=${id}`, undefined, { Upgrade: "websocket" }); expect([403, 404]).toContain((await watch(other.token)).status); - const inbox: { type: string }[] = []; + const inbox: { type: string; files?: string[] }[] = []; const ws = (await watch(u.token)).webSocket!; ws.accept(); - ws.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data)) as { type: string }); }); + ws.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data)) as { type: string; files?: string[] }); }); const folder = uuid(); await ok(api(u.token, "PUT", `/api/files/${folder}`, { type: "folder", project_id: id, name: "New" }), 201); await ok(api(u.token, "POST", "/api/files/bin", { ids: [folder] })); await new Promise((r) => setTimeout(r, 200)); - expect(inbox.filter((m) => m.type === "changed").length).toBe(2); + const heard = inbox.filter((m) => m.type === "changed"); + expect(heard.length).toBe(2); + // #599: a write of one file's own record names it; one that reaches further (the bin) names none. + expect(heard[0].files).toEqual([folder]); + expect(heard[1].files).toBeUndefined(); + ws.close(1000); + }); + + test("a change names its files only when nothing but their own records changed (#599)", async () => { + const id = uuid(); + await ok(api(u.token, "PUT", `/api/projects/${id}`, { name: `N ${id}` }), 201); + const inbox: { type: string; files?: string[] }[] = []; + const ws = (await api(u.token, "GET", `/api/live/root?project_id=${id}`, undefined, { Upgrade: "websocket" })).webSocket!; + ws.accept(); + ws.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data)) as { type: string; files?: string[] }); }); + const next = async () => { await new Promise((r) => setTimeout(r, 100)); return inbox.splice(0).filter((m) => m.type === "changed"); }; + + // A shortcut may point at a file that is not there yet: making that file changes the shortcut too (no longer missing). + const target = uuid(), shortcut = uuid(); + await ok(api(u.token, "PUT", `/api/files/${shortcut}`, { type: "shortcut", project_id: id, name: "To it", body: { app: null }, refs: [{ kind: "target", to: target }] }), 201); + expect(await next()).toEqual([{ type: "changed", files: [shortcut] }]); + await ok(api(u.token, "PUT", `/api/files/${target}`, { type: "folder", project_id: id, name: "It" }), 201); + expect(await next()).toEqual([{ type: "changed" }]); + + // A rename is the file's own; a move of several, and a duplicate, are not named. + await ok(api(u.token, "PUT", `/api/files/${target}`, { name: "It, renamed" })); + expect(await next()).toEqual([{ type: "changed", files: [target] }]); + await ok(api(u.token, "POST", "/api/files/move", { ids: [shortcut], container: target })); + expect(await next()).toEqual([{ type: "changed" }]); ws.close(1000); }); }); diff --git a/docs/api.md b/docs/api.md index f5ce1e8a..7ffebbf1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -91,7 +91,7 @@ A new project (`PUT /api/projects/:id`) starts without property definitions (#42 | POST | `/api/files/:id/lock` | `{ holder, take_over? }` (the editing window's token) → `{ lock: { by, until } }`: taken when free, run out or this window's (`take_over: true`: also from another window of the same person, #556); renewed the same way (it holds 60 s). `423` with `lock` when someone else holds it. Lockable types only (a canvas) | | DELETE | `/api/files/:id/lock?holder=` | Lets go; only the holder's call changes anything. `204` | | GET | `/api/canvases/:id/live?holder=` | WebSocket (`426` without the upgrade) to the file's `CanvasRoom` (`live.ts`; any lockable file: canvas, shot, timeline, else `400`): the editor when the window `holder` holds the lock, else a viewer (viewer access is enough), in every project (#426; `canvas_live` only decides whether clients stream the content). Editor sends `doc { body, base?, refs? }`, `draft { draft }`, `saved`, `held`; viewers get those and `editor { by }` (a user id or null). The room also hears the lock routes (taken, renewed, let go: `editor` to every socket, and to a viewer that joins), every save of the file (`saved`), and the lock running out (an alarm at its end: `editor { by: null }`). Other messages, and anything a viewer sends, are dropped | -| GET | `/api/live/root?project_id=` or `?home=1` | WebSocket to the root's room (#426; the `CanvasRoom` class under the name `root:` or `root:home:`): it hears `{ type: "changed" }` after every write that changed a file of the root, from any client, noted by the access checks (`touched`); taking or renewing an edit lock does not count. Viewer access is enough | +| GET | `/api/live/root?project_id=` or `?home=1` | WebSocket to the root's room (#426; the `CanvasRoom` class under the name `root:` or `root:home:`): it hears `{ type: "changed" }` after every write that changed a file of the root, from any client, noted by the access checks (`touched`); taking or renewing an edit lock does not count. A write that changed nothing but the own records of at most 16 files names them, `{ type: "changed", files: [ids] }` (#599: a file's name, body, references, place or values through `PUT /api/files/:id` or the property routes, a canvas's render, a photo and its images; not a changed property definition, nor a new file others already point at), so a client reads those with `GET /api/files/:id` instead of the root; without `files` anything in the root may have changed. Viewer access is enough | | PUT | `/api/canvases/:id/render`, `/thumbnail` | The body is the image (PNG, JPEG, WebP; 12 MB and 600 KB). Replaces the one stored | | GET | `/api/web?to=` | The bearer session (the phone's) as the cookie of the same session, and a `302` to that path of this site (for the Studio in the phone's web view). `400` for a path that is not of this site or without a bearer token | | GET | `/api/canvases/:id/image?size=render\|thumbnail` | Default `render`. An ETag; with `?v=` (the file's `updated_at`) cached for good, else revalidated. `404` until made | diff --git a/docs/features/files.md b/docs/features/files.md index f42b5753..bb11635e 100644 --- a/docs/features/files.md +++ b/docs/features/files.md @@ -24,7 +24,7 @@ Everything a user makes is a file ([07 · organisation](../rewrite/07-organisati - **Folders:** the project's folder tree, the account home's tree, and the recycle bin with its count. The open folder's path stays expanded. - **Properties:** nothing chosen: the folder and its count. One file: its icon, its name (editable in place), its type, Open, what it holds or opens, where it is, created, created by, changed, and **Used in** (the files that point at it). Several ticked: Move to… and To the recycle bin. - **Toolbar:** the path (each part a link and a drop target), search over names in the whole root (marked "whole project"), the Types filter once there is more than one type, List · Grid, New (folder). -- **Live** (#426): every root on screen keeps a socket to its room (`/api/live/root`); any write that changed its files, from any client (a photo uploaded from a phone, a change in another browser), makes it read the root again, once for a burst. No reload and no Reload button needed. +- **Live** (#426): every root on screen keeps a socket to its room (`/api/live/root`); any write that changed its files, from any client (a photo uploaded from a phone, a change in another browser), makes it read again what changed, once for a burst: the files the message names when only their own records changed (a save, a rename, values, an uploaded image), else the root (a move, the bin, a duplicate). The store (`files.ts`) does the same after its own changes (`loadFiles` for one file's record, `loadRoot` for the rest), runs a root's reads one after the other, and skips a message that a read begun after it already covers (#599: reading the whole root after every save cost about 1,200 database rows each time, twice per save in the window that saved). No reload and no Reload button needed. - **Selecting is an OS file manager's** (#426): a click selects a file (the panel shows it), Ctrl-click adds or removes one, Shift-click selects the range from the file last clicked; a drag on the empty part of the list or grid draws a rectangle and selects what it touches (Ctrl keeps the selection), and a click there clears it. No checkboxes or tick circles; hover is a light background, selected a stronger one (`useMarquee` and `clickSelect` in the design system). The status bar counts the selection, with Clear. New files are made from the New menu and the context menu of the empty space, never from a button per type. - **List:** name with its icon (a fixed folder's own glyph, arrow for a shortcut), type, "In" while searching, created; sortable by name, type and created, containers first. **Grid:** cards with the type icon and a line of facts. Sort and view are remembered per browser. - **Columns** (#426): every column a kind of list can show, the properties included; **Columns** in the toolbar (list view) shows or hides them (hidden, not deleted; *As they were* resets),, a header's right edge is dragged to size it (a handle shows while the header row is hovered; the columns keep fixed widths and an empty column after them takes the rest, so only that edge moves) and a header is dragged sideways to put the column elsewhere (the order, also of hidden columns, is kept; a new property column comes after the ordered ones). *As they were* also resets widths and order. Kept with the account per kind of list (folders, home, Photos, Shots, Sets, Locations), the same in every window and browser. Search keeps covering every property: a row that matched in a hidden column says which property and value. From b68f3823bec3f7aeba283ce7175552879331aad8 Mon Sep 17 00:00:00 2001 From: bubulux Date: Fri, 4 Dec 2026 18:13:13 +0100 Subject: [PATCH 2/2] Tests for what a write names and what the Studio's file store reads (#599) - Worker route test (live-root.test.ts): every kind of named write is checked against the whole root, read before and after: nothing but the named files may differ. The writes that reach further (a new file something points at, a changed definition, move, copy, bin, restore, more than 16 files) must stay unnamed. - Studio unit test (files.test.ts): the store's reads with fetch, WebSocket and the debounce timer stood in: named and plain changes, bursts, the window's own change read once, a change heard after a read began, a late answer of an earlier read, the fallbacks to the root, the socket coming back. - files.ts imports ./api.ts by its file name so node --test can load it, and exports `watch`. Co-Authored-By: Claude Fable 5.2 --- apps/studio/src/files.test.ts | 218 ++++++++++++++++++++++ apps/studio/src/files.ts | 7 +- apps/worker/test/routes/live-root.test.ts | 121 ++++++++++++ docs/testing.md | 4 +- 4 files changed, 345 insertions(+), 5 deletions(-) create mode 100644 apps/studio/src/files.test.ts create mode 100644 apps/worker/test/routes/live-root.test.ts diff --git a/apps/studio/src/files.test.ts b/apps/studio/src/files.test.ts new file mode 100644 index 00000000..2ba728c4 --- /dev/null +++ b/apps/studio/src/files.test.ts @@ -0,0 +1,218 @@ +/** + * The file store's reads (#599): what it reads after a change it heard or made, against a server and a socket + * that stand in for the real ones (`fetch`, `WebSocket`, the debounce timer). + */ +import { beforeEach, mock, test } from "node:test"; +import assert from "node:assert/strict"; +import type { FileRec } from "./api.ts"; + +// ---------- The server: its files, every request it got, and answers that can be held back ---------- +const server = new Map(); +let calls: string[] = []; +let hold: Promise | null = null; +/** Called with every write before it is answered: the room tells the sockets first, as the Worker does. */ +let onWrite: (method: string, path: string) => void = () => {}; +const answer = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); +const listed = (project: string, binned: boolean) => [...server.values()].filter((f) => f.project_id === project && !!f.deleted_at === binned).sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()) || a.id.localeCompare(b.id)); + +globalThis.fetch = (async (input: RequestInfo | URL, init: RequestInit = {}) => { + const url = new URL(String(input), "http://studio.test"), method = init.method ?? "GET"; + calls.push(`${method} ${url.pathname}${url.searchParams.has("bin") ? "?bin" : url.search ? "?list" : ""}`); + if (method === "GET") { + // What a read finds is fixed when it is asked; a held read is only answered later. + const found = url.pathname === "/api/files" + ? answer(200, { files: listed(url.searchParams.get("project_id")!, url.searchParams.has("bin")) }) + : server.has(url.pathname.split("/")[3]) ? answer(200, { file: server.get(url.pathname.split("/")[3]) }) : answer(404, { error: "file not found" }); + if (hold) await hold; + return found; + } + const id = url.pathname.split("/")[3]; + if (method === "PUT") server.set(id, { ...(server.get(id) ?? file(id, "", String((JSON.parse(String(init.body)) as { project_id?: string }).project_id))), ...(JSON.parse(String(init.body)) as Partial), updated_at: `t${calls.length}` }); + if (url.pathname === "/api/files/bin") for (const x of (JSON.parse(String(init.body)) as { ids: string[] }).ids) server.set(x, { ...server.get(x)!, deleted_at: "now" }); + onWrite(method, url.pathname); + return answer(200, method === "PUT" ? { file: server.get(id) } : {}); +}) as typeof fetch; + +class Socket { + static open: Socket[] = []; + onopen: (() => void) | null = null; + onmessage: ((e: { data: string }) => void) | null = null; + onclose: (() => void) | null = null; + url: string; + constructor(url: string) { this.url = url; Socket.open.push(this); } + close() { Socket.open = Socket.open.filter((s) => s !== this); } + say(m: unknown) { this.onmessage?.({ data: JSON.stringify(m) }); } +} +Object.defineProperty(globalThis, "WebSocket", { value: Socket, configurable: true, writable: true }); +Object.defineProperty(globalThis, "location", { value: { origin: "http://studio.test" }, configurable: true, writable: true }); +mock.timers.enable({ apis: ["setTimeout"] }); + +const store = await import("./files.ts"); + +function file(id: string, name: string, project: string, more: Partial = {}): FileRec { + return { id, project_id: project, home: false, type: "folder", name, container: null, internal_of: null, fixed: null, created_at: "t0", updated_at: "t0", created_by: null, deleted_at: null, lock: null, body_version: 1, ...more }; +} +/** Lets every request that is on its way be answered and put into the store. */ +const settle = async () => { for (let i = 0; i < 30; i++) await new Promise((r) => setImmediate(r)); }; +/** The debounce after a message passes; what it starts is answered. */ +const later = async () => { mock.timers.tick(250); await settle(); }; +const names = (project: string) => store.getRoot({ project }).files?.map((f) => f.name); + +let n = 0; +/** A project of three folders, read once and watched; `calls` starts empty. */ +async function watched() { + const project = `p${++n}`; + for (const [id, name] of [["a", "Alpha"], ["b", "beta"], ["c", "Gamma"]]) server.set(`${project}-${id}`, file(`${project}-${id}`, name, project)); + await store.loadRoot({ project }); + const stop = store.watch({ project }); + const socket = Socket.open.at(-1)!; + calls = []; + return { project, root: { project }, socket, stop, id: (x: string) => `${project}-${x}` }; +} +beforeEach(() => { server.clear(); calls = []; hold = null; onWrite = () => {}; }); + +test("a root is read with its bin; a read that waits for its turn answers every call", async () => { + const w = await watched(); + assert.deepEqual(names(w.project), ["Alpha", "beta", "Gamma"]); + let free = () => {}; + hold = new Promise((r) => { free = r; }); + const reads = [store.loadRoot(w.root)]; + await settle(); + reads.push(store.loadRoot(w.root), store.loadRoot(w.root), store.loadRoot(w.root)); + await settle(); + free(); hold = null; + await Promise.all(reads); + // The one under way, and one for everything asked meanwhile. + assert.deepEqual(calls, ["GET /api/files?list", "GET /api/files?bin", "GET /api/files?list", "GET /api/files?bin"]); + w.stop(); +}); + +test("a change that names its files reads those files only, and puts them in the list's order", async () => { + const w = await watched(); + server.set(w.id("c"), { ...server.get(w.id("c"))!, name: "aardvark" }); + server.set(w.id("d"), file(w.id("d"), "Beta 2", w.project)); + w.socket.say({ type: "changed", files: [w.id("c"), w.id("d")] }); + await later(); + assert.deepEqual(calls.sort(), [`GET /api/files/${w.id("c")}`, `GET /api/files/${w.id("d")}`]); + assert.deepEqual(names(w.project), ["aardvark", "Alpha", "beta", "Beta 2"]); + w.stop(); +}); + +test("a burst of changes is read once", async () => { + const w = await watched(); + for (let i = 0; i < 5; i++) { w.socket.say({ type: "changed", files: [w.id("a")] }); mock.timers.tick(100); } + await later(); + assert.deepEqual(calls, [`GET /api/files/${w.id("a")}`]); + w.stop(); +}); + +test("a change that names no files reads the root, and covers the named ones heard with it", async () => { + const w = await watched(); + w.socket.say({ type: "changed", files: [w.id("a")] }); + w.socket.say({ type: "changed" }); + await later(); + assert.deepEqual(calls, ["GET /api/files?list", "GET /api/files?bin"]); + w.stop(); +}); + +test("the window's own change of one file is read once: the message about it is covered by the read after it", async () => { + const w = await watched(); + onWrite = () => w.socket.say({ type: "changed", files: [w.id("a")] }); + await store.rename(server.get(w.id("a"))!, "Omega"); + await later(); + assert.deepEqual(calls, [`PUT /api/files/${w.id("a")}`, `GET /api/files/${w.id("a")}`]); + assert.deepEqual(names(w.project), ["beta", "Gamma", "Omega"]); + w.stop(); +}); + +test("the window's own wide change reads the root once", async () => { + const w = await watched(); + onWrite = () => w.socket.say({ type: "changed" }); + await store.bin(w.root, [w.id("b")]); + await later(); + assert.deepEqual(calls, ["POST /api/files/bin", "GET /api/files?list", "GET /api/files?bin"]); + assert.deepEqual(names(w.project), ["Alpha", "Gamma"]); + assert.deepEqual(store.getRoot(w.root).bin?.map((f) => f.name), ["beta"]); + w.stop(); +}); + +test("a change heard after a read began is read again", async () => { + const w = await watched(); + await store.loadFiles(w.root, [w.id("a")]); + server.set(w.id("a"), { ...server.get(w.id("a"))!, name: "Later" }); + w.socket.say({ type: "changed", files: [w.id("a")] }); + await later(); + assert.deepEqual(calls, [`GET /api/files/${w.id("a")}`, `GET /api/files/${w.id("a")}`]); + assert.deepEqual(names(w.project), ["beta", "Gamma", "Later"]); + w.stop(); +}); + +test("an earlier read that is answered late never replaces what a later read found", async () => { + const w = await watched(); + let free = () => {}; + hold = new Promise((r) => { free = r; }); + const whole = store.loadRoot(w.root); + await settle(); + // The root's read is on its way with the old name; the file changes and is read after it. + server.set(w.id("a"), { ...server.get(w.id("a"))!, name: "Newest" }); + // Only the root's read is held back: asked out of line, the file's answer would come first and be replaced. + hold = null; + const one = store.loadFiles(w.root, [w.id("a")]); + await settle(); + free(); + await Promise.all([whole, one]); + assert.deepEqual(names(w.project), ["beta", "Gamma", "Newest"]); + w.stop(); +}); + +test("a named file that is gone, or in the bin now, reads the root instead", async () => { + const w = await watched(); + server.delete(w.id("a")); + await store.loadFiles(w.root, [w.id("a")]); + assert.deepEqual(calls, [`GET /api/files/${w.id("a")}`, "GET /api/files?list", "GET /api/files?bin"]); + assert.deepEqual(names(w.project), ["beta", "Gamma"]); + calls = []; + server.set(w.id("b"), { ...server.get(w.id("b"))!, deleted_at: "now" }); + await store.loadFiles(w.root, [w.id("b")]); + assert.deepEqual(calls, [`GET /api/files/${w.id("b")}`, "GET /api/files?list", "GET /api/files?bin"]); + assert.deepEqual(names(w.project), ["Gamma"]); + w.stop(); +}); + +test("a binned file that was not listed changes nothing; another root's file reads the root", async () => { + const w = await watched(); + server.set(w.id("x"), file(w.id("x"), "In the bin", w.project, { deleted_at: "now" })); + await store.loadFiles(w.root, [w.id("x")]); + assert.deepEqual(calls, [`GET /api/files/${w.id("x")}`]); + assert.deepEqual(names(w.project), ["Alpha", "beta", "Gamma"]); + calls = []; + server.set("elsewhere", file("elsewhere", "Not ours", "another-project")); + await store.loadFiles(w.root, ["elsewhere"]); + assert.deepEqual(calls, ["GET /api/files/elsewhere", "GET /api/files?list", "GET /api/files?bin"]); + assert.deepEqual(names(w.project), ["Alpha", "beta", "Gamma"]); + w.stop(); +}); + +test("more files than are read one by one, and a root not read yet, read the root", async () => { + const w = await watched(); + await store.loadFiles(w.root, Array.from({ length: 17 }, (_, i) => `${w.project}-n${i}`)); + assert.deepEqual(calls, ["GET /api/files?list", "GET /api/files?bin"]); + calls = []; + server.set("fresh-a", file("fresh-a", "Only", "fresh")); + await store.loadFiles({ project: "fresh" }, ["fresh-a"]); + assert.deepEqual(calls, ["GET /api/files?list", "GET /api/files?bin"]); + assert.deepEqual(names("fresh"), ["Only"]); + w.stop(); +}); + +test("after a drop the socket comes back and the root is read for what was missed", async () => { + const w = await watched(); + w.socket.onclose?.(); + mock.timers.tick(3000); + const again = Socket.open.at(-1)!; + assert.notEqual(again, w.socket); + again.onopen?.(); + await settle(); + assert.deepEqual(calls, ["GET /api/files?list", "GET /api/files?bin"]); + w.stop(); +}); diff --git a/apps/studio/src/files.ts b/apps/studio/src/files.ts index 69692984..f3981d27 100644 --- a/apps/studio/src/files.ts +++ b/apps/studio/src/files.ts @@ -1,6 +1,6 @@ import { useEffect, useState } from "preact/hooks"; -import * as api from "./api"; -import type { FileRec, Root } from "./api"; +import * as api from "./api.ts"; +import type { FileRec, Root } from "./api.ts"; /** * The files of a root, one copy for every window (docs/rewrite/07-organisation.md): the Files app, @@ -132,7 +132,8 @@ function readHeard(r: Root, w: Watch) { if (root) void loadRoot(r); else if (files.length) void loadFiles(r, files); } -function watch(r: Root): () => void { +/** Keeps a root's socket open while someone shows the root (`useRoot`); the answer lets go of it. */ +export function watch(r: Root): () => void { const key = rootKey(r); let w = watches.get(key); if (w) { w.users++; return () => unwatch(key); } diff --git a/apps/worker/test/routes/live-root.test.ts b/apps/worker/test/routes/live-root.test.ts new file mode 100644 index 00000000..12b10ce8 --- /dev/null +++ b/apps/worker/test/routes/live-root.test.ts @@ -0,0 +1,121 @@ +/** + * What a root's live room says a write changed (#599): a write that names files (`{ type: "changed", files }`) + * promises that nothing but those files' own records changed, so a client reads them instead of the root. Every + * kind of named write is checked against the whole root, read before and after; the writes that reach further + * must stay unnamed. + */ +import { beforeAll, describe, expect, test } from "vitest"; +import { api, jpeg, newUser, ok, png, putImage, putRender, uuid, type User } from "./helpers.ts"; + +let u: User; +beforeAll(async () => { u = await newUser(); }); + +type Heard = { type: string; files?: string[] }; +const put = (id: string, body: unknown) => ok(api(u.token, "PUT", `/api/files/${id}`, body)); +const post = (path: string, body: unknown) => ok(api(u.token, "POST", path, body), [200, 201, 204]); + +describe("a root's live room names the files a write changed (#599)", () => { + test("a named write changes nothing but the files it names; wider writes are not named", async () => { + const project = uuid(); + await ok(api(u.token, "PUT", `/api/projects/${project}`, { name: `Named ${project}` }), 201); + const p = { project_id: project }; + const inbox: Heard[] = []; + const ws = (await api(u.token, "GET", `/api/live/root?project_id=${project}`, undefined, { Upgrade: "websocket" })).webSocket!; + ws.accept(); + ws.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data)) as Heard); }); + + /** Every file of the root as a client keeps it, live and binned, by id. */ + const root = async () => { + const q = `/api/files?project_id=${project}`; + const live = (await ok<{ files: { id: string }[] }>(api(u.token, "GET", `${q}&body=1&refs=1&values=1&internal=1`))).files; + const bin = (await ok<{ files: { id: string }[] }>(api(u.token, "GET", `${q}&bin=1`))).files; + return new Map([...live, ...bin.map((f) => ({ ...f, binned: true }))].map((f) => [f.id, JSON.stringify(f)])); + }; + /** Runs one write; says what the room told and which files of the root are different after it. */ + const step = async (run: () => Promise) => { + const before = await root(); + inbox.length = 0; + await run(); + // The room was told before the write answered; the message only has to arrive. + for (let i = 0; i < 200 && !inbox.some((m) => m.type === "changed"); i++) await new Promise((r) => setTimeout(r, 5)); + await new Promise((r) => setTimeout(r, 10)); + const heard = inbox.filter((m) => m.type === "changed"); + expect(heard.length).toBe(1); + const after = await root(); + const changed = [...new Set([...before.keys(), ...after.keys()])].filter((id) => before.get(id) !== after.get(id)); + return { files: heard[0].files, changed }; + }; + /** A write of files' own records: named, and nothing else is different. */ + const named = async (what: string, ids: string[], run: () => Promise) => { + const { files, changed } = await step(run); + expect(files, what).toBeDefined(); + expect([...files!].sort(), what).toEqual([...ids].sort()); + expect(changed.filter((id) => !files!.includes(id)), what).toEqual([]); + return changed; + }; + /** A write that reaches further: not named; `also` is a file it changed besides the one written. */ + const wide = async (what: string, run: () => Promise, also?: string) => { + const { files, changed } = await step(run); + expect(files, what).toBeUndefined(); + if (also) expect(changed, what).toContain(also); + }; + + const settings = (await ok<{ files: { id: string; name: string }[] }>(api(u.token, "GET", `/api/files?project_id=${project}&type=folder`))).files.find((f) => f.name === "Settings")!.id; + const a = uuid(), link = uuid(), target = uuid(), shot = uuid(), shot2 = uuid(), prog = uuid(), def = uuid(), photo = uuid(), canvas = uuid(); + + // A file's own record: made, renamed, put elsewhere. + expect(await named("a new folder", [a], () => put(a, { type: "folder", ...p, name: "A" }))).toEqual([a]); + await named("a rename", [a], () => put(a, { name: "A, renamed" })); + await named("a shortcut to a file that is not there yet", [link], () => put(link, { type: "shortcut", ...p, name: "To it", body: { app: null }, refs: [{ kind: "target", to: target }] })); + // The file the shortcut waits for: making it changes the shortcut (its reference is no longer missing). + await wide("a new file something points at", () => put(target, { type: "folder", ...p, name: "It" }), link); + await named("a move by its own record", [a], () => put(a, { container: target })); + + // A shot, and a progression inside it: saving the progression changes the shot's "changed" too. + await named("a new shot", [shot], () => put(shot, { type: "shot", ...p })); + await named("a new shot", [shot2], () => put(shot2, { type: "shot", ...p })); + const body = { timing: { mode: "each" }, frame: null, overlayShown: true }; + await named("a progression made inside a shot", [prog, shot], () => put(prog, { type: "progression", ...p, name: "Progression 1", internal_of: shot, body })); + await named("a shot's content", [shot], () => put(shot, { refs: [{ kind: "content", to: prog }] })); + expect(await named("a progression saved", [prog, shot], () => put(prog, { body: { ...body, overlayShown: false } }))).toContain(shot); + + // Property values are the file's own; a changed definition refits the values of every file that has one. + const choice = (...labels: string[]) => ({ field: "choice", attached: [{ type: "shot" }], order: 50, options: labels.map((label, i) => ({ id: label.toLowerCase(), label, color: i + 1 })) }); + await named("a new property", [def], () => put(def, { type: "property", ...p, name: "Mood", container: settings, body: choice("Calm", "Tense") })); + expect(await named("a value on one file", [shot], () => ok(api(u.token, "PUT", `/api/files/${shot}/properties`, { values: { [def]: "calm" } })))).toEqual([shot]); + await named("a value on several files", [shot, shot2], () => post("/api/properties/set", { ids: [shot, shot2], values: { [def]: "calm" } })); + await named("a property renamed", [def], () => put(def, { name: "Mood of the scene" })); + await wide("a changed definition", () => put(def, { body: choice("Tense") }), shot); + + // A photo and its images, a canvas and its render. + await named("a photo", [photo], () => ok(api(u.token, "PUT", `/api/photos/${photo}`, { ...p, origin: "import", media_type: "image/jpeg", taken_at: "2026-11-01T10:00:00Z", width: 4000, height: 3000, exif: {}, readout: {} }))); + for (const part of ["thumbnail", "preview", "original"] as const) await named(`a photo's ${part}`, [photo], () => ok(putImage(u.token, photo, part, jpeg(`${photo}-${part}`)))); + await named("a canvas", [canvas], () => put(canvas, { type: "canvas", ...p, name: "Canvas" })); + await named("a canvas's render", [canvas], () => ok(putRender(u.token, canvas, "render", png("render")))); + + // What moves, bins or copies files reaches further than one record. + await wide("a move", () => post("/api/files/move", { ids: [a], container: null })); + await wide("a copy", () => post(`/api/files/${canvas}/duplicate`, { id: uuid() })); + await wide("the recycle bin", () => post("/api/files/bin", { ids: [target] }), link); + await wide("a restore", () => post("/api/files/restore", { ids: [target] }), link); + ws.close(1000); + }, 30_000); + + test("more files than a client would read one by one are not named", async () => { + const project = uuid(); + await ok(api(u.token, "PUT", `/api/projects/${project}`, { name: `Many ${project}` }), 201); + const def = uuid(), shots = Array.from({ length: 17 }, () => uuid()); + const settings = (await ok<{ files: { id: string; name: string }[] }>(api(u.token, "GET", `/api/files?project_id=${project}&type=folder`))).files.find((f) => f.name === "Settings")!.id; + await put(def, { type: "property", project_id: project, name: "Note", container: settings, body: { field: "text", attached: [{ type: "shot" }], order: 50 } }); + for (const s of shots) await put(s, { type: "shot", project_id: project }); + const inbox: Heard[] = []; + const ws = (await api(u.token, "GET", `/api/live/root?project_id=${project}`, undefined, { Upgrade: "websocket" })).webSocket!; + ws.accept(); + ws.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data)) as Heard); }); + await post("/api/properties/set", { ids: shots.slice(0, 16), values: { [def]: "a" } }); + await post("/api/properties/set", { ids: shots, values: { [def]: "b" } }); + await new Promise((r) => setTimeout(r, 100)); + expect(inbox.filter((m) => m.type === "changed").map((m) => m.files?.length)).toEqual([16, undefined]); + ws.close(1000); + }); +}); diff --git a/docs/testing.md b/docs/testing.md index 063a0513..cb4a1ae9 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -9,9 +9,9 @@ What runs where, and how to add a test. All of it runs in `make check` (`pnpm te | `packages/model` | `node --test` | Node | The shared model of the rewrite: file types, body and reference checks, placement rules | | `packages/vocab`, `packages/fov-math` | `node --test` | Node | Pure functions of the first app, until its clients are rebuilt: fields, filters, daylight; FOV, overlay, reframe math | | `apps/worker` project `unit` (`test/unit/`) | Vitest | Node | Password hashing, session tokens, workspace roles | -| `apps/worker` project `routes` (`test/routes/`) | Vitest + `@cloudflare/vitest-plugin` | workerd (Miniflare), local D1 + R2 | Requests through the Worker's own `fetch` and `scheduled`: tenancy on every route, the file routes (making, moving, the recycle bin, copies, internal files, roles), project names, sessions, response headers and the CSRF guard, the storage snapshot, the preview room | +| `apps/worker` project `routes` (`test/routes/`) | Vitest + `@cloudflare/vitest-plugin` | workerd (Miniflare), local D1 + R2 | Requests through the Worker's own `fetch` and `scheduled`: tenancy on every route, the file routes (making, moving, the recycle bin, copies, internal files, roles), project names, sessions, response headers and the CSRF guard, the storage snapshot, the preview room, what a root's live room says a write changed (`live-root.test.ts`, #599: a write that names files changed nothing else in the root) | | `apps/admin` (`test/`) | Vitest + `@cloudflare/vitest-plugin` | workerd, the app's schema | The admin plane: the Access JWT check, the local bypass and its hostname guard, account actions, the audit trail | -| `apps/studio` | `node --test` | Node | The shortcut registry | +| `apps/studio` | `node --test` | Node | The shortcut registry; the window manager, the desktop grid and the keyboard maps; erasing on a canvas, cutting on a timeline; the file store's reads (`files.test.ts`, #599: what is read after a change heard or made, with `fetch`, `WebSocket` and the debounce timer stood in) | | `apps/mobile` | `node --test` | Node | Calibration, EXIF, framing, lens, zoom, layouts; lights: the command queue, the connection manager (fake link and timers), scan suggestions, byte helpers, the NEEWER light and battery frames and drivers, the Bluetooth Mesh stack and provisioning against the Mesh Profile 1.0.1 §8 sample data, the proxy session, configuration and the Aputure driver against a simulated light (`mesh/fakeNode.testlib.ts`), the Aputure commands against the reference's vectors (`src/**/*.test.ts`) | | End-to-end | | | Not yet (#222) |