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
21 changes: 19 additions & 2 deletions apps/mobile/src/ext/flows/ui/Editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import {
addKeyframe, addMarker, addTrack, fmtSeconds, FlowPlayer, patchMarker, patchTrack, removeKeys, removeTrack, setDuration, setKeyframe,
DEFAULT_VIEW, START_KEYFRAME, VIEW_LABELS, type Flow, type FlowBody, type FlowView, type Keyframe, type KeyframeSize,
} from "@openclapper/ext-flows";
import { ApiError, canCall, lockFile, unlockFile } from "../../../api";
import { ApiError, authHeaders, canCall, lockFile, unlockFile } from "../../../api";
import { API_URL } from "../../../config";
import { log } from "../../../log";
import { useBack } from "../../../shell/back";
import { Banner, Block, Button, Header, Hint, IconButton, Input, ListRow, makeStyles, Seg, Sheet, SheetList, Slider, Toggle, type, useTheme } from "../../../ui";
Expand Down Expand Up @@ -76,7 +77,23 @@ export function FlowEditor({ flow, back }: { flow: LocalFlow; back: () => void }
};
void take();
const h = setInterval(() => void take(), RENEW_MS);
return () => { stop = true; clearInterval(h); if (holderRef.current) void unlockFile(flow.id, holderRef.current).catch(() => undefined); };
// The file's live room (#426): who edits is never stale. Freed: take it at once; saved elsewhere: read it again.
let ws: WebSocket | null = null, retry: ReturnType<typeof setTimeout> | undefined;
const open = () => {
if (stop || flow.updatedAt === null || !canCall()) return;
// React Native's WebSocket takes headers: the session goes as it does for every call (link.ts).
const s = new (WebSocket as unknown as new (url: string, protocols: string[] | null, opts: { headers: Record<string, string> }) => WebSocket)(`${API_URL.replace(/^http/, "ws")}/api/canvases/${flow.id}/live?holder=${holder}`, null, { headers: authHeaders() });
ws = s;
s.onmessage = (e) => {
let m: { type?: string; by?: string | null };
try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; }
if (m.type === "editor" && !m.by && !holderRef.current) void take();
else if (m.type === "saved" && !holderRef.current) void loadFlows(flow.projectId);
};
s.onclose = () => { if (ws === s) ws = null; if (!stop) retry = setTimeout(open, 5000); };
};
open();
return () => { stop = true; clearInterval(h); clearTimeout(retry); ws?.close(); if (holderRef.current) void unlockFile(flow.id, holderRef.current).catch(() => undefined); };
}, [flow.id]);
const locked = lock.state === "theirs" || lock.state === "asking";
// Read-only, it shows the flow as its editor last saved it.
Expand Down
15 changes: 9 additions & 6 deletions apps/studio/src/apps/CanvasApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,11 @@ export function Editing({ file, files, projectId, me, nameOf, active, hosted, li
};
const apply = (b: CanvasBody, bid: string | null) => { setDoc(b); setBaseId(bid); latest.current = { doc: b, baseId: bid }; setRev((r) => r + 1); };

// The live socket: the editor when this window holds the lock, else a viewer; opened again on Edit and Stop editing, and after a drop.
// The live socket: the editor when this window holds the lock, else a viewer; opened again on Edit and Stop editing, and
// after a drop. In every project, so who edits is never stale (#426); strokes and the canvas stream only in a realtime one.
const streaming = useRef(live === "realtime");
streaming.current = live === "realtime";
useEffect(() => {
if (live !== "realtime") return;
let ws: WebSocket | null = null, done = false, retry: ReturnType<typeof setTimeout> | undefined;
const open = () => {
const s = new WebSocket(`${location.origin.replace(/^http/, "ws")}/api/canvases/${file.id}/live?holder=${holder}`);
Expand All @@ -126,18 +128,19 @@ export function Editing({ file, files, projectId, me, nameOf, active, hosted, li
if (held.current) return;
let m: { type?: string; body?: CanvasBody; base?: string | null; draft?: Draft | null; by?: string | null };
try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; }
if (m.type === "doc" && m.body) { apply(m.body, m.base ?? null); setRemoteDraft(null); }
else if (m.type === "draft") setRemoteDraft(m.draft ?? null);
if (m.type === "doc" && m.body) { if (streaming.current) { apply(m.body, m.base ?? null); setRemoteDraft(null); } }
else if (m.type === "draft") { if (streaming.current) setRemoteDraft(m.draft ?? null); }
else if (m.type === "saved") void reread(false).catch(() => {});
else if (m.type === "editor") { setLockedBy(m.by ? nameOf(m.by) : null); if (!m.by) setRemoteDraft(null); }
else if (m.type === "editor") { setLockedBy(m.by ? nameOf(m.by) : null); if (!m.by) { setRemoteDraft(null); void reread(false).catch(() => {}); } }
};
s.onclose = () => { if (sock.current === s) { sock.current = null; setConnected(false); } if (!done) retry = setTimeout(open, 3000); };
};
open();
return () => { done = true; clearTimeout(retry); if (sock.current === ws) { sock.current = null; setConnected(false); } ws?.close(); };
}, [live, editing]);
}, [editing]);
/** Sends the canvas (or the stroke being drawn) to the viewers, at most every SEND_MS; the last state always goes. */
const send = (what: { doc: true } | { draft: Draft | null }) => {
if (!streaming.current) return;
const st = sendState.current;
if ("doc" in what) { st.doc = true; st.draft = null; } else st.draft = what.draft;
if (st.timer) return;
Expand Down
15 changes: 10 additions & 5 deletions apps/studio/src/lock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,12 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o
return () => { clearInterval(renew); clearInterval(look); window.removeEventListener("pagehide", bye); bye(); };
}, [file.id]);

