-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes_handler.go
363 lines (314 loc) · 11.5 KB
/
routes_handler.go
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package main
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strconv"
"strings"
"time"
"github.com/drand/drand/v2/common"
proto "github.com/drand/drand/v2/protobuf/drand"
"github.com/drand/http-server/grpc"
"github.com/go-chi/chi/v5"
)
var FrontrunTiming time.Duration
func GetBeacon(c *grpc.Client, isV2 bool) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
m, err := createRequestMD(r)
if err != nil {
slog.Error("unable to create metadata for request", "error", err)
http.Error(w, "Failed to get beacon", http.StatusInternalServerError)
return
}
roundStr := chi.URLParam(r, "round")
round, err := strconv.ParseUint(roundStr, 10, 64)
if err != nil {
w.Header().Set("Cache-Control", "public, max-age=604800, immutable")
http.Error(w, "Failed to parse round. Err: "+err.Error(), http.StatusBadRequest)
return
}
info, err := c.GetChainInfo(r.Context(), m)
if err != nil {
slog.Error("[GetBeacon] error retrieving chain info from primary client", "error", err)
// we will skip cache-age setting, something is wrong
w.Header().Set("Cache-Control", "must-revalidate, no-cache, max-age=0")
if errors.Is(err, context.Canceled) {
http.Error(w, "timeout", http.StatusGatewayTimeout)
} else if strings.Contains(err.Error(), "unknown chain hash") {
http.Error(w, "unknown chain hash", http.StatusBadRequest)
} else {
http.Error(w, "Failed to get beacon", http.StatusInternalServerError)
}
return
}
nextTime, nextRound := info.ExpectedNext()
if round >= nextRound+1 { // never happens when fetching latest because round == 0
w.Header().Set("Cache-Control", "must-revalidate, no-cache, max-age=0")
slog.Error("[GetBeacon] Future beacon was requested, unexpected", "requested", round, "expected", nextRound, "from", r.RemoteAddr)
// I know, 425 is meant to indicate a replay attack risk, but hey, it's the perfect error name!
http.Error(w, "Requested future beacon", http.StatusTooEarly)
return
} else if round == nextRound {
// we wait until the round is supposed to be emitted, minus frontrun to account for network latency anyway
time.Sleep(time.Duration(nextTime-time.Now().Unix())*time.Second - FrontrunTiming)
}
beacon, err := c.GetBeacon(r.Context(), m, round)
if err != nil {
if err != nil {
slog.Error("all clients are unable to provide beacons", "error", err)
w.Header().Set("Cache-Control", "must-revalidate, no-cache, max-age=0")
http.Error(w, "Failed to get beacon", http.StatusInternalServerError)
return
}
}
if isV2 {
// we make sure that the V2 api aren't marshaling randommness
beacon.UnsetRandomness()
} else {
// we need to set the randomness since the nodes are not supposed to send it over the wire anymore
beacon.SetRandomness()
}
json, err := json.Marshal(beacon)
if err != nil {
w.Header().Set("Cache-Control", "must-revalidate, no-cache, max-age=0")
http.Error(w, "Failed to Encode beacon in hex", http.StatusInternalServerError)
return
}
if round != 0 {
// i.e. we're not fetching latest, we can store these beacons for a long time
w.Header().Set("Cache-Control", "public, max-age=604800, immutable")
} else {
cacheTime := nextTime - time.Now().Unix()
if cacheTime < 0 {
cacheTime = 0
}
// we're fetching latest we need to stop caching in time for the next round
w.Header().Set("Cache-Control",
fmt.Sprintf("public, must-revalidate, max-age=%d", cacheTime))
slog.Debug("[GetBeacon] StatusOK", "cachetime", cacheTime)
}
w.WriteHeader(http.StatusOK)
w.Write(json)
}
}
func GetChains(c *grpc.Client) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
chains, err := c.GetChains(r.Context())
if err != nil {
if err != nil {
slog.Error("failed to get chains from all clients", "error", err)
http.Error(w, "Failed to get chains", http.StatusInternalServerError)
return
}
}
json, err := json.Marshal(chains)
if err != nil {
slog.Error("failed to encode chain in json", "error", err)
http.Error(w, "Failed to encode chains", http.StatusInternalServerError)
return
}
w.Write(json)
}
}
func GetHealth(c *grpc.Client) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// we never cache health requests (rate-limiting should prevent DoS at the proxy level)
w.Header().Set("Cache-Control", "no-cache")
m, err := createRequestMD(r)
if err != nil {
slog.Error("[GetHealth] unable to create metadata for request", "error", err)
http.Error(w, "Failed to get health", http.StatusInternalServerError)
return
}
latest, err := c.GetBeacon(r.Context(), m, 0)
if err != nil {
slog.Error("[GetHealth] failed to get latest beacon", "error", err)
http.Error(w, "Failed to get latest beacon for health", http.StatusInternalServerError)
return
}
info, err := c.GetChainInfo(r.Context(), m)
if err != nil {
slog.Error("[GetHealth] failed to get chain info", "error", err)
http.Error(w, "Failed to get chain info for health", http.StatusInternalServerError)
return
}
_, next := info.ExpectedNext()
if next-2 > latest.Round {
// we force a retry with another backend if we see a discrepancy in case that backend is stuck on a old latest beacon
slog.Debug("[GetHealth] forcing retry with other SubConn")
ctx := context.WithValue(r.Context(), grpc.SkipCtxKey{}, true)
latest, err = c.GetBeacon(ctx, m, 0)
if err != nil {
slog.Error("[GetHealth] failed to get latest beacon", "error", err)
http.Error(w, "Failed to get latest beacon for health", http.StatusInternalServerError)
return
}
}
if latest.Round >= next-2 {
w.WriteHeader(http.StatusOK)
} else {
slog.Debug("[GetHealth] http.StatusServiceUnavailable", "current", latest.Round, "expected", next-1)
w.WriteHeader(http.StatusServiceUnavailable)
}
resp := make(map[string]uint64)
resp["current"] = latest.Round
resp["expected"] = next - 1
json, err := json.Marshal(resp)
if err != nil {
slog.Error("[GetHealth] unable to encode HealthStatus in json", "error", err)
http.Error(w, "Failed to encode HealthStatus", http.StatusInternalServerError)
return
}
w.Write(json)
}
}
func GetBeaconIds(c *grpc.Client) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
ids, _, err := c.GetBeaconIds(r.Context())
if err != nil {
slog.Error("[GetBeaconIds] failed to get beacon ids from client", "error", err)
http.Error(w, "Failed to get beacon ids", http.StatusServiceUnavailable)
return
}
json, err := json.Marshal(ids)
if err != nil {
slog.Error("[GetBeaconIds] failed to encode beacon ids in json", "error", err)
http.Error(w, "Failed to produce beacon ids", http.StatusInternalServerError)
}
w.Write(json)
}
}
func GetInfoV1(c *grpc.Client) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
m, err := createRequestMD(r)
if err != nil {
slog.Error("[GetInfoV1] unable to create metadata for request", "error", err)
http.Error(w, "Failed to get info", http.StatusInternalServerError)
return
}
chains, err := c.GetChainInfo(r.Context(), m)
if err != nil {
if err != nil {
slog.Error("[GetInfoV1] failed to get ChainInfo from all clients", "error", err)
http.Error(w, "Failed to get ChainInfo", http.StatusInternalServerError)
return
}
}
json, err := json.Marshal(chains.V1())
if err != nil {
slog.Error("[GetInfoV1] unable to encode ChainInfo in json", "error", err)
http.Error(w, "Failed to encode ChainInfo", http.StatusInternalServerError)
return
}
w.Write(json)
}
}
func GetInfoV2(c *grpc.Client) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
m, err := createRequestMD(r)
if err != nil {
slog.Error("[GetInfoV2] unable to create metadata for request", "error", err)
http.Error(w, "Failed to get info", http.StatusInternalServerError)
return
}
chains, err := c.GetChainInfo(r.Context(), m)
if err != nil {
if err != nil {
slog.Error("[GetInfoV2] failed to get ChainInfo", "error", err)
http.Error(w, "Failed to get ChainInfo", http.StatusInternalServerError)
return
}
}
json, err := json.Marshal(chains)
if err != nil {
slog.Error("[GetInfoV2] unable to encode ChainInfo in json", "error", err)
http.Error(w, "Failed to encode ChainInfo", http.StatusInternalServerError)
return
}
w.Write(json)
}
}
func GetLatest(c *grpc.Client, isV2 bool) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
m, err := createRequestMD(r)
if err != nil {
slog.Error("[GetLatest] unable to create metadata for request", "error", err)
http.Error(w, "Failed to get latest", http.StatusInternalServerError)
return
}
beacon, err := c.GetBeacon(r.Context(), m, 0)
if err != nil {
if err != nil {
slog.Error("[GetLatest] unable to get beacon from any grpc client", "error", err)
http.Error(w, "Failed to get beacon", http.StatusInternalServerError)
return
}
}
// TODO: should we rather use the api.version key from the request context set in apiVersionCtx?
// the current way of doing it probably allows the compiler to inline the right path tho...
if isV2 {
// we make sure that the V2 api aren't marshaling randommness
beacon.UnsetRandomness()
} else {
// we need to set the randomness since the nodes are not supposed to send it over the wire anymore
beacon.SetRandomness()
}
json, err := json.Marshal(beacon)
if err != nil {
slog.Error("[GetLatest] unable to encode beacon in json", "error", err)
http.Error(w, "Failed to encode beacon", http.StatusInternalServerError)
return
}
w.Write(json)
}
}
func GetNext(c *grpc.Client) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
m, err := createRequestMD(r)
if err != nil {
slog.Error("[GetNext] unable to create metadata for request", "error", err)
http.Error(w, "Failed to get latest", http.StatusInternalServerError)
return
}
beacon, err := c.Next(r.Context(), m)
if err != nil {
slog.Error("[GetNext] unable to get next beacon from any grpc client", "error", err)
http.Error(w, "Failed to get beacon", http.StatusInternalServerError)
return
}
json, err := json.Marshal(beacon)
if err != nil {
slog.Error("[GetNext] unable to encode beacon in json", "error", err)
http.Error(w, "Failed to encode beacon", http.StatusInternalServerError)
return
}
w.Write(json)
}
}
func createRequestMD(r *http.Request) (*proto.Metadata, error) {
chainhash := chi.URLParam(r, "chainhash")
beaconID := chi.URLParam(r, "beaconID")
// handling the default case
if chainhash == "" && beaconID == "" {
return &proto.Metadata{BeaconID: common.DefaultBeaconID}, nil
}
// warning when unusual request is built
if len(chainhash) == 64 && beaconID != "" {
slog.Warn("[createRequestMD] unexpectedly, createRequestMD got both a chainhash and a beaconID. Ignoring beaconID")
}
// handling the beacon ID case
if beaconID != "" && chainhash == "" {
return &proto.Metadata{BeaconID: beaconID}, nil
}
// handling the chain hash case
hash, err := hex.DecodeString(chainhash)
if err != nil {
slog.Error("[createRequestMD] error decoding hex", "chainhash", chainhash, "error", err)
return nil, errors.New("unable to decode chainhash as hex")
}
return &proto.Metadata{ChainHash: hash}, nil
}