|
| 1 | +import { Service } from '@botpress/messaging-engine' |
| 2 | +import * as promex from '@bpinternal/promex' |
| 3 | +import { defaultNormalizers } from '@promster/express' |
| 4 | +import type { Express } from 'express' |
| 5 | +import client from 'prom-client' |
| 6 | +import yn from 'yn' |
| 7 | +import { ConversationEvents } from '../conversations/events' |
| 8 | +import { ConversationService } from '../conversations/service' |
| 9 | +import { MessageEvents } from '../messages/events' |
| 10 | +import { MessageService } from '../messages/service' |
| 11 | + |
| 12 | +const messagesCount = new client.Counter({ |
| 13 | + name: 'messages_total', |
| 14 | + help: 'Counter of all messages.' |
| 15 | +}) |
| 16 | + |
| 17 | +const conversationsCount = new client.Counter({ |
| 18 | + name: 'conversations_total', |
| 19 | + help: 'Counter of all conversations.' |
| 20 | +}) |
| 21 | + |
| 22 | +export class MetricsService extends Service { |
| 23 | + private metricsEnabled: boolean |
| 24 | + private port: number |
| 25 | + |
| 26 | + constructor(private conversations: ConversationService, private messages: MessageService) { |
| 27 | + super() |
| 28 | + this.metricsEnabled = yn(process.env.METRICS_ENABLED) ?? false |
| 29 | + this.port = process.env.METRICS_PORT ? parseInt(process.env.METRICS_PORT) : 9090 |
| 30 | + } |
| 31 | + |
| 32 | + async destroy() { |
| 33 | + if (!this.metricsEnabled) { |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + await promex.stop() |
| 38 | + } |
| 39 | + |
| 40 | + init(app: Express) { |
| 41 | + if (!this.metricsEnabled) { |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + promex.config({ normalizePath: defaultNormalizers.normalizePath }) |
| 46 | + promex.init(app) |
| 47 | + } |
| 48 | + |
| 49 | + async setup() { |
| 50 | + if (!this.metricsEnabled) { |
| 51 | + return |
| 52 | + } |
| 53 | + |
| 54 | + this.messages.events.on(MessageEvents.Created, this.handleMessageCreated.bind(this)) |
| 55 | + this.conversations.events.on(ConversationEvents.Created, this.handleConversationCreated.bind(this)) |
| 56 | + |
| 57 | + await promex.start({ port: this.port }) |
| 58 | + } |
| 59 | + |
| 60 | + private async handleMessageCreated() { |
| 61 | + messagesCount.inc() |
| 62 | + } |
| 63 | + |
| 64 | + private async handleConversationCreated() { |
| 65 | + conversationsCount.inc() |
| 66 | + } |
| 67 | +} |
0 commit comments