a demonstration replicated social networking web app built with anproto
wiredove.net/
social
ed25519
protocols
1const SAMPLES_PER_METRIC = 60
2const LOG_EVERY_N = 20
3const metrics = new Map()
4
5const nowMs = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())
6
7const isEnabled = () => {
8 if (typeof window === 'undefined') { return false }
9 if (window.__perfMetrics === true) { return true }
10 try {
11 return localStorage.getItem('wiredove.perf') === '1'
12 } catch {
13 return false
14 }
15}
16
17const percentile = (values, p) => {
18 if (!values.length) { return 0 }
19 const sorted = [...values].sort((a, b) => a - b)
20 const idx = Math.min(sorted.length - 1, Math.max(0, Math.floor((sorted.length - 1) * p)))
21 return sorted[idx]
22}
23
24const pushMetric = (name, duration) => {
25 const record = metrics.get(name) || { values: [], count: 0 }
26 record.values.push(duration)
27 if (record.values.length > SAMPLES_PER_METRIC) {
28 record.values.shift()
29 }
30 record.count += 1
31 metrics.set(name, record)
32 if (record.count % LOG_EVERY_N !== 0) { return }
33 const p50 = percentile(record.values, 0.5)
34 const p95 = percentile(record.values, 0.95)
35 const avg = record.values.reduce((sum, value) => sum + value, 0) / record.values.length
36 console.log(`[perf] ${name} n=${record.values.length} avg=${avg.toFixed(1)}ms p50=${p50.toFixed(1)}ms p95=${p95.toFixed(1)}ms`)
37}
38
39export const perfStart = (name, detail = '') => {
40 if (!isEnabled()) { return null }
41 return { name, detail, t0: nowMs() }
42}
43
44export const perfEnd = (token) => {
45 if (!token || !token.name) { return 0 }
46 const duration = nowMs() - token.t0
47 const metricName = token.detail ? `${token.name}:${token.detail}` : token.name
48 pushMetric(metricName, duration)
49 return duration
50}
51
52export const perfMeasure = async (name, fn, detail = '') => {
53 const token = perfStart(name, detail)
54 try {
55 return await fn()
56 } finally {
57 perfEnd(token)
58 }
59}