CognxSafeTrack commited on
Commit Β·
70901bb
1
Parent(s): aa52c48
fix(stt): resolve post-transcription silence and harden gateway detection
Browse filesFiles changed (3)
141 unmodified lines142143144145146147148149150151152153154155156141 unmodified lines}}, async (request, reply) => {const { phone, text, audioUrl } = request.body;if (!phone || text === undefined) {return reply.code(400).send({ error: 'phone and text are required' });}// Fire and await - ensuring the worker knows if it failedtry {await WhatsAppService.handleIncomingMessage(phone, text, audioUrl);} catch (err: any) {request.log.error(`[INTERNAL] handleIncomingMessage error: ${err.message}`);return reply.code(500).send({ error: err.message });}141 unmodified lines142143144145146147148149150151152153154155156157158159160161162141 unmodified lines}}, async (request, reply) => {const { phone, text, audioUrl } = request.body;const traceId = `[INTERNAL-TX-${phone.slice(-4)}]`;if (!phone || text === undefined) {request.log.warn(`${traceId} Missing phone or text in handle-message request`);return reply.code(400).send({ error: 'phone and text are required' });}request.log.info(`${traceId} Received transcribed text: "${text.substring(0, 100)}..."`);// Fire and await - ensuring the worker knows if it failedtry {await WhatsAppService.handleIncomingMessage(phone, text, audioUrl);request.log.info(`${traceId} Successfully processed message`);} catch (err: any) {request.log.error(`${traceId} handleIncomingMessage error: ${err.message}`);return reply.code(500).send({ error: err.message });}
112 unmodified lines1131141151161171181192 unmodified lines12212312412512612712810 unmodified lines139140141142143144145112 unmodified lines// ββ 2. Forward to Railway Internal Worker (if configured as Gateway) ββconst railwayInternalUrl = process.env.RAILWAY_INTERNAL_URL;const isGateway = process.env.IS_GATEWAY === 'true' || process.env.HF_SPACE_ID !== undefined;if (railwayInternalUrl && isGateway) {// Loop protection: don't forward to yourself2 unmodified linesrequest.log.warn('[WEBHOOK] Loop detected: RAILWAY_INTERNAL_URL matches self. Skipping forward.');} else {const targetUrl = `${railwayInternalUrl.replace(/\/$/, '')}/v1/internal/whatsapp/inbound`;request.log.info(`[WEBHOOK] Gateway Mode: Forwarding payload to ${targetUrl}`);try {// Fire and forget (don't await) to ensure fast 200 response to Meta10 unmodified linesrequest.log.error(`[WEBHOOK] Forward to Railway failed: ${err.message}`);});// π¨ CRITICAL: CRUCIAL EXIT POINTreturn reply.code(200).send('EVENT_RECEIVED');} catch (error: any) {request.log.error(`[WEBHOOK] Forward throwing error: ${error?.message}`);112 unmodified lines1131141151161171181191201211221231241251261271282 unmodified lines13113213313413513613710 unmodified lines148149150151152153154112 unmodified lines// ββ 2. Forward to Railway Internal Worker (if configured as Gateway) ββconst railwayInternalUrl = process.env.RAILWAY_INTERNAL_URL;// Hardened Gateway Detection:// We are a gateway if:// 1. IS_GATEWAY is explicitly true// 2. We are running on Hugging Face (HF_SPACE_ID exists)// 3. We have a RAILWAY_INTERNAL_URL but NOT a RAILWAY_STATIC_URL (not on Railway)const isGateway =process.env.IS_GATEWAY === 'true' ||process.env.HF_SPACE_ID !== undefined ||(!!railwayInternalUrl && !process.env.RAILWAY_STATIC_URL);if (railwayInternalUrl && isGateway) {// Loop protection: don't forward to yourself2 unmodified linesrequest.log.warn('[WEBHOOK] Loop detected: RAILWAY_INTERNAL_URL matches self. Skipping forward.');} else {const targetUrl = `${railwayInternalUrl.replace(/\/$/, '')}/v1/internal/whatsapp/inbound`;request.log.info(`[WEBHOOK] GATEWAY MODE: Forwarding payload to ${targetUrl}`);try {// Fire and forget (don't await) to ensure fast 200 response to Meta10 unmodified linesrequest.log.error(`[WEBHOOK] Forward to Railway failed: ${err.message}`);});// π¨ CRITICAL: CRUCIAL EXIT POINT FOR GATEWAYreturn reply.code(200).send('EVENT_RECEIVED');} catch (error: any) {request.log.error(`[WEBHOOK] Forward throwing error: ${error?.message}`);
509 unmodified lines5105115125135145155161 unmodified line518519520521522523524509 unmodified linesconst traceId = `[STT-FLOW-${phone.slice(-4)}]`;console.log(`${traceId} Forwarding to API handle-message...`);const handleRes = await fetch(`${AI_API_BASE_URL.replace(/\/$/, "")}/v1/internal/handle-message`, {method: 'POST',headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },body: JSON.stringify({ phone, text: transcribedText, audioUrl })1 unmodified lineif (!handleRes.ok) {const errText = await handleRes.text();console.error(`${traceId} API handle-message failed: ${errText}`);throw new Error(`API handle-message failed: ${handleRes.status}`);}console.log(`${traceId} API handle-message success.`);509 unmodified lines5105115125135145155165175185195205215225235245255265275285295305311 unmodified line533534535536537538539509 unmodified linesconst traceId = `[STT-FLOW-${phone.slice(-4)}]`;console.log(`${traceId} Forwarding to API handle-message...`);// βββ Port Hardening: Handle HF Space 7860 vs Local 8080 βββββββββlet finalApiUrl = AI_API_BASE_URL.replace(/\/$/, "");if (finalApiUrl.includes('localhost:8080')) {try {// Quick check if 8080 is up, if not assume 7860 (Hugging Face)const pingRes = await fetch('http://localhost:8080/health').catch(() => null);if (!pingRes || !pingRes.ok) {console.log(`${traceId} Local port 8080 not responding, trying 7860 (HF Default)...`);finalApiUrl = finalApiUrl.replace('8080', '7860');}} catch (e) {finalApiUrl = finalApiUrl.replace('8080', '7860');}}const handleRes = await fetch(`${finalApiUrl}/v1/internal/handle-message`, {method: 'POST',headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },body: JSON.stringify({ phone, text: transcribedText, audioUrl })1 unmodified lineif (!handleRes.ok) {const errText = await handleRes.text();console.error(`${traceId} API handle-message failed (HTTP ${handleRes.status}): ${errText}`);throw new Error(`API handle-message failed: ${handleRes.status}`);}console.log(`${traceId} API handle-message success.`);
apps/api/src/routes/internal.ts+7-1
apps/api/src/routes/whatsapp.ts+12-3
apps/whatsapp-worker/src/index.ts+17-2