♻️ Refactor info command code

This commit is contained in:
LittleSheep 2024-10-03 01:41:39 +08:00
parent 70e5e5eddf
commit 2125239d42

View File

@ -1,5 +1,5 @@
import { Command, Option, type Usage } from "clipanion" import { Command, Option, type Usage } from "clipanion"
import { RsConfig } from "../utils/config.ts" import { RsConfig, type RsConfigServerData } from "../utils/config.ts"
import { createAuthHeader } from "../utils/auth.ts" import { createAuthHeader } from "../utils/auth.ts"
import chalk from "chalk" import chalk from "chalk"
import ora from "ora" import ora from "ora"
@ -37,6 +37,51 @@ export class InfoCommand extends Command {
return uptimeParts.join(", ") return uptimeParts.join(", ")
} }
async fetchOverview(server: RsConfigServerData) {
try {
const res = await fetch(`${server.url}/cgi/stats`, {
headers: {
Authorization: createAuthHeader(server.credential)
}
})
if (res.status !== 200) {
throw new Error(await res.text())
}
const data = await res.json()
this.context.stdout.write(`\nServer stats of ${chalk.bold(this.label)}\n`)
this.context.stdout.write(`Uptime: ${chalk.bold(InfoCommand.formatUptime(data["uptime"]))}\n`)
this.context.stdout.write(`Traffic since last startup: ${chalk.bold(data["traffic"]["total"])}\n`)
this.context.stdout.write(`Unique clients since last startup: ${chalk.bold(data["traffic"]["unique_client"])}\n`)
this.context.stdout.write(`\nServer info of ${chalk.bold(this.label)}\n`)
this.context.stdout.write(`Warden Applications: ${chalk.bold(data["applications"])}\n`)
this.context.stdout.write(`Destinations: ${chalk.bold(data["destinations"])}\n`)
this.context.stdout.write(`Locations: ${chalk.bold(data["locations"])}\n`)
this.context.stdout.write(`Regions: ${chalk.bold(data["regions"])}\n`)
} catch (e) {
return
}
}
async fetchTrace(server: RsConfigServerData) {
const res = await fetch(`${server.url}/cgi/traces`, {
headers: {
Authorization: createAuthHeader(server.credential)
}
})
if (res.status !== 200) {
throw new Error(await res.text())
}
const data = await res.json()
for (const trace of data) {
const ts = new Date(trace["timestamp"]).toLocaleString()
const path = [trace["region"], trace["location"], trace["destination"]].join(" ➜ ")
const uri = trace["uri"].split("?").length == 1 ? trace["uri"] : trace["uri"].split("?")[0] + ` ${chalk.grey(`w/ query parameters`)}`
this.context.stdout.write(`${chalk.bgGrey(`[${ts}]`)} ${chalk.bold(path)} ${chalk.cyan(trace["ip_address"])} ${uri}\n`)
}
}
async execute() { async execute() {
const config = await RsConfig.getInstance() const config = await RsConfig.getInstance()
@ -56,55 +101,21 @@ export class InfoCommand extends Command {
switch (this.area) { switch (this.area) {
case "overview": case "overview":
try { try {
const res = await fetch(`${server.url}/cgi/stats`, { await this.fetchOverview(server)
headers: {
Authorization: createAuthHeader(server.credential)
}
})
if (res.status !== 200) {
throw new Error(await res.text())
}
const prefTook = performance.now() - prefStart const prefTook = performance.now() - prefStart
spinner.succeed(`Fetching completed in ${(prefTook / 1000).toFixed(2)}s 🎉`) spinner.succeed(`Fetching completed in ${(prefTook / 1000).toFixed(2)}s 🎉`)
const data = await res.json()
this.context.stdout.write(`\nServer stats of ${chalk.bold(this.label)}\n`)
this.context.stdout.write(`Uptime: ${chalk.bold(InfoCommand.formatUptime(data["uptime"]))}\n`)
this.context.stdout.write(`Traffic since last startup: ${chalk.bold(data["traffic"]["total"])}\n`)
this.context.stdout.write(`Unique clients since last startup: ${chalk.bold(data["traffic"]["unique_client"])}\n`)
this.context.stdout.write(`\nServer info of ${chalk.bold(this.label)}\n`)
this.context.stdout.write(`Warden Applications: ${chalk.bold(data["applications"])}\n`)
this.context.stdout.write(`Destinations: ${chalk.bold(data["destinations"])}\n`)
this.context.stdout.write(`Locations: ${chalk.bold(data["locations"])}\n`)
this.context.stdout.write(`Regions: ${chalk.bold(data["regions"])}\n`)
} catch (e) { } catch (e) {
spinner.fail(`Server with label ${chalk.bold(this.label)} is not running! 😢`) spinner.fail(`Server with label ${chalk.bold(this.label)} is not running! 😢`)
return
} }
break break
case "trace": case "trace":
while (true) { while (true) {
try { try {
const res = await fetch(`${server.url}/cgi/traces`, { await this.fetchTrace(server)
headers: {
Authorization: createAuthHeader(server.credential)
}
})
if (res.status !== 200) {
throw new Error(await res.text())
}
const prefTook = performance.now() - prefStart const prefTook = performance.now() - prefStart
if (!this.loop) { if (!this.loop) {
spinner.succeed(`Fetching completed in ${(prefTook / 1000).toFixed(2)}s 🎉`) spinner.succeed(`Fetching completed in ${(prefTook / 1000).toFixed(2)}s 🎉`)
} }
const data = await res.json()
for (const trace of data) {
const ts = new Date(trace["timestamp"]).toLocaleString()
const path = [trace["region"], trace["location"], trace["destination"]].join(" ➜ ")
const uri = trace["uri"].split("?").length == 1 ? trace["uri"] : trace["uri"].split("?")[0] + ` ${chalk.grey(`w/ query parameters`)}`
this.context.stdout.write(`${chalk.bgGrey(`[${ts}]`)} ${chalk.bold(path)} ${chalk.cyan(trace["ip_address"])} ${uri}\n`)
}
} catch (e) { } catch (e) {
spinner.fail(`Server with label ${chalk.bold(this.label)} is not running! 😢`) spinner.fail(`Server with label ${chalk.bold(this.label)} is not running! 😢`)
return return
@ -113,9 +124,9 @@ export class InfoCommand extends Command {
if (!this.loop) { if (!this.loop) {
break break
} else { } else {
spinner.text = 'Updating...' spinner.text = "Updating..."
await new Promise(resolve => setTimeout(resolve, 3000)) await new Promise(resolve => setTimeout(resolve, 3000))
this.context.stdout.write('\x1Bc') this.context.stdout.write("\x1Bc")
} }
} }
break break