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 const concurrency = env().WORKER_CONCURRENCY;3031 // ---- handlers ----32 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) => {33 const res = await runCrawl(data.connectorId, { mode: data.mode ?? 'incremental', limit: data.limit, trigger: data.trigger ?? 'schedule' });34 if (res.recordsRaw > 0) await queue.send(JOBS.normalizeBatch, { connectorId: data.connectorId }, { singletonKey: `normalize:${data.connectorId}`, singletonSeconds: 30 });35 });36 await queue.work<{ connectorId?: string }>(JOBS.normalizeBatch, { concurrency: 2, pollingIntervalSeconds: 5 }, async (data) => {37 let total = 0;38 for (let i = 0; i < 40; i++) {39 const r = await normalizeBatch({ connectorId: data.connectorId, limit: 500 });40 total += r.processed;41 if (r.processed < 500) break;42 }43 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 });44 });45 const RESOLVE_WORKERS = Number(process.env.RESOLVE_CONCURRENCY ?? 3);46 // Release rows claimed by a previous worker process that died mid-batch.47 await db().execute(sql`update normalized_records set status = 'pending' where status = 'processing'`);48 await queue.work<Record<string, never>>(JOBS.resolveBatch, { concurrency: RESOLVE_WORKERS, pollingIntervalSeconds: 5 }, async () => {49 const touched = new Set<string>();50 for (let i = 0; i < 40; i++) {51 const r = await resolveBatch({ limit: 500 });52 for (const a of r.touchedAssets) touched.add(a);53 if (r.processed < 500) break;54 }55 if ((await pendingCount()) > 0) for (let k = 0; k < RESOLVE_WORKERS; k++) await queue.send(JOBS.resolveBatch, {}, { singletonKey: `resolve:${k}`, singletonSeconds: 30, startAfterSeconds: 5 });56 if (touched.size) await queue.send(JOBS.valuationAsset, { assetIds: [...touched].slice(0, 5000) }, { singletonKey: `value:${Date.now()}` });57 });58 await queue.work<{ assetIds: string[] }>(JOBS.valuationAsset, { concurrency: 1, pollingIntervalSeconds: 5 }, async (data) => {59 await valueMany(data.assetIds, { concurrency: 4 });60 });61 await queue.work<{ all?: boolean; rebuildHistory?: boolean }>(JOBS.valuationRebuild, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {62 await computePremiums();63 const ids = await assetsNeedingValuation({ all: data.all, limit: 200_000 });64 await valueMany(ids, { rebuildHistory: data.rebuildHistory, concurrency: 4 });65 });66 await queue.work(JOBS.indicesDaily, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {67 await runIndices();68 });69 await queue.work(JOBS.snapshotsDaily, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {70 await runCategorySnapshots();71 });72 await queue.work(JOBS.radarScan, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {73 await runRadar();74 });75 await queue.work(JOBS.healthCompute, { concurrency: 1, pollingIntervalSeconds: 30 }, async () => {76 await computeHealth();77 });78 await queue.work<{ backfill?: boolean }>(JOBS.fxSync, { concurrency: 1, pollingIntervalSeconds: 30 }, async (data) => {79 await syncFx({ backfill: data.backfill });80 });81 await queue.work(JOBS.benchmarksSync, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {82 await syncBenchmarks();83 });84 await queue.work(JOBS.listingsExpire, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {85 await expireListings();86 });87 await queue.work(JOBS.accountJobs, { concurrency: 1, pollingIntervalSeconds: 60 }, async () => {88 try {89 const accountModule = './account/index.ts'; // provided by the account module when present90 const mod = (await import(accountModule)) as { runAccountJobs?: (d: ReturnType<typeof db>) => Promise<unknown> };91 if (mod.runAccountJobs) await mod.runAccountJobs(db());92 } catch (err) {93 if (!/Cannot find module|ERR_MODULE_NOT_FOUND/.test(String(err))) log.error({ err }, 'account jobs failed');94 }95 });9697 // ---- schedules (UTC) ----98 await queue.schedule(JOBS.fxSync, '15 16 * * 1-5', {}); // after ECB 16:00 CET publication99 await queue.schedule(JOBS.benchmarksSync, '30 22 * * *', {});100 await queue.schedule(JOBS.valuationRebuild, '0 3 * * *', { all: false });101 await queue.schedule(JOBS.snapshotsDaily, '20 4 * * *', {});102 await queue.schedule(JOBS.indicesDaily, '40 4 * * *', {});103 await queue.schedule(JOBS.radarScan, '0 5 * * *', {});104 await queue.schedule(JOBS.healthCompute, '*/30 * * * *', {});105 await queue.schedule(JOBS.listingsExpire, '10 * * * *', {});106 await queue.schedule(JOBS.accountJobs, '*/10 * * * *', {});107108 // ---- crawl scheduler loop ----109 const tick = async () => {110 try {111 await scheduleDueCrawls(queue);112 } catch (err) {113 log.error({ err }, 'scheduler tick failed');114 }115 };116 await tick();117 const timer = setInterval(tick, 60_000);118 // hourly incremental valuation for assets with fresh evidence119 const hourly = setInterval(() => void queue.send(JOBS.valuationRebuild, { all: false }, { singletonKey: 'valuation:hourly', singletonSeconds: 3000 }), 3600_000);120 log.info({ concurrency }, 'worker started');121122 return async () => {123 clearInterval(timer);124 clearInterval(hourly);125 await queue.stop();126 await flushCosts();127 await closeDb();128 log.info('worker stopped');129 };130}131132const isMain = process.argv[1] && /workers\/main\.ts$/.test(process.argv[1]);133if (isMain) {134 startWorker()135 .then((stop) => {136 const shutdown = () => void stop().then(() => process.exit(0));137 process.on('SIGINT', shutdown);138 process.on('SIGTERM', shutdown);139 })140 .catch((err) => {141 logger.error({ err }, 'worker failed to start');142 process.exit(1);143 });144}145