import type { Request, Response, NextFunction } from 'express'; import { logger } from '../utils/logger'; export interface ErrorSimulationConfig { enabled: boolean; errorRate: number; // 0-1, percentage of requests that should error errorTypes: { '402': number; // out of credits '401': number; // authentication failed '403': number; // forbidden '422': number; // validation error '429': number; // rate limit '404': number; // not found '500': number; // internal server error '502': number; // bad gateway '503': number; // service unavailable }; } const defaultConfig: ErrorSimulationConfig = { enabled: process.env.ERROR_SIMULATION_ENABLED === 'true', errorRate: parseFloat(process.env.ERROR_RATE || '0.1'), // 10% default errorTypes: { '402': 0.25, // 25% of errors are 402 '401': 0.15, // 15% of errors are 401 '403': 0.1, // 10% of errors are 403 '422': 0.1, // 10% of errors are 422 '429': 0.15, // 15% of errors are 429 '404': 0.15, // 15% of errors are 404 '500': 0.05, // 5% of errors are 500 '502': 0.03, // 3% of errors are 502 '503': 0.02 // 2% of errors are 503 } }; export class ErrorSimulator { private static config: ErrorSimulationConfig = defaultConfig; static setConfig(config: Partial): void { this.config = { ...this.config, ...config }; logger.info('Error simulation config updated', { config: this.config }); } static getConfig(): ErrorSimulationConfig { return this.config; } static shouldInjectError(): boolean { if (!this.config.enabled) return false; return Math.random() < this.config.errorRate; } static getRandomErrorType(): '402' | '401' | '403' | '422' | '429' | '404' | '500' | '502' | '503' { const rand = Math.random(); let cumulative = 0; for (const [errorType, probability] of Object.entries(this.config.errorTypes)) { cumulative += probability; if (rand < cumulative) { return errorType as '402' | '401' | '429' | '404' | '500'; } } return '500'; // fallback } static generateErrorResponse(errorType: '402' | '401' | '403' | '422' | '429' | '404' | '500' | '502' | '503'): { status: number; body: unknown } { const timestamp = new Date().toISOString(); switch (errorType) { case '402': return { status: 402, body: { error: 'out_of_conversational_credits', message: 'You have run out of conversational credits. Please upgrade your plan.', status_code: 402, timestamp } }; case '401': return { status: 401, body: { error: 'authentication_failed', message: 'Invalid API key or authentication credentials.', status_code: 401, timestamp } }; case '429': return { status: 429, body: { error: 'rate_limit_exceeded', message: 'Rate limit exceeded. Please try again later.', status_code: 429, retry_after: Math.floor(Math.random() * 60) + 30, // 30-90 seconds timestamp } }; case '404': return { status: 404, body: { error: 'resource_not_found', message: 'The requested resource was not found.', status_code: 404, timestamp } }; case '403': return { status: 403, body: { error: 'forbidden', message: 'Access denied. You do not have permission to access this resource.', status_code: 403, timestamp } }; case '422': return { status: 422, body: { error: 'validation_error', message: 'The request data is invalid or malformed.', status_code: 422, timestamp } }; case '500': return { status: 500, body: { error: 'internal_server_error', message: 'An unexpected error occurred. Please try again.', status_code: 500, timestamp } }; case '502': return { status: 502, body: { error: 'bad_gateway', message: 'Bad gateway. The server received an invalid response from an upstream server.', status_code: 502, timestamp } }; case '503': return { status: 503, body: { error: 'service_unavailable', message: 'Service temporarily unavailable. Please try again later.', status_code: 503, timestamp } }; default: return { status: 500, body: { error: 'unknown_error', message: 'An unknown error occurred.', status_code: 500, timestamp } }; } } } export const errorSimulationMiddleware = (req: Request, res: Response, _next: NextFunction): void => { // Check for header-based error simulation first const simulateError = req.headers['x-simulate-error']; if (simulateError) { const errorType = simulateError as string; const errorResponse = ErrorSimulator.generateErrorResponse(errorType as '402' | '401' | '403' | '422' | '429' | '404' | '500' | '502' | '503'); logger.info('Injecting header-based simulated error', { method: req.method, url: req.url, errorType, status: errorResponse.status }); res.status(errorResponse.status).json(errorResponse.body); return; } // Fall back to random error injection if (ErrorSimulator.shouldInjectError()) { const errorType = ErrorSimulator.getRandomErrorType(); const errorResponse = ErrorSimulator.generateErrorResponse(errorType); logger.info('Injecting simulated error', { method: req.method, url: req.url, errorType, status: errorResponse.status }); res.status(errorResponse.status).json(errorResponse.body); return; } next(); };