Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { 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 base64const MAX_BATCH = 500;
@Injectable()export class SyncService { constructor(@Inject(CRDT_REPOSITORY) private readonly crdt: CrdtRepository) {}
manifest(ownerId: string | null): Promise<CrdtManifestEntry[]> { 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');}