diff --git a/apps/studio/src/files.ts b/apps/studio/src/files.ts index 24d3ca6..1c6967f 100644 --- a/apps/studio/src/files.ts +++ b/apps/studio/src/files.ts @@ -27,7 +27,7 @@ export async function loadRoot(r: Root): Promise { } catch (e) { put(r, { error: (e as Error).message }); } } /** Forget everything (another account signed in). */ -export function clearFiles() { roots.clear(); notify(); } +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(); } /** The root a file belongs to. */ export const rootOf = (f: Pick): Root => (f.project_id ? { project: f.project_id } : "home"); @@ -51,6 +51,42 @@ export const purge = (r: Root, ids: string[]) => change(r, () => api.purgeFiles( export const emptyBin = (r: Root) => change(r, () => api.emptyBin(r)); export const duplicate = (f: FileRec, more: { name?: string; container?: string | null } = {}) => change(rootOf(f), () => api.duplicateFile(f.id, { id: crypto.randomUUID(), ...more })); +// ---------- 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 }>(); +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 }; + watches.set(key, w); + const entry = w; + const open = (again: boolean) => { + if (entry.users === 0) return; + const q = r === "home" ? "home=1" : `project_id=${r.project}`; + const ws = new WebSocket(`${location.origin.replace(/^http/, "ws")}/api/live/root?${q}`); + entry.ws = ws; + ws.onopen = () => { if (again) void loadRoot(r); }; + ws.onmessage = (e) => { + if (!String(e.data).includes("\"changed\"")) return; + clearTimeout(entry.soon); + entry.soon = setTimeout(() => void loadRoot(r), 250); + }; + ws.onclose = () => { if (entry.ws === ws) entry.ws = null; if (entry.users > 0) entry.retry = setTimeout(() => open(true), 3000); }; + }; + open(false); + return () => unwatch(key); +} +function unwatch(key: string) { + const w = watches.get(key); + if (!w || --w.users > 0) return; + clearTimeout(w.retry); clearTimeout(w.soon); + w.ws?.close(); + watches.delete(key); +} + export function useRoot(r: Root): RootFiles { const key = rootKey(r); const [, tick] = useState(0); @@ -58,7 +94,8 @@ export function useRoot(r: Root): RootFiles { const cb = () => tick((n) => n + 1); listeners.add(cb); if (!roots.get(key)?.files) void loadRoot(r); - return () => { listeners.delete(cb); }; + const stop = watch(r); + return () => { listeners.delete(cb); stop(); }; }, [key]); return getRoot(r); } diff --git a/apps/worker/src/files.ts b/apps/worker/src/files.ts index cb83987..ac5be1c 100644 --- a/apps/worker/src/files.ts +++ b/apps/worker/src/files.ts @@ -7,7 +7,7 @@ import type { Ctx, Env } from "./index.ts"; import { assertNotLocked, assertPresetChange, assertPresetsFree, copyFrames, copyRenders, frameStatements, removeRenders, renderKeys, shotFrameStatements } from "./canvas.ts"; import { copyPhotos, objectsOf, removeOrphans } from "./photos.ts"; import { nextName, refitValues, searchTexts, templateStatements, valuesOf } from "./properties.ts"; -import { assertAccess, assertProjectRef, assertRank, type Access, type Role } from "./tenancy.ts"; +import { assertAccess, assertProjectRef, assertRank, touch, type Access, type Role } from "./tenancy.ts"; /** * Files (docs/rewrite/07-organisation.md, 10-conclusion.md): one set of routes for every type. A @@ -75,6 +75,7 @@ function checkAccess(a: Access, f: FileRow | null, min: Role): FileRow { if (f.home_of) { if (f.home_of !== a.tenant.userId) throw new HttpError(404, "file not found"); } else assertRank(a, f.ws, min, "file not found"); + touch(a, f.project_id ?? `home:${f.home_of}`, min); return f; } @@ -122,7 +123,7 @@ function assertIds(v: unknown): string[] { async function rootFrom(ctx: Ctx, projectId: unknown, home: unknown, min: Role, inBody: boolean): Promise { const wantsHome = home === true || home === "1" || home === "true"; if ((projectId == null) === !wantsHome) throw new HttpError(400, "name a root: project_id, or home"); - if (wantsHome) return { kind: "home", projectId: null, userId: ctx.tenant.userId }; + if (wantsHome) { touch(ctx, `home:${ctx.tenant.userId}`, min); return { kind: "home", projectId: null, userId: ctx.tenant.userId }; } const pid = assertUuid(projectId, "project_id"); if (inBody) await assertProjectRef(ctx, pid, min); else await assertAccess(ctx, "project", pid, min); diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts index f4e878b..9f45dd0 100644 --- a/apps/worker/src/index.ts +++ b/apps/worker/src/index.ts @@ -3,6 +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 { provider } from "@openclapper/auth-provider"; import { HttpError, json } from "@openclapper/service-kit"; import { purgeExpired } from "./files.ts"; @@ -34,6 +35,8 @@ export interface Ctx { url: URL; identity: Identity; tenant: Tenant; + /** The roots this request may change, noted by the access checks (tenancy.ts `touch`). */ + touched?: Set; } /** A session, everywhere: local development signs in too (dev@localhost, `make init`), so it behaves like production. */ @@ -64,7 +67,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); - return await router.handle(request.method, url.pathname, { request, env, url, identity, tenant }); + const touched = new Set(); + const res = await router.handle(request.method, url.pathname, { request, env, url, identity, tenant, touched }); + // 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. + 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))); + } + return res; } catch (err) { if (err instanceof HttpError) return json({ error: err.message }, err.status); console.error("unhandled", err); diff --git a/apps/worker/src/live.ts b/apps/worker/src/live.ts index 5051b38..b860d9b 100644 --- a/apps/worker/src/live.ts +++ b/apps/worker/src/live.ts @@ -2,6 +2,7 @@ import { DurableObject } from "cloudflare:workers"; import { assertUuid, HttpError, type Router } from "@openclapper/service-kit"; import { fileType } from "@openclapper/model"; import { accessFile } from "./files.ts"; +import { assertAccess } from "./tenancy.ts"; import type { Ctx, Env } from "./index.ts"; /** @@ -32,6 +33,23 @@ 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. + */ + r.on("GET", "/api/live/root", async (ctx) => { + const { env, request, url, tenant } = ctx; + if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") throw new HttpError(426, "websocket upgrade expected"); + const project = url.searchParams.get("project_id"); + let key: string; + if (url.searchParams.get("home") === "1") key = `home:${tenant.userId}`; + else if (project) { const pid = assertUuid(project, "project_id"); await assertAccess(ctx, "project", pid, "viewer"); key = pid; } + else throw new HttpError(400, "name a root: project_id, or home"); + const to = new URL(request.url); + to.search = new URLSearchParams({ role: "viewer", user: tenant.userId, holder: "root-watcher" }).toString(); + return env.CANVAS_LIVE.get(env.CANVAS_LIVE.idFromName(`root:${key}`)).fetch(new Request(to, request)); + }); + /** The live socket of a lockable file (`?holder=`): the editor when this window holds the lock, else a viewer. */ r.on("GET", "/api/canvases/:id/live", async (ctx, { id }) => { const { env, request, url, tenant } = ctx; @@ -59,6 +77,13 @@ 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) { + 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" }) })); + } catch (e) { console.warn("live: root not told", root, e); } +} + type Role = "editor" | "viewer"; interface Who { user: string; holder: string } @@ -107,7 +132,7 @@ 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 }): Promise { - if (m.type === "saved") { this.sendAll({ type: "saved" }); return new Response(null, { status: 204 }); } + if (m.type === "saved" || m.type === "changed") { this.sendAll({ type: m.type }); return new Response(null, { status: 204 }); } await this.ctx.storage.put("file", m.file); this.sendAll({ type: "editor", by: m.by ?? null }); 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/tenancy.ts b/apps/worker/src/tenancy.ts index 8592a79..6f8f6fd 100644 --- a/apps/worker/src/tenancy.ts +++ b/apps/worker/src/tenancy.ts @@ -34,7 +34,14 @@ export async function loadTenant(env: { DB: D1Database }, userId: string): Promi export interface Access { env: { DB: D1Database }; tenant: Tenant; + /** + * The roots a request was allowed to change ("" or "home:"), noted by the access checks; after + * a write that succeeded the Worker tells each root's live room, so open clients read it again (#426). + */ + touched?: Set; } +/** Notes a root a write may change (see Access.touched). */ +export const touch = (a: Access, root: string, min: Role) => { if (min !== "viewer") a.touched?.add(root); }; /** * Each owned kind → SQL from one id up to its workspace (no row = the id does not exist). Files are @@ -64,7 +71,9 @@ export function assertRank(a: Access, workspaceId: string | null | undefined, mi * workspace's row answers like a missing one (404), so ids reveal nothing. Returns the workspace id. */ export async function assertAccess(a: Access, kind: Owned, id: string, min: Role): Promise { - return assertRank(a, await workspaceOf(a.env, kind, id), min, `${kind} not found`); + const ws = assertRank(a, await workspaceOf(a.env, kind, id), min, `${kind} not found`); + if (kind === "project") touch(a, id, min); + return ws; } /** @@ -84,7 +93,9 @@ export async function accessIfExists(a: Access, kind: Owned, id: string, min: Ro export async function assertRef(a: Access, kind: Owned, id: string, min: Role = "editor"): Promise { const ws = await workspaceOf(a.env, kind, id); if (!ws || !a.tenant.ranks.has(ws)) throw new HttpError(400, `${kind}_id does not exist`); - return assertRank(a, ws, min); + const rank = assertRank(a, ws, min); + if (kind === "project") touch(a, id, min); + return rank; } export const assertProjectRef = (a: Access, projectId: string, min: Role = "editor") => assertRef(a, "project", projectId, min); diff --git a/apps/worker/test/routes/projects.test.ts b/apps/worker/test/routes/projects.test.ts index 2eefb95..9ac64b1 100644 --- a/apps/worker/test/routes/projects.test.ts +++ b/apps/worker/test/routes/projects.test.ts @@ -43,3 +43,22 @@ describe("a project's description and picture", () => { expect((await api(u.token, "GET", `/api/projects/${id}/picture`)).status).toBe(404); }); }); + +describe("a root's live room (#426)", () => { + test("a watcher of a project hears every write that changed its files; another workspace cannot watch", async () => { + const id = uuid(); + 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 ws = (await watch(u.token)).webSocket!; + ws.accept(); + ws.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data)) as { type: 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); + ws.close(1000); + }); +}); diff --git a/apps/worker/test/routes/tenancy.test.ts b/apps/worker/test/routes/tenancy.test.ts index cb26c19..23c208d 100644 --- a/apps/worker/test/routes/tenancy.test.ts +++ b/apps/worker/test/routes/tenancy.test.ts @@ -67,6 +67,7 @@ const ROUTES: Record = { "DELETE /api/files/:id/lock": { kind: "id", path: (a) => `/api/files/${a.canvas}/lock?holder=holder-0001`, ownerStatus: [204] }, "PUT /api/canvases/:id/:part": { kind: "exempt", why: "the body is raw bytes, which the generic case cannot send; canvas.test.ts checks another workspace's upload is refused" }, "GET /api/canvases/:id/image": { kind: "id", path: (a) => `/api/canvases/${a.canvas}/image` }, + "GET /api/live/root": { kind: "exempt", why: "a websocket upgrade, which the generic case does not send; projects.test.ts checks another workspace is refused and a watcher hears changes" }, "GET /api/canvases/:id/live": { kind: "exempt", why: "a websocket upgrade, which the generic case does not send; canvas.test.ts checks another workspace gets 404" }, "GET /api/web": { kind: "exempt", why: "no resource: it hands the caller's own bearer session to a web view as a cookie; canvas.test.ts checks it" }, "POST /api/devices/register": { kind: "exempt", why: "no id: a device is found by the caller's own user and the fingerprint; devices.test.ts checks that another account with the same fingerprint gets a record of its own" }, diff --git a/docs/api.md b/docs/api.md index 31e99e6..5ee1424 100644 --- a/docs/api.md +++ b/docs/api.md @@ -90,6 +90,7 @@ A new project starts with the default properties in its Settings folder (`PUT /a | POST | `/api/files/:id/lock` | `{ holder }` (the editing window's token) → `{ lock: { by, until } }`: taken when free, run out or this window's; 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 | | 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 2772b5f..2f95714 100644 --- a/docs/features/files.md +++ b/docs/features/files.md @@ -24,6 +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. - **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), and a header's right edge is dragged to size it. 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.