SPB Git

spb/rareindex

Public
10.2 KB · 177 lines typescript
1import { loadDotenv } from './lib/env.ts';2loadDotenv();3process.env.RI_SERVICE ??= 'rareindex-worker';45import { env, logger } from '@rareindex/shared';6import { createQueue, JOBS } from './lib/queue.ts';7import { closeDb, db } from './lib/db.ts';8import { flushCosts } from './lib/costs.ts';9import { runCrawl } from './crawler/run.ts';10import { scheduleDueCrawls } from './crawler/scheduler.ts';11import { normalizeBatch } from './normalizer/index.ts';12import { sql } from 'drizzle-orm';13import { pendingCount, resolveBatch } from './entity-resolution/index.ts';14import { assetsNeedingValuation, computePremiums, valueMany } from './valuation/run.ts';15import { runCategorySnapshots, runIndices, runRadar } from './indices/run.ts';16import { syncFx } from './fx.ts';17import { syncBenchmarks } from './benchmarks.ts';18import { computeHealth } from './health.ts';19import { expireListings } from './listings-expire.ts';20import { processImages } from './image-processing/index.ts';21import { verifyCertificates } from './certs-verify.ts';2223/**24 * RareIndex worker process (PM2: rareindex-worker). One process runs the queue handlers and the25 * scheduler; scale out by starting more processes against the same database.26 */27export async function startWorker(): Promise<() => Promise<void>> {28  const log = logger.child({ component: 'worker' });29  const queue = createQueue();30  await queue.start();31  // Single-worker deployment: jobs left 'active' by a previous process (restart/crash) would wait for32  // their expiry (hours). Re-queue them so crawls resume immediately.33  await db().execute(sql`update pgboss.job set state = 'retry', started_on = null where state = 'active' and started_on < now() - interval '90 seconds'`);34  // Runs left 'running' by a dead process can never finish: close them so the per-connector guard below works.35  await db().execute(sql`update connector_runs set status = 'failed', finished_at = now(), error = 'worker restarted' where status = 'running'`);36  // Collapse duplicate queued crawls per connector (keep the oldest).37  await db().execute(sql`delete from pgboss.job j using pgboss.job k where j.name = 'crawl.run' and k.name = 'crawl.run' and j.state in ('created','retry') and k.state in ('created','retry') and j.data->>'connectorId' = k.data->>'connectorId' and j.created_on > k.created_on`);38  const concurrency = env().WORKER_CONCURRENCY;3940  // ---- handlers ----41  await queue.work<{ connectorId: string; mode?: 'incremental' | 'backfill' | 'probe'; limit?: number; trigger?: string }>(JOBS.crawlRun, { concurrency: Math.max(1, Math.floor(concurrency / 2)), pollingIntervalSeconds: 5 }, async (data) => {42    // One crawl per connector at a time (duplicates waste engine credits and crawl slots).43    const [running] = (await db().execute(sql`select 1 from connector_runs where connector_id = ${data.connectorId} and status = 'running' and started_at > now() - interval '6 hours' limit 1`)) as unknown as unknown[];44    if (running) {45      log.info({ connector: data.connectorId }, 'crawl already running; skipping duplicate job');46      return;47    }48    const res = await runCrawl(data.connectorId, { mode: data.mode ?? 'incremental', limit: data.limit, trigger: data.trigger ?? 'schedule' });49    if (res.recordsRaw > 0) await queue.send(JOBS.normalizeBatch, { connectorId: data.connectorId }, { singletonKey: `normalize:${data.connectorId}`, singletonSeconds: 30 });50  });51  await queue.work<{ connectorId?: string }>(JOBS.normalizeBatch, { concurrency: 2, pollingIntervalSeconds: 5 }, async (data) => {52    let total = 0;53    let more = false;54    for (let i = 0; i < 40; i++) {55      const r = await normalizeBatch({ connectorId: data.connectorId, limit: 500 });56      total += r.processed;57      more = r.processed >= 500;58      if (!more) break;59    }60    // Large crawls (100k+ raw rows) exceed one job's budget: chain another job instead of leaving rows unprocessed.61    if (more) await queue.send(JOBS.normalizeBatch, { connectorId: data.connectorId }, { singletonKey: `normalize:${data.connectorId ?? 'all'}:${Date.now()}`, startAfterSeconds: 1 });62    if (total > 0) for (let k = 0; k < Number(process.env.RESOLVE_CONCURRENCY ?? 3); k++) await queue.send(JOBS.resolveBatch, {}, { singletonKey: `resolve:${k}`, singletonSeconds: 30 });63  });64  const RESOLVE_WORKERS = Number(process.env.RESOLVE_CONCURRENCY ?? 3);65  // Release rows claimed by a previous worker process that died mid-batch.66  await db().execute(sql`update normalized_records set status = 'pending' where status = 'processing'`);67  await queue.work<Record<string, never>>(JOBS.resolveBatch, { concurrency: RESOLVE_WORKERS, pollingIntervalSeconds: 5 }, async () => {68    const touched = new Set<string>();69    for (let i = 0; i < 40; i++) {70      const r = await resolveBatch({ limit: 500 });71      for (const a of r.touchedAssets) touched.add(a);72      if (r.processed < 500) break;73    }74    if ((await pendingCount()) > 0) for (let k = 0; k < RESOLVE_WORKERS; k++) await queue.send(JOBS.resolveBatch, {}, { singletonKey: `resolve:${k}`, singletonSeconds: 30, startAfterSeconds: 5 });75    if (touched.size) await queue.send(JOBS.valuationAsset, { assetIds: [...touched].slice(0, 5000) }, { singletonKey: `value:${Date.now()}` });76    if (touched.size) await queue.send(JOBS.imagesProcess, { assetIds: [...touched].slice(0, 5000), limit: 5000 }, { singletonKey: `images:${Date.now()}` });77  });78  await queue.work<{ assetIds: string[] }>(JOBS.valuationAsset, { concurrency: 1, pollingIntervalSeconds: 5 }, async (data) => {79    await valueMany(data.assetIds, { concurrency: 4 });80  });81  await queue.work<{ all?: boolean; rebuildHistory?: boolean }>(JOBS.valuationRebuild, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {82    await computePremiums();83    const ids = await assetsNeedingValuation({ all: data.all, limit: 200_000 });84    await valueMany(ids, { rebuildHistory: data.rebuildHistory, concurrency: 4 });85  });86  await queue.work(JOBS.indicesDaily, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {87    await runIndices();88  });89  await queue.work(JOBS.snapshotsDaily, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {90    await runCategorySnapshots();91  });92  await queue.work(JOBS.radarScan, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {93    await runRadar();94  });95  await queue.work(JOBS.healthCompute, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {96    await computeHealth();97  });98  await queue.work<{ backfill?: boolean }>(JOBS.fxSync, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {99    await syncFx({ backfill: data.backfill });100  });101  await queue.work(JOBS.benchmarksSync, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {102    await syncBenchmarks();103  });104  await queue.work<{ assetIds?: string[]; limit?: number; recheck?: boolean }>(JOBS.imagesProcess, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {105    await processImages({ assetIds: data.assetIds, limit: data.limit ?? 2000, recheck: data.recheck ?? false });106  });107  await queue.work(JOBS.listingsExpire, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {108    await expireListings();109  });110  await queue.work<{ limit?: number; grader?: string }>(JOBS.certsVerify, { concurrency: 1, pollingIntervalSeconds: 60 }, async (data) => {111    await verifyCertificates({ limit: data.limit ?? 100, grader: data.grader });112  });113  await queue.work(JOBS.accountJobs, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {114    try {115      const accountModule = './account/index.ts'; // provided by the account module when present116      const mod = (await import(accountModule)) as { runAccountJobs?: (d: ReturnType<typeof db>) => Promise<unknown> };117      if (mod.runAccountJobs) await mod.runAccountJobs(db());118    } catch (err) {119      if (!/Cannot find module|ERR_MODULE_NOT_FOUND/.test(String(err))) log.error({ err }, 'account jobs failed');120    }121  });122123  // ---- schedules (UTC) ----124  await queue.schedule(JOBS.fxSync, '15 16 * * 1-5', {}); // after ECB 16:00 CET publication125  await queue.schedule(JOBS.benchmarksSync, '30 22 * * *', {});126  await queue.schedule(JOBS.valuationRebuild, '0 3 * * *', { all: false });127  await queue.schedule(JOBS.snapshotsDaily, '20 4 * * *', {});128  await queue.schedule(JOBS.indicesDaily, '40 4 * * *', {});129  await queue.schedule(JOBS.radarScan, '0 5 * * *', {});130  await queue.schedule(JOBS.healthCompute, '*/30 * * * *', {});131  await queue.schedule(JOBS.listingsExpire, '10 * * * *', {});132  await queue.schedule(JOBS.certsVerify, '25 * * * *', { limit: 100 }); // SPEC §22: verify cert numbers seen on marketplaces against public grader lookups133  await queue.schedule(JOBS.imagesProcess, '50 5 * * *', { limit: 20000, recheck: true });134  await queue.schedule(JOBS.imagesProcess, '*/15 * * * *', { limit: 3000 });135  await queue.schedule(JOBS.accountJobs, '*/10 * * * *', {});136137  // ---- crawl scheduler loop ----138  const tick = async () => {139    try {140      await scheduleDueCrawls(queue);141      // Normalize whatever raw rows exist even while long crawls are still running (sales show up progressively).142      await queue.send(JOBS.normalizeBatch, {}, { singletonKey: 'normalize:periodic', singletonSeconds: 120 });143    } catch (err) {144      log.error({ err }, 'scheduler tick failed');145    }146  };147  await tick();148  if ((await pendingCount()) > 0) for (let k = 0; k < RESOLVE_WORKERS; k++) await queue.send(JOBS.resolveBatch, {}, { singletonKey: `resolve:${k}`, singletonSeconds: 30 });149  const timer = setInterval(tick, 60_000);150  // hourly incremental valuation for assets with fresh evidence151  const hourly = setInterval(() => void queue.send(JOBS.valuationRebuild, { all: false }, { singletonKey: 'valuation:hourly', singletonSeconds: 3000 }), 3600_000);152  log.info({ concurrency }, 'worker started');153154  return async () => {155    clearInterval(timer);156    clearInterval(hourly);157    await queue.stop();158    await flushCosts();159    await closeDb();160    log.info('worker stopped');161  };162}163164const isMain = process.argv[1] && /workers\/main\.ts$/.test(process.argv[1]);165if (isMain) {166  startWorker()167    .then((stop) => {168      const shutdown = () => void stop().then(() => process.exit(0));169      process.on('SIGINT', shutdown);170      process.on('SIGTERM', shutdown);171    })172    .catch((err) => {173      logger.error({ err }, 'worker failed to start');174      process.exit(1);175    });176}177
Files · d732f70ce5489245a263ca6bcf09fbebc0d2be77
Menu

Theme