feat: add durable service event poller
This commit is contained in:
1 parent
f72deb01b1
commit
84e6fa58fd
9 files changed
+104
-2
No files matched your search
@@ -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 }); }
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
Reference in new issue
Block a user