68 lines
2.0 KiB
JavaScript
68 lines
2.0 KiB
JavaScript
/**
|
|
* glance 数据存储:默认 sqlite 位于 ~/.kit/glance.db(不存在则创建)
|
|
* 依赖 bun:sqlite,仅在调用时加载,避免影响 node 环境下的其他命令。
|
|
*/
|
|
const fs = require("fs");
|
|
const os = require("os");
|
|
const path = require("path");
|
|
|
|
function defaultDbPath() {
|
|
return path.join(os.homedir(), ".kit", "glance.db");
|
|
}
|
|
|
|
function open(dbPath) {
|
|
dbPath = dbPath || defaultDbPath();
|
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
|
|
const { Database } = require("bun:sqlite");
|
|
const db = new Database(dbPath);
|
|
db.exec(`CREATE TABLE IF NOT EXISTS glance (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
ts INTEGER NOT NULL,
|
|
target TEXT NOT NULL,
|
|
pid INTEGER,
|
|
port INTEGER,
|
|
cpu REAL,
|
|
mem REAL,
|
|
handle INTEGER
|
|
)`);
|
|
db.exec("CREATE INDEX IF NOT EXISTS idx_glance_lookup ON glance(pid, port, ts)");
|
|
return db;
|
|
}
|
|
|
|
/**
|
|
* 插入一条监控记录
|
|
* @param db database
|
|
* @param record {ts, target, pid, port, cpu, mem, handle}
|
|
*/
|
|
function insert(db, record) {
|
|
db.query("INSERT INTO glance (ts, target, pid, port, cpu, mem, handle) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
.run(record.ts, record.target, record.pid ?? null, record.port ?? null, record.cpu ?? null, record.mem ?? null, record.handle ?? null);
|
|
}
|
|
|
|
/**
|
|
* 按时间范围查询监控数据(忽略 target,pid/port 二者取其一)
|
|
* @param db database
|
|
* @param opts {pid?, port?, start, end}
|
|
* @returns rows
|
|
*/
|
|
function queryRange(db, opts) {
|
|
let where;
|
|
const params = [];
|
|
if (opts.pid != null) {
|
|
where = "pid = ?";
|
|
params.push(opts.pid);
|
|
} else {
|
|
where = "port = ?";
|
|
params.push(opts.port);
|
|
}
|
|
params.push(opts.start, opts.end);
|
|
return db.query(`SELECT ts, target, pid, port, cpu, mem, handle FROM glance WHERE ${where} AND ts >= ? AND ts < ? ORDER BY ts ASC`).all(...params);
|
|
}
|
|
|
|
module.exports = {
|
|
defaultDbPath,
|
|
open,
|
|
insert,
|
|
queryRange
|
|
}; |