Merge pull request #34 from yunyingk/feat/issue-12-event-poller

feat: add durable service event poller
This commit is contained in:
yunyingk authored and GitHub committed 2026-09-05 20:48:45 +08:00
commit a5bfaafa10
9 files changed
+104 -2

No files matched your search

+2
View File
@@ -52,6 +52,7 @@ metadata:
| 工作流详情与开通切换 | `hose workflow get`, `hose workflow toggle` | [references/workflow.md](references/workflow.md) |
| 工作流节点树、代码依赖与静态诊断 | `hose workflow analyze <pipelineId>` | [references/workflow.md](references/workflow.md) |
| 常驻守护进程管理 / 后台运行 | `hose service start`, `hose service status` | [references/service.md](references/service.md) |
| 待办/消息事件轮询与去重 | `hose service poll --corp=<id>` | [references/service.md](references/service.md) |
| 启动本地 HTTP 服务 / 打开可视化交互文档 | `hose http --port=8888` (访问 `/docs`) | [references/service.md](references/service.md) |
| CLI 同进程执行网关 / REST 接口调用 | `POST /api/cli`, `GET /v1/corps` | [references/service.md](references/service.md) |
| 导出标准 OpenAPI 3.1.0 JSON 规范 | `hose openapi`, `hose openapi --raw` | [references/service.md](references/service.md) |
@@ -109,6 +110,7 @@ hose workflow analyze wf_01k83y... --json # 输出节点树、引用依
hose http --port=8888 # 启动前台 HTTP 服务与交互式文档
hose service start # 后台启动常驻守护进程服务
hose service status # 查看常驻守护进程运行状态与端点
hose service poll --corp=ID01ofWoOC1wiX --json # 轮询待办/消息并去重落盘
hose service logs # 查看常驻守护进程日志
hose service stop # 停止后台常驻守护进程
```
+9
View File
@@ -33,6 +33,15 @@ hose-use service run
每次执行 `service status` 或 `service start` 时,系统会自动探测记录的 PID:
- 若进程已终止(孤儿 PID)或 PID 被其它非 `hose` 进程复用,系统会自动执行自愈逻辑,清理失效的 PID 文件。
### 事件轮询与去重 (`service poll`)
单次读取待办和未读消息,按事件 ID 写入 `~/.config/hose-use/events-<corpId>.json`,重复轮询不会重复返回已观察事件:
```bash
hose-use service poll --corp=<corpId>
hose-use service poll --corp=<corpId> --limit=100 --json
```
---
## 2. 前台 HTTP 服务 (`http` / `serve`)
+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; }