import { Inject, Injectable, OnApplicationBootstrap, OnModuleDestroy } from '@nestjs/common'; import { LoroDoc } from 'loro-crdt'; import { CRDT_REPOSITORY, DOC_LOCK, type CrdtRepository, type DocLockPort } from '../domain/ports'; const COMPACT_AFTER_UPDATES = 128; const RUN_EVERY_MS = 6 * 60 * 60 * 1000; // Folds a (user, doc) pair's update log into one snapshot row once enough // updates pile up, then drops the covered rows. This is the only place the // server ever opens a Loro doc; everywhere else the payloads are opaque. @Injectable() export class CompactionService implements OnApplicationBootstrap, OnModuleDestroy { private timer: ReturnType | null = null; constructor( @Inject(CRDT_REPOSITORY) private readonly crdt: CrdtRepository, @Inject(DOC_LOCK) private readonly lock: DocLockPort, ) {} onApplicationBootstrap(): void { void this.run(); this.timer = setInterval(() => void this.run(), RUN_EVERY_MS); this.timer.unref?.(); } onModuleDestroy(): void { if (this.timer) clearInterval(this.timer); } async run(): Promise { let compacted = 0; for (const { user_id, doc_id, count } of await this.crdt.updateCounts()) { if (count < COMPACT_AFTER_UPDATES) continue; try { await this.compact(user_id, doc_id); compacted += 1; } catch (e) { console.error(`compaction failed for ${doc_id}:`, e); } } return compacted; } private async compact(userId: string | null, docId: string): Promise { // Hold a doc-scoped lock so two API replicas against one Postgres never // fold the same doc at once; on sqlite the single writer already does. await this.lock.withDocLock(userId, docId, async () => { const snap = await this.crdt.getSnapshot(userId, docId); const rows = await this.crdt.listForCompaction(userId, docId); if (!rows.length) return; const doc = new LoroDoc(); if (snap) doc.import(Buffer.from(snap.payload, 'base64')); for (const row of rows) doc.import(Buffer.from(row.payload, 'base64')); const uptoSeq = Math.max(rows[rows.length - 1].seq, snap?.upto_seq ?? 0); const payload = Buffer.from(doc.export({ mode: 'snapshot' })).toString('base64'); await this.crdt.replaceSnapshot(userId, docId, payload, uptoSeq); }); } }