Skip to content

Commit 95d7213

Browse files
committed
feat: added memory monitory to notify if the memory consump.. is beyond the treshold value
1 parent 4fccc89 commit 95d7213

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

src/components/utils/memMonitor.ts

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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 detected: ${used.toFixed(2)} MB`
55+
);
56+
}
57+
}
58+
}, this.interval);
59+
}
60+
61+
stop(): void {
62+
if (this.timer) {
63+
clearInterval(this.timer);
64+
}
65+
}
66+
}

src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff 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();
2427
checkRequirements();
2528

2629
const commandPrefix = process.env.COMMAND_PREFIX || "!";

0 commit comments

Comments
 (0)