File size: 2,431 Bytes
a8f4b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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;
  }
}