SPB Git

Repository Public

sync.ts 5.4 KB 89 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Chat SPBoucher AI8 * File             : src/lib/sync.ts9 * Module           : lib10 * Repository       : https://git.spboucher.ai/chat-spboucher-ai11 * Project Website  : https://chat.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 */4243import "server-only";44import { sql } from "./db";4546/**47 * Change feed shared by the three clients (web, macOS, iOS). Every mutation appends one row to `sync_events`48 * (monotonic `seq`) and wakes the open `/api/events` streams. A client that was offline resumes with `?after=<seq>`49 * and replays what it missed; the event only says WHAT changed — the client then re-reads that entity, so the server50 * row is always the single truth (last write wins on the server clock; drafts carry their own `updatedAt`).51 *52 * In-process fan-out: correct for the single `next start` instance this app runs as.53 */54export type SyncEntity = "conversation" | "message" | "project" | "prompt" | "preset" | "model" | "settings" | "memory" | "draft" | "provider" | "attachment" | "artifact";55export interface SyncEvent { seq: number; at: string; entity: SyncEntity; id: string | null; op: "upsert" | "delete"; origin: string | null }5657declare global { var __csa_sync: { listeners: Set<(e: SyncEvent) => void>; lastPrune: number } | undefined }58const hub = (globalThis.__csa_sync ??= { listeners: new Set(), lastPrune: 0 });5960export async function publish(entity: SyncEntity, id: string | null, op: "upsert" | "delete" = "upsert", origin: string | null = null): Promise<void> {61  try {62    const r = await sql<{ seq: string; at: Date }[]>`INSERT INTO sync_events (entity, entity_id, op, origin) VALUES (${entity}, ${id}, ${op}, ${origin}) RETURNING seq, at`;63    const ev: SyncEvent = { seq: Number(r[0].seq), at: r[0].at.toISOString(), entity, id, op, origin };64    for (const l of hub.listeners) { try { l(ev); } catch { /* a broken subscriber never blocks a mutation */ } }65    if (Date.now() - hub.lastPrune > 6 * 3600_000) { hub.lastPrune = Date.now(); void sql`DELETE FROM sync_events WHERE at < now() - interval '14 days'`.catch(() => {}); }66  } catch { /* the feed is best effort: a mutation never fails because of it */ }67}6869export function onSync(l: (e: SyncEvent) => void): () => void { hub.listeners.add(l); return () => { hub.listeners.delete(l); }; }7071export async function eventsAfter(after: number, limit = 500): Promise<{ events: SyncEvent[]; head: number; truncated: boolean }> {72  const rows = await sql<{ seq: string; at: Date; entity: SyncEntity; entity_id: string | null; op: "upsert" | "delete"; origin: string | null }[]>`SELECT * FROM sync_events WHERE seq > ${after} ORDER BY seq ASC LIMIT ${limit + 1}`;73  const head = Number((await sql<{ m: string | null }[]>`SELECT max(seq) AS m FROM sync_events`)[0].m ?? 0);74  const oldest = Number((await sql<{ m: string | null }[]>`SELECT min(seq) AS m FROM sync_events`)[0].m ?? 0);75  // `truncated`: the client is further behind than the feed keeps (or than one page) → it must reload everything76  const truncated = rows.length > limit || (after > 0 && oldest > after + 1) ;77  return { events: rows.slice(0, limit).map(r => ({ seq: Number(r.seq), at: r.at.toISOString(), entity: r.entity, id: r.entity_id, op: r.op, origin: r.origin })), head, truncated };78}7980/** Entity touched by a successful mutation on an API path (used by the route guard). */81export function entityForPath(pathname: string, method: string): { entity: SyncEntity; id: string | null; op: "upsert" | "delete" } | null {82  const seg = pathname.split("/").filter(Boolean); // api, <collection>, <id?>, …83  if (seg[0] !== "api") return null;84  const map: Record<string, SyncEntity> = { conversations: "conversation", projects: "project", prompts: "prompt", presets: "preset", models: "model", settings: "settings", memories: "memory", drafts: "draft", providers: "provider", attachments: "attachment", artifacts: "artifact" };85  const entity = map[seg[1]]; if (!entity) return null;86  const id = seg[2] && !["refresh", "export", "route", "detail"].includes(seg[2]) ? seg[2] : null;87  return { entity, id, op: method === "DELETE" && seg.length <= 3 ? "delete" : "upsert" };88}89
Files main
Menu

Theme