SPB Git

Repository Public

service.ts 7.1 KB 106 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : src/lib/canvas/service.ts9 * Description      : canvas storage (SPEC §3.4). A canvas is a page of type10 *                    `canvas` plus one row in `canvases`; it is saved with the11 *                    same optimistic model as a page (`baseVersion` →12 *                    compare-and-set in one statement → 409 with the server13 *                    copy). Clients merge by node / edge id when both sides14 *                    changed different ids. The change feed (`rev`, tombstone)15 *                    comes from the triggers of 0003.16 * Module           : lib17 * Repository       : https://git.spboucher.ai/note-spboucher-ai18 * Project Website  : https://note.spboucher.ai19 * Created          : 2026-11-1920 * Last Modified    : 2026-11-1921 *22 * Author           : Simon-Pierre Boucher23 * Position         : Professor of Finance24 * Institution      : Université du Québec en Outaouais (UQO)25 * Organization     : SP Boucher26 * Website          : https://spboucher.ai27 * Git              : https://git.spboucher.ai28 *29 * Preferred Contact: contact@spboucher.ai30 * Development      : dev@spboucher.ai31 * Support          : support@spboucher.ai32 * Security/Admin   : admin@spboucher.ai33 *34 * Copyright (c) 202635 * Simon-Pierre Boucher36 * All rights reserved where applicable. This file is governed by the37 * applicable project license, copyright notices and relevant law.38 * Existing third-party rights and notices remain unaffected.39 *40 * License          : None specified (no license file in this repository)41 *42 * Do not embed credentials, private keys, access tokens,43 * certificates or confidential personal information.44 *45 * =============================================================================46 * END OF SP BOUCHER SOURCE HEADER47 * =============================================================================48 */4950import { and, eq, inArray, sql as dsql } from "drizzle-orm";51import { db, schema } from "@/db";52import { HttpError } from "@/lib/errors";53import { sameJson } from "@/lib/same-json";54import { recordCoalesced } from "@/lib/events/service";55import { canvasProblem, canvasRefs, EMPTY_CANVAS, type CanvasData } from "./format";56import { canvasText } from "./export";57import { wordCount } from "@/lib/editor/text";58import { enqueue, QUEUES } from "@/lib/jobs";5960const C = schema.canvases; const P = schema.pages;61export interface CanvasOut { pageId: string; title: string; data: CanvasData; version: number; rev: number; updatedAt: Date }62async function canvasPage(wsId: string, pageId: string, opts: { includeDeleted?: boolean } = {}) {63  const [p] = await db.select({ id: P.id, title: P.title, type: P.type, deletedAt: P.deletedAt }).from(P).where(and(eq(P.id, pageId), eq(P.workspaceId, wsId)));64  if (!p || (p.deletedAt && !opts.includeDeleted)) throw new HttpError(404, "Canvas not found", "not_found");65  if (p.type !== "canvas") throw new HttpError(404, "This page is not a canvas", "not_canvas");66  return p;67}68/** The canvas of a page of type `canvas` (readable in the trash too). A page that has no row yet (type changed by hand, restored backup) gets an empty one. */69export async function getCanvas(wsId: string, pageId: string): Promise<CanvasOut> {70  const p = await canvasPage(wsId, pageId, { includeDeleted: true });71  let [c] = await db.select().from(C).where(eq(C.pageId, pageId));72  if (!c) { await db.insert(C).values({ pageId, workspaceId: wsId, data: EMPTY_CANVAS() }).onConflictDoNothing(); [c] = await db.select().from(C).where(eq(C.pageId, pageId)); }73  return { pageId, title: p.title, data: c.data as CanvasData, version: c.version, rev: c.rev, updatedAt: c.updatedAt };74}75export const canvasConflict = (c: CanvasOut) => ({ server: { version: c.version, data: c.data, updatedAt: c.updatedAt } });76/**77 * Save. The write happens only if the row is still at `baseVersion` (one statement); otherwise 409 `conflict` with the server copy and78 * nothing is written. Saving exactly what is stored is a no-op (same version, no event). Journal: `canvas.edited`, coalesced like79 * `page.edited` (at most one per canvas per 10 minutes).80 */81export async function putCanvas(wsId: string, pageId: string, data: unknown, baseVersion: number): Promise<{ version: number; rev: number; updatedAt: Date; unchanged: boolean }> {82  const problem = canvasProblem(data); if (problem) throw new HttpError(/too large|at most \d+ (nodes|edges)/.test(problem) ? 413 : 400, `Invalid canvas: ${problem}`, "bad_canvas");83  const p = await canvasPage(wsId, pageId); const cur = await getCanvas(wsId, pageId);84  if (cur.version !== baseVersion) throw new HttpError(409, "This canvas was changed in another session", "conflict", canvasConflict(cur));85  if (sameJson(cur.data, data)) return { version: cur.version, rev: cur.rev, updatedAt: cur.updatedAt, unchanged: true };86  const d = data as CanvasData; const refs = canvasRefs(d);87  const saved = await db.transaction(async (tx) => {88    const [row] = await tx.update(C).set({ data: d, version: dsql`${C.version} + 1`, updatedAt: new Date() }).where(and(eq(C.pageId, pageId), eq(C.version, baseVersion))).returning({ version: C.version, rev: C.rev, updatedAt: C.updatedAt });89    if (!row) return null;90    // page cards make the canvas a backlink of those pages (links kind `canvas`; the document links of the page are untouched)91    await tx.delete(schema.links).where(and(eq(schema.links.fromPageId, pageId), eq(schema.links.kind, "canvas")));92    const targets = refs.pages.filter((id) => id !== pageId);93    if (targets.length) { const valid = await tx.select({ id: P.id }).from(P).where(and(eq(P.workspaceId, wsId), inArray(P.id, targets))); if (valid.length) await tx.insert(schema.links).values(valid.map((v) => ({ fromPageId: pageId, toPageId: v.id, kind: "canvas" }))).onConflictDoNothing(); }94    // the canvas page shows up in "recent" and moves in the page feed; the text of its cards (text, LaTeX, addresses, edge labels) becomes95    // the page's plain text, so full-text search (`tsv`) finds a canvas by what is written on it96    const plain = canvasText(d);97    await tx.update(P).set({ updatedAt: new Date(), plainText: plain, wordCount: wordCount(plain) }).where(eq(P.id, pageId));98    return row;99  });100  if (!saved) throw new HttpError(409, "This canvas was changed in another session", "conflict", canvasConflict(await getCanvas(wsId, pageId)));101  // semantic index of the page (same queue and throttle as a page save); never fails the save102  await enqueue(QUEUES.index, { sourceType: "page", sourceId: pageId, workspaceId: wsId }, { singletonKey: `page:${pageId}`, singletonSeconds: 20, singletonNextSlot: true }).catch(() => {});103  await recordCoalesced({ workspaceId: wsId, kind: "canvas.edited", pageId, entityKind: "canvas", entityId: pageId, summary: p.title, data: { version: saved.version, nodes: d.nodes.length, edges: d.edges.length } });104  return { ...saved, unchanged: false };105}106
Files main
Menu

Theme