Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions apps/studio/src/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function loadRoot(r: Root): Promise<void> {
} 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<FileRec, "project_id">): Root => (f.project_id ? { project: f.project_id } : "home");
Expand All @@ -51,14 +51,51 @@ 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<string, { users: number; ws: WebSocket | null; retry?: ReturnType<typeof setTimeout>; soon?: ReturnType<typeof setTimeout> }>();
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);
useEffect(() => {
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);
}
Expand Down
5 changes: 3 additions & 2 deletions apps/worker/src/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -122,7 +123,7 @@ function assertIds(v: unknown): string[] {
async function rootFrom(ctx: Ctx, projectId: unknown, home: unknown, min: Role, inBody: boolean): Promise<Root> {
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);
Expand Down
12 changes: 11 additions & 1 deletion apps/worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<string>;
}

/** A session, everywhere: local development signs in too (dev@localhost, `make init`), so it behaves like production. */
Expand Down Expand Up @@ -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<string>();
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);
Expand Down
27 changes: 26 additions & 1 deletion apps/worker/src/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

/**
Expand Down Expand Up @@ -32,6 +33,23 @@ const readHolder = (v: string | null) => {
};

export function registerLiveRoutes(r: Router<Ctx>) {
/**
* 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;
Expand Down Expand Up @@ -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:<project id>" or "root:home:<user id>") 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 }

Expand Down Expand Up @@ -107,7 +132,7 @@ export class CanvasRoom extends DurableObject<Env> {

/** 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<Response> {
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); }
Expand Down
15 changes: 13 additions & 2 deletions apps/worker/src/tenancy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ("<project id>" or "home:<user id>"), 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<string>;
}
/** 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
Expand Down Expand Up @@ -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<string> {
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;
}

/**
Expand All @@ -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<string> {
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);
Expand Down
19 changes: 19 additions & 0 deletions apps/worker/test/routes/projects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
1 change: 1 addition & 0 deletions apps/worker/test/routes/tenancy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ const ROUTES: Record<string, Case> = {
"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" },
Expand Down
1 change: 1 addition & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<project id>` or `root:home:<user id>`): 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=<path>` | 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 |
Expand Down
1 change: 1 addition & 0 deletions docs/features/files.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading