Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 27 additions & 5 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
configureRateLimiters,
} from "./middleware/auth";
import { setupWebSocketServer } from "./services/websocket-server";
import { checkDbConnection } from "./config/database";
import pool, { checkDbConnection } from "./config/database";
import { validateContractIds } from "./config/stellar";
import prisma from "./db/prisma";
import redisClient from "./config/redis";
Expand Down Expand Up @@ -68,6 +68,28 @@ const server = createServer(app);
// Attach WebSocket server
setupWebSocketServer(server);

async function shutdown(code: number) {
logger.info(`[System] Shutting down with code ${code}...`);
try {
// Wait for the HTTP server to finish ongoing requests
await new Promise<void>((resolve) => {
server.close(() => resolve());
});

// Cleanup DB and Redis
await prisma.$disconnect();
await pool.end();
await redisClient.quit();
} catch (err) {
logger.error({ err }, "[System] Error during shutdown cleanup");
}
process.exit(code);
}

// Ensure the application shuts down gracefully on OS signals
process.on("SIGTERM", () => shutdown(0));
process.on("SIGINT", () => shutdown(0));

// Start server
async function start() {
// Validate contract IDs — throws in production, warns in development
Expand All @@ -80,7 +102,7 @@ async function start() {
logger.fatal(
"[DB] PostgreSQL connection failed — aborting in production",
);
process.exit(1);
await shutdown(1);
}
logger.warn("[DB] Could not connect to PostgreSQL — running without DB");
} else {
Expand All @@ -94,7 +116,7 @@ async function start() {
} catch (err) {
if (process.env.NODE_ENV === "production") {
logger.fatal("[DB] Prisma connection failed — aborting in production");
process.exit(1);
await shutdown(1);
}
logger.warn("[DB] Prisma client unavailable — running without ORM");
}
Expand All @@ -109,9 +131,9 @@ async function start() {
}

if (process.env.NODE_ENV !== 'test') {
start().catch((err) => {
start().catch(async (err) => {
console.error('Failed to start server:', err);
process.exit(1);
await shutdown(1);
});
}

Expand Down
Loading