Make builds reproducible and redeploys graceful
All checks were successful
Build and Deploy / build-and-push (push) Successful in 43s

- Install with npm ci from package-lock.json so a rebuild can't pull
  different dependency versions than were tested.
- Run node directly (not via npm) so it receives SIGTERM and can drain
  queued webhooks; give the stack a 60s stop_grace_period and start the
  new task before stopping the old one.
- Add .dockerignore and stop tracking dist/ (already gitignored and
  rebuilt by the Dockerfile).

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 4fe5830f8f
commit c5e168429d
7 changed files with 23 additions and 105 deletions

9
.dockerignore Normal file
View File

@@ -0,0 +1,9 @@
node_modules
dist
.env
.git
data-runtime
graphs-temp
*.php
NexStar*.json
caue-teste-tiny.json

View File

@@ -3,9 +3,9 @@ FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files and install all dependencies (including devDependencies for TypeScript)
COPY package.json ./
RUN npm install
# Copy package files and install the exact locked dependencies (including devDependencies for TypeScript)
COPY package.json package-lock.json ./
RUN npm ci
# Copy source code and build
COPY . .
@@ -16,9 +16,9 @@ FROM node:20-alpine
WORKDIR /app
# Copy package files and install ONLY production dependencies
COPY package.json ./
RUN npm install --omit=dev
# Copy package files and install ONLY the locked production dependencies
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
# Copy built code from the builder stage
COPY --from=builder /app/dist ./dist
@@ -27,5 +27,5 @@ COPY --from=builder /app/data ./data
# Expose the port the app runs on
EXPOSE 3000
# Command to run the application
CMD ["npm", "start"]
# Run node directly so it receives SIGTERM on redeploy and can finish queued webhooks
CMD ["node", "dist/index.js"]

View File

@@ -1,40 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleTinyOrderUpdate = void 0;
const n8n_service_1 = require("../services/n8n.service");
const handleTinyOrderUpdate = async (req, res) => {
try {
let payload = req.body;
// Parse 'dados' if it comes as a JSON string
if (typeof payload.dados === 'string') {
try {
payload.dados = JSON.parse(payload.dados);
}
catch (e) {
console.error('Could not parse "dados" as JSON string.', e);
}
}
console.log('Received webhook from Tiny:', JSON.stringify(payload, null, 2));
// Acknowledge Tiny immediately
res.status(200).send('OK');
if (!payload || Object.keys(payload).length === 0) {
console.warn('Received empty payload from Tiny webhook.');
return;
}
const transformedData = {
source: 'tiny_webhook_middleware',
event: payload.tipo || 'atualizacao_pedido',
dados: payload.dados,
raw_payload: payload
};
// Forward to n8n asynchronously
await (0, n8n_service_1.sendToN8n)(transformedData);
}
catch (error) {
console.error('Error handling Tiny webhook:', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Internal server error processing webhook.' });
}
}
};
exports.handleTinyOrderUpdate = handleTinyOrderUpdate;

20
dist/index.js vendored
View File

@@ -1,20 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const dotenv_1 = __importDefault(require("dotenv"));
const webhook_route_1 = __importDefault(require("./routes/webhook.route"));
dotenv_1.default.config();
const app = (0, express_1.default)();
const port = process.env.PORT || 3000;
app.use(express_1.default.json());
app.use(express_1.default.urlencoded({ extended: true }));
app.use('/api/webhooks', webhook_route_1.default);
app.get('/health', (req, res) => {
res.status(200).json({ status: 'OK', message: 'Tiny-n8n middleware is running.' });
});
app.listen(port, () => {
console.log(`[server]: Middleware server is running at http://localhost:${port}`);
});

View File

@@ -1,7 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const webhook_controller_1 = require("../controllers/webhook.controller");
const router = (0, express_1.Router)();
router.post('/tiny/order-status', webhook_controller_1.handleTinyOrderUpdate);
exports.default = router;

View File

@@ -1,30 +0,0 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendToN8n = void 0;
const axios_1 = __importDefault(require("axios"));
const sendToN8n = async (data) => {
const n8nWebhookUrl = process.env.N8N_WEBHOOK_URL;
if (!n8nWebhookUrl) {
console.error('N8N_WEBHOOK_URL is not defined in environment variables.');
return;
}
try {
console.log(`Forwarding payload to n8n at ${n8nWebhookUrl}...`);
const response = await axios_1.default.post(n8nWebhookUrl, data, {
headers: {
'Content-Type': 'application/json'
}
});
console.log(`Successfully forwarded to n8n. Status: ${response.status}`);
}
catch (error) {
console.error('Failed to forward payload to n8n.', error.message);
if (error.response) {
console.error('n8n Response:', error.response.status, error.response.data);
}
}
};
exports.sendToN8n = sendToN8n;

View File

@@ -48,6 +48,12 @@ services:
# - nginx-proxy-manager-network
volumes:
- middleware_data:/app/data-runtime
# Give the app time to finish queued webhooks on redeploy (SHUTDOWN_GRACE_MS is 50s).
stop_grace_period: 60s
deploy:
update_config:
# Start the new task before stopping the old one so webhooks keep landing during a redeploy.
order: start-first
# networks:
# nginx-proxy-manager-network: