Skip to content

Commit

Permalink
feat(status): init statistics api
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Mar 10, 2021
1 parent fbd767a commit 66a46a6
Show file tree
Hide file tree
Showing 4 changed files with 403 additions and 12 deletions.
4 changes: 3 additions & 1 deletion packages/plugin-status/server/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,10 @@ Database.extend('koishi-plugin-mysql', {
},
})

Database.extend('koishi-plugin-mysql', ({ tables }) => {
Database.extend('koishi-plugin-mysql', ({ tables, Domain }) => {
tables.user.lastCall = 'timestamp'
tables.channel.name = 'varchar(50)'
tables.channel.activity = new Domain.Json()
})

Database.extend('koishi-plugin-mongo', {
Expand Down
24 changes: 14 additions & 10 deletions packages/plugin-status/server/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ import { Time } from 'koishi-utils'
import { cpus } from 'os'
import { mem } from 'systeminformation'

export type Rate = [app: number, total: number]
export type LoadRate = [app: number, total: number]
export type MessageRate = [send: number, receive: number]

let usage = getCpuUsage()
let appRate: number
let usedRate: number

async function memoryRate(): Promise<Rate> {
async function memoryRate(): Promise<LoadRate> {
const { total, active } = await mem()
return [process.memoryUsage().rss / total, active / total]
}
Expand Down Expand Up @@ -44,29 +45,32 @@ function updateCpuUsage() {
}

export interface BotData {
username?: string
username: string
selfId: string
platform: Platform
code: Bot.Status
sent: number
received: number
currentRate: MessageRate
recentRate?: MessageRate[]
}

export namespace BotData {
function accumulate(record: number[]) {
return record.slice(1).reduce((prev, curr) => prev + curr, 0)
}

export const from = async (bot: Bot) => ({
platform: bot.platform,
selfId: bot.selfId,
username: bot.username,
code: await bot.getStatus(),
sent: bot.messageSent.slice(1).reduce((prev, curr) => prev + curr, 0),
received: bot.messageReceived.slice(1).reduce((prev, curr) => prev + curr, 0),
currentRate: [accumulate(bot.messageSent), accumulate(bot.messageReceived)],
} as BotData)
}

export interface Profile {
bots: BotData[]
memory: Rate
cpu: Rate
memory: LoadRate
cpu: LoadRate
}

export namespace Profile {
Expand All @@ -79,7 +83,7 @@ export namespace Profile {
memoryRate(),
Promise.all(ctx.bots.map(BotData.from)),
])
const cpu: Rate = [appRate, usedRate]
const cpu: LoadRate = [appRate, usedRate]
return { bots, memory, cpu } as Profile
}

Expand Down
Loading

0 comments on commit 66a46a6

Please sign in to comment.