This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
system.go
415 lines (345 loc) · 10.4 KB
/
system.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
package batched
import (
"context"
"errors"
"fmt"
"strconv"
"sync"
"time"
"github.com/ipfs/go-cid"
"github.com/ipfs/go-datastore"
provider "github.com/ipfs/go-ipfs-provider"
"github.com/ipfs/go-ipfs-provider/queue"
"github.com/ipfs/go-ipfs-provider/simple"
logging "github.com/ipfs/go-log"
"github.com/ipfs/go-verifcid"
"github.com/multiformats/go-multihash"
)
var log = logging.Logger("provider.batched")
type BatchProvidingSystem struct {
ctx context.Context
close context.CancelFunc
closewg sync.WaitGroup
reprovideInterval time.Duration
initalReprovideDelay time.Duration
initialReprovideDelaySet bool
rsys provideMany
keyProvider simple.KeyChanFunc
q *queue.Queue
ds datastore.Batching
reprovideCh chan cid.Cid
totalProvides, lastReprovideBatchSize int
avgProvideDuration, lastReprovideDuration time.Duration
}
var _ provider.System = (*BatchProvidingSystem)(nil)
type provideMany interface {
ProvideMany(ctx context.Context, keys []multihash.Multihash) error
Ready() bool
}
// Option defines the functional option type that can be used to configure
// BatchProvidingSystem instances
type Option func(system *BatchProvidingSystem) error
var lastReprovideKey = datastore.NewKey("/provider/reprovide/lastreprovide")
func New(provider provideMany, q *queue.Queue, opts ...Option) (*BatchProvidingSystem, error) {
s := &BatchProvidingSystem{
reprovideInterval: time.Hour * 24,
rsys: provider,
keyProvider: nil,
q: q,
ds: datastore.NewMapDatastore(),
reprovideCh: make(chan cid.Cid),
}
for _, o := range opts {
if err := o(s); err != nil {
return nil, err
}
}
// Setup default behavior for the initial reprovide delay
//
// If the reprovide ticker is larger than a minute (likely),
// provide once after we've been up a minute.
//
// Don't provide _immediately_ as we might be just about to stop.
if !s.initialReprovideDelaySet && s.reprovideInterval > time.Minute {
s.initalReprovideDelay = time.Minute
s.initialReprovideDelaySet = true
}
if s.keyProvider == nil {
s.keyProvider = func(ctx context.Context) (<-chan cid.Cid, error) {
ch := make(chan cid.Cid)
close(ch)
return ch, nil
}
}
// This is after the options processing so we do not have to worry about leaking a context if there is an
// initialization error processing the options
ctx, cancel := context.WithCancel(context.Background())
s.ctx = ctx
s.close = cancel
return s, nil
}
func Datastore(batching datastore.Batching) Option {
return func(system *BatchProvidingSystem) error {
system.ds = batching
return nil
}
}
func ReproviderInterval(duration time.Duration) Option {
return func(system *BatchProvidingSystem) error {
system.reprovideInterval = duration
return nil
}
}
func KeyProvider(fn simple.KeyChanFunc) Option {
return func(system *BatchProvidingSystem) error {
system.keyProvider = fn
return nil
}
}
func initialReprovideDelay(duration time.Duration) Option {
return func(system *BatchProvidingSystem) error {
system.initialReprovideDelaySet = true
system.initalReprovideDelay = duration
return nil
}
}
func (s *BatchProvidingSystem) Run() {
// how long we wait between the first provider we hear about and batching up the provides to send out
const pauseDetectionThreshold = time.Millisecond * 500
// how long we are willing to collect providers for the batch after we receive the first one
const maxCollectionDuration = time.Minute * 10
provCh := s.q.Dequeue()
s.closewg.Add(1)
go func() {
defer s.closewg.Done()
m := make(map[cid.Cid]struct{})
// setup stopped timers
maxCollectionDurationTimer := time.NewTimer(time.Hour)
pauseDetectTimer := time.NewTimer(time.Hour)
stopAndEmptyTimer(maxCollectionDurationTimer)
stopAndEmptyTimer(pauseDetectTimer)
// make sure timers are cleaned up
defer maxCollectionDurationTimer.Stop()
defer pauseDetectTimer.Stop()
resetTimersAfterReceivingProvide := func() {
firstProvide := len(m) == 0
if firstProvide {
// after receiving the first provider start up the timers
maxCollectionDurationTimer.Reset(maxCollectionDuration)
pauseDetectTimer.Reset(pauseDetectionThreshold)
} else {
// otherwise just do a full restart of the pause timer
stopAndEmptyTimer(pauseDetectTimer)
pauseDetectTimer.Reset(pauseDetectionThreshold)
}
}
for {
performedReprovide := false
// at the start of every loop the maxCollectionDurationTimer and pauseDetectTimer should be already be
// stopped and have empty channels
loop:
for {
select {
case <-maxCollectionDurationTimer.C:
// if this timer has fired then the pause timer has started so let's stop and empty it
stopAndEmptyTimer(pauseDetectTimer)
break loop
default:
}
select {
case c := <-provCh:
resetTimersAfterReceivingProvide()
m[c] = struct{}{}
continue
default:
}
select {
case c := <-provCh:
resetTimersAfterReceivingProvide()
m[c] = struct{}{}
case c := <-s.reprovideCh:
resetTimersAfterReceivingProvide()
m[c] = struct{}{}
performedReprovide = true
case <-pauseDetectTimer.C:
// if this timer has fired then the max collection timer has started so let's stop and empty it
stopAndEmptyTimer(maxCollectionDurationTimer)
break loop
case <-maxCollectionDurationTimer.C:
// if this timer has fired then the pause timer has started so let's stop and empty it
stopAndEmptyTimer(pauseDetectTimer)
break loop
case <-s.ctx.Done():
return
}
}
if len(m) == 0 {
continue
}
keys := make([]multihash.Multihash, 0, len(m))
for c := range m {
delete(m, c)
// hash security
if err := verifcid.ValidateCid(c); err != nil {
log.Errorf("insecure hash in reprovider, %s (%s)", c, err)
continue
}
keys = append(keys, c.Hash())
}
for !s.rsys.Ready() {
log.Debugf("reprovider system not ready")
select {
case <-time.After(time.Minute):
case <-s.ctx.Done():
return
}
}
log.Debugf("starting provide of %d keys", len(keys))
start := time.Now()
err := s.rsys.ProvideMany(s.ctx, keys)
if err != nil {
log.Debugf("providing failed %v", err)
continue
}
dur := time.Since(start)
totalProvideTime := int64(s.totalProvides) * int64(s.avgProvideDuration)
recentAvgProvideDuration := time.Duration(int64(dur) / int64(len(keys)))
s.avgProvideDuration = time.Duration((totalProvideTime + int64(dur)) / int64(s.totalProvides+len(keys)))
s.totalProvides += len(keys)
log.Debugf("finished providing of %d keys. It took %v with an average of %v per provide", len(keys), dur, recentAvgProvideDuration)
if performedReprovide {
s.lastReprovideBatchSize = len(keys)
s.lastReprovideDuration = dur
if err := s.ds.Put(lastReprovideKey, storeTime(time.Now())); err != nil {
log.Errorf("could not store last reprovide time: %v", err)
}
if err := s.ds.Sync(lastReprovideKey); err != nil {
log.Errorf("could not perform sync of last reprovide time: %v", err)
}
}
}
}()
s.closewg.Add(1)
go func() {
defer s.closewg.Done()
var initialReprovideCh, reprovideCh <-chan time.Time
// If reproviding is enabled (non-zero)
if s.reprovideInterval > 0 {
reprovideTicker := time.NewTicker(s.reprovideInterval)
defer reprovideTicker.Stop()
reprovideCh = reprovideTicker.C
// if there is a non-zero initial reprovide time that was set in the initializer or if the fallback has been
if s.initialReprovideDelaySet {
initialReprovideTimer := time.NewTimer(s.initalReprovideDelay)
defer initialReprovideTimer.Stop()
initialReprovideCh = initialReprovideTimer.C
}
}
for s.ctx.Err() == nil {
select {
case <-initialReprovideCh:
case <-reprovideCh:
case <-s.ctx.Done():
return
}
err := s.reprovide(s.ctx, false)
// only log if we've hit an actual error, otherwise just tell the client we're shutting down
if s.ctx.Err() == nil && err != nil {
log.Errorf("failed to reprovide: %s", err)
}
}
}()
}
func stopAndEmptyTimer(t *time.Timer) {
if !t.Stop() {
<-t.C
}
}
func storeTime(t time.Time) []byte {
val := []byte(fmt.Sprintf("%d", t.UnixNano()))
return val
}
func parseTime(b []byte) (time.Time, error) {
tns, err := strconv.ParseInt(string(b), 10, 64)
if err != nil {
return time.Time{}, err
}
return time.Unix(0, tns), nil
}
func (s *BatchProvidingSystem) Close() error {
s.close()
err := s.q.Close()
s.closewg.Wait()
return err
}
func (s *BatchProvidingSystem) Provide(cid cid.Cid) error {
return s.q.Enqueue(cid)
}
func (s *BatchProvidingSystem) Reprovide(ctx context.Context) error {
return s.reprovide(ctx, true)
}
func (s *BatchProvidingSystem) reprovide(ctx context.Context, force bool) error {
if !s.shouldReprovide() && !force {
return nil
}
kch, err := s.keyProvider(ctx)
if err != nil {
return err
}
reprovideCidLoop:
for {
select {
case c, ok := <-kch:
if !ok {
break reprovideCidLoop
}
select {
case s.reprovideCh <- c:
case <-ctx.Done():
return ctx.Err()
}
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
func (s *BatchProvidingSystem) getLastReprovideTime() (time.Time, error) {
val, err := s.ds.Get(lastReprovideKey)
if errors.Is(err, datastore.ErrNotFound) {
return time.Time{}, nil
}
if err != nil {
return time.Time{}, fmt.Errorf("could not get last reprovide time")
}
t, err := parseTime(val)
if err != nil {
return time.Time{}, fmt.Errorf("could not decode last reprovide time, got %q", string(val))
}
return t, nil
}
func (s *BatchProvidingSystem) shouldReprovide() bool {
t, err := s.getLastReprovideTime()
if err != nil {
log.Debugf("getting last reprovide time failed: %s", err)
return false
}
if time.Since(t) < time.Duration(float64(s.reprovideInterval)*0.5) {
return false
}
return true
}
type BatchedProviderStats struct {
TotalProvides, LastReprovideBatchSize int
AvgProvideDuration, LastReprovideDuration time.Duration
}
// Stat returns various stats about this provider system
func (s *BatchProvidingSystem) Stat(ctx context.Context) (BatchedProviderStats, error) {
// TODO: Does it matter that there is no locking around the total+average values?
return BatchedProviderStats{
TotalProvides: s.totalProvides,
LastReprovideBatchSize: s.lastReprovideBatchSize,
AvgProvideDuration: s.avgProvideDuration,
LastReprovideDuration: s.lastReprovideDuration,
}, nil
}