feat: add durable service event poller

This commit is contained in:
gitea committed 2026-09-05 20:48:32 +08:00
1 parent f72deb01b1
commit 84e6fa58fd
9 files changed
+104 -2

No files matched your search

+15
View File
@@ -5,6 +5,9 @@ import { runServiceCommand, ServiceConfig, getPidFile, getLogFile } from "../ser
import { printJson, printKeyValue } from "../printer.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../types.js";
import { createEkbClient } from "../../core/auth/ekb.js";
import { EventStore } from "../../domains/events/store.js";
import { pollEvents } from "../../domains/events/poller.js";
export const SERVICE_STATE_DIR = process.env.HOSE_STATE_DIR || join(homedir(), ".config", "hose-use");
@@ -16,6 +19,18 @@ export async function handleServiceCommand(
const port = numberOption(parsed.options, ["port", "p"]);
const host = stringOption(parsed.options, ["host", "h"]);
if (action === "poll") {
const corp = runtime.selectedCorp;
if (!corp) throw new Error("事件轮询需要企业上下文,请通过 --corp=<id> 指定企业。");
const corpId = corp.corpId || corp.id;
const client = await createEkbClient(corp);
const limit = numberOption(parsed.options, ["limit", "count", "n"], 50) || 50;
const store = new EventStore(join(SERVICE_STATE_DIR, `events-${corpId}.json`));
const result = await pollEvents(client, corpId, store, limit);
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
return { stdout: `====== 事件轮询 (企业: ${corp.name}) ======\n${printKeyValue({ "待办扫描": result.scanned.todo, "未读消息扫描": result.scanned.messages, "新增事件": result.newEvents.length, "重复事件": result.duplicateCount, "事件状态文件": join(SERVICE_STATE_DIR, `events-${corpId}.json`) })}\n`, stderr: "", exitCode: 0 };
}
const config: ServiceConfig = {
appRoot: runtime.appRoot || process.cwd(),
entryFile: runtime.entryFile || join(runtime.appRoot || process.cwd(), "src", "cli.ts"),
+2 -1
View File
@@ -132,7 +132,7 @@ export function printHelp(): string {
update 版本自更新与发布记录 (update, update check, update --changelog)
openapi OpenAPI 3.1.0 规范导出 (openapi, openapi --raw, openapi paths, openapi info)
http 启动轻量 HTTP Server 与交互式文档 (http [--port=8888] [--host=127.0.0.1])
service 常驻守护进程管理 (service start|stop|restart|status|logs)
service 常驻守护进程管理 (service start|stop|restart|status|logs|poll)
mcp MCP Server 运行 (serve)
version 查看版本信息
@@ -181,6 +181,7 @@ export function printHelp(): string {
hose-use http --port=8888 # 启动本地 HTTP 服务与可视化交互文档
hose-use service start # 后台启动常驻守护进程服务
hose-use service status # 查看守护进程运行状态与接口地址
hose-use service poll --corp=<id> # 轮询待办/消息并持久化去重事件
hose-use probe # 诊断当前企业鉴权连通性
hose-use skill install # 安装 Agent 技能到用户目录
hose-use update # 自动检查并升级到最新版本
+1 -1
View File
@@ -39,7 +39,7 @@ export async function runServiceCommand(
case undefined:
return serviceStatus(config);
default:
throw new Error("用法: hose service <start|stop|restart|status|logs>");
throw new Error("用法: hose service <start|stop|restart|status|logs|poll>");
}
}
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "bun:test";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { EventStore } from "./store.js";
import { pollEvents } from "./poller.js";
describe("Event poller", () => {
it("persists dedupe keys and only returns new events", async () => {
const dir = mkdtempSync(join(tmpdir(), "hose-events-"));
try {
const store = new EventStore(join(dir, "events.json"));
const client = { get: async (path: string) => new Response(JSON.stringify(path.includes("messages") ? { count: 1, items: [{ id: "m-1", title: "新消息", read: false, updateTime: 10 }] } : { count: 0, items: [] }),), post: async () => new Response(JSON.stringify({ count: 1, items: [{ id: "t-1", updateTime: 11, flowId: { form: { title: "待审单据" } } }] })) } as any;
const first = await pollEvents(client, "corp-1", store, 10);
const second = await pollEvents(client, "corp-1", store, 10);
expect(first.newEvents).toHaveLength(2); expect(second.newEvents).toHaveLength(0); expect(second.duplicateCount).toBe(2);
expect(JSON.parse(readFileSync(join(dir, "events.json"), "utf8")).version).toBe(1);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
});
+22
View File
@@ -0,0 +1,22 @@
import type { KyInstance } from "ky";
import { listMessages } from "../message/tools.js";
import { listTasks } from "../task/tools.js";
import { EventStore } from "./store.js";
import type { EventPollResult, EventRecord } from "./types.js";
function eventId(kind: EventRecord["kind"], id: string, updatedAt?: number): string { return `${kind}:${id}:${updatedAt ?? 0}`; }
export async function pollEvents(client: KyInstance, corpId: string, store: EventStore, count = 50): Promise<EventPollResult> {
const observedAt = Date.now();
const [todo, messages] = await Promise.all([
listTasks(client, corpId, "todo", { start: 0, count }),
listMessages(client, corpId, { start: 0, count, read: false }),
]);
const candidates: EventRecord[] = [
...todo.items.map((payload) => ({ id: eventId("todo", payload.taskId, payload.updatedAt || payload.actionTime), kind: "todo" as const, corpId, observedAt, payload })),
...messages.items.map((payload) => ({ id: eventId("message", payload.id, payload.updateTime || payload.createTime), kind: "message" as const, corpId, observedAt, payload })),
];
const newEvents = candidates.filter((event) => !store.has(event.id));
store.commit(candidates);
return { corpId, observedAt, scanned: { todo: todo.items.length, messages: messages.items.length }, newEvents, duplicateCount: candidates.length - newEvents.length };
}
+27
View File
@@ -0,0 +1,27 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import type { EventRecord } from "./types.js";
interface PersistedEvents { version: 1; events: Record<string, number>; }
const MAX_EVENTS = 2000;
export class EventStore {
constructor(private readonly filePath: string) {}
private read(): PersistedEvents {
if (!existsSync(this.filePath)) return { version: 1, events: {} };
try {
const parsed = JSON.parse(readFileSync(this.filePath, "utf8")) as Partial<PersistedEvents>;
return { version: 1, events: parsed.events && typeof parsed.events === "object" ? parsed.events : {} };
} catch { return { version: 1, events: {} }; }
}
has(id: string): boolean { return Object.prototype.hasOwnProperty.call(this.read().events, id); }
commit(records: EventRecord[]): void {
if (!records.length) return;
const data = this.read();
const merged = { ...data.events };
for (const record of records) merged[record.id] = record.observedAt;
const entries = Object.entries(merged).sort((a, b) => a[1] - b[1]).slice(-MAX_EVENTS);
mkdirSync(dirname(this.filePath), { recursive: true, mode: 0o700 });
writeFileSync(this.filePath, `${JSON.stringify({ version: 1, events: Object.fromEntries(entries) }, null, 2)}\n`, { mode: 0o600 });
}
}
+6
View File
@@ -0,0 +1,6 @@
import type { MessageItem } from "../message/types.js";
import type { TaskItem } from "../task/types.js";
export type EventKind = "todo" | "message";
export interface EventRecord { id: string; kind: EventKind; corpId: string; observedAt: number; payload: TaskItem | MessageItem; }
export interface EventPollResult { corpId: string; observedAt: number; scanned: { todo: number; messages: number }; newEvents: EventRecord[]; duplicateCount: number; }