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:
Cauê Faleiros
2026-10-08 15:12:09 -03:00
parent 54ffbe1b04
commit 4fe5830f8f
10 changed files with 500 additions and 33 deletions

89
test/helpers.ts Normal file
View File

@@ -0,0 +1,89 @@
import axios from 'axios';
// Each test file runs in its own process; set env before requiring app modules,
// since they read their config at load time.
export function setTestEnv(overrides: Record<string, string>) {
delete process.env.TINY_WEBHOOK_SECRET;
delete process.env.N8N_WEBHOOK_GRAPHS;
delete process.env.GRAPHS_API_URL;
delete process.env.NEXSTAR_GRAPHS_API_URL;
delete process.env.TINY_LIVE_MAX_QUEUE_WAIT_MS;
Object.assign(process.env, {
TINY_API_TOKEN: 'mock-token',
N8N_WEBHOOK_STATUS: 'http://n8n.test/status',
TINY_LIVE_REQUEST_DELAY_MS: '0',
TINY_LOOKUP_RETRY_DELAY_MS: '5',
N8N_RETRY_DELAY_MS: '5',
...overrides
});
}
export type PostCall = { url: string; data: any };
type PostHandler = (url: string, data: any) => Promise<any>;
// Replaces axios.post for the whole process. Returns the recorded calls.
export function mockAxiosPost(handler: PostHandler): PostCall[] {
const calls: PostCall[] = [];
(axios as any).post = async (url: string, data: any) => {
calls.push({ url, data });
return handler(url, data);
};
return calls;
}
export function tinyOrder(id: string, overrides: Record<string, any> = {}) {
return {
data: {
retorno: {
status: 'OK',
status_processamento: '3',
pedido: {
id,
numero: '140255',
numero_ecommerce: '39BAECDB7D',
data_pedido: '08/10/2026',
data_prevista: '08/10/2026',
cliente: { nome: 'Cliente Teste', celular: '(16) 99999-0000', email: 'cliente@test' },
total_pedido: '136.49',
id_vendedor: '977231477',
nome_vendedor: 'Lais Sousa Da Silva',
situacao: 'Pronto para envio',
forma_envio: 'X',
codigo_rastreamento: '',
url_rastreamento: '',
itens: [{ item: { codigo: 'BLCS.PTO.G1' } }],
...overrides
}
}
}
};
}
export function tinyError(codigo: string, erro: string) {
return { data: { retorno: { status: 'Erro', codigo_erro: codigo, erros: [{ erro }] } } };
}
export function axiosError(code: string, status?: number) {
const error: any = new Error(status ? `Request failed with status code ${status}` : code);
error.code = code;
if (status) error.response = { status, data: {} };
return error;
}
export const fakeRes = () => ({ status() { return this; }, send() { return this; }, json() { return this; } }) as any;
export const orderWebhook = (id: string | number, codigoSituacao: string, descricaoSituacao: string) => ({
query: {},
body: { dados: { id, codigoSituacao, descricaoSituacao } }
}) as any;
export const isTinyCall = (url: string) => url.includes('api.tiny.com.br');
export function silenceConsole() {
const original = { log: console.log, warn: console.warn, error: console.error };
const warnings: string[] = [];
console.log = () => {};
console.warn = (...args: any[]) => { warnings.push(args.join(' ')); };
console.error = (...args: any[]) => { warnings.push(args.join(' ')); };
return { warnings, restore: () => Object.assign(console, original) };
}

27
test/live-queue.test.ts Normal file
View File

@@ -0,0 +1,27 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { setTestEnv, mockAxiosPost, tinyOrder, fakeRes, orderWebhook, isTinyCall, silenceConsole } from './helpers';
// Real spacing between Olist calls, default max queue wait.
setTestEnv({ TINY_LIVE_REQUEST_DELAY_MS: '250' });
const { handleTinyOrderUpdate } = require('../src/controllers/webhook.controller');
const calls = mockAxiosPost(async (url, data) => {
if (!isTinyCall(url)) return { status: 200, data: {} };
return tinyOrder(new URLSearchParams(data.toString()).get('id')!);
});
test('a burst of webhooks is queued and every order is forwarded with Olist data', async () => {
const capture = silenceConsole();
try {
const ids = [1, 2, 3, 4, 5, 6, 7, 8].map(i => 2000 + i);
await Promise.all(ids.map(id => handleTinyOrderUpdate(orderWebhook(id, 'pronto_envio', 'Pronto para envio'), fakeRes())));
const forwarded = calls.filter(c => !isTinyCall(c.url)).map(c => c.data);
assert.equal(forwarded.length, ids.length);
assert.ok(forwarded.every(p => p.fone && p.forma_envio === 'X'), 'every order keeps phone and forma_envio');
assert.ok(!capture.warnings.some(w => w.includes('too busy')), 'no order skipped the Olist lookup');
} finally {
capture.restore();
}
});

51
test/n8n-service.test.ts Normal file
View File

