Stop losing notifications on Olist/n8n hiccups and redeploys
- Olist lookups: 20s timeout so one hung request can't stall the serial queue; retry temporary failures (codigo_erro 6/11/35/99, timeouts, 5xx) with backoff instead of forwarding orders without phone or forma_envio. Log "[Notification at risk]" when that still happens. - n8n forwarding: timeout plus retries, only when n8n certainly didn't run the workflow (connection refused, 502/503, 404 while restarting), so retries can't send a customer the same WhatsApp twice. Stop logging the start of N8N_AUTH_TOKEN. - On SIGTERM, stop accepting requests and finish webhooks already acked to Tiny (up to SHUTDOWN_GRACE_MS, default 50s). - Keep stock_memory.json and stock_log.csv on the data-runtime volume so stock stats survive redeploys. - Add a node:test suite (npm test) covering the payload n8n reads, the status cache, burst queueing, retries, stock files and shutdown drain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,10 +1,32 @@
|
||||
import { Router } from 'express';
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { handleTinyOrderUpdate, handleTinyStockUpdate, handleTinyGraphsUpdate } from '../controllers/webhook.controller';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post('/tiny/order-status', handleTinyOrderUpdate);
|
||||
router.post('/tiny/stock-update', handleTinyStockUpdate);
|
||||
router.post('/tiny/graphs-update', handleTinyGraphsUpdate);
|
||||
// Handlers ack Tiny first and keep working afterwards (queue, lookup, n8n forward).
|
||||
// Track that work so a shutdown can finish it instead of dropping notifications.
|
||||
const pendingWork = new Set<Promise<void>>();
|
||||
|
||||
export default router;
|
||||
const tracked = (handler: (req: Request, res: Response) => Promise<void>) => (req: Request, res: Response) => {
|
||||
const work: Promise<void> = handler(req, res).finally(() => pendingWork.delete(work));
|
||||
pendingWork.add(work);
|
||||
return work;
|
||||
};
|
||||
|
||||
// Resolves once all in-flight webhook work is done or the timeout passes; returns how many are left.
|
||||
export async function drainWebhookWork(timeoutMs: number): Promise<number> {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<void>(resolve => { timer = setTimeout(resolve, timeoutMs); });
|
||||
while (pendingWork.size > 0) {
|
||||
const done = await Promise.race([Promise.allSettled([...pendingWork]).then(() => true), timeout.then(() => false)]);
|
||||
if (!done) break;
|
||||
}
|
||||
clearTimeout(timer);
|
||||
return pendingWork.size;
|
||||
}
|
||||
|
||||
router.post('/tiny/order-status', tracked(handleTinyOrderUpdate));
|
||||
router.post('/tiny/stock-update', tracked(handleTinyStockUpdate));
|
||||
router.post('/tiny/graphs-update', tracked(handleTinyGraphsUpdate));
|
||||
|
||||
export default router;
|
||||
|
||||
Reference in New Issue
Block a user