ProjectOS / packages /knowledge-fabric /src /ArchiveService.ts
AnthropicallyHuggingFaces's picture
Sync full ProjectOS monorepo from GitHub 7f633f5
a8f4b72 verified
Raw History Blame Contribute Delete
2.43 kB
import { createHash, randomUUID } from 'node:crypto';
import type { DatabaseSync } from 'node:sqlite';
export type ArchiveInput = {
projectId?: string | null;
resourceType: string;
resourceId: string;
snapshotId?: string | null;
payload: Record<string, unknown>;
reason?: string;
archivedBy?: string;
retentionUntil?: string | null;
};
export class ArchiveService {
constructor(private readonly db: DatabaseSync) {}
archive(input: ArchiveInput) {
const payloadJson = JSON.stringify(input.payload);
const checksum = createHash('sha256').update(payloadJson).digest('hex');
const archiveId = randomUUID();
this.db.prepare(`INSERT INTO archive_records(archive_id, project_id, resource_type, resource_id, snapshot_id,
payload_json, checksum, archive_reason, archived_by, retention_until, metadata_json)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '{}')`)
.run(archiveId, input.projectId ?? null, input.resourceType, input.resourceId, input.snapshotId ?? null,
payloadJson, checksum, input.reason ?? '', input.archivedBy ?? null, input.retentionUntil ?? null);
return this.get(archiveId);
}
get(archiveId: string) {
const row = this.db.prepare('SELECT * FROM archive_records WHERE archive_id = ?').get(archiveId) as Record<string, unknown> | undefined;
if (!row) return null;
const payloadJson = String(row.payload_json);
const checksum = createHash('sha256').update(payloadJson).digest('hex');
if (checksum !== row.checksum) throw new Error(`Archived resource "${archiveId}" failed checksum validation.`);
return {
id: String(row.archive_id), projectId: row.project_id === null ? null : String(row.project_id),
resourceType: String(row.resource_type), resourceId: String(row.resource_id),
snapshotId: row.snapshot_id === null ? null : String(row.snapshot_id), payload: JSON.parse(payloadJson) as Record<string, unknown>,
checksum, reason: String(row.archive_reason), archivedAt: String(row.archived_at),
retentionUntil: row.retention_until === null ? null : String(row.retention_until)
};
}
restore(archiveId: string) {
const record = this.get(archiveId);
if (!record) throw new Error(`Archive record "${archiveId}" does not exist.`);
this.db.prepare('UPDATE archive_records SET restored_at = ? WHERE archive_id = ?').run(new Date().toISOString(), archiveId);
return record.payload;
}
}