SPB Git

spb/rareindex

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

Theme