/** * LandveX Gateway — HTTP Proxy * Routes requests to backend services */ import http from 'http'; export function proxyRequest(req, res, target) { const options = { hostname: target.host, port: target.port, path: req.url, method: req.method, headers: { ...req.headers, host: `${target.host}:${target.port}`, }, timeout: 30000, }; const proxyReq = http.request(options, (proxyRes) => { res.writeHead(proxyRes.statusCode || 500, proxyRes.headers); proxyRes.pipe(res); }); proxyReq.on('error', (err) => { console.error(`[PROXY ERROR] ${target.name}: ${err.message}`); res.statusCode = 502; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ error: 'Bad Gateway', service: target.name, message: err.message, })); }); proxyReq.on('timeout', () => { proxyReq.destroy(); res.statusCode = 504; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ error: 'Gateway Timeout', service: target.name, message: 'Request timed out', })); }); req.pipe(proxyReq); } export async function checkServiceHealth(service) { const start = Date.now(); return new Promise((resolve) => { const req = http.request({ hostname: service.host, port: service.port, path: service.healthPath, method: 'GET', timeout: 5000, }, (res) => { resolve({ healthy: res.statusCode === 200, latency: Date.now() - start, }); }); req.on('error', (err) => { resolve({ healthy: false, latency: Date.now() - start, error: err.message, }); }); req.on('timeout', () => { req.destroy(); resolve({ healthy: false, latency: Date.now() - start, error: 'Timeout', }); }); req.end(); }); }