// The live room: opened again when this window starts or stops editing (its role changes), and after a drop.
// The live room: opened again when this window starts or stops editing (its role changes), and after a drop. In every
// project, so who edits is never stale (#426); the content itself streams only in a realtime project.
const realtime = useRef(opts.realtime);
realtime.current = opts.realtime;
useEffect(() => {
if (!opts.realtime || opts.off) return;
if (opts.off) return;
let ws: WebSocket | null = null, done = false, retry: ReturnType<typeof setTimeout> | undefined;
const open = () => {
const s = new WebSocket(`${location.origin.replace(/^http/, "ws")}/api/canvases/${file.id}/live?holder=${holder}`);
Expand All @@ -98,16 +101,18 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o
if (held.current) return;
let m: { type?: string; body?: Record<string, unknown>; refs?: LiveDoc["refs"]; by?: string | null };
try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; }
if (m.type === "doc" && m.body) remote.current?.({ body: m.body, refs: m.refs });
if (m.type === "doc" && m.body) { if (realtime.current) remote.current?.({ body: m.body, refs: m.refs }); }
else if (m.type === "saved") void reread(false).catch(() => {});
else if (m.type === "editor") setBy(m.by ? nameOf(m.by) : null);
// Let go or run out: free to edit now, and the last save is read.
else if (m.type === "editor") { setBy(m.by ? nameOf(m.by) : null); if (!m.by) void reread(false).catch(() => {}); }
};
s.onclose = () => { if (sock.current === s) { sock.current = null; setLive(false); } if (!done) retry = setTimeout(open, 3000); };
};
open();
return () => { done = true; clearTimeout(retry); if (sock.current === ws) { sock.current = null; setLive(false); } ws?.close(); };
}, [opts.realtime, editing, file.id]);
}, [opts.off, editing, file.id]);
const send = (doc: () => LiveDoc) => {
if (!realtime.current) return;
const st = sending.current;
st.doc = doc;
if (st.timer) return;
Expand Down
5 changes: 4 additions & 1 deletion apps/worker/src/canvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* frames table kept from a canvas's body, the edit lock (one editor at a time, for every lockable
* type), a canvas's render and thumbnail, and the additive rule of presets.
*/
import { tellRoom } from "./live.ts";
import { assertUuid, HttpError, json, readJson, type Router } from "@openclapper/service-kit";
import { fileType, presetChangeError, type CanvasBody, type PresetBody, type ShotBody } from "@openclapper/model";
import { accessFile, fileOut } from "./files.ts";
Expand Down Expand Up @@ -132,14 +133,16 @@ export function registerCanvasRoutes(r: Router<Ctx>) {
).bind(f.id, tenant.userId, holder, until, now()).run();
const row = await env.DB.prepare("SELECT lock_by, lock_until FROM files WHERE id = ?1").bind(f.id).first<{ lock_by: string; lock_until: string }>();
if (!took.meta.changes) return json({ error: "someone else is editing this file", lock: { by: row!.lock_by, until: row!.lock_until } }, 423);
await tellRoom(env, f.id, { type: "lock", by: row!.lock_by, until: row!.lock_until });
return json({ lock: { by: row!.lock_by, until: row!.lock_until } });
});

