/** * Hocuspocus database extension persisting Y.js docs to Postgres * (`CollabDoc` table). * * `fetch({ documentName })` → Loads BLOB from Postgres on connect; returns * `null` when no row exists (Hocuspocus then * initialises a fresh in-memory Y.Doc). * `store({ documentName, state })` → Upserts the BLOB, bumps `version`, * refreshes `lastUpdatedAt`. Debounced by * Hocuspocus per the server-level * `debounce` / `maxDebounce` settings. * * The DocumentName is parsed via `parseDocumentName()` (see auth.ts) and is * authoritative for the `(tenantId, resourceType, resourceId)` triple. Auth * has already verified that the connection has access to this triple; here * we just persist the bytes. * * Refs: docs/improvement-plan/05-business-features/realtime-collab.md */ import { Database } from "@hocuspocus/extension-database"; import type { Extension } from "@hocuspocus/server"; import type { DbClient } from "@hivegrid/db/client.server"; import { parseDocumentName } from "./auth.js"; export type DatabaseExtensionDeps = { /** Prisma client (write-able). */ readonly db: Pick; /** Maximum bytes we will store per doc — protects from runaway state-bloat. */ readonly maxPayloadBytes: number; /** * Optional clock hook for deterministic tests. Defaults to `() => new Date()`. */ readonly clock?: () => Date; }; /** * Internal `fetch` implementation — exported for unit-testing. */ export async function fetchCollabDoc(documentName: string, deps: DatabaseExtensionDeps): Promise { const parsed = parseDocumentName(documentName); if (!parsed) return null; const row = await deps.db.collabDoc.findUnique({ where: { tenantId_resourceType_resourceId: { tenantId: parsed.tenantId, resourceType: parsed.resourceType, resourceId: parsed.resourceId, }, }, select: { ydocState: true }, }); if (!row) return null; // Prisma returns `Buffer` for Bytes columns — wrap to Uint8Array for Y.js. return new Uint8Array(row.ydocState); } /** * Internal `store` implementation — exported for unit-testing. */ export async function storeCollabDoc(documentName: string, state: Uint8Array, deps: DatabaseExtensionDeps): Promise { const parsed = parseDocumentName(documentName); if (!parsed) return; if (state.byteLength > deps.maxPayloadBytes) { throw new Error( `hocuspocus: refusing to persist Y.js state of ${state.byteLength} bytes — exceeds HOCUSPOCUS_MAX_PAYLOAD_BYTES=${deps.maxPayloadBytes}`, ); } const now = (deps.clock ?? (() => new Date()))(); const buffer = Buffer.from(state); await deps.db.collabDoc.upsert({ where: { tenantId_resourceType_resourceId: { tenantId: parsed.tenantId, resourceType: parsed.resourceType, resourceId: parsed.resourceId, }, }, create: { tenantId: parsed.tenantId, resourceType: parsed.resourceType, resourceId: parsed.resourceId, ydocState: buffer, version: 1, lastUpdatedAt: now, }, update: { ydocState: buffer, version: { increment: 1 }, lastUpdatedAt: now, }, }); } /** * Build the Hocuspocus database extension wired to the Prisma client. */ export function createDatabaseExtension(deps: DatabaseExtensionDeps): Extension { return new Database({ fetch: async ({ documentName }) => fetchCollabDoc(documentName, deps), store: async ({ documentName, state }) => storeCollabDoc(documentName, state, deps), }) as unknown as Extension; }