merge: integrate review-17-event-pagination
This commit is contained in:
commit
ae76b33c38
5 files changed
+311
-256
No files matched your search
Vendored
+249
-249
File diff suppressed because it is too large.
Load diff
@@ -17,3 +17,5 @@
|
||||
|
||||
- 本域无 `api.ts`:不直接触达 HTTP 传输层,复用 `task/` 与 `message/` 域的编排能力。
|
||||
- 事件 ID 含 `updatedAt`(消息含 `updateTime`),同一实体更新时视为新事件。
|
||||
|
||||
轮询页大小 `count` 按页使用,每轮扫描全部待办及未读消息,最多 10000 页;分页失败或不前进时明确报错且不提交本轮去重状态。页间重复事件按原事件 ID 去重,存储保留全部当前活动事件,避免活动数超过历史容量时反复报告。
|
||||
@@ -0,0 +1,36 @@
|
||||
import { afterEach, expect, test } from "bun:test";
|
||||
import { getDatabase, closeDatabase } from "../../core/db/index.js";
|
||||
import { EventStore } from "./store.js";
|
||||
import { pollEvents } from "./poller.js";
|
||||
afterEach(closeDatabase);
|
||||
function fixture(total: number, fail = false, stalled = false) {
|
||||
const starts: number[] = [];
|
||||
const items = Array.from({ length: total }, (_, i) => ({ id: `task-${i}`, updateTime: i + 1 }));
|
||||
const client = { get: async () => Response.json({ count: 0, items: [] }), post: async (_path: string, options: any) => {
|
||||
const { start, count } = options.json.limit; starts.push(start);
|
||||
if (fail && start > 0) throw new Error("page failed");
|
||||
return Response.json({ count: total, items: items.slice(stalled ? 0 : start, (stalled ? 0 : start) + count) });
|
||||
} } as any;
|
||||
return { starts, client, store: new EventStore("pagination", getDatabase(":memory:")) };
|
||||
}
|
||||
test("scans past the first page and deduplicates subsequent full polls", async () => {
|
||||
const f = fixture(51);
|
||||
const first = await pollEvents(f.client, "corp", f.store, 50);
|
||||
expect(first.newEvents).toHaveLength(51);
|
||||
expect(first.newEvents.at(-1)?.id).toBe("todo:task-50:51");
|
||||
expect(f.starts).toEqual([0, 50]);
|
||||
const second = await pollEvents(f.client, "corp", f.store, 50);
|
||||
expect(second.newEvents).toHaveLength(0); expect(second.duplicateCount).toBe(51);
|
||||
});
|
||||
test("retains dedupe state for all active events even above the history cap", async () => {
|
||||
const f = fixture(2501);
|
||||
expect((await pollEvents(f.client, "corp", f.store, 600)).newEvents).toHaveLength(2501);
|
||||
expect((await pollEvents(f.client, "corp", f.store, 600)).newEvents).toHaveLength(0);
|
||||
});
|
||||
for (const stalled of [false, true]) {
|
||||
test(`partial or stalled pagination cannot commit incomplete state (stalled=${stalled})`, async () => {
|
||||
const f = fixture(51, !stalled, stalled);
|
||||
await expect(pollEvents(f.client, "corp", f.store, 50)).rejects.toThrow();
|
||||
expect(f.store.has("todo:task-0:1")).toBe(false);
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { BusinessError, ValidationError } from "../../core/errors.js";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listMessages } from "../message/tools.js";
|
||||
import { listTasks } from "../task/tools.js";
|
||||
@@ -8,15 +9,31 @@ function eventId(kind: EventRecord["kind"], id: string, updatedAt?: number): str
|
||||
|
||||
export async function pollEvents(client: KyInstance, corpId: string, store: EventStore, count = 50): Promise<EventPollResult> {
|
||||
const observedAt = Date.now();
|
||||
if (!Number.isFinite(count) || count < 1) throw new ValidationError("事件轮询页大小必须为正数");
|
||||
count = Math.min(Math.floor(count), 1000);
|
||||
async function collect<T>(fetchPage: (start: number) => Promise<{ total: number; items: T[] }>, identity: (item: T) => string): Promise<T[]> {
|
||||
const items = new Map<string, T>();
|
||||
let start = 0;
|
||||
for (let pageNumber = 0; pageNumber < 10000; pageNumber++) {
|
||||
const page = await fetchPage(start);
|
||||
if (!page.items.length) return [...items.values()];
|
||||
const previousSize = items.size;
|
||||
for (const item of page.items) items.set(identity(item), item);
|
||||
if (items.size === previousSize) throw new BusinessError("事件分页未前进,未提交本轮去重状态,请重试");
|
||||
start += page.items.length;
|
||||
if (start >= page.total) return [...items.values()];
|
||||
}
|
||||
throw new BusinessError("事件扫描超过 10000 页,未提交本轮去重状态");
|
||||
}
|
||||
const [todo, messages] = await Promise.all([
|
||||
listTasks(client, corpId, "todo", { start: 0, count }),
|
||||
listMessages(client, corpId, { start: 0, count, read: false }),
|
||||
collect(start => listTasks(client, corpId, "todo", { start, count }), task => eventId("todo", task.taskId, task.updatedAt || task.actionTime)),
|
||||
collect(start => listMessages(client, corpId, { start, count, read: false }), message => eventId("message", message.id, message.updateTime || message.createTime)),
|
||||
]);
|
||||
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 })),
|
||||
...todo.map((payload) => ({ id: eventId("todo", payload.taskId, payload.updatedAt || payload.actionTime), kind: "todo" as const, corpId, observedAt, payload })),
|
||||
...messages.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 };
|
||||
return { corpId, observedAt, scanned: { todo: todo.length, messages: messages.length }, newEvents, duplicateCount: candidates.length - newEvents.length };
|
||||
}
|
||||
@@ -79,7 +79,7 @@ export class EventStore {
|
||||
LIMIT ?
|
||||
)
|
||||
`,
|
||||
[this.scopeKey, this.scopeKey, MAX_EVENTS]
|
||||
[this.scopeKey, this.scopeKey, Math.max(MAX_EVENTS, records.length)]
|
||||
);
|
||||
});
|
||||
tx(records);
|
||||
@@ -90,7 +90,7 @@ export class EventStore {
|
||||
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);
|
||||
.slice(-Math.max(MAX_EVENTS, records.length));
|
||||
mkdirSync(dirname(this.jsonPath), { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
this.jsonPath,
|
||||
|
||||
Reference in new issue
Block a user