/** Let go of the lock: JSON { holder }. Only its holder can; anyone else's call changes nothing. Always `204`. */
r.on("DELETE", "/api/files/:id/lock", async (ctx, { id }) => {
const f = await accessFile(ctx, assertUuid(id, "id"), "viewer");
const holder = readHolder(ctx.url.searchParams.get("holder"));
await ctx.env.DB.prepare("UPDATE files SET lock_by = NULL, lock_holder = NULL, lock_until = NULL WHERE id = ?1 AND lock_by = ?2 AND lock_holder = ?3").bind(f.id, ctx.tenant.userId, holder).run();
const letGo = await ctx.env.DB.prepare("UPDATE files SET lock_by = NULL, lock_holder = NULL, lock_until = NULL WHERE id = ?1 AND lock_by = ?2 AND lock_holder = ?3").bind(f.id, ctx.tenant.userId, holder).run();
if (letGo.meta.changes) await tellRoom(ctx.env, f.id, { type: "lock", by: null, until: null });
return new Response(null, { status: 204 });
});

Expand Down
3 changes: 3 additions & 0 deletions apps/worker/src/files.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
BIN_RETENTION_DAYS, canBeInternal, checkFile, containerTypes, defaultName, matchesSearch, FIXED_FOLDERS, fileType, SETTINGS_PAGE_NAMES, SETTINGS_PAGES, type SettingsPage, fileTypes, MAX_BULK, MAX_CONTAINER_DEPTH, MAX_FILE_NAME,
nameError, placementError, type Body, type CanvasBody, type FileType, type PresetBody, type Ref, type RootKind, type ShotBody, keepGuarded } from "@openclapper/model";
import { tellRoom } from "./live.ts";
import { assertUuid, HttpError, json, readJson, type Router } from "@openclapper/service-kit";
import type { Ctx, Env } from "./index.ts";
import { assertNotLocked, assertPresetChange, assertPresetsFree, copyFrames, copyRenders, frameStatements, removeRenders, renderKeys, shotFrameStatements } from "./canvas.ts";
Expand Down Expand Up @@ -453,6 +454,8 @@ export function registerFileRoutes(r: Router<Ctx>) {
await env.DB.batch(stmts);
// A changed definition: values that no longer fit it are fitted or dropped.
if (t.type === "property" && stored && save && root.projectId) await refitValues(env, root.projectId, fid);
// 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" });
return json({ file: await fileOut(env, fid) }, stored ? 200 : 201);
});

