Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/objects.test.ts10 * Module : server11 * Repository : https://git.spboucher.ai/vquant12 * Project Website : https://vquant.spboucher.ai13 * Created : 2026-11-2014 * Last Modified : 2026-11-2015 *16 * Author : Simon-Pierre Boucher17 * Position : Professor of Finance18 * Institution : Université du Québec en Outaouais (UQO)19 * Organization : SP Boucher20 * Website : https://spboucher.ai21 * Git : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development : dev@spboucher.ai25 * Support : support@spboucher.ai26 * Security/Admin : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier : MIT35 * License : MIT License36 * License File : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * Object store and sync (contract §1.1, §1.2), through HTTP on an in-process app with a temporary database.48 */49import { afterAll, beforeAll, describe, expect, it } from "vitest";50import { bootTestApp, openStream, sleep, type TestApp } from "./testkit";5152let t: TestApp;53let objects: typeof import("./objects");54let sync: typeof import("./sync");5556beforeAll(async () => {57 t = await bootTestApp();58 objects = await import("./objects");59 sync = await import("./sync");60});61afterAll(async () => {62 await t.close();63});6465const watchlist = (name = "Tech", symbols = ["AAPL", "MSFT"]) => ({ name, symbols });66const put = (user: string, kind: string, id: string, data: unknown, baseRev: number, headers?: Record<string, string>) => t.api(user, "PUT", `/api/v2/objects/${kind}/${id}`, { data, baseRev }, headers);6768describe("gate", () => {69 it("refuses a request that is not signed in", async () => {70 expect((await t.api(null, "GET", "/api/v2/objects/watchlist")).status).toBe(401);71 expect((await t.api(null, "GET", "/api/v2/sync/changes")).status).toBe(401);72 });73});7475describe("create, read, update", () => {76 it("creates with baseRev 0 and returns the envelope", async () => {77 const before = Date.now();78 const r = await put("alice", "watchlist", "wl-1", watchlist(), 0);79 expect(r.status).toBe(200);80 const o = r.body.object;81 expect(o).toMatchObject({ kind: "watchlist", id: "wl-1", rev: 1, deleted: false, device: "web", data: { name: "Tech", symbols: ["AAPL", "MSFT"] } });82 expect(Object.keys(o).sort()).toEqual(["createdAt", "data", "deleted", "device", "id", "kind", "rev", "seq", "updatedAt"]);83 expect(o.seq).toBeGreaterThan(0);84 expect(o.createdAt).toBeGreaterThanOrEqual(before);85 expect(o.updatedAt).toBe(o.createdAt);86 });8788 it("reads one object and lists a kind, newest first", async () => {89 await put("alice", "watchlist", "wl-2", watchlist("Banks", ["JPM"]), 0);90 const one = await t.api("alice", "GET", "/api/v2/objects/watchlist/wl-1");91 expect(one.status).toBe(200);92 expect(one.body.object.data.name).toBe("Tech");93 const list = await t.api("alice", "GET", "/api/v2/objects/watchlist");94 expect(list.status).toBe(200);95 const ids = list.body.objects.map((o: any) => o.id);96 expect(ids).toContain("wl-1");97 expect(ids).toContain("wl-2");98 expect(ids.indexOf("wl-2")).toBeLessThan(ids.indexOf("wl-1"));99 });100101 it("answers 404 for an object that does not exist", async () => {102 expect((await t.api("alice", "GET", "/api/v2/objects/watchlist/nope")).status).toBe(404);103 });104105 it("refuses to create over a live object: 409 with the stored envelope", async () => {106 const r = await put("alice", "watchlist", "wl-1", watchlist("Other"), 0);107 expect(r.status).toBe(409);108 expect(r.body.error).toBe("conflict");109 expect(r.body.current).toMatchObject({ id: "wl-1", rev: 1, data: { name: "Tech" } });110 });111112 it("accepts an update on the stored revision and bumps rev by one", async () => {113 const r = await put("alice", "watchlist", "wl-1", watchlist("Tech", ["AAPL", "MSFT", "NVDA"]), 1);114 expect(r.status).toBe(200);115 expect(r.body.object.rev).toBe(2);116 expect(r.body.object.data.symbols).toEqual(["AAPL", "MSFT", "NVDA"]);117 expect(r.body.object.updatedAt).toBeGreaterThanOrEqual(r.body.object.createdAt);118 });119120 it("refuses a stale update: 409 with the current envelope, nothing written", async () => {121 const r = await put("alice", "watchlist", "wl-1", watchlist("Stale"), 1);122 expect(r.status).toBe(409);123 expect(r.body.current.rev).toBe(2);124 expect(r.body.current.data.symbols).toEqual(["AAPL", "MSFT", "NVDA"]);125 const now = await t.api("alice", "GET", "/api/v2/objects/watchlist/wl-1");126 expect(now.body.object.rev).toBe(2);127 expect(now.body.object.data.name).toBe("Tech");128 });129130 it("refuses a revision from the future, and an update of something that was never created", async () => {131 expect((await put("alice", "watchlist", "wl-1", watchlist(), 99)).status).toBe(409);132 expect((await put("alice", "watchlist", "never", watchlist(), 3)).status).toBe(404);133 });134135 it("keeps unknown keys, at the top level and nested", async () => {136 const data = { name: "P", baseCurrency: "USD", futureField: { a: [1, 2, { b: null }] }, positions: [{ symbol: "AAPL", quantity: 3, lotId: "x-1", tags: ["core"] }] };137 const r = await put("alice", "portfolio", "pf-unknown", data, 0);138 expect(r.status).toBe(200);139 const back = await t.api("alice", "GET", "/api/v2/objects/portfolio/pf-unknown");140 expect(back.body.object.data).toEqual(data);141 });142143 it("records the native device id of the request, and \"web\" otherwise", async () => {144 const r = await put("alice", "watchlist", "wl-native", watchlist(), 0, { "x-test-device": "dev-1234" });145 expect(r.body.object.device).toBe("dev-1234");146 const r2 = await put("alice", "watchlist", "wl-native", watchlist("Renamed"), 1);147 expect(r2.body.object.device).toBe("web");148 });149});150151describe("validation", () => {152 it("refuses an unknown kind", async () => {153 expect((await put("alice", "secrets", "x", {}, 0)).status).toBe(404);154 expect((await t.api("alice", "GET", "/api/v2/objects/secrets")).status).toBe(404);155 });156157 it("refuses ids outside [A-Za-z0-9_-]{1,64}", async () => {158 expect((await put("alice", "watchlist", "a".repeat(65), watchlist(), 0)).status).toBe(400);159 expect((await put("alice", "watchlist", "has.dot", watchlist(), 0)).status).toBe(400);160 expect((await put("alice", "watchlist", "has%20space", watchlist(), 0)).status).toBe(400);161 expect((await put("alice", "watchlist", "a".repeat(64), watchlist(), 0)).status).toBe(200);162 expect((await put("alice", "watchlist", "Ok_id-9", watchlist(), 0)).status).toBe(200);163 });164165 it("refuses a body without data or with a bad baseRev", async () => {166 expect((await t.api("alice", "PUT", "/api/v2/objects/watchlist/v1", { baseRev: 0 })).status).toBe(400);167 expect((await t.api("alice", "PUT", "/api/v2/objects/watchlist/v1", { data: watchlist() })).status).toBe(400);168 expect((await put("alice", "watchlist", "v1", watchlist(), -1)).status).toBe(400);169 expect((await t.api("alice", "PUT", "/api/v2/objects/watchlist/v1", { data: watchlist(), baseRev: "0" })).status).toBe(400);170 expect((await put("alice", "watchlist", "v1", watchlist(), 1.5)).status).toBe(400);171 });172173 it("refuses data that is not an object", async () => {174 for (const data of ["text", 3, null, [1, 2]]) expect((await put("alice", "watchlist", "v2", data, 0)).status).toBe(400);175 });176177 it("checks each kind's required fields and names the field", async () => {178 const missing = await put("alice", "watchlist", "v3", { symbols: [] }, 0);179 expect(missing.status).toBe(400);180 expect(missing.body.error).toContain("name");181 expect((await put("alice", "watchlist", "v3", { name: "x", symbols: "AAPL" }, 0)).status).toBe(400);182 expect((await put("alice", "watchlist", "v3", { name: "x", symbols: Array.from({ length: 201 }, (_x, i) => `S${i}`) }, 0)).status).toBe(400);183 expect((await put("alice", "watchlist", "v3", { name: "x", symbols: Array.from({ length: 200 }, (_x, i) => `S${i}`) }, 0)).status).toBe(200);184 expect((await put("alice", "portfolio", "v4", { name: "p", positions: [] }, 0)).status).toBe(400); // baseCurrency185 expect((await put("alice", "portfolio", "v4", { name: "p", baseCurrency: "USD", positions: [{ symbol: "AAPL" }] }, 0)).status).toBe(400); // quantity186 expect((await put("alice", "portfolio", "v4", { name: "p", baseCurrency: "USD", positions: [{ symbol: "AAPL", quantity: "3" }] }, 0)).status).toBe(400);187 expect((await put("alice", "chart", "v5", { symbol: "AAPL", chartType: "pie" }, 0)).status).toBe(400);188 expect((await put("alice", "chart", "v5", { symbol: "AAPL", chartType: "candles", drawings: [{ id: "d1", type: "line", points: [{ t: 1700000000, p: 191.2 }] }] }, 0)).status).toBe(200);189 expect((await put("alice", "project", "v6", { title: "T", items: [{ id: "i1", type: "spreadsheet", ref: "x" }] }, 0)).status).toBe(400);190 expect((await put("alice", "project", "v6", { title: "T" }, 0)).status).toBe(400); // items191 expect((await put("alice", "note", "v7", { title: "T" }, 0)).status).toBe(400); // body192 expect((await put("alice", "workspace", "v8", { name: "W", layout: { type: "panel" }, panels: {} }, 0)).status).toBe(400);193 const layout = { type: "split", direction: "row", sizes: [50, 50], children: [{ type: "panel", panelId: "a" }, { type: "split", direction: "column", sizes: [1], children: [{ type: "panel", panelId: "b" }] }] };194 expect((await put("alice", "workspace", "v8", { name: "W", layout, panels: { a: { type: "chart", title: "A", config: { symbol: "AAPL" } }, b: { type: "spreadsheet" } } }, 0)).status).toBe(400);195 expect((await put("alice", "workspace", "v8", { name: "W", layout, panels: { a: { type: "chart", title: "A", config: { symbol: "AAPL" } }, b: { type: "news" } } }, 0)).status).toBe(200);196 });197198 it("has one preference object, id \"default\"", async () => {199 expect((await put("alice", "preference", "other", { theme: "dark" }, 0)).status).toBe(400);200 expect((await put("alice", "preference", "default", { upDownColors: "rainbow" }, 0)).status).toBe(400);201 const ok = await put("alice", "preference", "default", { theme: "dark", upDownColors: "cvd", routing: { strategy: "balanced", providers: ["anthropic"] }, budget: { maxCostUsd: 2 } }, 0);202 expect(ok.status).toBe(200);203 });204205 it("lets only the server write a review", async () => {206 const r = await put("alice", "review", "rv-1", { status: "done" }, 0);207 expect(r.status).toBe(403);208 expect(objects.getObject("alice", "review", "rv-1")).toBeNull();209 });210211 it("refuses data over 256 KB and accepts data just under", async () => {212 const big = await put("alice", "note", "big", { title: "Big", body: "x".repeat(256 * 1024) }, 0);213 expect(big.status).toBe(413);214 expect((await t.api("alice", "GET", "/api/v2/objects/note/big")).status).toBe(404);215 const ok = await put("alice", "note", "big", { title: "Big", body: "x".repeat(256 * 1024 - 200) }, 0);216 expect(ok.status).toBe(200);217 // multi-byte characters count in bytes, not characters218 expect((await put("alice", "note", "big-utf8", { title: "Big", body: "é".repeat(140 * 1024) }, 0)).status).toBe(413);219 });220});221222describe("delete and tombstones", () => {223 it("requires the revision being deleted", async () => {224 await put("alice", "watchlist", "del-1", watchlist("Doomed"), 0);225 expect((await t.api("alice", "DELETE", "/api/v2/objects/watchlist/del-1")).status).toBe(400);226 expect((await t.api("alice", "DELETE", "/api/v2/objects/watchlist/del-1?baseRev=0")).status).toBe(400);227 expect((await t.api("alice", "DELETE", "/api/v2/objects/watchlist/del-1?baseRev=abc")).status).toBe(400);228 const stale = await t.api("alice", "DELETE", "/api/v2/objects/watchlist/del-1?baseRev=7");229 expect(stale.status).toBe(409);230 expect(stale.body.current.rev).toBe(1);231 });232233 it("leaves a tombstone: gone from reads, present in the feed, content erased", async () => {234 const before = (await t.api("alice", "GET", "/api/v2/sync/changes?since=0")).body.seq;235 const r = await t.api("alice", "DELETE", "/api/v2/objects/watchlist/del-1?baseRev=1");236 expect(r.status).toBe(200);237 expect(r.body.object).toMatchObject({ id: "del-1", rev: 2, deleted: true, data: {} });238 expect(r.body.object.seq).toBe(before + 1);239 expect((await t.api("alice", "GET", "/api/v2/objects/watchlist/del-1")).status).toBe(404);240 const list = await t.api("alice", "GET", "/api/v2/objects/watchlist");241 expect(list.body.objects.some((o: any) => o.id === "del-1")).toBe(false);242 const feed = await t.api("alice", "GET", `/api/v2/sync/changes?since=${before}`);243 expect(feed.body.changes).toHaveLength(1);244 expect(feed.body.changes[0]).toMatchObject({ kind: "watchlist", id: "del-1", deleted: true, rev: 2, data: {} });245 const stored = t.db.prepare("SELECT data FROM vq_objects WHERE owner = 'alice' AND kind = 'watchlist' AND id = 'del-1'").get() as { data: string };246 expect(stored.data).toBe("{}");247 });248249 it("answers 404 when deleting again, and 409 when updating a tombstone with its revision", async () => {250 expect((await t.api("alice", "DELETE", "/api/v2/objects/watchlist/del-1?baseRev=2")).status).toBe(404);251 const r = await put("alice", "watchlist", "del-1", watchlist("Back?"), 2);252 expect(r.status).toBe(409);253 expect(r.body.current.deleted).toBe(true);254 });255256 it("re-creates over a tombstone with baseRev 0; the revision keeps counting", async () => {257 const r = await put("alice", "watchlist", "del-1", watchlist("Reborn"), 0);258 expect(r.status).toBe(200);259 expect(r.body.object).toMatchObject({ rev: 3, deleted: false, data: { name: "Reborn" } });260 expect((await t.api("alice", "GET", "/api/v2/objects/watchlist/del-1")).body.object.data.name).toBe("Reborn");261 });262263 it("writes an audit event for a deletion", async () => {264 const events = (await t.api("alice", "GET", "/api/v2/audit")).body.events;265 expect(events.some((e: any) => e.action === "object.delete" && e.target === "watchlist/del-1" && e.device === "web")).toBe(true);266 });267});268269describe("change feed", () => {270 it("assigns a strictly increasing seq to every accepted write, whatever the kind", async () => {271 const seqs: number[] = [];272 seqs.push((await put("carol", "watchlist", "s1", watchlist(), 0)).body.object.seq);273 seqs.push((await put("carol", "note", "s2", { title: "n", body: "b" }, 0)).body.object.seq);274 seqs.push((await put("carol", "watchlist", "s1", watchlist("x"), 1)).body.object.seq);275 seqs.push((await t.api("carol", "DELETE", "/api/v2/objects/note/s2?baseRev=1")).body.object.seq);276 seqs.push((await put("carol", "chart", "s3", { symbol: "SPY" }, 0)).body.object.seq);277 expect(seqs).toEqual([1, 2, 3, 4, 5]);278 // refused writes take no number279 expect((await put("carol", "watchlist", "s1", watchlist(), 0)).status).toBe(409);280 expect((await put("carol", "watchlist", "bad", { nope: 1 }, 0)).status).toBe(400);281 expect((await put("carol", "chart", "s4", { symbol: "QQQ" }, 0)).body.object.seq).toBe(6);282 });283284 it("returns the latest state of each changed object in ascending seq, tombstones included", async () => {285 const r = await t.api("carol", "GET", "/api/v2/sync/changes?since=0");286 expect(r.status).toBe(200);287 expect(r.body.seq).toBe(6);288 expect(r.body.more).toBe(false);289 expect(r.body.changes.map((c: any) => [c.kind, c.id, c.seq, c.deleted])).toEqual([290 ["watchlist", "s1", 3, false],291 ["note", "s2", 4, true],292 ["chart", "s3", 5, false],293 ["chart", "s4", 6, false],294 ]);295 });296297 it("honours since, kinds and limit (with more)", async () => {298 expect((await t.api("carol", "GET", "/api/v2/sync/changes?since=4")).body.changes.map((c: any) => c.seq)).toEqual([5, 6]);299 expect((await t.api("carol", "GET", "/api/v2/sync/changes?since=6")).body).toEqual({ changes: [], seq: 6, more: false });300 expect((await t.api("carol", "GET", "/api/v2/sync/changes?since=0&kinds=chart,note")).body.changes.map((c: any) => c.id)).toEqual(["s2", "s3", "s4"]);301 const page = await t.api("carol", "GET", "/api/v2/sync/changes?since=0&limit=2");302 expect(page.body.changes.map((c: any) => c.seq)).toEqual([3, 4]);303 expect(page.body.more).toBe(true);304 const rest = await t.api("carol", "GET", `/api/v2/sync/changes?since=${page.body.changes[1].seq}&limit=2`);305 expect(rest.body.changes.map((c: any) => c.seq)).toEqual([5, 6]);306 expect(rest.body.more).toBe(false);307 });308309 it("refuses a malformed since or an unknown kind", async () => {310 expect((await t.api("carol", "GET", "/api/v2/sync/changes?since=abc")).status).toBe(400);311 expect((await t.api("carol", "GET", "/api/v2/sync/changes?since=-1")).status).toBe(400);312 expect((await t.api("carol", "GET", "/api/v2/sync/changes?kinds=chart,passwords")).status).toBe(400);313 });314315 it("starts at seq 0 for a person who never wrote", async () => {316 expect((await t.api("frank", "GET", "/api/v2/sync/changes")).body).toEqual({ changes: [], seq: 0, more: false });317 });318});319320describe("versions", () => {321 it("archives each replaced revision of a versioned kind", async () => {322 await put("alice", "note", "ver-1", { title: "Draft", body: "one" }, 0);323 await put("alice", "note", "ver-1", { title: "Draft", body: "two" }, 1, { "x-test-device": "dev-9" });324 await put("alice", "note", "ver-1", { title: "Final", body: "three" }, 2);325 const list = await t.api("alice", "GET", "/api/v2/objects/note/ver-1/versions");326 expect(list.status).toBe(200);327 expect(list.body.versions.map((v: any) => [v.rev, v.device])).toEqual([[2, "dev-9"], [1, "web"]]);328 expect(Object.keys(list.body.versions[0]).sort()).toEqual(["device", "rev", "updatedAt"]);329 const v1 = await t.api("alice", "GET", "/api/v2/objects/note/ver-1/versions/1");330 expect(v1.status).toBe(200);331 expect(v1.body.object).toMatchObject({ kind: "note", id: "ver-1", rev: 1, deleted: false, data: { title: "Draft", body: "one" } });332 expect((await t.api("alice", "GET", "/api/v2/objects/note/ver-1/versions/2")).body.object.data.body).toBe("two");333 // the live revision is readable through the same route334 expect((await t.api("alice", "GET", "/api/v2/objects/note/ver-1/versions/3")).body.object.data.body).toBe("three");335 expect((await t.api("alice", "GET", "/api/v2/objects/note/ver-1/versions/4")).status).toBe(404);336 expect((await t.api("alice", "GET", "/api/v2/objects/note/ver-1/versions/x")).status).toBe(400);337 expect((await t.api("alice", "GET", "/api/v2/objects/note/missing/versions")).status).toBe(404);338 });339340 it("keeps no versions for a kind that is not versioned", async () => {341 await put("alice", "watchlist", "ver-wl", watchlist("a"), 0);342 await put("alice", "watchlist", "ver-wl", watchlist("b"), 1);343 expect((await t.api("alice", "GET", "/api/v2/objects/watchlist/ver-wl/versions")).body.versions).toEqual([]);344 });345346 it("keeps the last 30 revisions only", async () => {347 await put("alice", "project", "ver-many", { title: "v0", items: [] }, 0);348 for (let rev = 1; rev <= 34; rev++) expect((await put("alice", "project", "ver-many", { title: `v${rev}`, items: [] }, rev)).status).toBe(200);349 const versions = (await t.api("alice", "GET", "/api/v2/objects/project/ver-many/versions")).body.versions;350 expect(versions).toHaveLength(30);351 expect(versions[0].rev).toBe(34);352 expect(versions[29].rev).toBe(5);353 expect((await t.api("alice", "GET", "/api/v2/objects/project/ver-many/versions/4")).status).toBe(404);354 expect((await t.api("alice", "GET", "/api/v2/objects/project/ver-many/versions/5")).body.object.data.title).toBe("v4");355 });356357 it("drops the archived revisions when the object is deleted", async () => {358 const del = await t.api("alice", "DELETE", "/api/v2/objects/note/ver-1?baseRev=3");359 expect(del.status).toBe(200);360 expect((await t.api("alice", "GET", "/api/v2/objects/note/ver-1/versions")).status).toBe(404);361 const left = t.db.prepare("SELECT count(*) AS n FROM vq_object_versions WHERE owner = 'alice' AND kind = 'note' AND id = 'ver-1'").get() as { n: number };362 expect(left.n).toBe(0);363 });364});365366describe("isolation between people", () => {367 it("never lets another person read, list, version or see changes of someone's objects", async () => {368 await put("alice", "note", "private-1", { title: "Alice only", body: "secret plan" }, 0);369 await put("alice", "note", "private-1", { title: "Alice only", body: "secret plan v2" }, 1);370 expect((await t.api("bob", "GET", "/api/v2/objects/note/private-1")).status).toBe(404);371 expect((await t.api("bob", "GET", "/api/v2/objects/note")).body.objects).toEqual([]);372 expect((await t.api("bob", "GET", "/api/v2/objects/note/private-1/versions")).status).toBe(404);373 expect((await t.api("bob", "GET", "/api/v2/objects/note/private-1/versions/1")).status).toBe(404);374 const feed = await t.api("bob", "GET", "/api/v2/sync/changes?since=0");375 expect(JSON.stringify(feed.body)).not.toContain("secret plan");376 expect(feed.body.changes.every((c: any) => c.id !== "private-1")).toBe(true);377 });378379 it("never lets another person update or delete them, even with the right revision", async () => {380 const upd = await put("bob", "note", "private-1", { title: "Hijacked", body: "x" }, 2);381 expect(upd.status).toBe(404);382 expect((await t.api("bob", "DELETE", "/api/v2/objects/note/private-1?baseRev=2")).status).toBe(404);383 const mine = await t.api("alice", "GET", "/api/v2/objects/note/private-1");384 expect(mine.body.object).toMatchObject({ rev: 2, data: { body: "secret plan v2" } });385 });386387 it("gives each person their own object under the same id, and their own seq", async () => {388 const created = await put("bob", "note", "private-1", { title: "Bob's", body: "mine" }, 0);389 expect(created.status).toBe(200);390 expect(created.body.object.rev).toBe(1);391 expect((await t.api("alice", "GET", "/api/v2/objects/note/private-1")).body.object.data.title).toBe("Alice only");392 expect((await t.api("bob", "GET", "/api/v2/objects/note/private-1")).body.object.data.title).toBe("Bob's");393 const aliceSeq = (await t.api("alice", "GET", "/api/v2/sync/changes?since=999999")).body.seq;394 const bobSeq = (await t.api("bob", "GET", "/api/v2/sync/changes?since=999999")).body.seq;395 expect(bobSeq).toBe(created.body.object.seq);396 expect(aliceSeq).toBeGreaterThan(bobSeq);397 });398399 it("keeps the audit log per person", async () => {400 const bob = (await t.api("bob", "GET", "/api/v2/audit")).body.events;401 expect(bob.every((e: any) => e.target !== "watchlist/del-1")).toBe(true);402 });403});404405describe("internal API", () => {406 it("writeObject creates and updates on behalf of the server, with rev, seq and device", async () => {407 const created = objects.writeObject<{ status: string }>("alice", "review", "rv-srv", (cur) => {408 expect(cur).toBeNull();409 return { status: "running" };410 });411 expect(created).toMatchObject({ kind: "review", id: "rv-srv", rev: 1, device: "server", data: { status: "running" } });412 const updated = objects.writeObject<{ status: string }>("alice", "review", "rv-srv", (cur) => ({ ...cur!, status: "done" }));413 expect(updated).toMatchObject({ rev: 2, data: { status: "done" } });414 expect(updated!.seq).toBe(created!.seq + 1);415 // readable by the person through HTTP; a client still cannot write it416 expect((await t.api("alice", "GET", "/api/v2/objects/review/rv-srv")).body.object.data.status).toBe("done");417 expect((await t.api("bob", "GET", "/api/v2/objects/review/rv-srv")).status).toBe(404);418 });419420 it("writeObject leaves everything alone when the mutation returns null", () => {421 const before = objects.currentSeq("alice");422 const same = objects.writeObject("alice", "review", "rv-srv", () => null);423 expect(same).toMatchObject({ rev: 2 });424 expect(objects.writeObject("alice", "review", "rv-none", () => null)).toBeNull();425 expect(objects.currentSeq("alice")).toBe(before);426 });427428 it("writeObject validates like a client write and rolls back when the mutation throws", () => {429 const before = objects.currentSeq("alice");430 expect(() => objects.writeObject("alice", "watchlist", "srv-bad", () => ({ symbols: [] }) as any)).toThrow(/name/);431 expect(() =>432 objects.writeObject("alice", "watchlist", "srv-bad", () => {433 throw new Error("boom");434 }),435 ).toThrow("boom");436 expect(objects.getObject("alice", "watchlist", "srv-bad")).toBeNull();437 expect(objects.currentSeq("alice")).toBe(before);438 });439440 it("a server write makes a client's older revision stale", async () => {441 await put("alice", "watchlist", "srv-race", watchlist("client"), 0);442 objects.writeObject("alice", "watchlist", "srv-race", (cur) => ({ ...cur!, symbols: ["TSLA"] }));443 const r = await put("alice", "watchlist", "srv-race", watchlist("client again"), 1);444 expect(r.status).toBe(409);445 expect(r.body.current).toMatchObject({ rev: 2, device: "server", data: { symbols: ["TSLA"] } });446 });447448 it("putObject and deleteObject report refusals as ObjectError with a status", () => {449 expect(() => objects.putObject("alice", "watchlist", "api-1", { name: "x", symbols: [] }, 5, "web")).toThrow(objects.ObjectError);450 const o = objects.putObject("alice", "watchlist", "api-1", { name: "x", symbols: [] }, 0, "web");451 try {452 objects.putObject("alice", "watchlist", "api-1", { name: "y", symbols: [] }, 0, "web");453 expect.unreachable();454 } catch (e) {455 expect(e).toBeInstanceOf(objects.ObjectError);456 expect((e as InstanceType<typeof objects.ObjectError>).status).toBe(409);457 expect((e as InstanceType<typeof objects.ObjectError>).current?.rev).toBe(o.rev);458 }459 expect(objects.deleteObject("alice", "watchlist", "api-1", null, "server").deleted).toBe(true);460 expect(objects.getObject("alice", "watchlist", "api-1")).toBeNull();461 expect(objects.getObject("alice", "watchlist", "api-1", { includeDeleted: true })?.deleted).toBe(true);462 expect(objects.listObjects("alice", "watchlist").some((x) => x.id === "api-1")).toBe(false);463 });464});465466describe("sync stream", () => {467 it("says hello with the latest seq, as an event stream", async () => {468 const s = openStream(t.base, "carol");469 try {470 const hello = await s.waitFor((e) => e.event === "hello");471 expect(hello.data).toEqual({ type: "hello", seq: 6 });472 expect(s.status()).toBe(200);473 expect(String(s.headers()["content-type"])).toContain("text/event-stream");474 expect(s.headers()["content-encoding"]).toBeUndefined();475 } finally {476 s.close();477 }478 });479480 it("delivers a change to every stream of its owner and to nobody else", async () => {481 const a1 = openStream(t.base, "dave");482 const a2 = openStream(t.base, "dave");483 const other = openStream(t.base, "erin");484 try {485 await Promise.all([a1, a2, other].map((s) => s.waitFor((e) => e.event === "hello")));486 const created = (await put("dave", "watchlist", "live-1", watchlist(), 0, { "x-test-device": "dev-7" })).body.object;487 for (const s of [a1, a2]) {488 const change = await s.waitFor((e) => e.event === "change");489 expect(change.data).toEqual({ type: "change", kind: "watchlist", id: "live-1", rev: 1, seq: created.seq, deleted: false, device: "dev-7" });490 }491 const deleted = (await t.api("dave", "DELETE", "/api/v2/objects/watchlist/live-1?baseRev=1")).body.object;492 const tomb = await a1.waitFor((e) => e.event === "change" && e.data.deleted === true);493 expect(tomb.data).toMatchObject({ id: "live-1", rev: 2, seq: deleted.seq, deleted: true });494 // a refused write is not announced495 await put("dave", "watchlist", "live-1", watchlist(), 9);496 // Erin writes too, so her stream is known to be alive: it must hold her event and none of Dave's.497 await put("erin", "watchlist", "erin-1", watchlist(), 0);498 await other.waitFor((e) => e.event === "change" && e.data.id === "erin-1");499 expect(other.events.filter((e) => e.event === "change").map((e) => e.data.id)).toEqual(["erin-1"]);500 expect(a1.events.filter((e) => e.event === "change")).toHaveLength(2);501 expect(JSON.stringify(a1.events)).not.toContain("erin-1");502 } finally {503 a1.close();504 a2.close();505 other.close();506 }507 });508509 it("delivers server-authored writes and hints, per owner", async () => {510 const mine = openStream(t.base, "dave");511 const other = openStream(t.base, "erin");512 try {513 await Promise.all([mine, other].map((s) => s.waitFor((e) => e.event === "hello")));514 objects.writeObject("dave", "review", "rv-live", () => ({ status: "running" }));515 expect((await mine.waitFor((e) => e.event === "change" && e.data.kind === "review")).data.device).toBe("server");516 sync.publishHint("dave", "generations", "gen-1");517 sync.publishHint("dave", "sessions");518 expect((await mine.waitFor((e) => e.event === "hint" && e.data.topic === "generations")).data).toEqual({ type: "hint", topic: "generations", id: "gen-1" });519 expect((await mine.waitFor((e) => e.event === "hint" && e.data.topic === "sessions")).data).toEqual({ type: "hint", topic: "sessions" });520 sync.publishHint("erin", "quant_jobs", "job-1");521 await other.waitFor((e) => e.event === "hint");522 expect(other.events.filter((e) => e.event !== "hello").map((e) => e.data)).toEqual([{ type: "hint", topic: "quant_jobs", id: "job-1" }]);523 expect(mine.events.some((e) => e.event === "hint" && e.data.topic === "quant_jobs")).toBe(false);524 } finally {525 mine.close();526 other.close();527 }528 });529530 it("forgets a stream when its client disconnects", async () => {531 await sleep(100);532 const before = sync.streamCount("frank");533 const s = openStream(t.base, "frank");534 await s.waitFor((e) => e.event === "hello");535 expect(sync.streamCount("frank")).toBe(before + 1);536 s.close();537 for (let i = 0; i < 40 && sync.streamCount("frank") !== before; i++) await sleep(25);538 expect(sync.streamCount("frank")).toBe(before);539 // publishing to nobody is harmless540 expect(() => sync.publishHint("frank", "sessions")).not.toThrow();541 });542543 it("refuses the stream to a request that is not signed in", async () => {544 const res = await fetch(`${t.base}/api/v2/sync/stream`);545 expect(res.status).toBe(401);546 });547});548549describe("rate limit of writes", () => {550 it("limits one person's writes without touching reads or other people", async () => {551 objects.configureWriteLimit(3, 0);552 try {553 const statuses: number[] = [];554 for (let i = 0; i < 5; i++) statuses.push((await put("frank", "watchlist", `rl-${i}`, watchlist(), 0)).status);555 expect(statuses).toEqual([200, 200, 200, 429, 429]);556 const limited = await put("frank", "watchlist", "rl-x", watchlist(), 0);557 expect(limited.body.error).toMatch(/too many/i);558 expect(limited.headers.get("retry-after")).toBe("5");559 // deletes and the other /api/v2 writes share the limit560 expect((await t.api("frank", "DELETE", "/api/v2/objects/watchlist/rl-0?baseRev=1")).status).toBe(429);561 expect((await t.api("frank", "PUT", "/api/v2/memory/settings", { enabled: true })).status).toBe(429);562 expect((await t.api("frank", "GET", "/api/v2/objects/watchlist")).status).toBe(200);563 expect((await t.api("frank", "GET", "/api/v2/sync/changes")).status).toBe(200);564 expect((await put("erin", "watchlist", "rl-other", watchlist(), 0)).status).toBe(200);565 expect((await t.api("frank", "GET", "/api/v2/objects/watchlist")).body.objects.map((o: any) => o.id).sort()).toEqual(["rl-0", "rl-1", "rl-2"]);566 } finally {567 objects.configureWriteLimit(240, 4);568 }569 expect((await put("frank", "watchlist", "rl-after", watchlist(), 0)).status).toBe(200);570 });571});572