@@ -0,0 +1,51 @@
import { test, before, after, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import { setTestEnv, mockAxiosPost, axiosError, silenceConsole } from './helpers';
setTestEnv({});
const { sendToN8n } = require('../src/services/n8n.service');
let responses: Array<() => any> = [];
const calls = mockAxiosPost(async () => {
const next = responses.shift();
return next ? next() : { status: 200, data: {} };
});
let capture: ReturnType<typeof silenceConsole>;
before(() => { capture = silenceConsole(); });
after(() => capture.restore());
beforeEach(() => { calls.length = 0; responses = []; });
const fail = (code: string, status?: number) => () => { throw axiosError(code, status); };
test('retries when n8n refuses the connection (n8n restarting)', async () => {
responses = [fail('ECONNREFUSED')];
await sendToN8n({ id: 1 }, 'http://n8n.test/status');
assert.equal(calls.length, 2);
});
test('retries when the proxy says n8n is down (502/503)', async () => {
responses = [fail('ERR_BAD_RESPONSE', 502), fail('ERR_BAD_RESPONSE', 503)];
await sendToN8n({ id: 1 }, 'http://n8n.test/status');
assert.equal(calls.length, 3);
});
test('retries 404 while n8n has not registered the webhook yet, up to the max attempts', async () => {
responses = [1, 2, 3, 4, 5, 6].map(() => fail('ERR_BAD_REQUEST', 404));
await sendToN8n({ id: 1 }, 'http://n8n.test/status');
assert.equal(calls.length, 5);
});
test('does not retry when n8n may already have received the request', async () => {
for (const failure of [fail('ECONNABORTED'), fail('ECONNRESET'), fail('ERR_BAD_RESPONSE', 504), fail('ERR_BAD_RESPONSE', 500), fail('ERR_BAD_REQUEST', 400)]) {
calls.length = 0;
responses = [failure];
await sendToN8n({ id: 1 }, 'http://n8n.test/status');
assert.equal(calls.length, 1);
}
});
test('sends once when n8n answers', async () => {
await sendToN8n({ id: 1 }, 'http://n8n.test/status');
assert.equal(calls.length, 1);
});

102
test/order-webhook.test.ts Normal file
View File

@@ -0,0 +1,102 @@
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { setTestEnv, mockAxiosPost, tinyOrder, tinyError, axiosError, fakeRes, orderWebhook, isTinyCall, silenceConsole } from './helpers';
setTestEnv({});
const { handleTinyOrderUpdate } = require('../src/controllers/webhook.controller');
let tinyResponses: Record<string, Array<() => any>> = {};
const calls = mockAxiosPost(async (url, data) => {
if (!isTinyCall(url)) return { status: 200, data: {} };
const id = new URLSearchParams(data.toString()).get('id')!;
const next = tinyResponses[id]?.shift();
if (!next) throw new Error(`No mocked Tiny response left for order ${id}`);
return next();
});
const tinyCallsFor = (id: string) => calls.filter(c => isTinyCall(c.url) && new URLSearchParams(c.data.toString()).get('id') === id);
const forwardedFor = (id: string) => calls.filter(c => !isTinyCall(c.url) && String(c.data.id) === id).map(c => c.data);
let consoleCapture: ReturnType<typeof silenceConsole>;
before(() => { consoleCapture = silenceConsole(); });
after(() => consoleCapture.restore());
test('forwards the flat payload n8n relies on', async () => {
tinyResponses['1001'] = [() => tinyOrder('1001')];
await handleTinyOrderUpdate(orderWebhook(1001, 'pronto_envio', 'Pronto para envio'), fakeRes());
const [payload] = forwardedFor('1001');
assert.deepEqual(Object.keys(payload), [
'id', 'numero', 'numero_ecommerce', 'data_pedido', 'data_prevista', 'nome', 'valor', 'id_vendedor',
'nome_vendedor', 'whatsapp_vendedor', 'situacao', 'fone', 'email', 'status_processamento',
'forma_envio', 'codigo_rastreamento', 'url_rastreamento', 'itens'
]);
assert.equal(payload.situacao, 'Pronto para envio');
assert.equal(payload.forma_envio, 'X');
assert.equal(payload.fone, '(16) 99999-0000');
assert.equal(payload.numero_ecommerce, '39BAECDB7D');
assert.equal(payload.valor, 136.49);
});
test('a status change minutes later refetches instead of reusing the old status', async () => {
tinyResponses['1002'] = [
() => tinyOrder('1002', { situacao: 'Preparando envio' }),
() => tinyOrder('1002', { situacao: 'Pronto para envio' })
];
await handleTinyOrderUpdate(orderWebhook(1002, 'preparando_envio', 'Preparando envio'), fakeRes());
await handleTinyOrderUpdate(orderWebhook(1002, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.deepEqual(forwardedFor('1002').map(p => p.situacao), ['Preparando envio', 'Pronto para envio']);
assert.equal(tinyCallsFor('1002').length, 2);
});
test('a same-status duplicate webhook reuses the cached lookup', async () => {
tinyResponses['1003'] = [() => tinyOrder('1003')];
await handleTinyOrderUpdate(orderWebhook(1003, 'pronto_envio', 'Pronto para envio'), fakeRes());
await handleTinyOrderUpdate(orderWebhook(1003, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1003').length, 1);
assert.equal(forwardedFor('1003').length, 2);
});
test('retries when Olist rate-limits the lookup (codigo_erro 6)', async () => {
tinyResponses['1004'] = [
() => tinyError('6', 'API bloqueada momentaneamente - muitos acessos no último minuto'),
() => tinyOrder('1004')
];
await handleTinyOrderUpdate(orderWebhook(1004, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1004').length, 2);
assert.equal(forwardedFor('1004')[0].fone, '(16) 99999-0000');
});
test('retries when the Olist request times out', async () => {
tinyResponses['1005'] = [
() => { throw axiosError('ECONNABORTED'); },
() => tinyOrder('1005')
];
await handleTinyOrderUpdate(orderWebhook(1005, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1005').length, 2);
assert.equal(forwardedFor('1005')[0].forma_envio, 'X');
});
test('does not retry a permanent Olist error, and flags the order as at risk', async () => {
tinyResponses['1006'] = [() => tinyError('32', 'Pedido não localizado')];
consoleCapture.warnings.length = 0;
await handleTinyOrderUpdate(orderWebhook(1006, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1006').length, 1);
const [payload] = forwardedFor('1006');
assert.equal(payload.fone, '');
assert.equal(payload.situacao, 'Pronto para envio');
assert.ok(consoleCapture.warnings.some(w => w.includes('[Notification at risk] Order ID 1006')));
});
test('gives up after the configured attempts when Olist stays rate-limited', async () => {
tinyResponses['1007'] = [1, 2, 3].map(() => () => tinyError('6', 'API bloqueada'));
await handleTinyOrderUpdate(orderWebhook(1007, 'pronto_envio', 'Pronto para envio'), fakeRes());
assert.equal(tinyCallsFor('1007').length, 3);
assert.equal(forwardedFor('1007').length, 1);
});

View File

@@ -0,0 +1,67 @@
import { test, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'fs';
import os from 'os';
import path from 'path';
import express from 'express';
import { AddressInfo } from 'net';
import { setTestEnv, mockAxiosPost, tinyOrder, fakeRes, isTinyCall, silenceConsole } from './helpers';
const runtimeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tiny-webhook-test-'));
setTestEnv({ RUNTIME_DATA_DIR: runtimeDir, N8N_WEBHOOK_STOCK: 'http://n8n.test/stock', TINY_LIVE_REQUEST_DELAY_MS: '300' });
const { handleTinyStockUpdate } = require('../src/controllers/webhook.controller');
const webhookRoutes = require('../src/routes/webhook.route');
const calls = mockAxiosPost(async (url, data) => {
if (!isTinyCall(url)) return { status: 200, data: {} };
return tinyOrder(new URLSearchParams(data.toString()).get('id')!);
});
const capture = silenceConsole();
after(() => {
capture.restore();
fs.rmSync(runtimeDir, { recursive: true, force: true });
});
const stockWebhook = (saldo: number) => ({ query: {}, body: { dados: { idProduto: '555', nome: 'Camiseta', saldo } } }) as any;
test('stock memory and CSV are written to the persistent runtime directory', async () => {
await handleTinyStockUpdate(stockWebhook(10), fakeRes());
await handleTinyStockUpdate(stockWebhook(25), fakeRes());
const memory = JSON.parse(fs.readFileSync(path.join(runtimeDir, 'stock_memory.json'), 'utf-8'));
assert.equal(memory['555'].saldo, 25);
assert.ok(fs.readFileSync(path.join(runtimeDir, 'stock_log.csv'), 'utf-8').includes('"555","Camiseta","10","25","15"'));
const forwarded = calls.filter(c => c.url === 'http://n8n.test/stock').map(c => c.data.dados);
assert.equal(forwarded[1].delta_estoque, 15);
});
test('draining on shutdown waits for webhooks that were acked but still queued', async () => {
const app = express();
app.use(express.json());
app.use('/api/webhooks', webhookRoutes.default);
const server = app.listen(0);
const { port } = server.address() as AddressInfo;
try {
const ids = [3001, 3002, 3003];
for (const id of ids) {
const res = await fetch(`http://127.0.0.1:${port}/api/webhooks/tiny/order-status`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dados: { id, codigoSituacao: 'pronto_envio', descricaoSituacao: 'Pronto para envio' } })
});
assert.equal(res.status, 200);
}
const forwardedBefore = calls.filter(c => c.url === 'http://n8n.test/status').length;
assert.ok(forwardedBefore < ids.length, 'some orders are still queued when shutdown starts');
const remaining = await webhookRoutes.drainWebhookWork(10000);
assert.equal(remaining, 0);
assert.equal(calls.filter(c => c.url === 'http://n8n.test/status').length, ids.length);
} finally {
server.close();
}
});