Files
tiny-webhook/test/stock-and-shutdown.test.ts
Cauê Faleiros 4fe5830f8f 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>
2026-10-08 15:12:09 -03:00

68 lines
2.9 KiB
TypeScript

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();
}
});