| 31 | let iter = 0; |
| 32 | |
| 33 | async function monitorActivity(): Promise<void> { |
| 34 | try { |
| 35 | iter++; |
| 36 | const result = await pool.query('SELECT * FROM pg_stat_activity'); |
| 37 | const rows = result.rows; |
| 38 | const rowCount = rows.length; |
| 39 | if (rowCount < ALERT_THRESHOLD && iter % 12 !== 0) { |
| 40 | return; |
| 41 | } |
| 42 | // Create filename with ISO timestamp (path-safe) and row count |
| 43 | const isoTimestamp = new Date().toISOString().replace(/:/g, '-'); |
| 44 | const filename = `log_${isoTimestamp}__${rowCount}.json`; |
| 45 | const filepath = path.join(LOG_DIR, filename); |
| 46 | |
| 47 | // Write to file (with BigInt serialization support) |
| 48 | await writeFile( |
| 49 | filepath, |
| 50 | JSON.stringify( |
| 51 | rows, |
| 52 | (_, value: unknown) => (typeof value === 'bigint' ? value.toString() : value), |
| 53 | 2 |
| 54 | ) |
| 55 | ); |
| 56 | |
| 57 | const now = new Date().toISOString(); |
| 58 | console.log(`[${now}] 📊 Logged ${rowCount} active connections to ${filename}`); |
| 59 | |
| 60 | // Play alert if threshold exceeded |
| 61 | if (rowCount >= ALERT_THRESHOLD) { |
| 62 | console.log( |
| 63 | `⚠️ WARNING: Connection count (${rowCount}) reached threshold (${ALERT_THRESHOLD})` |
| 64 | ); |
| 65 | await playAlertSound(); |
| 66 | } |
| 67 | } catch (error) { |
| 68 | console.error('❌ Error monitoring pg_stat_activity:', error); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | async function run(): Promise<void> { |
| 73 | console.log('🚀 Starting PostgreSQL activity monitor'); |