Spaces:
Sleeping
Sleeping
File size: 2,039 Bytes
b480ef7 | 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 | import { app } from './app';
import { env } from './config/env';
import { connectDatabase, disconnectDatabase } from './config/database';
import { keepAwakeService } from './services/keepAwake.service';
import { logger } from './utils/logger';
const startServer = async () => {
try {
// 1. Establish MongoDB connection
await connectDatabase(env.MONGO_URI);
// 2. Start Express HTTP Server
const server = app.listen(env.PORT, () => {
logger.info(`🚀 Auth Service running in [${env.NODE_ENV}] mode on port ${env.PORT}`);
logger.info(`🔗 Health check available at: http://localhost:${env.PORT}/health`);
// 3. Start Keep-Awake Engine for Hugging Face Spaces
keepAwakeService.start();
});
// 4. Graceful Shutdown Handlers
const gracefulShutdown = async (signal: string) => {
logger.info(`Received ${signal}. Starting graceful shutdown...`);
// Stop keep-awake timer
keepAwakeService.stop();
// Stop accepting new connections
server.close(async () => {
logger.info('HTTP server closed.');
// Close MongoDB connection
await disconnectDatabase();
logger.info('Graceful shutdown completed. Exiting.');
process.exit(0);
});
// Force shutdown after 10 seconds if connections don't close
setTimeout(() => {
logger.error('Forced shutdown due to timeout.');
process.exit(1);
}, 10000);
};
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('unhandledRejection', (reason: unknown) => {
logger.error('Unhandled Promise Rejection:', reason);
});
process.on('uncaughtException', (error: Error) => {
logger.error('Uncaught Exception:', error);
process.exit(1);
});
} catch (error) {
logger.error('Fatal error during service startup:', error);
process.exit(1);
}
};
// Start the service
if (process.env.NODE_ENV !== 'test') {
startServer();
}
|