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
2 changes: 2 additions & 0 deletions apps/studio/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ export const fetchFiles = (r: Root) => get<{ files: FileRec[] }>(`/api/files?${r
export const putValues = (id: string, values: Record<string, unknown>) => send<{ values: Record<string, unknown> }>("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<string, unknown>) => send<unknown>("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);
Expand Down
4 changes: 2 additions & 2 deletions apps/studio/src/apps/CanvasApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion apps/studio/src/apps/DevicesApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<DeviceBody>) => void api.putFile(d.id, { body: { ...b, ...change } }).then(() => store.loadRoot("home"), toastError);
const save = (change: Partial<DeviceBody>) => 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.
Expand Down
2 changes: 1 addition & 1 deletion apps/studio/src/apps/LayoutsApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>)) 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(); } }, []);
Expand Down
4 changes: 2 additions & 2 deletions apps/studio/src/apps/PresetsApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -54,7 +54,7 @@ function PresetPage({ p, used, onDuplicate, onGone }: { p: Preset; used: Set<num
const [own, setOwn] = useState<number | null>(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);
Expand Down
2 changes: 1 addition & 1 deletion apps/studio/src/apps/TimelineApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion apps/studio/src/ext/flows/FlowsApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> }, 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");
Expand Down
2 changes: 1 addition & 1 deletion apps/studio/src/ext/hardware/RemotesApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
218 changes: 218 additions & 0 deletions apps/studio/src/files.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, FileRec>();
let calls: string[] = [];
let hold: Promise<void> | 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<FileRec>), 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> = {}): 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();
});
Loading
Loading