2021-05-13 20:33:16 +00:00
//! Code taken from NinoDiscord/Nino
import prom from "prom-client"
import { createServer , IncomingMessage , ServerResponse } from 'http'
import vars from "../../variables"
import Logger from "./logger"
export default class Prometheus {
public commandsExecuted ! : prom . Counter < string >
public messagesSeen ! : prom . Counter < string >
2021-05-14 19:49:47 +00:00
public guildCount ! : prom . Gauge < string >
public totalGuilds ! : prom . Gauge < string >
2021-05-23 03:59:25 +00:00
public uptime ! : prom . Gauge < string >
2021-07-08 11:49:09 +00:00
public events ! : prom . Counter < string >
2021-05-13 20:33:16 +00:00
# server ! : ReturnType < typeof createServer >
load() {
prom . collectDefaultMetrics ( )
this . commandsExecuted = new prom . Counter ( {
labelNames : [ 'command' ] ,
name : "thaldrin_commands_executed" ,
help : "How many commands Thaldrin has executed successfully"
} )
this . messagesSeen = new prom . Counter ( {
name : "thaldrin_messages_seen" ,
help : "How many Messages Thaldrin has seen throughout the process lifespan"
} )
this . guildCount = new prom . Gauge ( {
name : "thaldrin_guild_count" ,
2021-05-14 19:49:47 +00:00
help : "Number of Guilds Thaldrin joined this Lifecycle"
} )
this . totalGuilds = new prom . Gauge ( {
name : "thaldrin_guilds_total" ,
help : "Total Number of Guilds Thaldrin is in"
2021-05-13 20:33:16 +00:00
} )
2021-07-08 11:49:09 +00:00
this . events = new prom . Counter ( {
labelNames : [ 'event' ] ,
name : "thaldrin_discord_events" ,
help : "Received WebSocket events from Discord"
} )
2021-05-23 03:59:25 +00:00
this . uptime = new prom . Gauge ( {
name : "thaldrin_uptime" ,
help : "Thaldrin's Uptime"
} )
2021-05-13 20:33:16 +00:00
this . # server = createServer ( this . onRequest . bind ( this ) ) ;
2021-05-16 00:11:55 +00:00
this . # server . once ( 'listening' , ( ) = > Logger . info ( { type : 'event:prometheusStart' , message : ` Prometheus: Listening at http://localhost: ${ vars . prometheus . port } ` } ) ) ;
2021-05-13 20:33:16 +00:00
this . # server . on ( 'error' , error = > console . error ( error ) ) ;
this . # server . listen ( vars . prometheus . port ) ;
}
private async onRequest ( req : IncomingMessage , res : ServerResponse ) {
2021-05-23 03:59:25 +00:00
this . uptime . set ( process . uptime ( ) )
2021-05-13 20:33:16 +00:00
if ( req . url ! === '/metrics' ) {
res . writeHead ( 200 , { 'Content-Type' : prom . register . contentType } ) ;
res . write ( await prom . register . metrics ( ) ) ;
} else if ( req . url ! === '/favicon.ico' ) {
res . writeHead ( 404 , { 'Content-Type' : 'application/json' } ) ;
res . write ( '{"fuck":"you uwu"}' ) ;
} else {
res . writeHead ( 400 , { 'Content-Type' : 'application/json' } ) ;
res . write ( '{"uwu":"owo"}' ) ;
}
res . end ( ) ;
}
}
export const Prom = new Prometheus ( )