Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
✨ Add metrics module (#1142)
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Jan 9, 2021
1 parent 670e7b3 commit ede77f4
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/modules/metrics/metrics.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Controller, Get, Post } from '@nestjs/common';
import { Scopes } from '../auth/scope.decorator';
import { ProcessMetricData } from './metrics.interface';
import { MetricsService } from './metrics.service';

@Controller('metrics')
export class MetricsController {
constructor(private metricsService: MetricsService) {}

/** Get process metrics */
@Get('process')
@Scopes('metric:read-process')
process(): Promise<ProcessMetricData[]> {
return this.metricsService.getProcessMetrics();
}

/** Update metrics */
@Post('update')
@Scopes('metric:write-process')
update(): Promise<ProcessMetricData[]> {
return this.metricsService.updateProcessMetrics();
}
}
5 changes: 5 additions & 0 deletions src/modules/metrics/metrics.interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface ProcessMetricData {
date: Date;
cpu: number;
memory: number;
}
12 changes: 12 additions & 0 deletions src/modules/metrics/metrics.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { PrismaModule } from '../../providers/prisma/prisma.module';
import { MetricsController } from './metrics.controller';
import { MetricsService } from './metrics.service';

@Module({
imports: [PrismaModule],
controllers: [MetricsController],
providers: [MetricsService],
exports: [MetricsService],
})
export class MetricsModule {}
26 changes: 26 additions & 0 deletions src/modules/metrics/metrics.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Injectable } from '@nestjs/common';
import CircularBuffer from 'circularbuffer';
import pidusage from 'pidusage';
import { PrismaService } from '../../providers/prisma/prisma.service';
import type { ProcessMetricData } from './metrics.interface';

@Injectable()
export class MetricsService {
private queue = new CircularBuffer<ProcessMetricData>(60);

constructor(private prisma: PrismaService) {}

async updateProcessMetrics(): Promise<ProcessMetricData[]> {
const stats = await pidusage(process.pid);
this.queue.enq({
date: new Date(),
cpu: Math.round(stats.cpu * 100) / 100,
memory: Math.round(stats.memory * 100) / 100,
});
return this.getProcessMetrics();
}

async getProcessMetrics(): Promise<ProcessMetricData[]> {
return this.queue.toArray();
}
}

0 comments on commit ede77f4

Please sign in to comment.