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