-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
163 lines (145 loc) · 5.03 KB
/
index.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import ms from 'ms'
import assert from 'node:assert'
import * as Sentry from '@sentry/node'
import { preprocess } from './lib/preprocess.js'
import { evaluate } from './lib/evaluate.js'
import { RoundData } from './lib/round.js'
import { refreshDatabase } from './lib/platform-stats.js'
import timers from 'node:timers/promises'
// Tweak this value to improve the chances of the data being available
const PREPROCESS_DELAY = 60_000
const EVALUATE_DELAY = PREPROCESS_DELAY + 60_000
export const startEvaluate = async ({
ieContract,
fetchMeasurements,
fetchRoundDetails,
recordTelemetry,
createPgClient,
logger,
setScores,
prepareProviderRetrievalResultStats
}) => {
assert(typeof createPgClient === 'function', 'createPgClient must be a function')
const rounds = {
current: null,
previous: null
}
const cidsSeen = []
const roundsSeen = []
let lastNewEventSeenAt = null
const onMeasurementsAdded = async (cid, _roundIndex) => {
const roundIndex = BigInt(_roundIndex)
if (cidsSeen.includes(cid)) return
cidsSeen.push(cid)
if (cidsSeen.length > 1000) cidsSeen.shift()
lastNewEventSeenAt = new Date()
if (!rounds.current) {
rounds.current = new RoundData(roundIndex)
} else if (rounds.current.index !== roundIndex) {
// This occassionally happens because of a race condition between onMeasurementsAdded
// and onRoundStart event handlers.
// See https://github.com/filecoin-station/spark-evaluate/issues/233
const msg = 'Round index mismatch when processing MeasurementsAdded event'
const details = {
currentRoundIndex: rounds.current.index,
eventRoundIndex: roundIndex,
measurementsCid: cid
}
console.error(msg, details)
Sentry.captureException(new Error(msg), { extra: details })
return
}
console.log('Event: MeasurementsAdded', { roundIndex })
console.log(`Sleeping for ${PREPROCESS_DELAY}ms before preprocessing to improve chances of the data being available`)
await timers.setTimeout(PREPROCESS_DELAY)
console.log(`Now preprocessing measurements for CID ${cid} in round ${roundIndex}`)
// Preprocess
try {
await preprocess({
round: rounds.current,
cid,
roundIndex,
fetchMeasurements,
recordTelemetry,
logger
})
} catch (err) {
console.error('CANNOT PREPROCESS MEASUREMENTS [ROUND=%s]:', roundIndex, err)
Sentry.captureException(err, {
extra: {
roundIndex,
measurementsCid: cid
}
})
}
}
const onRoundStart = async (_roundIndex) => {
const roundIndex = BigInt(_roundIndex)
if (roundsSeen.includes(roundIndex)) return
roundsSeen.push(roundIndex)
if (roundsSeen.length > 1000) roundsSeen.shift()
lastNewEventSeenAt = new Date()
console.log('Event: RoundStart', { roundIndex })
if (!rounds.current) {
console.error('No current round data available, skipping evaluation')
return
}
rounds.previous = rounds.current
rounds.current = new RoundData(roundIndex)
console.log('Advanced the current round to %s', roundIndex)
// TODO: Fix this properly and implement a signalling mechanism allowing the "preprocess" step
// to notify the "evaluate" when the preprocessing is done, so that we don't have to use a timer
// here. See also https://github.com/filecoin-station/spark-evaluate/issues/64
console.log(`Sleeping for ${EVALUATE_DELAY}ms before evaluating the round to let the preprocess step finish for the last batch of measurements`)
await timers.setTimeout(EVALUATE_DELAY)
console.log(`Now evaluating the round ${roundIndex}`)
// Evaluate previous round
const evaluatedRoundIndex = roundIndex - 1n
evaluate({
round: rounds.previous,
roundIndex: evaluatedRoundIndex,
ieContract,
fetchRoundDetails,
recordTelemetry,
createPgClient,
logger,
setScores,
prepareProviderRetrievalResultStats
}).catch(err => {
console.error('CANNOT EVALUATE ROUND %s:', evaluatedRoundIndex, err)
Sentry.captureException(err, {
extra: {
roundIndex: evaluatedRoundIndex
}
})
})
}
// Listen for events
ieContract.on('MeasurementsAdded', (...args) => {
onMeasurementsAdded(...args).catch(err => {
console.error('CANNOT ADD MEASUREMENTS:', err)
Sentry.captureException(err)
})
})
ieContract.on('RoundStart', (...args) => {
onRoundStart(...args).catch(err => {
console.error('CANNOT HANDLE START OF ROUND %s:', args[0], err)
Sentry.captureException(err)
})
})
// Periodically update tables aggregating fine-grained statistics
setInterval(() => refreshDatabase(createPgClient), ms('4 hours'))
while (true) {
await timers.setTimeout(10_000)
if (lastNewEventSeenAt) {
recordTelemetry('last_new_event_seen', point => {
point.intField(
'age_s',
Math.round(
(new Date().getTime() - lastNewEventSeenAt.getTime()) / 1000
)
)
})
}
}
}