File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import v8 from "v8" ;
2+ import log from "./log" ;
3+
4+ interface MemoryMonitorOptions {
5+ interval ?: number ;
6+ thresholdMB ?: number ;
7+ }
8+
9+ interface MemoryStats {
10+ usedMB : number ;
11+ heapStats : ReturnType < typeof v8 . getHeapStatistics > ;
12+ timestamp : string ;
13+ }
14+
15+ export class MemoryMonitor {
16+ private interval : number ;
17+ private thresholdMB : number ;
18+ private history : MemoryStats [ ] ;
19+ private timer ?: NodeJS . Timeout ;
20+
21+ constructor ( {
22+ interval = 60000 ,
23+ thresholdMB = 500 ,
24+ } : MemoryMonitorOptions = { } ) {
25+ this . interval = interval ;
26+ this . thresholdMB = thresholdMB ;
27+ this . history = [ ] ;
28+ }
29+
30+ start ( ) : void {
31+ this . timer = setInterval ( ( ) => {
32+ const used = process . memoryUsage ( ) . heapUsed / 1024 / 1024 ;
33+ const stats : MemoryStats = {
34+ usedMB : used ,
35+ heapStats : v8 . getHeapStatistics ( ) ,
36+ timestamp : new Date ( ) . toISOString ( ) ,
37+ } ;
38+
39+ this . history . push ( stats ) ;
40+
41+ if ( used > this . thresholdMB ) {
42+ log . warn (
43+ "MemoryMonitor" ,
44+ `High memory usage detected: ${ used . toFixed ( 2 ) } MB`
45+ ) ;
46+ }
47+
48+ // Oh shit!
49+ if ( this . history . length > 5 ) {
50+ const lastFive = this . history . slice ( - 5 ) . map ( ( h ) => h . usedMB ) ;
51+ if ( lastFive . every ( ( val , i , arr ) => i === 0 || val > arr [ i - 1 ] ) ) {
52+ log . warn (
53+ "MemoryMonitor" ,
54+ "Potential memory leak heap consistently increasing"
55+ ) ;
56+ }
57+ }
58+ } , this . interval ) ;
59+ }
60+
61+ stop ( ) : void {
62+ if ( this . timer ) {
63+ clearInterval ( this . timer ) ;
64+ }
65+ }
66+ }
Original file line number Diff line number Diff line change @@ -20,7 +20,10 @@ import {
2020 wyr ,
2121 greetings ,
2222} from "./components/utils/data" ;
23+ import { MemoryMonitor } from "./components/utils/memMonitor" ;
2324
25+ const monitor = new MemoryMonitor ( { interval : 30000 } ) ;
26+ monitor . start ( ) ;
2427checkRequirements ( ) ;
2528
2629const commandPrefix = process . env . COMMAND_PREFIX || "!" ;
You can’t perform that action at this time.
0 commit comments