返回 DeepSeek-Reasonix
appLifecycleProbe.ts
根目录 / desktop / frontend / src / app-runtime / appLifecycleProbe.ts
1 export type LifecycleProbeSnapshot = {
2 committedRenders: number;
3 liveRenderTokens: number;
4 liveRenderTokenIds: number[];
5 activeOperations: number;
6 activeSubscriptions: number;
7 invariantViolations: number;
8 overflow: boolean;
9 };
10
11 type AppLifecycleProbeApi = { snapshot(): LifecycleProbeSnapshot };
12
13 declare global {
14 interface Window { __reasonixAppLifecycle?: AppLifecycleProbeApi }
15 }
16
17 // Qualification is finite. Overflow invalidates the evidence; never evict live refs.
18 const MAX_RENDER_REFS = 65_536;
19 const renderRefs = new Map<number, WeakRef<object>>();
20 const renderIds = new WeakMap<object, number>();
21 let committedRenders = 0;
22 let activeOperations = 0;
23 let activeSubscriptions = 0;
24 let invariantViolations = 0;
25 let overflow = false;
26
27 function enabled(): boolean {
28 if (typeof window === "undefined") return false;
29 const params = new URLSearchParams(window.location.search);
30 return params.get("app-lifecycle-probe") === "1" || params.get("bench") === "1";
31 }
32
33 function liveIds(): number[] {
34 const ids: number[] = [];
35 for (const [id, ref] of renderRefs) {
36 if (ref.deref()) ids.push(id);
37 else renderRefs.delete(id);
38 }
39 return ids;
40 }
41
42 function publishApi(): void {
43 if (!enabled() || window.__reasonixAppLifecycle) return;
44 window.__reasonixAppLifecycle = {
45 snapshot: () => {
46 const liveRenderTokenIds = liveIds();
47 return {
48 committedRenders, liveRenderTokens: liveRenderTokenIds.length, liveRenderTokenIds,
49 activeOperations, activeSubscriptions, invariantViolations, overflow,
50 };
51 },
52 };
53 }
54
55 export function createAppRenderToken(): object | null {
56 if (!enabled()) return null;
57 publishApi();
58 return {};
59 }
60
61 export function commitAppRenderToken(token: object | null): void {
62 if (!token || renderIds.has(token)) return;
63 const id = ++committedRenders;
64 renderIds.set(token, id);
65 if (renderRefs.size >= MAX_RENDER_REFS) liveIds();
66 if (renderRefs.size >= MAX_RENDER_REFS) {
67 overflow = true;
68 return;
69 }
70 renderRefs.set(id, new WeakRef(token));
71 }
72
73 export function trackAppOperation(delta: 1 | -1): void {
74 if (!enabled()) return;
75 activeOperations += delta;
76 if (activeOperations < 0) invariantViolations += 1;
77 }
78
79 export function trackAppSubscription(delta: 1 | -1): void {
80 if (!enabled()) return;
81 activeSubscriptions += delta;
82 if (activeSubscriptions < 0) invariantViolations += 1;
83 }
84
84 lines TYPESCRIPT