fix: เพิ่ม Graceful Shutdown - ป้องกัน connection in app file, Log Mnddleware + Memory Store
This commit is contained in:
parent
a194d8594b
commit
e068aafe3a
3 changed files with 137 additions and 33 deletions
46
src/app.ts
46
src/app.ts
|
|
@ -11,6 +11,7 @@ import { AppDataSource } from "./database/data-source";
|
|||
import { RegisterRoutes } from "./routes";
|
||||
import { OrganizationController } from "./controllers/OrganizationController";
|
||||
import logMiddleware from "./middlewares/logs";
|
||||
import { logMemoryStore } from "./utils/log-memory-store";
|
||||
import { CommandController } from "./controllers/CommandController";
|
||||
import { ProfileSalaryController } from "./controllers/ProfileSalaryController";
|
||||
import { DateSerializer } from "./interfaces/date-serializer";
|
||||
|
|
@ -20,6 +21,9 @@ import { initWebSocket } from "./services/webSocket";
|
|||
async function main() {
|
||||
await AppDataSource.initialize();
|
||||
|
||||
// Initialize LogMemoryStore after database is ready
|
||||
logMemoryStore.initialize();
|
||||
|
||||
// Setup custom Date serialization for local timezone
|
||||
DateSerializer.setupDateSerialization();
|
||||
|
||||
|
|
@ -93,7 +97,7 @@ async function main() {
|
|||
});
|
||||
|
||||
// app.listen(APP_PORT, APP_HOST, () => console.log(`Listening on: http://localhost:${APP_PORT}`));
|
||||
app.listen(
|
||||
const server = app.listen(
|
||||
APP_PORT,
|
||||
APP_HOST,
|
||||
() => (
|
||||
|
|
@ -111,6 +115,46 @@ async function main() {
|
|||
}
|
||||
|
||||
runMessageQueue();
|
||||
|
||||
// Graceful Shutdown
|
||||
const gracefulShutdown = async (signal: string) => {
|
||||
console.log(`\n[APP] ${signal} received. Starting graceful shutdown...`);
|
||||
|
||||
// Stop accepting new connections
|
||||
server.close(() => {
|
||||
console.log("[APP] HTTP server closed");
|
||||
});
|
||||
|
||||
// Force close after timeout
|
||||
const shutdownTimeout = setTimeout(() => {
|
||||
console.error("[APP] Forced shutdown after timeout");
|
||||
process.exit(1);
|
||||
}, 30000); // 30 seconds timeout
|
||||
|
||||
try {
|
||||
// Close database connections
|
||||
if (AppDataSource.isInitialized) {
|
||||
await AppDataSource.destroy();
|
||||
console.log("[APP] Database connections closed");
|
||||
}
|
||||
|
||||
// Destroy LogMemoryStore
|
||||
logMemoryStore.destroy();
|
||||
console.log("[APP] LogMemoryStore destroyed");
|
||||
|
||||
clearTimeout(shutdownTimeout);
|
||||
console.log("[APP] Graceful shutdown completed");
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
console.error("[APP] Error during shutdown:", error);
|
||||
clearTimeout(shutdownTimeout);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for shutdown signals
|
||||
process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
|
||||
process.on("SIGINT", () => gracefulShutdown("SIGINT"));
|
||||
}
|
||||
|
||||
main();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue