forked from Prompt-Hash-Stellar/prompt-hash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformanceAudit.ts
More file actions
98 lines (84 loc) · 2.31 KB
/
Copy pathperformanceAudit.ts
File metadata and controls
98 lines (84 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { metrics } from "./metrics";
export type AuditScope =
| "marketplace_load"
| "prompt_detail_load"
| "browse_load"
| "sell_form_load"
| "profile_load"
| "wallet_connect"
| "purchase_flow"
| string;
export interface AuditEntry {
scope: AuditScope;
startedAt: number;
duration: number;
metadata?: Record<string, string | number | boolean>;
}
const BUDGET_MS: Record<string, number> = {
marketplace_load: 1500,
prompt_detail_load: 1000,
browse_load: 1200,
sell_form_load: 800,
profile_load: 1000,
wallet_connect: 3000,
purchase_flow: 5000,
};
const _log: AuditEntry[] = [];
export function startAudit(scope: AuditScope): () => AuditEntry {
const startedAt = performance.now();
return (metadata?: Record<string, string | number | boolean>): AuditEntry => {
const duration = Math.round(performance.now() - startedAt);
const entry: AuditEntry = { scope, startedAt, duration, metadata };
_log.push(entry);
metrics.emit(`perf_${scope}_duration_ms`, duration, { scope });
const budget = BUDGET_MS[scope];
if (budget !== undefined && duration > budget) {
metrics.emit("perf_budget_exceeded_total", 1, {
scope,
budget_ms: budget,
actual_ms: duration,
});
}
return entry;
};
}
export function getAuditLog(): readonly AuditEntry[] {
return _log;
}
export function clearAuditLog(): void {
_log.splice(0, _log.length);
}
export function getAuditSummary(): {
scope: AuditScope;
count: number;
avgMs: number;
maxMs: number;
overBudget: number;
}[] {
const byScope = new Map<
AuditScope,
{ total: number; count: number; max: number; overBudget: number }
>();
for (const entry of _log) {
const existing = byScope.get(entry.scope) ?? {
total: 0,
count: 0,
max: 0,
overBudget: 0,
};
const budget = BUDGET_MS[entry.scope] ?? Infinity;
byScope.set(entry.scope, {
total: existing.total + entry.duration,
count: existing.count + 1,
max: Math.max(existing.max, entry.duration),
overBudget: existing.overBudget + (entry.duration > budget ? 1 : 0),
});
}
return Array.from(byScope.entries()).map(([scope, data]) => ({
scope,
count: data.count,
avgMs: Math.round(data.total / data.count),
maxMs: data.max,
overBudget: data.overBudget,
}));
}