|
1 | | -import mongoose from 'mongoose'; |
| 1 | +import mongoose, { ClientSession } from 'mongoose'; |
2 | 2 | import logger from './logger'; |
3 | 3 | import env from './env'; |
4 | 4 |
|
| 5 | +/** Active multi-document sessions started via `startTrackedSession`. */ |
| 6 | +const activeSessions = new Set<ClientSession>(); |
| 7 | + |
| 8 | +export const getActiveTransactionCount = (): number => activeSessions.size; |
| 9 | + |
| 10 | +/** |
| 11 | + * Start a mongoose session that is registered for graceful-shutdown |
| 12 | + * draining. Prefer this over `mongoose.startSession()` for any work that |
| 13 | + * must finish (or be waited on) before the process exits. |
| 14 | + */ |
| 15 | +export const startTrackedSession = async (): Promise<ClientSession> => { |
| 16 | + const session = await mongoose.startSession(); |
| 17 | + activeSessions.add(session); |
| 18 | + |
| 19 | + const originalEndSession = session.endSession.bind(session); |
| 20 | + session.endSession = (async ( |
| 21 | + ...args: Parameters<ClientSession['endSession']> |
| 22 | + ): Promise<void> => { |
| 23 | + activeSessions.delete(session); |
| 24 | + await originalEndSession(...args); |
| 25 | + }) as ClientSession['endSession']; |
| 26 | + |
| 27 | + return session; |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * Poll until all tracked sessions have ended, or until `timeoutMs` elapses. |
| 32 | + * Does not abort sessions — callers should finish or abort their own work. |
| 33 | + */ |
| 34 | +export const waitForActiveTransactions = async (timeoutMs: number): Promise<void> => { |
| 35 | + const deadline = Date.now() + timeoutMs; |
| 36 | + const pollMs = 100; |
| 37 | + |
| 38 | + while (activeSessions.size > 0 && Date.now() < deadline) { |
| 39 | + logger.info( |
| 40 | + `[Database] Waiting for ${activeSessions.size} active transaction session(s)...`, |
| 41 | + ); |
| 42 | + await new Promise((resolve) => setTimeout(resolve, pollMs)); |
| 43 | + } |
| 44 | + |
| 45 | + if (activeSessions.size > 0) { |
| 46 | + logger.warn( |
| 47 | + `[Database] Proceeding with ${activeSessions.size} active session(s) still open`, |
| 48 | + ); |
| 49 | + } else { |
| 50 | + logger.info('[Database] Active transaction sessions drained'); |
| 51 | + } |
| 52 | +}; |
| 53 | + |
| 54 | +/** |
| 55 | + * Close the mongoose connection after outstanding buffered operations |
| 56 | + * complete (`force = false`). Safe to call when already disconnected. |
| 57 | + */ |
| 58 | +export const disconnectDatabase = async (): Promise<void> => { |
| 59 | + if (mongoose.connection.readyState === 0) { |
| 60 | + logger.info('[Database] MongoDB already disconnected'); |
| 61 | + return; |
| 62 | + } |
| 63 | + |
| 64 | + await mongoose.connection.close(false); |
| 65 | + logger.info('[Database] MongoDB connection closed'); |
| 66 | +}; |
| 67 | + |
5 | 68 | export const connectDatabase = async (): Promise<void> => { |
6 | 69 | try { |
7 | 70 | const mongoUri = env.MONGODB_URI; |
@@ -31,11 +94,8 @@ export const connectDatabase = async (): Promise<void> => { |
31 | 94 | logger.info(`MongoDB connected to ${mongoose.connection.host}`); |
32 | 95 | }); |
33 | 96 |
|
34 | | - process.on('SIGINT', async () => { |
35 | | - await mongoose.connection.close(); |
36 | | - logger.info('MongoDB connection closed through app termination'); |
37 | | - process.exit(0); |
38 | | - }); |
| 97 | + // SIGINT / SIGTERM are handled centrally by GracefulShutdownService so |
| 98 | + // we do not register a competing process.exit handler here. |
39 | 99 | } catch (error) { |
40 | 100 | logger.error('❌ Failed to connect to MongoDB:', error); |
41 | 101 | process.exit(1); |
|
0 commit comments