fix disposal of ServerStatsService and QueueStatsService

This commit is contained in:
Hazelnoot 2025-06-25 22:16:06 -04:00
parent d4105dee0c
commit c79d66d48b
2 changed files with 117 additions and 38 deletions

View file

@ -12,6 +12,22 @@ import type { OnApplicationShutdown } from '@nestjs/common';
import { MiMeta } from '@/models/_.js';
import { DI } from '@/di-symbols.js';
export interface Stats {
cpu: number,
mem: {
used: number,
active: number,
},
net: {
rx: number,
tx: number,
},
fs: {
r: number,
w: number,
},
}
const ev = new Xev();
const interval = 2000;
@ -23,12 +39,19 @@ const round = (num: number) => Math.round(num * 10) / 10;
export class ServerStatsService implements OnApplicationShutdown {
private intervalId: NodeJS.Timeout | null = null;
private log: Stats[] = [];
constructor(
@Inject(DI.meta)
private meta: MiMeta,
) {
}
@bindThis
private async onRequestStatsLog(x: { id: string, length: number }) {
ev.emit(`serverStatsLog:${x.id}`, this.log.slice(0, x.length));
}
/**
* Report server stats regularly
*/
@ -36,11 +59,8 @@ export class ServerStatsService implements OnApplicationShutdown {
public async start(): Promise<void> {
if (!this.meta.enableServerMachineStats) return;
const log = [] as any[];
ev.on('requestServerStatsLog', x => {
ev.emit(`serverStatsLog:${x.id}`, log.slice(0, x.length));
});
this.log = [];
ev.on('requestServerStatsLog', this.onRequestStatsLog);
const tick = async () => {
const cpu = await cpuUsage();
@ -64,8 +84,8 @@ export class ServerStatsService implements OnApplicationShutdown {
},
};
ev.emit('serverStats', stats);
log.unshift(stats);
if (log.length > 200) log.pop();
this.log.unshift(stats);
if (this.log.length > 200) this.log.pop();
};
tick();
@ -78,6 +98,11 @@ export class ServerStatsService implements OnApplicationShutdown {
if (this.intervalId) {
clearInterval(this.intervalId);
}
this.log = [];
ev.off('requestServerStatsLog', this.onRequestStatsLog);
ev.dispose();
}
@bindThis
@ -89,9 +114,13 @@ export class ServerStatsService implements OnApplicationShutdown {
// CPU STAT
function cpuUsage(): Promise<number> {
return new Promise((res, rej) => {
osUtils.cpuUsage((cpuUsage) => {
res(cpuUsage);
});
try {
osUtils.cpuUsage((cpuUsage) => {
res(cpuUsage);
});
} catch (err) {
rej(err);
}
});
}