import { BadRequestException, Inject, Injectable } from '@nestjs/common'; import { CRDT_REPOSITORY, type CrdtManifestEntry, type CrdtRepository, type CrdtUpdateRow, } from '../domain/ports'; // Doc ids the sync log accepts: the workspace, the attempt log, and one // annotations doc per document uuid. const DOC_ID = /^(workspace|attempts|ann:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/; const MAX_PAYLOAD_CHARS = 4 * 1024 * 1024; // ~3 MB of update bytes as base64 const MAX_BATCH = 500; @Injectable() export class SyncService { constructor(@Inject(CRDT_REPOSITORY) private readonly crdt: CrdtRepository) {} manifest(ownerId: string | null): Promise { return this.crdt.manifest(ownerId); } async updatesSince( ownerId: string | null, docId: string, afterSeq: number, ): Promise<{ updates: CrdtUpdateRow[]; latest_seq: number }> { assertDocId(docId); const updates = await this.crdt.listSince(ownerId, docId, afterSeq); // A compacted snapshot stands in for the update rows it folded. Loro // imports snapshot bytes like any update, so the cursor just jumps. const snap = await this.crdt.getSnapshot(ownerId, docId); if (snap && afterSeq < snap.upto_seq) { updates.unshift({ seq: snap.upto_seq, payload: snap.payload }); } const latest = updates.length ? updates[updates.length - 1].seq : await this.crdt.latestSeq(ownerId, docId); return { updates, latest_seq: latest }; } async push( ownerId: string | null, docId: string, payloads: string[], deviceId: string | null, ): Promise<{ latest_seq: number }> { assertDocId(docId); if (payloads.length > MAX_BATCH) throw new BadRequestException('Too many updates in one push'); for (const p of payloads) { if (typeof p !== 'string' || !p.length) throw new BadRequestException('Empty update payload'); if (p.length > MAX_PAYLOAD_CHARS) throw new BadRequestException('Update payload too large'); } return { latest_seq: await this.crdt.append(ownerId, docId, payloads, deviceId) }; } } function assertDocId(docId: string): void { if (!DOC_ID.test(docId)) throw new BadRequestException('Unknown doc id'); }