Expand Down
57 changes: 48 additions & 9 deletions apps/worker/src/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import type { Ctx, Env } from "./index.ts";
* `{ type: "saved" }` (after a save, when the canvas was too large to send).
* Room → viewers: the same `doc`, `draft` and `saved`, and `{ type: "editor", by }` when an editor connects, renews
* or leaves (by: a user id, or null).
*
* The lock itself is live in every project (#426): the lock routes tell the room when it is taken, renewed or let
* go, a save tells it `saved`, and an alarm at the lock's end says when it ran out, so who edits is never stale on
* any client, the device's Flows editor included. Only the content (`doc`, `draft`) waits for a realtime project.
*/

/** Larger messages are dropped: the editor then sends none and viewers read the canvas from the API after each save. */
Expand All @@ -28,32 +32,41 @@ const readHolder = (v: string | null) => {
};

export function registerLiveRoutes(r: Router<Ctx>) {
/**
* The live socket of a canvas (`?holder=`): the editor when this window holds the lock, else a viewer.
* `409` when the project watches its canvases every 5 seconds instead.
*/
/** 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;
if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") throw new HttpError(426, "websocket upgrade expected");
const f = await accessFile(ctx, assertUuid(id, "id"), "viewer");
if (!fileType(f.type)?.lockable) throw new HttpError(400, "only a file edited under a lock is watched live");
const holder = readHolder(url.searchParams.get("holder"));
const row = await env.DB.prepare("SELECT f.lock_by, f.lock_holder, f.lock_until, p.canvas_live FROM files f JOIN projects p ON p.id = f.project_id WHERE f.id = ?1")
.bind(f.id).first<{ lock_by: string | null; lock_holder: string | null; lock_until: string | null; canvas_live: string }>();
if (row?.canvas_live !== "realtime") throw new HttpError(409, "this project's canvases are not watched in realtime");
const row = await env.DB.prepare("SELECT lock_by, lock_holder, lock_until FROM files WHERE id = ?1")
.bind(f.id).first<{ lock_by: string | null; lock_holder: string | null; lock_until: string | null }>();
if (!row) throw new HttpError(404, "file not found");
const editor = row.lock_by === tenant.userId && row.lock_holder === holder && !!row.lock_until && row.lock_until > new Date().toISOString();
const to = new URL(request.url);
to.search = new URLSearchParams({ role: editor ? "editor" : "viewer", user: tenant.userId, holder }).toString();
return env.CANVAS_LIVE.get(env.CANVAS_LIVE.idFromName(f.id)).fetch(new Request(to, request));
});
}

/**
* Tells a file's room what changed outside it: the lock (who holds it now, and until when) or a save. Never fails
* the request that changed it: the room is a convenience, the database is the truth.
*/
export async function tellRoom(env: Env, fileId: string, msg: { type: "lock"; by: string | null; until: string | null } | { type: "saved" }) {
try {
await env.CANVAS_LIVE.get(env.CANVAS_LIVE.idFromName(fileId)).fetch(new Request("https://room/notify", { method: "POST", body: JSON.stringify({ file: fileId, ...msg }) }));
} catch (e) { console.warn("live: room not told", fileId, e); }
}

type Role = "editor" | "viewer";
interface Who { user: string; holder: string }

export class CanvasRoom extends DurableObject<Env> {
async fetch(request: Request): Promise<Response> {
const q = new URL(request.url).searchParams;
const url = new URL(request.url);
if (url.pathname === "/notify") return this.notify(await request.json());
const q = url.searchParams;
const role = q.get("role") === "editor" ? "editor" : "viewer";
const who: Who = { user: q.get("user") ?? "", holder: q.get("holder") ?? "" };
const { 0: client, 1: server } = new WebSocketPair();
Expand All @@ -63,8 +76,11 @@ export class CanvasRoom extends DurableObject<Env> {
server.serializeAttachment(who);
if (role === "editor") this.send("viewer", { type: "editor", by: who.user });
else {
// Who edits: the editor's socket, else the lock as the routes last told it (one taken without a socket: the device).
const ed = this.open("editor")[0];
server.send(JSON.stringify({ type: "editor", by: ed ? (ed.deserializeAttachment() as Who).user : null }));
const lock = await this.ctx.storage.get<{ by: string; until: string }>("lock");
const held = lock && new Date(lock.until).getTime() > Date.now() ? lock.by : null;
server.send(JSON.stringify({ type: "editor", by: ed ? (ed.deserializeAttachment() as Who).user : held }));
}
return new Response(null, { status: 101, webSocket: client });
}
Expand All @@ -89,6 +105,29 @@ export class CanvasRoom extends DurableObject<Env> {
if (this.ctx.getTags(ws)[0] === "editor" && this.open("editor", ws).length === 0) this.send("viewer", { type: "editor", by: null });
}

/** 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 }); }
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); }
else { await this.ctx.storage.delete("lock"); await this.ctx.storage.deleteAlarm(); }
return new Response(null, { status: 204 });
}

/** The lock's end passed: unless it was renewed, it ran out, and everyone hears it is free. */
async alarm() {
const file = await this.ctx.storage.get<string>("file");
if (!file) return;
const row = await this.env.DB.prepare("SELECT lock_by, lock_until FROM files WHERE id = ?1").bind(file).first<{ lock_by: string | null; lock_until: string | null }>();
const until = row?.lock_until ? new Date(row.lock_until).getTime() : 0;
if (row?.lock_by && until > Date.now()) { await this.ctx.storage.setAlarm(until + 1000); return; }
await this.ctx.storage.delete("lock");
this.sendAll({ type: "editor", by: null });
}

private sendAll(msg: unknown) { this.send("viewer", msg); this.send("editor", msg); }

async webSocketError(ws: WebSocket) {
await this.webSocketClose(ws, 1011);
}
Expand Down
23 changes: 21 additions & 2 deletions apps/worker/test/routes/canvas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,29 @@ describe("live updates", () => {
viewer.send(JSON.stringify({ type: "doc", body: { forged: true }, base: null }));
editor.send(JSON.stringify({ type: "draft", draft: null }));
await new Promise((r) => setTimeout(r, 200));
expect(inbox).toEqual([{ type: "editor", by: null }, { type: "editor", by: u.id }, { type: "doc", body, base: null }, { type: "draft", draft: null }]);
// The lock was taken before the viewer came: it hears who holds it at once (#426).
expect(inbox).toEqual([{ type: "editor", by: u.id }, { type: "editor", by: u.id }, { type: "doc", body, base: null }, { type: "draft", draft: null }]);
editor.close(1000); viewer.close(1000);
// A project that watches the content every 5 seconds still gets the lock live.
await ok(api(u.token, "PUT", `/api/projects/${project}`, { name: `P ${project}`, canvas_live: "gradual" }));
expect((await live("wviewer000001")).status).toBe(409);
expect((await live("wviewer000002")).status).toBe(101);
});

test("the lock is live without an editor's socket: taken, saved and let go reach every watcher (#426)", async () => {
await newProject();
const c = uuid();
const body = { surface: { kind: "blank", aspect: 1.5, color: 0 }, objects: [], frames: [], picture: null, linkCentres: true, comments: [] };
await put(c, { type: "canvas", project_id: project, body }, 201);
const inbox: unknown[] = [];
const viewer = (await api(u.token, "GET", `/api/canvases/${c}/live?holder=wviewer000003`, undefined, { Upgrade: "websocket" })).webSocket!;
viewer.accept();
viewer.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data))); });
await ok(api(u.token, "POST", `/api/files/${c}/lock`, { holder: "wdevice000001" }));
await ok(api(u.token, "PUT", `/api/files/${c}`, { body }, { "x-lock-holder": "wdevice000001" }));
expect((await api(u.token, "DELETE", `/api/files/${c}/lock?holder=wdevice000001`)).status).toBe(204);
await new Promise((r) => setTimeout(r, 200));
expect(inbox).toEqual([{ type: "editor", by: null }, { type: "editor", by: u.id }, { type: "saved" }, { type: "editor", by: null }]);
viewer.close(1000);
});
});

Expand Down
Loading
Loading