This repository has been archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
status.js
98 lines (86 loc) · 2.2 KB
/
status.js
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
// SPDX-FileCopyrightText: 2021 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
const Obv = require('obz')
module.exports = function Status(log, jitdb) {
const stats = {
log: log.since.value || 0,
jit: {},
indexes: {},
progress: 0,
}
const obv = Obv().set(stats)
const EMIT_INTERVAL = 1000
let i = 0
let iTimer = 0
let timer = null
function avgPercent(offsets, stats) {
if (offsets.length === 0) return 1 // assume 100% if there are no numbers
const logSize = Math.max(1, stats.log)
const N = offsets.length
return Math.min(
offsets
.map((offset) => Math.max(0, offset)) // avoid negative numbers
.map((offset) => offset / logSize) // this index's progress
.reduce((sum, x) => sum + x, 0) / N, // avg = (sum of all progress) / N
1 // never go above 1
)
}
function avgOffset(offsets, stats) {
const logSize = Math.max(1, stats.log)
return avgPercent(offsets, stats) * logSize
}
// Crunch stats numbers to produce one number for the "indexing" progress
function calculateProgress() {
if (!stats.log || stats.log < 0) return 1
const avgJITDBOffset = avgOffset(Object.values(stats.jit), stats)
const offsets = Object.values(stats.indexes).concat(avgJITDBOffset)
return avgPercent(offsets, stats)
}
jitdb.status((jitStats) => {
updateLog()
stats.jit = jitStats
update()
})
function update() {
++i
if (!timer) {
iTimer = i
emit()
setTimer()
}
}
function emit() {
stats.progress = calculateProgress()
obv.set(stats)
}
function setTimer() {
// Turn on
timer = setInterval(() => {
if (i === iTimer) {
// Turn off because nothing has been updated recently
clearInterval(timer)
timer = null
i = iTimer = 0
} else {
iTimer = i
emit()
}
}, EMIT_INTERVAL)
if (timer.unref) timer.unref()
}
function updateLog() {
stats.log = log.since.value || 0
}
function updateIndex(name, offset) {
if (stats.indexes[name] === offset) return
updateLog()
stats.indexes[name] = offset
update()
}
return {
obv,
updateLog,
updateIndex,
}
}