voko-worker-main.js 1.12 KB
/**
 * `voko-worker` 进程入口:每 2 秒领取并执行到期的 vk_jobs,并投递到期的 Webhook(见 SDD「定时任务与事件」)。
 */

import { createRuntime } from './assembly/runtime.js'

const TICK_MS = 2000
const HEARTBEAT_EVERY_TICKS = 30

const runtime = await createRuntime({ service: '@voko/worker' })
let ticks = 0
let stopping = false

async function tick() {
  await runtime.services.jobs.runDue({})
  await runtime.services.webhooks.deliverDue({})
  ticks += 1
  if (ticks % HEARTBEAT_EVERY_TICKS === 1) {
    await runtime.services.jobs.ensureDaily({})
    await runtime.services.scheduleDigests({})
  }
  if (ticks % HEARTBEAT_EVERY_TICKS === 0) runtime.logger.info('worker 心跳', { ticks })
}

async function loop() {
  while (!stopping) {
    await tick()
    await new Promise((resolve) => setTimeout(resolve, TICK_MS))
  }
  await runtime.close()
}

runtime.logger.info('worker 已启动', { tick_ms: TICK_MS })
process.once('SIGINT', () => { stopping = true })
process.once('SIGTERM', () => { stopping = true })
loop().catch((err) => {
  console.error('voko-worker crashed:', err)
  process.exit(1)
})