SPB Git

Repository Public

sync-client.ts 15.6 KB 227 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : src/lib/canvas/sync-client.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/note-spboucher-ai11 * Project Website  : https://note.spboucher.ai12 * Created          : 2026-11-1913 * Last Modified    : 2026-11-1914 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243"use client";44/**45 * file: src/lib/canvas/sync-client.ts46 * description: autosave engine of one canvas (browser side of `PUT /api/canvases/<pageId>`, docs/next/API-NEXT.md §4.8).47 *   - a change is sent 900 ms after the last one, one request at a time, never in the middle of a gesture (`hold`);48 *   - every save carries the version it was based on; on 409 the server copy is merged with the local document against the49 *     remembered base (three-way merge by node / edge id, src/lib/canvas/merge.ts), the result is shown and sent again;50 *   - what the merge could not settle is listed in `conflicts` (non-blocking: the canvas stays editable; nothing was lost);51 *   - the unsaved document AND its base are mirrored to IndexedDB (the app's draft store, key `canvas:<pageId>`), so a closed tab,52 *     a dead battery or a lost network cannot lose work — it is replayed (or merged) on the next visit;53 *   - the viewport is view state: a change of the viewport alone is never sent (it would create a version for nothing — the API has no54 *     version-free write); it travels with the next real change, and each device remembers its own in localStorage.55 * author: Simon-Pierre Boucher — contact@spboucher.ai56 */57import { api, ApiError } from "@/lib/client/api";58import { deleteDraft, getDraft, putDraft } from "@/lib/client/offline";59import { danglingEdges, jsonEqual, mergeCanvas, readCanvas, removeEdges, type CanvasConflict, type CanvasData } from "./model";6061export type CanvasSyncStatus = "saved" | "saving" | "offline" | "error";62export interface CanvasServerCopy { data: CanvasData; version: number; updatedAt: string }63export interface CanvasSyncState { status: CanvasSyncStatus; error: string | null; savedAt: string; conflicts: CanvasConflict[]; version: number; pending: boolean }64export interface CanvasSyncHooks {65  /** the document on screen */ current: () => CanvasData;66  /** show a document that did not come from the user (merge result, newer server copy, recovered draft) */67  applyRemote: (doc: CanvasData, why: "merge" | "remote" | "draft") => void;68  onDraftRestored?: () => void; onRemoteUpdate?: () => void; onConflicts?: (added: CanvasConflict[]) => void;69}70const DEBOUNCE = 900, DRAFT_DEBOUNCE = 350, MAX_REBASES = 6;71const draftKey = (pageId: string) => `canvas:${pageId}`;72const vpKey = (pageId: string) => `note-canvas-vp-${pageId}`;73/** Everything but the viewport: what makes a canvas "changed". */74const content = (d: CanvasData) => { const { viewport: _v, ...rest } = d; return rest; };75export const sameContent = (a: CanvasData, b: CanvasData) => a === b || jsonEqual(content(a), content(b));76const conflictKey = (c: CanvasConflict) => `${c.kind}:${c.id}`;7778export function readLocalViewport(pageId: string): CanvasData["viewport"] | null {79  try { const v = JSON.parse(localStorage.getItem(vpKey(pageId)) ?? "null"); return v && Number.isFinite(v.x) && Number.isFinite(v.y) && v.zoom > 0 ? { x: v.x, y: v.y, zoom: v.zoom } : null; } catch { return null; }80}81export function writeLocalViewport(pageId: string, v: { x: number; y: number; zoom: number }) { try { localStorage.setItem(vpKey(pageId), JSON.stringify({ x: v.x, y: v.y, zoom: v.zoom })); } catch { /* storage full or disabled: the viewport is a comfort */ } }8283export class CanvasSync {84  private base: CanvasData; private version: number;85  private state: CanvasSyncState; private listeners = new Set<() => void>();86  private dirty = false; private inflight = false; private held = false; private blocked = false; private disposed = false;87  private timer: ReturnType<typeof setTimeout> | null = null; private draftTimer: ReturnType<typeof setTimeout> | null = null; private backoff = 0;88  private stash: CanvasServerCopy | null = null;89  private cleanup: (() => void)[] = [];9091  constructor(private pageId: string, initial: CanvasServerCopy, private hooks: CanvasSyncHooks, private readOnly = false) {92    this.base = readCanvas(initial.data); this.version = initial.version;93    this.state = { status: "saved", error: null, savedAt: initial.updatedAt, conflicts: [], version: initial.version, pending: false };94  }95  get = () => this.state;96  subscribe = (l: () => void) => { this.listeners.add(l); return () => { this.listeners.delete(l); }; };97  private set(p: Partial<CanvasSyncState>) { if (this.disposed) return; this.state = { ...this.state, ...p, version: this.version, pending: this.dirty || this.inflight }; for (const l of this.listeners) l(); }9899  /** Replays the draft of a previous visit and starts listening to the network and to the tab's visibility. Call once, from an effect. */100  start() {101    this.disposed = false;102    void this.restoreDraft();103    const online = () => { this.backoff = 0; if (this.dirty) void this.flush(); else if (this.state.status === "offline") this.set({ status: "saved", error: null }); };104    const offline = () => { if (this.dirty || this.inflight) this.set({ status: "offline" }); };105    const leave = () => { if (this.dirty) { this.writeDraft(); this.beacon(); } };106    const vis = () => { if (document.visibilityState === "hidden") leave(); else void this.check(); };107    const focus = () => void this.check();108    window.addEventListener("online", online); window.addEventListener("offline", offline); window.addEventListener("pagehide", leave); document.addEventListener("visibilitychange", vis); window.addEventListener("focus", focus);109    this.cleanup.push(() => { window.removeEventListener("online", online); window.removeEventListener("offline", offline); window.removeEventListener("pagehide", leave); document.removeEventListener("visibilitychange", vis); window.removeEventListener("focus", focus); });110  }111  /** Stops the timers and listeners; a pending change is sent one last time (the draft stays on the device until it is confirmed). */112  dispose() {113    if (this.timer) clearTimeout(this.timer); if (this.draftTimer) clearTimeout(this.draftTimer);114    if (this.dirty) { this.writeDraft(); this.held = false; void this.flush(); }115    for (const c of this.cleanup) c(); this.cleanup = []; this.disposed = true;116  }117118  /** The document changed (a user edit). Cheap to call on every change. */119  notify() {120    if (this.readOnly) return;121    const doc = this.hooks.current();122    if (sameContent(doc, this.base)) { // back to what the server holds (undo): nothing to send123      this.dirty = false; this.blocked = false; if (this.timer) { clearTimeout(this.timer); this.timer = null; }124      if (!this.inflight) { void deleteDraft(draftKey(this.pageId)); this.set({ status: "saved", error: null }); }125      return;126    }127    this.dirty = true; this.blocked = false;128    if (!this.draftTimer) this.draftTimer = setTimeout(() => { this.draftTimer = null; this.writeDraft(); }, DRAFT_DEBOUNCE);129    this.set({ status: this.state.status === "offline" ? "offline" : "saving" });130    this.schedule(DEBOUNCE);131  }132  /** `true` while a gesture is in progress (drag, resize, ink stroke, layout animation): nothing is sent and no remote copy is applied until `hold(false)`. */133  hold(on: boolean) {134    if (on === this.held) return; this.held = on; if (on) return;135    if (this.stash) { const s = this.stash; this.stash = null; this.rebase(s); }136    if (this.dirty) this.schedule(DEBOUNCE);137  }138  retry = () => { this.blocked = false; this.backoff = 0; if (this.dirty) void this.flush(); else this.set({ status: "saved", error: null }); };139  /** Removes a conflict from the review list (after "keep mine" / "keep theirs"). */140  dismiss(c: CanvasConflict) { this.set({ conflicts: this.state.conflicts.filter((x) => conflictKey(x) !== conflictKey(c)) }); }141  dismissAll() { this.set({ conflicts: [] }); }142143  private schedule(ms: number) { if (this.timer) clearTimeout(this.timer); this.timer = setTimeout(() => { this.timer = null; void this.flush(); }, ms); }144  private writeDraft() {145    if (!this.dirty || this.disposed) return;146    void putDraft({ pageId: draftKey(this.pageId), baseVersion: this.version, patch: { data: this.hooks.current(), base: this.base }, updatedAt: Date.now() });147  }148  /** What is sent: the document on screen, minus edges that lost an end (the server would refuse the whole save). */149  private outgoing(): CanvasData { const d = this.hooks.current(); const bad = danglingEdges(d); return bad.length ? removeEdges(d, bad.map((e) => e.id)) : d; }150151  async flush(): Promise<void> {152    if (this.timer) { clearTimeout(this.timer); this.timer = null; }153    if (!this.dirty || this.inflight || this.held || this.blocked || this.readOnly) return;154    for (let attempt = 0; attempt < MAX_REBASES; attempt++) {155      const sent = this.outgoing(); this.inflight = true; this.set({ status: this.state.status === "offline" ? "offline" : "saving" });156      try {157        const r = await api<{ version: number; updatedAt: string }>(`/api/canvases/${this.pageId}`, { method: "PUT", json: { data: sent, baseVersion: this.version }, timeoutMs: 25_000 });158        this.inflight = false; this.base = sent; this.version = r.version; this.backoff = 0;159        if (sameContent(this.hooks.current(), sent)) { this.dirty = false; if (this.draftTimer) { clearTimeout(this.draftTimer); this.draftTimer = null; } await deleteDraft(draftKey(this.pageId)); this.set({ status: "saved", error: null, savedAt: r.updatedAt }); }160        else { this.set({ savedAt: r.updatedAt }); this.writeDraft(); this.schedule(400); } // edited while the request was in flight161        return;162      } catch (e) {163        this.inflight = false; const err = e as ApiError;164        if (err.status === 409 && err.code === "conflict" && err.body?.server) {165          const server = err.body.server as CanvasServerCopy;166          if (this.held) { this.stash = server; this.set({}); return; } // mid-gesture: merge when the gesture ends167          this.rebase(server); if (!this.dirty) return; continue; // merged: send the result on top of the server's version168        }169        if (err.status === 401) { this.set({ status: "error", error: "Sign-in required — your changes are kept on this device." }); return; }170        if (err.status === 0 || err.status >= 500) {171          this.set({ status: err.status === 0 || (typeof navigator !== "undefined" && !navigator.onLine) ? "offline" : "error", error: err.message });172          this.backoff = Math.min(30_000, this.backoff ? this.backoff * 2 : 3000); this.schedule(this.backoff); return;173        }174        this.blocked = true; this.set({ status: "error", error: err.message }); return; // 4xx: sending the same document again cannot succeed175      }176    }177    this.schedule(2000); // the canvas kept moving under us: breathe, then try again178  }179180  /**181   * The server holds a newer copy. Three-way merge of (remembered base, document on screen, server copy); the result replaces the182   * document on screen, the server copy becomes the new base, and what could not be settled joins the review list.183   */184  private rebase(server: CanvasServerCopy) {185    const local = this.hooks.current(); const remote = readCanvas(server.data);186    const m = mergeCanvas(this.base, local, remote);187    this.base = remote; this.version = server.version;188    if (m.merged !== local) this.hooks.applyRemote(m.merged, "merge");189    this.dirty = !sameContent(m.merged, remote);190    if (m.conflicts.length) { const fresh = new Map(this.state.conflicts.map((c) => [conflictKey(c), c])); for (const c of m.conflicts) fresh.set(conflictKey(c), c); this.set({ conflicts: [...fresh.values()] }); this.hooks.onConflicts?.(m.conflicts); }191    if (!this.dirty) { void deleteDraft(draftKey(this.pageId)); this.set({ status: "saved", error: null, savedAt: server.updatedAt }); } else this.writeDraft();192  }193194  /** Another session may have written while this tab was in the background. */195  async check(): Promise<void> {196    if (this.disposed || document.visibilityState !== "visible" || this.inflight || this.held) return;197    try {198      const s = await api<CanvasServerCopy>(`/api/canvases/${this.pageId}`, { timeoutMs: 10_000 });199      if (this.disposed || s.version === this.version || this.inflight) return;200      if (this.held) { this.stash = s; return; }201      if (!this.dirty) { this.base = readCanvas(s.data); this.version = s.version; if (!sameContent(this.hooks.current(), this.base)) { this.hooks.applyRemote({ ...this.base, viewport: this.hooks.current().viewport }, "remote"); this.hooks.onRemoteUpdate?.(); } this.set({ savedAt: s.updatedAt }); }202      else { this.rebase(s); if (this.dirty) void this.flush(); }203    } catch { /* offline or signed out: handled by the save path */ }204  }205206  private async restoreDraft() {207    if (this.readOnly) return;208    const d = await getDraft(draftKey(this.pageId)); if (!d || this.disposed) return;209    const p = d.patch as { data?: unknown; base?: unknown }; if (!p?.data) { await deleteDraft(draftKey(this.pageId)); return; }210    const mine = readCanvas(p.data);211    if (sameContent(mine, this.base)) { await deleteDraft(draftKey(this.pageId)); return; }212    if (d.baseVersion === this.version) { this.hooks.applyRemote(mine, "draft"); this.dirty = true; }213    else { // the canvas moved on while the draft waited: merge the draft with the newer copy against the base it was made from214      const base = readCanvas(p.base ?? this.base); const m = mergeCanvas(base, mine, this.base);215      this.hooks.applyRemote(m.merged, "draft"); this.dirty = !sameContent(m.merged, this.base);216      if (m.conflicts.length) { this.set({ conflicts: m.conflicts }); this.hooks.onConflicts?.(m.conflicts); }217    }218    this.hooks.onDraftRestored?.();219    if (this.dirty) { this.set({ status: "saving" }); void this.flush(); } else await deleteDraft(draftKey(this.pageId));220  }221  /** Last chance when the tab goes away: a keepalive request with the same version check (bodies above ~60 KB are refused by browsers; the draft covers those). */222  private beacon() {223    if (this.inflight || this.blocked || this.readOnly || typeof navigator === "undefined" || !navigator.onLine) return;224    try { const body = JSON.stringify({ data: this.outgoing(), baseVersion: this.version }); if (body.length > 60_000) return; fetch(`/api/canvases/${this.pageId}`, { method: "PUT", body, keepalive: true, headers: { "content-type": "application/json" }, credentials: "same-origin" }).catch(() => {}); } catch { /* the draft is on the device */ }225  }226}227
Files main
Menu

Theme