import { Injectable, Logger, OnApplicationBootstrap, OnModuleDestroy, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { AppConfig } from '../config/app-config.schema.js'; import { MetricsService } from '../metrics/metrics.service.js'; import { BrokerClient } from './broker.client.js'; import { FaultInjector } from './fault-injector.js'; import { JobsRepository } from './jobs.repository.js'; const BATCH_SIZE = 100; /** * Runs only in the API process. `publishPending` holds one transaction around * the broker confirms and the `published_at` update; a crash before the mark * rolls the transaction back and republishes the same message after restart. * That duplicate is expected: the worker fences it on job status. */ @Injectable() export class OutboxRelay implements OnApplicationBootstrap, OnModuleDestroy { private readonly logger = new Logger(OutboxRelay.name); private timer: NodeJS.Timeout | undefined; private running = false; private again = false; private current: Promise | undefined; private failing = false; constructor( private readonly config: ConfigService, private readonly repository: JobsRepository, private readonly broker: BrokerClient, private readonly faults: FaultInjector, private readonly metrics: MetricsService, ) {} onApplicationBootstrap(): void { const interval = this.config.getOrThrow('OUTBOX_POLL_INTERVAL_MS'); this.timer = setInterval(() => this.kick(), interval); this.timer.unref(); this.kick(); } async onModuleDestroy(): Promise { clearInterval(this.timer); this.timer = undefined; await this.current; } kick(): void { if (this.running) { this.again = true; return; } this.running = true; this.current = this.drain() .catch((error: unknown) => { this.metrics.increment('outbox.publish_failed'); if (!this.failing) { this.failing = true; this.logger.warn( `Outbox publish failed: ${error instanceof Error ? error.message : 'unknown error'}`, ); } }) .finally(() => { this.running = false; this.current = undefined; if (this.again) { this.again = false; this.kick(); } }); } private async drain(): Promise { const published = await this.repository.publishPending( BATCH_SIZE, (message) => this.broker.publish(message), () => this.faults.point('relay.after_publish_before_mark'), ); if (published > 0) { this.metrics.add('outbox.published', published); if (this.failing) { this.failing = false; this.logger.log('Outbox publishing recovered'); } } } }