返回 DeepSeek-Reasonix
contentRequestScheduler.ts
根目录 / desktop / frontend / src / lib / contentRequestScheduler.ts
1 import { RESOURCE_BUDGETS } from "./resourceBudgets";
2
3 type Owner = { active: number };
4
5 type Task = {
6 owner: Owner;
7 run: () => void;
8 cancel: () => void;
9 };
10
11 class ContentRequestScheduler {
12 private active = 0;
13 private queue: Task[] = [];
14
15 owner(): Owner { return { active: 0 }; }
16
17 schedule(owner: Owner, run: () => void, cancel: () => void): void {
18 this.queue.push({ owner, run, cancel });
19 this.drain();
20 }
21
22 release(owner: Owner): void {
23 owner.active = Math.max(0, owner.active - 1);
24 this.active = Math.max(0, this.active - 1);
25 this.drain();
26 }
27
28 cancel(owner: Owner): void {
29 const retained: Task[] = [];
30 for (const task of this.queue) {
31 if (task.owner === owner) task.cancel();
32 else retained.push(task);
33 }
34 this.queue = retained;
35 }
36
37 private drain(): void {
38 while (this.active < RESOURCE_BUDGETS.contentReadsGlobal) {
39 const index = this.queue.findIndex((task) => task.owner.active < RESOURCE_BUDGETS.contentReadsPerSession);
40 if (index < 0) return;
41 const [task] = this.queue.splice(index, 1);
42 this.active += 1;
43 task.owner.active += 1;
44 task.run();
45 }
46 }
47 }
48
49 export const contentRequestScheduler = new ContentRequestScheduler();
50
50 lines TYPESCRIPT