forked from Vatix-Protocol/vatix-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
371 lines (331 loc) · 12 KB
/
Copy pathindex.ts
File metadata and controls
371 lines (331 loc) · 12 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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import Fastify, {
type FastifyServerOptions,
type FastifyInstance,
type FastifyRequest,
type FastifyReply,
} from "fastify";
import { pathToFileURL } from "node:url";
import { errorHandler } from "./api/middleware/errorHandler.js";
import positionsRouter from "./api/routes/positions.js";
import { NotFoundError, ValidationError } from "./api/middleware/errors.js";
import { signingService } from "./services/signing.js";
import "dotenv/config";
import { getPrismaClient } from "./services/prisma.js";
import { marketsRoutes } from "./api/routes/markets.js";
import { ordersRoutes } from "./api/routes/orders.js";
import { fillsRoutes } from "./api/routes/fills.js";
import { adminRoutes } from "./api/routes/admin.js";
import { healthRoutes } from "./api/routes/health.js";
import { readyRoute } from "./api/routes/ready.js";
import { metricsRoutes } from "./api/routes/metrics.js";
import { createReadyDeps } from "./api/deps/ready-deps.js";
import { registerDeprecatedAliases } from "./api/routes/legacy.js";
import { openApiSpec } from "./api/openapi.js";
import { rateLimiter } from "./api/middleware/rateLimiter.js";
import { requestLogger } from "./api/middleware/logger.js";
import {
makeGenReqId,
requestIdMiddleware,
} from "./api/middleware/requestId.js";
import { config } from "./config.js";
import { parseApiEnv } from "./env.js";
import { corsPlugin } from "./api/middleware/cors.js";
import { redis } from "./services/redis.js";
// Default: 64 KB. Override via BODY_LIMIT_BYTES env var.
// Oversized requests are rejected with 413 Request Entity Too Large.
const bodyLimit = Number(process.env.BODY_LIMIT_BYTES) || 65_536;
export interface BuildServerOptions {
logger?: FastifyServerOptions["logger"];
readyDeps?: Parameters<typeof readyRoute>[0];
registerTestRoutes?: boolean;
}
function createDefaultReadyDeps(): Parameters<typeof readyRoute>[0] {
return {
checkDatabase: async () => {
const prisma = getPrismaClient();
await prisma.$queryRaw`SELECT 1`;
},
checkRedis: async () => {
const ok = await redis.healthCheck();
if (!ok) throw new Error("Redis PING did not return PONG");
},
getLastIndexedAt: async () => {
const prisma = getPrismaClient();
const cursor = await prisma.indexerCursor.findFirst({
orderBy: { updatedAt: "desc" },
select: { updatedAt: true },
});
return cursor ? cursor.updatedAt.getTime() : null;
},
};
}
export function buildServer(options: BuildServerOptions = {}): FastifyInstance {
const server: FastifyInstance = Fastify({
logger: options.logger ?? true,
// Name the auto-bound pino field "requestId" so every request.log.*
// call carries it — not just the ones in requestLogger.
requestIdLogLabel: "requestId",
// Accept a valid incoming UUID from x-request-id before pino creates the
// child logger, so the binding is correct from the very first log entry.
genReqId: makeGenReqId(),
bodyLimit,
});
// Register error handler (must be before routes)
server.setErrorHandler(errorHandler);
// CORS — must be registered before routes so preflight OPTIONS requests are handled
server.register(corsPlugin);
// Resolve/generate request ID before anything else touches request.id
server.register(requestIdMiddleware);
// Register request logger (before routes so every request is captured)
server.register(requestLogger);
// Apply rate limiting globally, but exclude readiness/health probes
// K8s readiness probes (GET /v1/ready) must not be rate-limited or
// blocked by authentication so the cluster can determine service health
server.addHook("onRequest", (request, reply, done) => {
const isHealthProbe =
request.url === "/v1/ready" ||
request.url === "/v1/health" ||
request.url === "/metrics";
if (isHealthProbe) {
done();
} else {
rateLimiter(request, reply, done);
}
});
// Register API routes under /v1
server.register(
async (v1) => {
// Guard: any plugin within this scope must not hardcode a /v1 prefix on
// its own routes — the parent scope already adds it, which would produce
// double-prefixed paths like /v1/v1/markets.
v1.addHook("onRoute", (routeOptions) => {
if (routeOptions.url.startsWith("/v1/v1")) {
throw new Error(
`Plugin registered route "${routeOptions.url}" with a /v1 prefix ` +
`inside the /v1-scoped block — remove the prefix from the plugin.`
);
}
});
await v1.register(marketsRoutes);
await v1.register(ordersRoutes);
await v1.register(positionsRouter);
await v1.register(fillsRoutes);
await v1.register(adminRoutes);
await v1.register(healthRoutes);
await v1.register(readyRoute(options.readyDeps ?? createReadyDeps()));
v1.get("/openapi.json", async (_request, reply) => {
return reply.status(200).send(openApiSpec);
});
},
{ prefix: "/v1" }
);
registerDeprecatedAliases(server);
// Prometheus scrape endpoint, unversioned and unauthenticated by convention
// (restrict network access to it at the infra/ingress layer).
server.register(metricsRoutes);
// Serve interactive API documentation at /docs using Swagger UI (CDN-hosted).
// The spec is loaded from /v1/openapi.json at runtime so it stays in sync.
server.get("/docs", async (_request, reply) => {
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Vatix API Docs</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
url: "/v1/openapi.json",
dom_id: "#swagger-ui",
presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
layout: "BaseLayout",
deepLinking: true,
});
</script>
</body>
</html>`;
return reply.type("text/html").send(html);
});
// Gate test routes behind option and NODE_ENV !== "production"
const enableTestRoutes =
options.registerTestRoutes !== false &&
(process.env.NODE_ENV || "development") !== "production";
if (enableTestRoutes) {
server.log.warn(
"Test routes (/test/*) are enabled. Do not enable in production!"
);
// Test routes for error handling
server.get("/test/validation-error", async () => {
throw new ValidationError("Invalid input data", {
email: "Invalid email format",
password: "Password must be at least 8 characters",
});
});
server.get("/test/not-found", async () => {
throw new NotFoundError("Market not found");
});
server.get("/test/server-error", async () => {
throw new Error("Something went wrong internally");
});
}
// Global 404 handler — must be registered after all routes
// Throws through the error handler for consistent response format
server.setNotFoundHandler((request: FastifyRequest, reply: FastifyReply) => {
const requestId = request.id;
reply.status(404).send({
error: `Route ${request.method} ${request.url} not found`,
requestId,
statusCode: 404,
});
});
return server;
}
const start = async () => {
// Fail fast on invalid env before binding routes or opening connections.
parseApiEnv();
// Disable test routes in production
const registerTestRoutes = config.nodeEnv !== "production";
const server = buildServer({ registerTestRoutes });
// Set up global handlers for unhandled rejections and exceptions
// These handlers ensure all unhandled errors are logged and the process exits gracefully
process.on(
"unhandledRejection",
(reason: unknown, promise: Promise<unknown>) => {
const message = reason instanceof Error ? reason.message : String(reason);
const stack = reason instanceof Error ? reason.stack : undefined;
server.log.error(
{ reason: message, stack, promise: String(promise) },
"Unhandled promise rejection"
);
// Exit with error code after logging
process.exit(1);
}
);
process.on("uncaughtException", (error: Error) => {
server.log.error(
{ error: error.message, stack: error.stack },
"Uncaught exception"
);
// Exit with error code after logging
process.exit(1);
});
try {
// Initialize signing service BEFORE starting server
signingService.initialize();
// Hydrate in-memory order books from Postgres on cold start (#449).
// This eliminates the race window where a restart leaves books empty
// while open orders still exist in the database.
const { matchingService } = await import("./matching/matching-service.js");
await matchingService.hydrateAllActiveMarkets();
const port = config.port;
await server.listen({ port, host: "0.0.0.0" });
server.log.info(
{ nodeEnv: config.nodeEnv, port },
`Server running at http://localhost:${port}`
);
// Graceful shutdown handling
const VALID_SHUTDOWN_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
type ShutdownSignal = (typeof VALID_SHUTDOWN_SIGNALS)[number];
const SHUTDOWN_TIMEOUT_MS = 30_000; // 30 seconds
let isShuttingDown = false;
const shutdown = async (signal: ShutdownSignal) => {
if (
typeof signal !== "string" ||
signal.trim() === "" ||
!VALID_SHUTDOWN_SIGNALS.includes(
signal as (typeof VALID_SHUTDOWN_SIGNALS)[number]
)
) {
server.log.warn(
{
signal,
statusCode: 400,
component: "api-server",
validSignals: [...VALID_SHUTDOWN_SIGNALS],
},
"Graceful shutdown called with invalid signal"
);
return;
}
if (isShuttingDown) {
return;
}
isShuttingDown = true;
server.log.info(
{
signal,
component: "api-server",
status: "initiated",
},
"API server shutdown initiated"
);
// Set hard timeout to force exit if shutdown hangs
const timeoutHandle = setTimeout(() => {
server.log.error(
{
signal,
component: "api-server",
timeoutMs: SHUTDOWN_TIMEOUT_MS,
},
"Shutdown timeout exceeded, forcing exit"
);
process.exit(1);
}, SHUTDOWN_TIMEOUT_MS);
try {
// Close server — stops accepting new connections, drains in-flight requests
await server.close();
// Gracefully disconnect database and redis
const { disconnectPrisma } = await import("./services/prisma.js");
const { disconnectAnalyticsPrisma } =
await import("./services/analytics-prisma.js");
const { redis } = await import("./services/redis.js");
await Promise.allSettled([
disconnectPrisma(),
disconnectAnalyticsPrisma(),
redis.disconnect(),
]);
clearTimeout(timeoutHandle);
server.log.info(
{
signal,
component: "api-server",
status: "complete",
exitCode: 0,
},
"API server shutdown complete"
);
process.exit(0);
} catch (error) {
clearTimeout(timeoutHandle);
server.log.error(
{
signal,
component: "api-server",
status: "failed",
exitCode: 1,
error: error instanceof Error ? error.message : String(error),
},
"API server shutdown failed"
);
process.exit(1);
}
};
// Register signal handlers for graceful shutdown
process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));
process.on("SIGHUP", () => void shutdown("SIGHUP"));
} catch (err) {
server.log.error(err);
process.exit(1);
}
};
if (
process.argv[1] &&
import.meta.url === pathToFileURL(process.argv[1]).href
) {
start();
}