| 8 | } |
| 9 | |
| 10 | class DatabaseMonitor { |
| 11 | pool: Pool; |
| 12 | activeQueries: number = 0; |
| 13 | lastDecimalCount: number = 1; |
| 14 | |
| 15 | constructor(pool: Pool) { |
| 16 | this.pool = pool; |
| 17 | pool.on('acquire', this.onAcquire); |
| 18 | pool.on('release', this.onRelease); |
| 19 | pool.on('enqueue', this.onEnqueue); |
| 20 | } |
| 21 | |
| 22 | get queuedQueries(): number { |
| 23 | return this.pool.pool._connectionQueue.length; |
| 24 | } |
| 25 | |
| 26 | get outstandingQueries(): number { |
| 27 | return this.activeQueries + this.queuedQueries; |
| 28 | } |
| 29 | |
| 30 | countOutstandingQueries(): number { |
| 31 | const count = this.outstandingQueries; |
| 32 | const decimalCount = countDecimals(count); |
| 33 | if (decimalCount > this.lastDecimalCount) { |
| 34 | const lowerBound = Math.pow(10, this.lastDecimalCount); |
| 35 | console.log(`more than ${lowerBound - 1} queries outstanding`); |
| 36 | } else if (decimalCount < this.lastDecimalCount) { |
| 37 | const upperBound = Math.pow(10, decimalCount); |
| 38 | console.log(`fewer than ${upperBound} queries outstanding`); |
| 39 | } |
| 40 | this.lastDecimalCount = decimalCount; |
| 41 | return count; |
| 42 | } |
| 43 | |
| 44 | onAcquire: () => void = () => { |
| 45 | this.activeQueries += 1; |
| 46 | this.countOutstandingQueries(); |
| 47 | }; |
| 48 | |
| 49 | onRelease: () => void = () => { |
| 50 | this.activeQueries -= 1; |
| 51 | this.countOutstandingQueries(); |
| 52 | }; |
| 53 | |
| 54 | onEnqueue: () => void = () => { |
| 55 | this.countOutstandingQueries(); |
| 56 | }; |
| 57 | |
| 58 | reportLaggingQuery: (query: string) => void = query => { |
| 59 | const count = this.countOutstandingQueries(); |
| 60 | console.log( |
| 61 | `a query is taking more than ${queryWarnTime}ms to execute. ` + |
| 62 | `there are currently ${count} queries outstanding. query: ${query}`, |
| 63 | ); |
| 64 | }; |
| 65 | } |
| 66 | |
| 67 | export default DatabaseMonitor; |
nothing calls this directly
no test coverage detected