-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy patharchive-raffle-events.ts
More file actions
819 lines (738 loc) · 23.8 KB
/
Copy patharchive-raffle-events.ts
File metadata and controls
819 lines (738 loc) · 23.8 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
import { RaffleEventEntity } from "../database/entities/raffle-event.entity";
import {
ArchiveCheckpointEntity,
ArchiveJobStatus,
} from "../database/entities/archive-checkpoint.entity";
import { DataSource, In, LessThan, MoreThan, Repository } from "typeorm";
import * as crypto from "crypto";
import * as fs from "fs";
import * as path from "path";
import * as readline from "readline";
/** Env value that allows non-interactive destructive archival. */
export const CONFIRM_DELETE_ENV = "CONFIRM_DELETE";
export const CONFIRM_DELETE_VALUE = "yes";
/**
* Thrown when DRY_RUN=false but the operator has not confirmed deletion.
*/
export class ArchiveDeleteConfirmationError extends Error {
constructor(message: string) {
super(message);
this.name = "ArchiveDeleteConfirmationError";
}
}
/**
* Returns true when CONFIRM_DELETE=yes is set (case-sensitive value).
*/
export function isDeleteConfirmed(
env: NodeJS.ProcessEnv = process.env,
): boolean {
return env[CONFIRM_DELETE_ENV] === CONFIRM_DELETE_VALUE;
}
/**
* Interactive prompt used when stdin is a TTY and CONFIRM_DELETE is unset.
*/
export async function promptDeleteConfirmation(
question: (
prompt: string,
) => Promise<string> = defaultDeleteConfirmationQuestion,
): Promise<boolean> {
const answer = await question(
'This will DELETE archived raffle_events from the database after writing CSV. Type "yes" to continue: ',
);
return answer.trim().toLowerCase() === "yes";
}
function defaultDeleteConfirmationQuestion(prompt: string): Promise<string> {
const rl = readline.createInterface({
input: process.stdin,
output: process.stderr,
});
return new Promise((resolve) => {
rl.question(prompt, (answer) => {
rl.close();
resolve(answer);
});
});
}
/**
* Gate destructive archival runs. Dry runs always pass.
* Non-interactive environments must set CONFIRM_DELETE=yes.
*/
export async function requireDeleteConfirmation(options: {
dryRun: boolean;
env?: NodeJS.ProcessEnv;
stdinIsTTY?: boolean;
prompt?: () => Promise<boolean>;
}): Promise<void> {
if (options.dryRun) {
return;
}
const env = options.env ?? process.env;
if (isDeleteConfirmed(env)) {
return;
}
const stdinIsTTY =
options.stdinIsTTY ?? Boolean(process.stdin.isTTY);
if (stdinIsTTY) {
const confirmed = options.prompt
? await options.prompt()
: await promptDeleteConfirmation();
if (!confirmed) {
throw new ArchiveDeleteConfirmationError(
"Archival aborted: deletion not confirmed. Re-run and type \"yes\", " +
`or set ${CONFIRM_DELETE_ENV}=${CONFIRM_DELETE_VALUE} for non-interactive use.`,
);
}
return;
}
throw new ArchiveDeleteConfirmationError(
"Archival aborted: DRY_RUN=false deletes rows from raffle_events. " +
`Re-run with ${CONFIRM_DELETE_ENV}=${CONFIRM_DELETE_VALUE} to proceed, ` +
"or omit DRY_RUN=false for a dry run. See docs/database/raffle-events-retention.md.",
);
}
export interface ArchiveOptions {
retentionDays?: number;
batchSize?: number;
dryRun?: boolean;
outDir?: string;
maxBatch?: number;
resumeFromCheckpoint?: boolean;
}
export interface ArchiveResult {
totalArchived: number;
batchesProcessed: number;
filesCreated: string[];
checkpointId?: string;
resumed: boolean;
reachedMaxBatch: boolean;
}
export interface ArchiveProgress {
batchNumber: number;
totalArchived: number;
currentBatchSize: number;
timestamp: Date;
}
/**
* Format version used as part of the integrity hash. Bump this whenever the
* set of hashed fields or the canonicalization algorithm changes so existing
* checkpoints are rejected (rather than silently passing) verification.
*/
export const ARCHIVE_CHECKPOINT_INTEGRITY_VERSION = 1;
/**
* Fields fed into the integrity hash. Row-level metadata (id, startedAt,
* updatedAt, completedAt) is intentionally excluded so the hash compactly
* captures the state worth verifying and remains stable across saves.
*/
interface ArchivalCheckpointHashedState {
jobType: string;
lastProcessedTimestamp: string | null;
lastProcessedId: string | null;
totalArchived: number;
batchNumber: number;
status: ArchiveJobStatus;
configSnapshot: Record<string, unknown>;
integrityVersion: number;
}
/**
* Thrown when an in-progress checkpoint's stored integrity hash does not match
* the recomputed value on resume. The archive loop refuses to start in this
* case to prevent silently overwriting corrupted state.
*/
export class ArchiveCheckpointIntegrityError extends Error {
constructor(
message: string,
public readonly checkpointId: string,
public readonly expectedHash: string | null,
public readonly actualHash: string,
public readonly reason: string,
) {
super(message);
this.name = "ArchiveCheckpointIntegrityError";
}
}
export type ArchiveIntegrityVerificationStatus =
| "ok"
| "failed"
| "missing"; // legacy checkpoint, allowed for graceful migration
export interface ArchiveIntegrityVerificationResult {
status: ArchiveIntegrityVerificationStatus;
checkpointId: string;
storedHash: string | null;
computedHash: string;
checkedAt: Date;
reason?: string;
}
/** Recursively walk a value and sort object keys for stable canonicalization. */
function deepSortKeys(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map((entry) => deepSortKeys(entry));
}
if (value !== null && typeof value === "object") {
const obj = value as Record<string, unknown>;
const sortedKeys = Object.keys(obj).sort();
const ordered: Record<string, unknown> = {};
for (const key of sortedKeys) {
ordered[key] = deepSortKeys(obj[key]);
}
return ordered;
}
return value;
}
/** Canonical JSON serialization with recursively-sorted object keys. */
function canonicalizeCheckpointState(
state: ArchivalCheckpointHashedState,
): string {
return JSON.stringify(deepSortKeys(state));
}
/**
* SHA-256 (hex) over a canonicalized representation of the checkpoint's
* state-bearing fields. Pure, deterministic, side-effect-free.
*/
export function computeIntegrityHash(
checkpoint: ArchiveCheckpointEntity,
): string {
const timestamp: Date | null =
checkpoint.lastProcessedTimestamp instanceof Date
? checkpoint.lastProcessedTimestamp
: checkpoint.lastProcessedTimestamp
? new Date(checkpoint.lastProcessedTimestamp)
: null;
const state: ArchivalCheckpointHashedState = {
jobType: checkpoint.jobType,
lastProcessedTimestamp: timestamp ? timestamp.toISOString() : null,
lastProcessedId: checkpoint.lastProcessedId,
totalArchived: checkpoint.totalArchived,
batchNumber: checkpoint.batchNumber,
status: checkpoint.status,
configSnapshot: checkpoint.configSnapshot as unknown as Record<
string,
unknown
>,
integrityVersion: ARCHIVE_CHECKPOINT_INTEGRITY_VERSION,
};
return crypto
.createHash("sha256")
.update(canonicalizeCheckpointState(state))
.digest("hex");
}
/**
* Verify an in-progress checkpoint's integrity hash on resume.
*
* - storedHash null/undefined : 'missing' (legacy); allowed; hash backfilled on next save.
* - storedHash == computed : 'ok'.
* - storedHash != computed : 'failed'; caller MUST halt archival.
*/
export function verifyCheckpointIntegrity(
checkpoint: ArchiveCheckpointEntity,
): ArchiveIntegrityVerificationResult {
const computedHash = computeIntegrityHash(checkpoint);
// Coerce undefined (test mocks and any pre-migration row that never had the
// column) to null so legacy checkpoints are treated as 'missing' rather than
// as a hash mismatch.
const storedHash = checkpoint.integrityHash ?? null;
const checkedAt = new Date();
if (storedHash == null) {
return {
status: "missing",
checkpointId: checkpoint.id,
storedHash,
computedHash,
checkedAt,
reason:
"Checkpoint has no integrity hash (legacy state). Hash will be computed on next save.",
};
}
if (storedHash !== computedHash) {
return {
status: "failed",
checkpointId: checkpoint.id,
storedHash,
computedHash,
checkedAt,
reason: "Computed integrity hash does not match stored hash.",
};
}
return {
status: "ok",
checkpointId: checkpoint.id,
storedHash,
computedHash,
checkedAt,
};
}
/**
* Persist a verification failure on the checkpoint row and emit a structured
* alert. The stored integrity hash is intentionally NOT overwritten so
* operators retain the evidence of the mismatch.
*/
export async function recordIntegrityFailure(
checkpointRepo: Repository<ArchiveCheckpointEntity>,
checkpoint: ArchiveCheckpointEntity,
result: ArchiveIntegrityVerificationResult,
): Promise<void> {
checkpoint.status = ArchiveJobStatus.FAILED;
checkpoint.lastVerifiedAt = result.checkedAt;
checkpoint.verificationFailureReason =
result.reason ?? "Integrity hash mismatch";
await checkpointRepo.save(checkpoint);
raiseIntegrityAlert(checkpoint, result);
}
/**
* Emit a structured JSON alert to stderr. Severity is "critical" because a
* corrupted archival state could lead to data loss if silently overwritten.
*/
export function raiseIntegrityAlert(
checkpoint: ArchiveCheckpointEntity,
result: ArchiveIntegrityVerificationResult,
): void {
const alert = {
severity: "critical",
alert: "archive_checkpoint_integrity_mismatch",
checkpointId: checkpoint.id,
jobType: checkpoint.jobType,
batchNumber: checkpoint.batchNumber,
storedHash: result.storedHash,
computedHash: result.computedHash,
reason: result.reason,
checkedAt: result.checkedAt.toISOString(),
};
console.error(JSON.stringify(alert));
}
/**
* Archive old raffle_events to local CSV and delete them safely in batches.
* Supports resumable checkpointing, dry-run simulation, and max-batch limits.
*
* @param dataSource - TypeORM DataSource for transactional checkpoint updates
* @param opts - Configuration options for archiving behavior
* @returns Summary of archiving operation including counts and file paths
*/
export async function archiveOldRaffleEvents(
dataSource: DataSource,
opts: ArchiveOptions = {},
): Promise<ArchiveResult> {
const retentionDays = opts.retentionDays ?? 30;
const batchSize = opts.batchSize ?? 500;
const dryRun = opts.dryRun ?? true;
const outDir = opts.outDir ?? path.join(process.cwd(), "archives");
const maxBatch = opts.maxBatch;
const resumeFromCheckpoint = opts.resumeFromCheckpoint ?? true;
if (!fs.existsSync(outDir)) {
fs.mkdirSync(outDir, { recursive: true });
}
const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000);
const jobType = "raffle_events";
const eventRepo = dataSource.getRepository(RaffleEventEntity);
const checkpointRepo = dataSource.getRepository(ArchiveCheckpointEntity);
// Attempt to resume from existing checkpoint
let checkpoint: ArchiveCheckpointEntity | null = null;
let resumed = false;
if (resumeFromCheckpoint && !dryRun) {
checkpoint = await findOrCreateCheckpoint(
checkpointRepo,
jobType,
cutoff,
retentionDays,
batchSize,
maxBatch,
);
if (checkpoint.batchNumber > 0) {
// Verify the resumed checkpoint's integrity hash before any archival
// work begins. On mismatch we mark the checkpoint FAILED and refuse to
// start the loop, preserving the corrupt state for operator review.
const verification = verifyCheckpointIntegrity(checkpoint);
logIntegrityVerification(verification);
if (verification.status === "failed") {
await recordIntegrityFailure(checkpointRepo, checkpoint, verification);
throw new ArchiveCheckpointIntegrityError(
`Refusing to start archival: integrity verification failed for checkpoint ${checkpoint.id}. ` +
`Stored hash ${verification.storedHash} does not match computed hash ${verification.computedHash}. ` +
`Checkpoint marked FAILED -- manual intervention required.`,
checkpoint.id,
verification.storedHash,
verification.computedHash,
verification.reason ?? "Integrity hash mismatch",
);
}
// Verification passed (ok or missing-for-legacy). Persist lastVerifiedAt.
checkpoint.lastVerifiedAt = verification.checkedAt;
await checkpointRepo.save(checkpoint);
resumed = true;
logProgress({
message: `Resuming from checkpoint: batch ${checkpoint.batchNumber}, archived ${checkpoint.totalArchived} records`,
batchNumber: checkpoint.batchNumber,
totalArchived: checkpoint.totalArchived,
checkpointId: checkpoint.id,
});
}
}
let batchNumber = checkpoint?.batchNumber ?? 0;
let totalArchived = checkpoint?.totalArchived ?? 0;
const filesCreated: string[] = [];
let reachedMaxBatch = false;
logProgress({
message: `Starting archival: retentionDays=${retentionDays}, batchSize=${batchSize}, dryRun=${dryRun}, maxBatch=${maxBatch ?? "unlimited"}`,
batchNumber: 0,
totalArchived: 0,
});
while (true) {
// Check max batch limit
if (maxBatch !== undefined && batchNumber >= maxBatch) {
reachedMaxBatch = true;
logProgress({
message: `Reached max batch limit of ${maxBatch}, stopping`,
batchNumber,
totalArchived,
});
break;
}
// Query next batch of old events
const rows = await queryNextBatch(
eventRepo,
cutoff,
batchSize,
checkpoint?.lastProcessedTimestamp ?? null,
checkpoint?.lastProcessedId ?? null,
);
if (rows.length === 0) {
logProgress({
message: "No more records to archive",
batchNumber,
totalArchived,
});
break;
}
batchNumber += 1;
logProgress({
message: `Processing batch ${batchNumber}: ${rows.length} records`,
batchNumber,
totalArchived,
currentBatchSize: rows.length,
});
// Write to CSV
const filename = await writeBatchToCsv(
rows,
outDir,
cutoff,
batchNumber,
dryRun,
);
filesCreated.push(filename);
totalArchived += rows.length;
// Delete records and update checkpoint in a transaction
if (!dryRun) {
await dataSource.transaction(async (manager) => {
const ids = rows.map((r) => r.id);
await manager.delete(RaffleEventEntity, { id: In(ids) } as any);
// Update checkpoint
if (checkpoint) {
checkpoint.batchNumber = batchNumber;
checkpoint.totalArchived = totalArchived;
checkpoint.lastProcessedTimestamp = rows[rows.length - 1].indexedAt;
checkpoint.lastProcessedId = rows[rows.length - 1].id;
checkpoint.updatedAt = new Date();
// Recompute and persist the integrity hash inside the same
// transaction as the row-state update so they cannot drift apart.
checkpoint.integrityHash = computeIntegrityHash(checkpoint);
checkpoint.lastVerifiedAt = new Date();
await manager.save(checkpoint);
}
});
logProgress({
message: `Batch ${batchNumber} completed: archived ${rows.length} records, deleted from database`,
batchNumber,
totalArchived,
});
} else {
logProgress({
message: `[DRY-RUN] Batch ${batchNumber} completed: would archive ${rows.length} records (no deletion)`,
batchNumber,
totalArchived,
});
}
// If fewer than batchSize rows were returned, we're done
if (rows.length < batchSize) {
logProgress({
message: `Batch returned fewer than ${batchSize} records, archiving complete`,
batchNumber,
totalArchived,
});
break;
}
}
// Mark checkpoint as completed
if (checkpoint && !dryRun && !reachedMaxBatch) {
checkpoint.status = ArchiveJobStatus.COMPLETED;
checkpoint.completedAt = new Date();
// Keep the integrity hash in sync with the final status change so any
// resume after completion can verify it cleanly.
checkpoint.integrityHash = computeIntegrityHash(checkpoint);
checkpoint.lastVerifiedAt = new Date();
await checkpointRepo.save(checkpoint);
logProgress({
message: `Checkpoint marked as completed`,
batchNumber,
totalArchived,
checkpointId: checkpoint.id,
});
}
const result: ArchiveResult = {
totalArchived,
batchesProcessed: batchNumber,
filesCreated,
checkpointId: checkpoint?.id,
resumed,
reachedMaxBatch,
};
logProgress({
message: `Archival complete: ${totalArchived} records in ${batchNumber} batches, ${filesCreated.length} files created`,
batchNumber,
totalArchived,
});
return result;
}
/**
* Find existing checkpoint or create a new one for the archiving job.
* Ensures only one active checkpoint exists per job type.
*/
async function findOrCreateCheckpoint(
checkpointRepo: Repository<ArchiveCheckpointEntity>,
jobType: string,
cutoff: Date,
retentionDays: number,
batchSize: number,
maxBatch?: number,
): Promise<ArchiveCheckpointEntity> {
// Look for existing in-progress checkpoint
let checkpoint = await checkpointRepo.findOne({
where: {
jobType,
status: ArchiveJobStatus.IN_PROGRESS,
},
order: { startedAt: "DESC" },
});
if (checkpoint) {
// Validate checkpoint is for the same cutoff date
const checkpointCutoff = new Date(checkpoint.configSnapshot.cutoffDate);
if (checkpointCutoff.getTime() === cutoff.getTime()) {
return checkpoint;
}
// Different cutoff, mark old checkpoint as completed and create new one
checkpoint.status = ArchiveJobStatus.COMPLETED;
checkpoint.completedAt = new Date();
await checkpointRepo.save(checkpoint);
}
// Create new checkpoint
checkpoint = checkpointRepo.create({
jobType,
status: ArchiveJobStatus.IN_PROGRESS,
totalArchived: 0,
batchNumber: 0,
lastProcessedTimestamp: null,
lastProcessedId: null,
configSnapshot: {
retentionDays,
batchSize,
maxBatch,
cutoffDate: cutoff.toISOString(),
},
});
// Compute and store the integrity hash on creation so resume-time
// verification has a value to compare against from the very first save.
checkpoint.integrityHash = computeIntegrityHash(checkpoint);
checkpoint.lastVerifiedAt = new Date();
return await checkpointRepo.save(checkpoint);
}
/**
* Query the next batch of events to archive, resuming from checkpoint if available.
*/
async function queryNextBatch(
eventRepo: Repository<RaffleEventEntity>,
cutoff: Date,
batchSize: number,
lastProcessedTimestamp: Date | null,
lastProcessedId: string | null,
): Promise<RaffleEventEntity[]> {
const queryBuilder = eventRepo
.createQueryBuilder("event")
.where("event.indexedAt < :cutoff", { cutoff })
.orderBy("event.indexedAt", "ASC")
.addOrderBy("event.id", "ASC")
.take(batchSize);
// Resume from checkpoint if available
if (lastProcessedTimestamp && lastProcessedId) {
queryBuilder.andWhere(
"(event.indexedAt > :lastTimestamp OR (event.indexedAt = :lastTimestamp AND event.id > :lastId))",
{
lastTimestamp: lastProcessedTimestamp,
lastId: lastProcessedId,
},
);
}
return await queryBuilder.getMany();
}
/**
* Write a batch of events to CSV file.
*/
async function writeBatchToCsv(
rows: RaffleEventEntity[],
outDir: string,
cutoff: Date,
batchNumber: number,
dryRun: boolean,
): Promise<string> {
const filename = path.join(
outDir,
`raffle_events_${cutoff.toISOString().slice(0, 10)}_batch${String(batchNumber).padStart(4, "0")}.csv`,
);
const prefix = dryRun ? "[DRY-RUN] " : "";
logProgress({
message: `${prefix}Writing ${rows.length} records to ${filename}`,
batchNumber,
totalArchived: 0,
});
const header = [
"id",
"raffle_id",
"event_type",
"schema_version",
"ledger",
"tx_hash",
"payload_json",
"indexed_at",
];
const stream = fs.createWriteStream(filename, { encoding: "utf8" });
stream.write(header.join(",") + "\n");
for (const row of rows) {
const line = [
row.id,
String(row.raffleId),
row.eventType,
String(row.schemaVersion ?? 1),
String(row.ledger),
row.txHash,
JSON.stringify(row.payloadJson).replace(/\n/g, " ").replace(/\r/g, " "),
row.indexedAt.toISOString(),
]
.map((v) => {
if (typeof v === "string" && v.includes(",")) {
return `"${v.replace(/"/g, '""')}"`;
}
return v;
})
.join(",");
stream.write(line + "\n");
}
stream.end();
await new Promise<void>((resolve) => stream.on("finish", () => resolve()));
return filename;
}
/**
* Log progress with structured information for monitoring and debugging.
*/
function logProgress(progress: {
message: string;
batchNumber: number;
totalArchived: number;
currentBatchSize?: number;
checkpointId?: string;
timestamp?: Date;
}): void {
const timestamp = progress.timestamp ?? new Date();
const logEntry = {
timestamp: timestamp.toISOString(),
message: progress.message,
batchNumber: progress.batchNumber,
totalArchived: progress.totalArchived,
currentBatchSize: progress.currentBatchSize,
checkpointId: progress.checkpointId,
};
console.log(JSON.stringify(logEntry));
}
/**
* Emit a single JSON line describing the resume-time integrity verification
* result. Distinct from logProgress so observability pipelines can filter on
* `event: "archive_integrity_verification"`.
*/
function logIntegrityVerification(
result: ArchiveIntegrityVerificationResult,
): void {
const entry = {
event: "archive_integrity_verification",
status: result.status,
checkpointId: result.checkpointId,
storedHash: result.storedHash,
computedHash: result.computedHash,
reason: result.reason,
checkedAt: result.checkedAt.toISOString(),
};
if (result.status === "failed") {
console.error(JSON.stringify(entry));
} else {
console.log(JSON.stringify(entry));
}
}
// CLI entrypoint
if (require.main === module) {
(async () => {
const retentionDays = parseInt(
process.env.RAFFLE_EVENTS_RETENTION_DAYS ?? "30",
10,
);
const batchSize = parseInt(process.env.BATCH_SIZE ?? "500", 10);
const maxBatch = process.env.MAX_BATCH
? parseInt(process.env.MAX_BATCH, 10)
: undefined;
const dryRun = process.env.DRY_RUN !== "false"; // default true
const resumeFromCheckpoint = process.env.RESUME !== "false"; // default true
// Refuse destructive runs unless the operator confirms (TTY prompt or
// CONFIRM_DELETE=yes). See docs/database/raffle-events-retention.md.
await requireDeleteConfirmation({ dryRun });
// Lazy-load so unit tests importing this module do not pull AppDataSource.
const { AppDataSource } = await import("../data-source");
await AppDataSource.initialize();
console.log(
JSON.stringify({
message: "Starting raffle events archival",
config: {
retentionDays,
batchSize,
maxBatch: maxBatch ?? "unlimited",
dryRun,
resumeFromCheckpoint,
confirmDelete: isDeleteConfirmed(),
},
}),
);
const result = await archiveOldRaffleEvents(AppDataSource, {
retentionDays,
dryRun,
batchSize,
maxBatch,
resumeFromCheckpoint,
});
console.log(
JSON.stringify({
message: "Archival completed",
result: {
totalArchived: result.totalArchived,
batchesProcessed: result.batchesProcessed,
filesCreated: result.filesCreated.length,
checkpointId: result.checkpointId,
resumed: result.resumed,
reachedMaxBatch: result.reachedMaxBatch,
},
}),
);
await AppDataSource.destroy();
process.exit(0);
})().catch((err) => {
console.error(
JSON.stringify({
message: "Archival failed",
error: err.message,
stack: err.stack,
}),
);
process.exit(1);
});
}