import { Inject, Injectable, Logger, Optional } 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 { RedisClient } from '../redis/redis.client.js'; export type FaultPoint = | 'api.after_commit_before_publish' | 'relay.after_publish_before_mark' | 'worker.before_side_effect' | 'worker.after_side_effect' | 'worker.after_commit_before_ack'; export type FaultTarget = { attachmentId: string; pipelineVersion: number; }; export type FaultKind = 'permanent' | 'transient'; // Node timers overflow above 2^31-1 ms and fire immediately. const MAX_TIMER_MS = 2_147_483_647; export class InjectedFaultError extends Error { constructor(readonly kind: FaultKind) { super(`Injected ${kind} fault`); this.name = 'InjectedFaultError'; } } /** * Active only with FAULT_INJECTION_ENABLED=1. The switch is deliberately * checked before every Redis call so a normal stand never depends on Redis for * job correctness. * * `transient` stays until the key is deleted; every other value is consumed by * the first point that observes it. Worker points are addressed to one * attachment and pipeline version; the untargeted key is a fallback. */ @Injectable() export class FaultInjector { private readonly logger = new Logger(FaultInjector.name); private readonly enabled: boolean; constructor( config: ConfigService, @Optional() @Inject(RedisClient) private readonly redis: RedisClient | undefined, private readonly metrics: MetricsService, ) { this.enabled = config.getOrThrow('FAULT_INJECTION_ENABLED') === 1; } async point( name: FaultPoint, target?: FaultTarget, signal?: AbortSignal, ): Promise { if (!this.enabled || !this.redis) return; const keys = target ? [ `fault:${name}:${target.attachmentId}:${target.pipelineVersion}`, `fault:${name}`, ] : [`fault:${name}`]; for (const key of keys) { let value: string | null; let deleted: number; try { value = await this.redis.get(key); if (value === null) continue; if (value === 'transient') { this.metrics.increment('faults.triggered'); throw new InjectedFaultError('transient'); } deleted = await this.redis.del(key); } catch (error) { if (error instanceof InjectedFaultError) throw error; this.logger.warn( `Fault point ${name} could not read Redis: ${error instanceof Error ? error.message : 'unknown error'}`, ); return; } if (deleted !== 1) continue; // The action is outside the Redis try/catch: an abort or an injected // fault must reach the job processor, not be logged as an outage. await this.act(value, signal); return; } } private async act(value: string, signal?: AbortSignal): Promise { if (value === 'crash') { this.metrics.increment('faults.triggered'); // PID 1 in a container namespace may not be killable by SIGKILL; // exit 137 gives the same observable crash (no graceful shutdown). process.kill(process.pid, 'SIGKILL'); process.exit(137); } if (value === 'permanent') { this.metrics.increment('faults.triggered'); throw new InjectedFaultError('permanent'); } if (value.startsWith('delay:')) { const milliseconds = Number(value.slice('delay:'.length)); if (!Number.isFinite(milliseconds) || milliseconds < 0) return; this.metrics.increment('faults.triggered'); await this.sleep(Math.min(milliseconds, MAX_TIMER_MS), signal); } } private sleep(milliseconds: number, signal?: AbortSignal): Promise { if (signal?.aborted) return Promise.reject( signal.reason instanceof Error ? signal.reason : new Error('Aborted'), ); const { promise, resolve, reject } = Promise.withResolvers(); const timer = setTimeout(() => { signal?.removeEventListener('abort', cancel); resolve(); }, milliseconds); const cancel = (): void => { clearTimeout(timer); reject( signal?.reason instanceof Error ? signal.reason : new Error('Aborted'), ); }; signal?.addEventListener('abort', cancel, { once: true }); return promise; } }