generated from fission-codes/project-template
/
carmirror.go
430 lines (365 loc) · 11.2 KB
/
carmirror.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package carmirror
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
cmbatch "github.com/fission-codes/go-car-mirror/batch"
instrumented "github.com/fission-codes/go-car-mirror/core/instrumented"
"github.com/fission-codes/go-car-mirror/filter"
cmhttp "github.com/fission-codes/go-car-mirror/http"
cmipld "github.com/fission-codes/go-car-mirror/ipld"
stats "github.com/fission-codes/go-car-mirror/stats"
coreiface "github.com/ipfs/boxo/coreiface"
gocid "github.com/ipfs/go-cid"
golog "github.com/ipfs/go-log"
"github.com/pkg/errors"
"github.com/zeebo/xxh3"
)
const Version = "0.1.0"
var log = golog.Logger("kubo-car-mirror")
const HASH_FUNCTION = 3
func init() {
filter.RegisterHash(3, XX3HashBlockId)
}
func XX3HashBlockId(id cmipld.Cid, seed uint64) uint64 {
return xxh3.HashSeed(id.Bytes(), seed)
}
type CarMirror struct {
// CAR Mirror config
cfg *Config
// CoreAPI
capi coreiface.CoreAPI
// The block store
blockStore *KuboStore
// HTTP client for CAR Mirror requests
client *cmhttp.Client[cmipld.Cid, *cmipld.Cid]
// HTTP server for CAR Mirror requests
server *cmhttp.Server[cmipld.Cid, *cmipld.Cid]
}
// Config encapsulates CAR Mirror configuration
type Config struct {
HTTPRemoteAddr string
MaxBlocksPerRound uint32
MaxBlocksPerColdCall uint32
}
// Validate confirms the configuration is valid
func (cfg *Config) Validate() error {
if cfg.HTTPRemoteAddr == "" {
return fmt.Errorf("HTTPRemoteAddr is required")
}
if cfg.MaxBlocksPerRound < 1 {
return fmt.Errorf("MaxBlocksPerRound must be a positive number")
}
if cfg.MaxBlocksPerColdCall < 1 {
return fmt.Errorf("MaxBlocksPerColdCall must be a positive number")
}
return nil
}
// New creates a local CAR Mirror service.
func New(capi coreiface.CoreAPI, blockStore *KuboStore, opts ...func(cfg *Config)) (*CarMirror, error) {
// Add default stuff to the config
cfg := &Config{}
for _, opt := range opts {
opt(cfg)
}
if err := cfg.Validate(); err != nil {
return nil, err
}
cmResponderConfig := cmbatch.Config{
MaxBlocksPerRound: cfg.MaxBlocksPerRound,
MaxBlocksPerColdCall: cfg.MaxBlocksPerColdCall,
BloomFunction: HASH_FUNCTION,
BloomCapacity: 1024,
// TODO: Make this configurable via config file
Instrument: instrumented.INSTRUMENT_ORCHESTRATOR | instrumented.INSTRUMENT_STORE | instrumented.INSTRUMENT_FILTER,
}
cmServerConfig := cmhttp.Config{
Address: cfg.HTTPRemoteAddr,
}
cm := &CarMirror{
cfg: cfg,
capi: capi,
blockStore: blockStore,
client: cmhttp.NewClient[cmipld.Cid](blockStore, cmResponderConfig),
server: cmhttp.NewServer[cmipld.Cid](blockStore, cmServerConfig, cmResponderConfig),
}
return cm, nil
}
func (cm *CarMirror) StartRemote(ctx context.Context) error {
log.Debugw("enter", "object", "CarMirror", "method", "StartRemote")
if cm.server == nil {
return fmt.Errorf("CAR Mirror is not configured as a remote")
}
go func() {
<-ctx.Done()
if cm.server != nil {
cm.server.Stop()
}
}()
if cm.server != nil {
go cm.server.Start()
}
return nil
}
type PushParams struct {
Cid string
Addr string
Diff string
Stream bool
Background bool
}
func (cm *CarMirror) NewPushSessionHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
p := PushParams{
Cid: r.FormValue("cid"),
Addr: r.FormValue("addr"),
Diff: r.FormValue("diff"),
Stream: r.FormValue("stream") == "true",
Background: r.FormValue("background") == "true",
}
log.Debugw("NewPushSessionHandler", "params", p)
// Parse the CID
cid, err := gocid.Parse(p.Cid)
if err != nil {
WriteError(w, errors.Wrap(err, "failed to parse CID"))
return
}
// Need to get session, enqueue it, run it.
session := cm.client.GetSourceSession(p.Addr)
go func() {
if err := session.Enqueue(cmipld.WrapCid(cid)); err != nil {
log.Debugw("NewPushSessionHandler", "error", err)
WriteError(w, err)
return
}
}()
if !p.Background {
select {
case err := <-session.Done():
log.Debugw("NewPushSessionHandler", "session", "done")
if err != nil {
WriteError(w, err)
}
return
case <-time.After(10 * time.Minute):
// TODO: Unless we handle timeouts in a different manner, maybe make this default configurable plus overrideable per request
log.Debugw("NewPushSessionHandler", "session", "timeout")
}
}
}
})
}
type PullParams struct {
Cid string
Addr string
Stream bool
Background bool
}
func (cm *CarMirror) NewPullSessionHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
p := PullParams{
Cid: r.FormValue("cid"),
Addr: r.FormValue("addr"),
Stream: r.FormValue("stream") == "true",
Background: r.FormValue("background") == "true",
}
log.Debugw("NewPullSessionHandler", "params", p)
// Parse the CID
cid, err := gocid.Parse(p.Cid)
if err != nil {
WriteError(w, errors.Wrap(err, "failed to parse CID"))
return
}
// Initiate the pull
log.Debugw("before receive", "object", "CarMirror", "method", "NewPullSessionHandler", "cid", cid.String(), "addr", p.Addr)
session := cm.client.GetSinkSession(p.Addr)
go func() {
if err := session.Enqueue(cmipld.WrapCid(cid)); err != nil {
log.Debugw("NewPullSessionHandler", "error", err)
WriteError(w, err)
return
}
}()
if !p.Background {
select {
case err := <-session.Done():
log.Debugw("NewPullSessionHandler", "session", "done")
if err != nil {
WriteError(w, err)
}
return
case <-time.After(10 * time.Minute):
// TODO: Do we want this shorter? In particular for CI so we can kill hung sessions instead of waiting way too long?
// TODO: Unless we handle timeouts in a different manner, maybe make this default configurable plus overrideable per request
log.Debugw("NewPullSessionHandler", "session", "timeout")
}
}
}
})
}
// TODO: Any params?
type LsParams struct {
}
type LsResponse struct {
SessionId string
SessionInfo string
}
func (cm *CarMirror) LsHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
p := LsParams{}
log.Debugw("LsHandler", "params", p)
sessionMap := make(map[string]LsResponse)
sessions := make([]LsResponse, 0)
// Start off with the list of sessions from the stats, so they are returned even if closed.
// TODO: This is error prone since we're assuming prefixes (i.e. keys) in the snapshot are session ids.
// Currently that is true, but it may not always be true.
for _, key := range stats.GLOBAL_REPORTING.Snapshot().Keys() {
session := strings.Split(key, ".")[0]
sessionMap[session] = LsResponse{SessionId: session, SessionInfo: "unknown"}
}
log.Debugw("LsHandler", "server.sinkSessions", cm.server.SinkSessions())
sessionTokens := cm.server.SinkSessions()
for _, sessionToken := range sessionTokens {
sessionInfo, err := cm.server.SinkInfo(sessionToken)
if err != nil {
log.Debugw("LsHandler", "error", err)
WriteError(w, err)
return
}
sessionMap[string(sessionToken)] = LsResponse{SessionId: string(sessionToken), SessionInfo: sessionInfo.String()}
log.Debugw("LsHandler", "sessionInfo", sessionInfo)
}
log.Debugw("LsHandler", "server.sourceSessions", cm.server.SourceSessions())
sessionTokens = cm.server.SourceSessions()
for _, sessionToken := range sessionTokens {
sessionInfo, err := cm.server.SourceInfo(sessionToken)
if err != nil {
log.Debugw("LsHandler", "error", err)
WriteError(w, err)
return
}
sessionMap[string(sessionToken)] = LsResponse{SessionId: string(sessionToken), SessionInfo: sessionInfo.String()}
log.Debugw("LsHandler", "sessionInfo", sessionInfo)
}
log.Debugw("LsHandler", "client.sinkSessions", cm.client.SinkSessions())
// TODO: update client.SinkSessions to return a slice of session tokens instead of strings
clientSessionTokens := cm.client.SinkSessions()
for _, sessionToken := range clientSessionTokens {
sessionInfo, err := cm.client.SinkInfo(sessionToken)
if err != nil {
log.Debugw("LsHandler", "error", err)
WriteError(w, err)
return
}
sessionMap[string(sessionToken)] = LsResponse{SessionId: string(sessionToken), SessionInfo: sessionInfo.String()}
log.Debugw("LsHandler", "sessionInfo", sessionInfo)
}
log.Debugw("LsHandler", "client.sourceSessions", cm.client.SourceSessions())
clientSessionTokens = cm.client.SourceSessions()
for _, sessionToken := range clientSessionTokens {
sessionInfo, err := cm.client.SourceInfo(sessionToken)
if err != nil {
log.Debugw("LsHandler", "error", err)
WriteError(w, err)
return
}
sessionMap[string(sessionToken)] = LsResponse{SessionId: string(sessionToken), SessionInfo: sessionInfo.String()}
log.Debugw("LsHandler", "sessionInfo", sessionInfo)
}
for _, session := range sessionMap {
sessions = append(sessions, session)
}
// Write the response
// TODO: Sort them?
json.NewEncoder(w).Encode(sessions)
return
}
})
}
type CancelParams struct {
Session string
}
func (cm *CarMirror) CancelHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
p := CancelParams{
Session: r.FormValue("session"),
}
log.Debugw("CancelHandler", "params", p)
for _, sessionToken := range cm.client.SinkSessions() {
if string(sessionToken) == p.Session {
if err := cm.client.CancelSink(sessionToken); err != nil {
log.Debugw("CancelHandler", "error", err)
WriteError(w, err)
return
}
WriteSuccess(w)
return
}
}
for _, sessionToken := range cm.client.SourceSessions() {
if string(sessionToken) == p.Session {
if err := cm.client.CancelSource(sessionToken); err != nil {
log.Debugw("CancelHandler", "error", err)
WriteError(w, err)
return
}
WriteSuccess(w)
return
}
}
// If we get here, we didn't find the session
WriteError(w, fmt.Errorf("session not found"))
}
})
}
type StatsParams struct {
Session string
}
func (cm *CarMirror) StatsHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
p := StatsParams{
Session: r.FormValue("session"),
}
log.Debugw("StatsHandler", "params", p)
snapshot := stats.GLOBAL_REPORTING.Snapshot()
if p.Session != "" {
snapshot = snapshot.Filter(p.Session)
}
b, err := snapshot.MarshalJSON()
if err != nil {
log.Debugw("StatsHandler", "error", err)
WriteError(w, err)
return
}
w.WriteHeader(http.StatusOK)
w.Write(b)
}
})
}
func WriteSuccess(w http.ResponseWriter) {
w.WriteHeader(http.StatusOK)
res := map[string]string{
"status": "OK",
}
json.NewEncoder(w).Encode(res)
}
func WriteError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
e := map[string]string{
"error": err.Error(),
}
json.NewEncoder(w).Encode(e)
}