|
| 1 | +import { loadCompassConfig } from "@core/config/compass.config"; |
| 2 | +import { Logger } from "@core/logger/winston.logger"; |
| 3 | +import { SyncJobIdSchema } from "@core/types/sync/identity.contracts"; |
| 4 | +import { FAILED_JOB_MAX_REQUEUES } from "@sync/domain/failed-job-requeue.service"; |
| 5 | +import { JobRepository } from "@sync/storage/repositories/job.repository"; |
| 6 | +import { SyncMongoService } from "@sync/storage/sync-mongo.service"; |
| 7 | + |
| 8 | +const logger = Logger("scripts.commands.manage-failed-jobs"); |
| 9 | + |
| 10 | +function syncMongoUri(): string { |
| 11 | + const fromEnv = process.env["SYNC_MONGO_URI"]?.trim(); |
| 12 | + if (fromEnv) return fromEnv; |
| 13 | + const uri = loadCompassConfig().sync?.mongoUri?.trim(); |
| 14 | + if (!uri) { |
| 15 | + throw new Error( |
| 16 | + "Set SYNC_MONGO_URI or add sync.mongoUri to compass.yaml before manage-failed-jobs", |
| 17 | + ); |
| 18 | + } |
| 19 | + return uri; |
| 20 | +} |
| 21 | + |
| 22 | +function flagValue(args: string[], name: string): string | undefined { |
| 23 | + const index = args.indexOf(name); |
| 24 | + if (index < 0) return undefined; |
| 25 | + return args[index + 1]; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Operator tooling for Sync jobs that exhausted the self-heal requeue budget |
| 30 | + * and still occupy a coalescing key. Default actions are dry-run; `--apply` |
| 31 | + * persists. |
| 32 | + * |
| 33 | + * bun run cli manage-failed-jobs list |
| 34 | + * bun run cli manage-failed-jobs clear --id <id> --coalescing-key <key> [--apply] |
| 35 | + * bun run cli manage-failed-jobs requeue --id <id> [--apply] |
| 36 | + */ |
| 37 | +export async function runManageFailedJobs(): Promise<void> { |
| 38 | + const args = process.argv.slice(3); |
| 39 | + const action = args[0]; |
| 40 | + if (action !== "list" && action !== "clear" && action !== "requeue") { |
| 41 | + throw new Error( |
| 42 | + "Usage: manage-failed-jobs <list|clear|requeue> [--id …] [--coalescing-key …] [--apply]", |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + const apply = args.includes("--apply"); |
| 47 | + const syncMongo = new SyncMongoService(); |
| 48 | + try { |
| 49 | + await syncMongo.connect({ |
| 50 | + uri: syncMongoUri(), |
| 51 | + enforceLeastPrivilege: false, |
| 52 | + forbiddenDatabaseName: "prod_calendar", |
| 53 | + }); |
| 54 | + const jobs = new JobRepository(syncMongo.db); |
| 55 | + |
| 56 | + if (action === "list") { |
| 57 | + const [count, sample] = await Promise.all([ |
| 58 | + jobs.countExhaustedFailed(FAILED_JOB_MAX_REQUEUES), |
| 59 | + jobs.listExhaustedFailed(FAILED_JOB_MAX_REQUEUES), |
| 60 | + ]); |
| 61 | + const report = { |
| 62 | + maxRequeues: FAILED_JOB_MAX_REQUEUES, |
| 63 | + count, |
| 64 | + sampleSize: sample.length, |
| 65 | + truncated: count > sample.length, |
| 66 | + jobs: sample.map((job) => ({ |
| 67 | + id: job.id, |
| 68 | + coalescingKey: job.coalescingKey, |
| 69 | + connectionId: job.connectionId, |
| 70 | + failureClass: job.failureClass, |
| 71 | + requeuedCount: job.requeuedCount, |
| 72 | + updatedAt: job.updatedAt.toISOString(), |
| 73 | + })), |
| 74 | + }; |
| 75 | + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); |
| 76 | + logger.info( |
| 77 | + `manage-failed-jobs list count=${report.count} sample=${report.sampleSize} truncated=${report.truncated}`, |
| 78 | + ); |
| 79 | + await syncMongo.disconnect(); |
| 80 | + process.exit(0); |
| 81 | + } |
| 82 | + |
| 83 | + const idRaw = flagValue(args, "--id"); |
| 84 | + if (!idRaw) { |
| 85 | + throw new Error(`manage-failed-jobs ${action} requires --id <SyncJobId>`); |
| 86 | + } |
| 87 | + const id = SyncJobIdSchema.parse(idRaw); |
| 88 | + const existing = await jobs.findByIdUnscoped(id); |
| 89 | + if (!existing) { |
| 90 | + throw new Error(`No job found for id=${id}`); |
| 91 | + } |
| 92 | + if (existing.state !== "failed") { |
| 93 | + throw new Error( |
| 94 | + `Job id=${id} is state=${existing.state}; ${action} only accepts failed jobs`, |
| 95 | + ); |
| 96 | + } |
| 97 | + |
| 98 | + if (action === "clear") { |
| 99 | + const coalescingKey = |
| 100 | + flagValue(args, "--coalescing-key") ?? existing.coalescingKey; |
| 101 | + if (coalescingKey !== existing.coalescingKey) { |
| 102 | + throw new Error( |
| 103 | + `coalescing-key mismatch for id=${id}: expected ${existing.coalescingKey}`, |
| 104 | + ); |
| 105 | + } |
| 106 | + const report = { |
| 107 | + dryRun: !apply, |
| 108 | + action: "clear" as const, |
| 109 | + id, |
| 110 | + coalescingKey, |
| 111 | + state: existing.state, |
| 112 | + }; |
| 113 | + if (apply) { |
| 114 | + const ok = await jobs.remove(id, coalescingKey); |
| 115 | + if (!ok) { |
| 116 | + throw new Error(`Failed to clear id=${id} key=${coalescingKey}`); |
| 117 | + } |
| 118 | + } |
| 119 | + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); |
| 120 | + logger.info( |
| 121 | + `manage-failed-jobs clear dryRun=${report.dryRun} id=${id} key=${coalescingKey}`, |
| 122 | + ); |
| 123 | + await syncMongo.disconnect(); |
| 124 | + process.exit(0); |
| 125 | + } |
| 126 | + |
| 127 | + const report = { |
| 128 | + dryRun: !apply, |
| 129 | + action: "requeue" as const, |
| 130 | + id, |
| 131 | + coalescingKey: existing.coalescingKey, |
| 132 | + requeuedCount: existing.requeuedCount, |
| 133 | + }; |
| 134 | + if (apply) { |
| 135 | + const ok = await jobs.requeue(id, new Date()); |
| 136 | + if (!ok) { |
| 137 | + throw new Error(`Failed to requeue id=${id}`); |
| 138 | + } |
| 139 | + } |
| 140 | + process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); |
| 141 | + logger.info(`manage-failed-jobs requeue dryRun=${report.dryRun} id=${id}`); |
| 142 | + await syncMongo.disconnect(); |
| 143 | + process.exit(0); |
| 144 | + } catch (error) { |
| 145 | + logger.error(error); |
| 146 | + try { |
| 147 | + await syncMongo.disconnect(); |
| 148 | + } catch { |
| 149 | + // ignore |
| 150 | + } |
| 151 | + process.exit(1); |
| 152 | + } |
| 153 | +} |
0 commit comments