-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
210 lines (183 loc) · 7.13 KB
/
app.js
File metadata and controls
210 lines (183 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
const express = require('express');
const cors = require('cors');
const swaggerJsDoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const compression = require('compression');
const { recordRequest, snapshotAndReset } = require('./metrics');
// Register split endpoint modules (DB + routes colocated) while keeping a single DB pool
const endpoints = require('./endpoints');
const { checkHealth, shutdown: dbShutdown } = require('./endpoints/dbClient');
const { startPolling: startCachePolling, stopPolling: stopCachePolling } = require('./endpoints/responseCache');
const app = express();
const port = parseInt(process.env.API_PORT || '3000', 10);
// --- Automatic async error forwarding ---
// Wrap async route handlers so thrown/rejected errors reach the global error middleware immediately
['get','post','put','delete','patch'].forEach(method => {
const orig = app[method].bind(app);
app[method] = (path, ...handlers) => {
const wrapped = handlers.map(h => {
if (typeof h === 'function' && h.constructor && h.constructor.name === 'AsyncFunction') {
return function wrappedAsyncHandler(req, res, next) {
Promise.resolve(h(req, res, next)).catch(err => {
if (!res.headersSent && !res.writableEnded) {
return next(err);
}
// Avoid double-send: just log since response is already on the wire
console.error('Handler error after response sent:', req.method, req.originalUrl, err);
});
};
}
return h;
});
return orig(path, ...wrapped);
};
});
// --- Request timeout safeguard ---
// Ensures a hung handler (e.g., unresolved promise) returns a 503 instead of stalling indefinitely
const ROUTE_TIMEOUT_MS = process.env.ROUTE_TIMEOUT_MS ? parseInt(process.env.ROUTE_TIMEOUT_MS) : 30000;
app.use((req, res, next) => {
res.setTimeout(ROUTE_TIMEOUT_MS, () => {
// Mark as timed-out to prevent later handlers from writing again
res.locals.timedOut = true;
if (!res.headersSent && !res.writableEnded) {
console.error('Request timed out:', req.method, req.originalUrl);
try { res.status(503).json({ error: 'Timeout', message: 'Request exceeded time limit' }); } catch {}
}
});
next();
});
// --- Response guard to prevent double-send after timeout or prior writes ---
app.use((_req, res, next) => {
const origJson = res.json.bind(res);
const origSend = res.send.bind(res);
res.json = (body) => {
if (res.headersSent || res.writableEnded || res.locals.timedOut) return res;
return origJson(body);
};
res.send = (body) => {
if (res.headersSent || res.writableEnded || res.locals.timedOut) return res;
return origSend(body);
};
next();
});
const swaggerOptions = {
definition: {
openapi: '3.0.0',
info: {
title: 'Entropia Nexus API',
version: '1.0.0',
description: 'Serves all entities from the Entropia Nexus database.',
},
servers: [
{
url: 'https://api.entropianexus.com',
description: 'Production server'
}
]
},
// Path to the API docs (use only modular endpoint files)
apis: ['./endpoints/*.js'],
};
const swaggerDocs = swaggerJsDoc(swaggerOptions);
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs, { explorer: true, customCss: '.swagger-ui .topbar { display: none }', customSiteTitle: 'Entropia Nexus API', apisSorter: 'alpha', operationsSorter: 'alpha' }));
app.use(compression());
app.use(cors());
app.use(express.json());
// Per-request timing (compact): record duration and route
app.use((req, res, next) => {
const start = process.hrtime.bigint();
res.on('finish', () => {
const durMs = Number(process.hrtime.bigint() - start) / 1e6;
const path = (req.route && req.route.path) || req.path || req.originalUrl || 'unknown';
recordRequest(req.method, path, durMs);
});
next();
});
// Periodic compact performance report (no spam)
const REPORT_EVERY_MS = parseInt(process.env.METRICS_EVERY_MS || '60000', 10);
setInterval(() => {
const mem = process.memoryUsage();
const snap = snapshotAndReset();
console.log('[metrics]', {
upMs: snap.elapsedMs,
req: { count: snap.requests, avgMs: Math.round(snap.avgReqMs), slow: snap.slowRequests },
sql: { count: snap.queries, avgMs: Math.round(snap.avgQueryMs), slow: snap.slowQueries },
topRoutes: snap.byRoute,
mem: {
rssMB: Math.round(mem.rss / 1024 / 1024),
heapUsedMB: Math.round(mem.heapUsed / 1024 / 1024),
extMB: Math.round(mem.external / 1024 / 1024)
}
});
}, REPORT_EVERY_MS).unref();
app.disable('x-powered-by');
const server = app.listen(port, () => {
console.log(`App running on port ${port}.`);
});
// Attach modular endpoints
try { endpoints.registerAll(app); } catch (e) { console.warn('Endpoints registration failed:', e?.message); }
// Start cache change-tracking poller (non-blocking — API works without it)
startCachePolling().catch(e => console.warn('[cache] Initial poll failed:', e?.message));
app.get('/schema.json', (_req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerDocs);
});
// Global error handling middleware
app.use((err, req, res, _next) => {
console.error('API Error:', err);
console.error('URL:', req.originalUrl);
console.error('Method:', req.method);
// Send a generic error response to prevent crashes
if (!res.headersSent) {
res.status(500).json({
error: 'Internal server error',
message: process.env.NODE_ENV === 'production' ? 'Something went wrong' : err.message
});
}
});
// Health check endpoint
app.get('/health', async (_req, res) => {
const dbHealth = await checkHealth();
const allHealthy = dbHealth.nexus && dbHealth.users;
res.status(allHealthy ? 200 : 503).json({
status: allHealthy ? 'healthy' : 'degraded',
databases: dbHealth,
uptime: process.uptime(),
});
});
// Handle 404 errors
app.use((req, res) => {
res.status(404).json({
error: 'Not found',
message: `Route ${req.originalUrl} not found`
});
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, _promise) => {
console.error('Unhandled Promise Rejection:', reason);
});
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
gracefulShutdown('uncaughtException');
});
// Graceful shutdown handler
let isShuttingDown = false;
async function gracefulShutdown(signal) {
if (isShuttingDown) return;
isShuttingDown = true;
console.log(`\n[shutdown] Received ${signal}, shutting down gracefully...`);
// Stop accepting new connections
server.close(() => {
console.log('[shutdown] HTTP server closed');
});
// Stop cache poller
stopCachePolling();
// Close database pools
await dbShutdown();
console.log('[shutdown] Cleanup complete, exiting');
process.exit(0);
}
// Handle termination signals
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));