|
| 1 | +import { |
| 2 | + QueryExecutor, |
| 3 | + insertUnassignedStewardships, |
| 4 | + listCriticalPackagesWithoutStewardship, |
| 5 | +} from '@crowd/data-access-layer' |
| 6 | +import { getServiceChildLogger } from '@crowd/logging' |
| 7 | + |
| 8 | +const log = getServiceChildLogger('stewardship-backfill') |
| 9 | + |
| 10 | +export interface BackfillResult { |
| 11 | + inserted: number |
| 12 | + skipped: number |
| 13 | + batches: number |
| 14 | +} |
| 15 | + |
| 16 | +interface BackfillOptions { |
| 17 | + batchSize: number |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Seeds one `stewardships` row (status=unassigned, origin=auto_imported) for |
| 22 | + * every critical package that doesn't already have one. Idempotent: ON CONFLICT |
| 23 | + * DO NOTHING means re-running is safe and will just report 0 inserts. |
| 24 | + * |
| 25 | + * Designed to be called from a Temporal activity or directly from the bin script. |
| 26 | + * The `isStopping` callback lets the caller signal a graceful shutdown between |
| 27 | + * batches — the function returns the totals collected so far. |
| 28 | + */ |
| 29 | +export async function runStewardshipBackfill( |
| 30 | + qx: QueryExecutor, |
| 31 | + options: BackfillOptions, |
| 32 | + isStopping: () => boolean = () => false, |
| 33 | +): Promise<BackfillResult> { |
| 34 | + const { batchSize } = options |
| 35 | + let lastId = 0 |
| 36 | + let inserted = 0 |
| 37 | + let skipped = 0 |
| 38 | + let batches = 0 |
| 39 | + |
| 40 | + while (!isStopping()) { |
| 41 | + const ids = await listCriticalPackagesWithoutStewardship(qx, { |
| 42 | + afterId: lastId, |
| 43 | + limit: batchSize, |
| 44 | + }) |
| 45 | + |
| 46 | + if (ids.length === 0) break |
| 47 | + |
| 48 | + const batchInserted = await insertUnassignedStewardships(qx, ids) |
| 49 | + const batchSkipped = ids.length - batchInserted |
| 50 | + |
| 51 | + inserted += batchInserted |
| 52 | + skipped += batchSkipped |
| 53 | + batches++ |
| 54 | + lastId = ids[ids.length - 1] |
| 55 | + |
| 56 | + log.info({ batches, inserted, skipped, lastId, batchInserted, batchSkipped }, 'Batch complete.') |
| 57 | + } |
| 58 | + |
| 59 | + return { inserted, skipped, batches } |
| 60 | +} |
0 commit comments