SPB Git

spb/rareindex

Public
9.8 KB · 172 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';2122/**23 * RareIndex worker process (PM2: rareindex-worker). One process runs the queue handlers and the24 * scheduler; scale out by starting more processes against the same database.25 */26export async function startWorker(): Promise<() => Promise<void>> {27  const log = logger.child({ component: 'worker' });28  const queue = createQueue();29  await queue.start();30  // Single-worker deployment: jobs left 'active' by a previous process (restart/crash) would wait for31  // their expiry (hours). Re-queue them so crawls resume immediately.32  await db().execute(sql`update pgboss.job set state = 'retry', started_on = null where state = 'active' and started_on < now() - interval '90 seconds'`);33  // Runs left 'running' by a dead process can never finish: close them so the per-connector guard below works.34  await db().execute(sql`update connector_runs set status = 'failed', finished_at = now(), error = 'worker restarted' where status = 'running'`);35  // Collapse duplicate queued crawls per connector (keep the oldest).36  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`);37  const concurrency = env().WORKER_CONCURRENCY;3839  // ---- handlers ----40  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) => {41    // One crawl per connector at a time (duplicates waste engine credits and crawl slots).42    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[];43    if (running) {44      log.info({ connector: data.connectorId }, 'crawl already running; skipping duplicate job');45      return;46    }47    const res = await runCrawl(data.connectorId, { mode: data.mode ?? 'incremental', limit: data.limit, trigger: data.trigger ?? 'schedule' });48    if (res.recordsRaw > 0) await queue.send(JOBS.normalizeBatch, { connectorId: data.connectorId }, { singletonKey: `normalize:${data.connectorId}`, singletonSeconds: 30 });49  });50  await queue.work<{ connectorId?: string }>(JOBS.normalizeBatch, { concurrency: 2, pollingIntervalSeconds: 5 }, async (data) => {51    let total = 0;52    let more = false;53    for (let i = 0; i < 40; i++) {54      const r = await normalizeBatch({ connectorId: data.connectorId, limit: 500 });55      total += r.processed;56      more = r.processed >= 500;57      if (!more) break;58    }59    // Large crawls (100k+ raw rows) exceed one job's budget: chain another job instead of leaving rows unprocessed.60    if (more) await queue.send(JOBS.normalizeBatch, { connectorId: data.connectorId }, { singletonKey: `normalize:${data.connectorId ?? 'all'}:${Date.now()}`, startAfterSeconds: 1 });61    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 });62  });63  const RESOLVE_WORKERS = Number(process.env.RESOLVE_CONCURRENCY ?? 3);64  // Release rows claimed by a previous worker process that died mid-batch.65  await db().execute(sql`update normalized_records set status = 'pending' where status = 'processing'`);66  await queue.work<Record<string, never>>(JOBS.resolveBatch, { concurrency: RESOLVE_WORKERS, pollingIntervalSeconds: 5 }, async () => {67    const touched = new Set<string>();68    for (let i = 0; i < 40; i++) {69      const r = await resolveBatch({ limit: 500 });70      for (const a of r.touchedAssets) touched.add(a);71      if (r.processed < 500) break;72    }73    if ((await pendingCount()) > 0) for (let k = 0; k < RESOLVE_WORKERS; k++) await queue.send(JOBS.resolveBatch, {}, { singletonKey: `resolve:${k}`, singletonSeconds: 30, startAfterSeconds: 5 });74    if (touched.size) await queue.send(JOBS.valuationAsset, { assetIds: [...touched].slice(0, 5000) }, { singletonKey: `value:${Date.now()}` });75    if (touched.size) await queue.send(JOBS.imagesProcess, { assetIds: [...touched].slice(0, 5000), limit: 5000 }, { singletonKey: `images:${Date.now()}` });76  });77  await queue.work<{ assetIds: string[] }>(JOBS.valuationAsset, { concurrency: 1, pollingIntervalSeconds: 5 }, async (data) => {78    await valueMany(data.assetIds, { concurrency: 4 });79  });80  await queue.work<{ all?: boolean; rebuildHistory?: boolean }>(JOBS.valuationRebuild, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {81    await computePremiums();82    const ids = await assetsNeedingValuation({ all: data.all, limit: 200_000 });83    await valueMany(ids, { rebuildHistory: data.rebuildHistory, concurrency: 4 });84  });85  await queue.work(JOBS.indicesDaily, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {86    await runIndices();87  });88  await queue.work(JOBS.snapshotsDaily, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {89    await runCategorySnapshots();90  });91  await queue.work(JOBS.radarScan, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {92    await runRadar();93  });94  await queue.work(JOBS.healthCompute, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {95    await computeHealth();96  });97  await queue.work<{ backfill?: boolean }>(JOBS.fxSync, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {98    await syncFx({ backfill: data.backfill });99  });100  await queue.work(JOBS.benchmarksSync, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {101    await syncBenchmarks();102  });103  await queue.work<{ assetIds?: string[]; limit?: number; recheck?: boolean }>(JOBS.imagesProcess, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {104    await processImages({ assetIds: data.assetIds, limit: data.limit ?? 2000, recheck: data.recheck ?? false });105  });106  await queue.work(JOBS.listingsExpire, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {107    await expireListings();108  });109  await queue.work(JOBS.accountJobs, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {110    try {111      const accountModule = './account/index.ts'; // provided by the account module when present112      const mod = (await import(accountModule)) as { runAccountJobs?: (d: ReturnType<typeof db>) => Promise<unknown> };113      if (mod.runAccountJobs) await mod.runAccountJobs(db());114    } catch (err) {115      if (!/Cannot find module|ERR_MODULE_NOT_FOUND/.test(String(err))) log.error({ err }, 'account jobs failed');116    }117  });118119  // ---- schedules (UTC) ----120  await queue.schedule(JOBS.fxSync, '15 16 * * 1-5', {}); // after ECB 16:00 CET publication121  await queue.schedule(JOBS.benchmarksSync, '30 22 * * *', {});122  await queue.schedule(JOBS.valuationRebuild, '0 3 * * *', { all: false });123  await queue.schedule(JOBS.snapshotsDaily, '20 4 * * *', {});124  await queue.schedule(JOBS.indicesDaily, '40 4 * * *', {});125  await queue.schedule(JOBS.radarScan, '0 5 * * *', {});126  await queue.schedule(JOBS.healthCompute, '*/30 * * * *', {});127  await queue.schedule(JOBS.listingsExpire, '10 * * * *', {});128  await queue.schedule(JOBS.imagesProcess, '50 5 * * *', { limit: 20000, recheck: true });129  await queue.schedule(JOBS.imagesProcess, '*/15 * * * *', { limit: 3000 });130  await queue.schedule(JOBS.accountJobs, '*/10 * * * *', {});131132  // ---- crawl scheduler loop ----133  const tick = async () => {134    try {135      await scheduleDueCrawls(queue);136      // Normalize whatever raw rows exist even while long crawls are still running (sales show up progressively).137      await queue.send(JOBS.normalizeBatch, {}, { singletonKey: 'normalize:periodic', singletonSeconds: 120 });138    } catch (err) {139      log.error({ err }, 'scheduler tick failed');140    }141  };142  await tick();143  if ((await pendingCount()) > 0) for (let k = 0; k < RESOLVE_WORKERS; k++) await queue.send(JOBS.resolveBatch, {}, { singletonKey: `resolve:${k}`, singletonSeconds: 30 });144  const timer = setInterval(tick, 60_000);145  // hourly incremental valuation for assets with fresh evidence146  const hourly = setInterval(() => void queue.send(JOBS.valuationRebuild, { all: false }, { singletonKey: 'valuation:hourly', singletonSeconds: 3000 }), 3600_000);147  log.info({ concurrency }, 'worker started');148149  return async () => {150    clearInterval(timer);151    clearInterval(hourly);152    await queue.stop();153    await flushCosts();154    await closeDb();155    log.info('worker stopped');156  };157}158159const isMain = process.argv[1] && /workers\/main\.ts$/.test(process.argv[1]);160if (isMain) {161  startWorker()162    .then((stop) => {163      const shutdown = () => void stop().then(() => process.exit(0));164      process.on('SIGINT', shutdown);165      process.on('SIGTERM', shutdown);166    })167    .catch((err) => {168      logger.error({ err }, 'worker failed to start');169      process.exit(1);170    });171}172
Files · f5091c0a3f32b0f99bc705c36f16b636342fbdb4
Menu

Theme