-
Notifications
You must be signed in to change notification settings - Fork 0
/
pin.go
745 lines (637 loc) · 14.6 KB
/
pin.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
package rcpinner
import (
"context"
"fmt"
"sync"
"github.com/ipfs/boxo/ipld/merkledag"
pin "github.com/ipfs/boxo/pinning/pinner"
"github.com/ipfs/go-cid"
ds "github.com/ipfs/go-datastore"
ipld "github.com/ipfs/go-ipld-format"
)
const (
basePath = "/pins"
rIndexPath = "/pins/idx_r"
dIndexPath = "/pins/idx_d"
)
var (
linkRecursive string
linkDirect string
)
func init() {
recursiveStr, ok := pin.ModeToString(pin.Recursive)
if !ok {
panic("could not find recursive pin enum")
}
linkRecursive = recursiveStr
directStr, ok := pin.ModeToString(pin.Direct)
if !ok {
panic("could not find direct pin enum")
}
linkDirect = directStr
}
var _ pin.Pinner = (*RcPinner)(nil)
type syncDAGService interface {
ipld.DAGService
Sync() error
}
type noSyncDAGService struct {
ipld.DAGService
}
func (d *noSyncDAGService) Sync() error {
return nil
}
// RcPinner implements the Pinner interface
type RcPinner struct {
dstore ds.Datastore
dserv syncDAGService
cidRIdx *index
cidDIdx *index
autoSync bool
clean int64
dirty int64
mu sync.RWMutex
}
// New creates a new pinner and loads its keysets from the given datastore. If
// there is no data present in the datastore, then an empty pinner is returned.
//
// By default, changes are automatically flushed to the datastore. This can be
// disabled by calling SetAutosync(false), which will require that Flush be
// called explicitly.
func New(
ctx context.Context,
dstore ds.Datastore,
dserv ipld.DAGService,
) (*RcPinner, error) {
syncDserv, ok := dserv.(syncDAGService)
if !ok {
syncDserv = &noSyncDAGService{dserv}
}
cidRIdx, err := newIndex(ctx, dstore, ds.NewKey(rIndexPath))
if err != nil {
return nil, err
}
cidDIdx, err := newIndex(ctx, dstore, ds.NewKey(dIndexPath))
if err != nil {
return nil, err
}
return &RcPinner{
autoSync: true,
cidRIdx: cidRIdx,
cidDIdx: cidDIdx,
dserv: syncDserv,
dstore: dstore,
}, nil
}
// SetAutosync allows auto-syncing to be enabled or disabled during runtime.
// This may be used to turn off autosync before doing many repeated pinning
// operations, and then turn it on after. Returns the previous value.
func (p *RcPinner) SetAutosync(auto bool) bool {
p.mu.Lock()
defer p.mu.Unlock()
p.autoSync, auto = auto, p.autoSync
return auto
}
// Pin the given node, optionally recursive
func (p *RcPinner) Pin(
ctx context.Context,
nd ipld.Node,
recursive bool,
) error {
if err := p.dserv.Add(ctx, nd); err != nil {
return err
}
if recursive {
return p.doPinRecursive(ctx, nd.Cid(), true)
}
return p.doPinDirect(ctx, nd.Cid())
}
func (p *RcPinner) doPinDirect(
ctx context.Context,
c cid.Cid,
) error {
p.mu.Lock()
defer p.mu.Unlock()
if _, err := p.cidDIdx.inc(ctx, c, 1); err != nil {
return err
}
if err := p.flushPins(ctx, false); err != nil {
return err
}
return nil
}
func (p *RcPinner) doPinRecursive(
ctx context.Context,
c cid.Cid,
fetch bool,
) error {
// NOTE(kmax): fetch DAG data first before bump the index count.
// This is to ensure that when the count is bumped, the data is guaranteed
// to exist locally (unless they are GC'ed whiling being fetched).
// Failure to bump the count after data fetch is fine. The data can be
// purged by GC without harm.
if fetch {
// Fetch graph starting at node identified by cid
if err := FetchGraphWithDepthLimit(ctx, c, -1, p.dserv); err != nil {
return err
}
// If autosyncing, sync dag service before making any change to pins
if err := p.flushDagService(ctx, false); err != nil {
return err
}
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if err := func() error {
p.mu.Lock()
defer p.mu.Unlock()
if _, err := p.cidRIdx.inc(ctx, c, 1); err != nil {
return err
}
if err := p.flushPins(ctx, false); err != nil {
return err
}
return nil
}(); err != nil {
return err
}
return nil
}
// Unpin a given key
func (p *RcPinner) Unpin(ctx context.Context, c cid.Cid, recursive bool) error {
p.mu.Lock()
defer p.mu.Unlock()
idx := p.index(recursive)
rcnt, err := idx.get(ctx, c)
if err != nil {
return err
}
if rcnt == 0 {
return pin.ErrNotPinned
}
if _, err := idx.dec(ctx, c, 1); err != nil {
return err
}
return p.flushPins(ctx, false)
}
// GetCount returns the reference count pinned in the index for the
// given CID. The API looks up only the exact CID given in the index.
// It does not check descendent recursively.
func (p *RcPinner) GetCount(
ctx context.Context,
c cid.Cid,
recursive bool,
) (uint16, error) {
p.mu.Lock()
defer p.mu.Unlock()
rcnt, err := p.index(recursive).get(ctx, c)
if err != nil {
return 0, err
}
return rcnt, nil
}
// IncCount increases reference count for the given CID. This is a shortcut for
// adding a reference count without going through the heavy pinning process.
func (p *RcPinner) IncCount(
ctx context.Context,
c cid.Cid,
recursive bool,
) error {
p.mu.Lock()
defer p.mu.Unlock()
if _, err := p.index(recursive).inc(ctx, c, 1); err != nil {
return err
}
if err := p.flushPins(ctx, false); err != nil {
return err
}
return nil
}
// DecCount decreases reference count for the given CID. Same as Unpin.
func (p *RcPinner) DecCount(
ctx context.Context,
c cid.Cid,
recursive bool,
) error {
return p.Unpin(ctx, c, recursive)
}
type UpdateCount struct {
CID cid.Cid
Recursive bool
}
// UpdateCounts updates reference count for the given CIDs. It ensures the op
// is all or nothing.
func (p *RcPinner) UpdateCounts(
ctx context.Context,
incs []*UpdateCount,
decs []*UpdateCount,
) error {
p.mu.Lock()
defer p.mu.Unlock()
// Sanity check to ensure decs can succeed.
for _, dec := range decs {
cnt, _ := p.index(dec.Recursive).get(ctx, dec.CID)
if cnt == 0 {
return pin.ErrNotPinned
}
}
for _, inc := range incs {
if _, err := p.index(inc.Recursive).inc(ctx, inc.CID, 1); err != nil {
return err
}
}
for _, dec := range decs {
if _, err := p.index(dec.Recursive).dec(ctx, dec.CID, 1); err != nil {
return err
}
}
if err := p.flushPins(ctx, false); err != nil {
return err
}
return nil
}
// IsPinned returns whether or not the given key is pinned
// and an explanation of why its pinned
func (p *RcPinner) IsPinned(
ctx context.Context,
c cid.Cid,
) (string, bool, error) {
p.mu.RLock()
defer p.mu.RUnlock()
return p.isPinnedWithType(ctx, c, pin.Any)
}
// IsPinnedWithType returns whether or not the given cid is pinned with the
// given pin type, as well as returning the type of pin its pinned with.
func (p *RcPinner) IsPinnedWithType(
ctx context.Context,
c cid.Cid,
mode pin.Mode,
) (string, bool, error) {
p.mu.RLock()
defer p.mu.RUnlock()
return p.isPinnedWithType(ctx, c, mode)
}
func (p *RcPinner) isPinnedWithType(
ctx context.Context,
c cid.Cid,
mode pin.Mode,
) (string, bool, error) {
switch mode {
case pin.Recursive:
rcnt, err := p.cidRIdx.get(ctx, c)
if err != nil {
return "", false, err
} else if rcnt > 0 {
return linkRecursive, true, nil
}
return "", false, nil
case pin.Direct:
rcnt, err := p.cidDIdx.get(ctx, c)
if err != nil {
return "", false, err
} else if rcnt > 0 {
return linkDirect, true, nil
}
return "", false, nil
case pin.Internal:
return "", false, nil
case pin.Indirect:
case pin.Any:
rcnt, err := p.cidRIdx.get(ctx, c)
if err != nil {
return "", false, err
} else if rcnt > 0 {
return linkRecursive, true, nil
}
rcnt, err = p.cidDIdx.get(ctx, c)
if err != nil {
return "", false, err
} else if rcnt > 0 {
return linkDirect, true, nil
}
// Continue to check indirect.
default:
return "", false,
fmt.Errorf(
"invalid Pin Mode '%d', must be one of {%d, %d, %d, %d, %d}",
mode,
pin.Direct,
pin.Indirect,
pin.Recursive,
pin.Internal,
pin.Any,
)
}
// Default is Indirect
visitedSet := cid.NewSet()
// No index for given CID, so search children of all recursive pinned CIDs
var has bool
var k cid.Cid
if err := p.cidRIdx.forEach(
ctx,
func(rc cid.Cid, _ uint16) (bool, error) {
var err error
if has, err = hasChild(
ctx,
p.dserv,
rc,
c,
visitedSet.Visit,
); err != nil {
return false, err
}
if has {
k = rc
}
return !has, nil
},
); err != nil {
return "", false, err
}
if has {
return k.String(), true, nil
}
return "", false, nil
}
// CheckIfPinned checks if a set of keys are pinned, more efficient than
// calling IsPinned for each key, returns the pinned status of cid(s)
//
// TODO: If a CID is pinned by multiple pins, should they all be reported?
func (p *RcPinner) CheckIfPinned(
ctx context.Context,
cids ...cid.Cid,
) ([]pin.Pinned, error) {
pinned := make([]pin.Pinned, 0, len(cids))
toCheck := cid.NewSet()
p.mu.RLock()
defer p.mu.RUnlock()
// First check for non-Indirect pins directly
for _, c := range cids {
rrcnt, err := p.cidRIdx.get(ctx, c)
if err != nil {
return nil, err
}
drcnt, err := p.cidDIdx.get(ctx, c)
if err != nil {
return nil, err
}
if rrcnt > 0 && drcnt > 0 {
pinned = append(pinned, pin.Pinned{
Key: c,
Mode: pin.Any,
})
} else if rrcnt > 0 {
pinned = append(pinned, pin.Pinned{
Key: c,
Mode: pin.Recursive,
})
} else if drcnt > 0 {
pinned = append(pinned, pin.Pinned{
Key: c,
Mode: pin.Direct,
})
} else {
toCheck.Add(c)
}
}
visited := cid.NewSet()
if err := p.cidRIdx.forEach(
ctx,
func(rc cid.Cid, _ uint16) (bool, error) {
if err := merkledag.Walk(
ctx,
merkledag.GetLinksWithDAG(p.dserv),
rc,
func(c cid.Cid) bool {
if toCheck.Len() == 0 || !visited.Visit(c) {
return false
}
if toCheck.Has(c) {
pinned = append(pinned, pin.Pinned{
Key: c,
Mode: pin.Indirect,
Via: rc,
})
toCheck.Remove(c)
}
return true
},
merkledag.Concurrent(),
); err != nil {
return false, err
}
return toCheck.Len() > 0, nil
},
); err != nil {
return nil, err
}
// Anything left in toCheck is not pinned
for _, k := range toCheck.Keys() {
pinned = append(pinned, pin.Pinned{
Key: k,
Mode: pin.NotPinned,
})
}
return pinned, nil
}
// DirectKeys returns a slice containing the directly pinned keys
func (p *RcPinner) DirectKeys(ctx context.Context) <-chan pin.StreamedCid {
out := make(chan pin.StreamedCid)
re := make(chan *StreamedCidWithCount)
go func() {
p.mu.RLock()
defer p.mu.RUnlock()
defer close(re)
keysWithCount(ctx, p.cidDIdx, re)
}()
go func() {
defer close(out)
for v := range re {
out <- v.Cid
}
}()
return out
}
// DirectKeysWithCount streams out directly pinned keys with reference count.
func (p *RcPinner) DirectKeysWithCount(
ctx context.Context,
) <-chan *StreamedCidWithCount {
out := make(chan *StreamedCidWithCount)
go func() {
p.mu.RLock()
defer p.mu.RUnlock()
defer close(out)
keysWithCount(ctx, p.cidDIdx, out)
}()
return out
}
// RecursiveKeys streams out recursively pinned keys
func (p *RcPinner) RecursiveKeys(ctx context.Context) <-chan pin.StreamedCid {
out := make(chan pin.StreamedCid)
re := make(chan *StreamedCidWithCount)
go func() {
p.mu.RLock()
defer p.mu.RUnlock()
defer close(re)
keysWithCount(ctx, p.cidRIdx, re)
}()
go func() {
defer close(out)
for v := range re {
out <- v.Cid
}
}()
return out
}
// RecursiveKeysWithCount streams out recursively pinned keys with
// reference count.
func (p *RcPinner) RecursiveKeysWithCount(
ctx context.Context,
) <-chan *StreamedCidWithCount {
out := make(chan *StreamedCidWithCount)
go func() {
p.mu.RLock()
defer p.mu.RUnlock()
defer close(out)
keysWithCount(ctx, p.cidRIdx, out)
}()
return out
}
type StreamedCidWithCount struct {
Cid pin.StreamedCid
Count uint16
}
// keysWithCount streams out pinned keys with corresponding reference count.
func keysWithCount(
ctx context.Context,
idx *index,
out chan *StreamedCidWithCount,
) {
cidSet := cid.NewSet()
if err := idx.forEach(
ctx,
func(c cid.Cid, cnt uint16) (bool, error) {
if cidSet.Has(c) || cnt == 0 {
return true, nil
}
select {
case <-ctx.Done():
return false, nil
case out <- &StreamedCidWithCount{
Cid: pin.StreamedCid{C: c},
Count: cnt,
}:
}
cidSet.Add(c)
return true, nil
},
); err != nil {
out <- &StreamedCidWithCount{
Cid: pin.StreamedCid{Err: err},
}
}
}
// InternalPins returns all cids kept pinned for the internal state of the
// pinner
func (p *RcPinner) InternalPins(ctx context.Context) <-chan pin.StreamedCid {
out := make(chan pin.StreamedCid)
close(out)
return out
}
func (p *RcPinner) Update(
ctx context.Context,
from cid.Cid,
to cid.Cid,
unpin bool,
) error {
return ErrUpdateUnsupported
}
func (p *RcPinner) flushDagService(ctx context.Context, force bool) error {
if !p.autoSync && !force {
return nil
}
if err := p.dserv.Sync(); err != nil {
return fmt.Errorf("cannot sync pinned data: %v", err)
}
return nil
}
func (p *RcPinner) flushPins(ctx context.Context, force bool) error {
if !p.autoSync && !force {
return nil
}
if err := p.dstore.Sync(ctx, ds.NewKey(basePath)); err != nil {
return fmt.Errorf("cannot sync pin state: %v", err)
}
return nil
}
// Flush encodes and writes pinner keysets to the datastore
func (p *RcPinner) Flush(ctx context.Context) error {
p.mu.Lock()
defer p.mu.Unlock()
err := p.flushDagService(ctx, true)
if err != nil {
return err
}
return p.flushPins(ctx, true)
}
// PinWithMode allows the user to have fine grained control over pin
// counts
func (p *RcPinner) PinWithMode(
ctx context.Context,
c cid.Cid,
mode pin.Mode,
) error {
switch mode {
case pin.Recursive:
return p.doPinRecursive(ctx, c, true)
case pin.Direct:
return p.doPinDirect(ctx, c)
default:
return fmt.Errorf("unrecognized pin mode")
}
}
// TotalPinnedCount returns total reference count pinned in the index.
func (p *RcPinner) TotalPinnedCount(recursive bool) uint64 {
p.mu.Lock()
defer p.mu.Unlock()
return p.index(recursive).totalCount()
}
// hasChild recursively looks for a Cid among the children of a root Cid.
// The visit function can be used to shortcut already-visited branches.
func hasChild(
ctx context.Context,
ng ipld.NodeGetter,
root cid.Cid,
child cid.Cid,
visit func(cid.Cid) bool,
) (bool, error) {
links, err := ipld.GetLinks(ctx, ng, root)
if err != nil {
return false, err
}
for _, lnk := range links {
c := lnk.Cid
if lnk.Cid.Equals(child) {
return true, nil
}
if visit(c) {
has, err := hasChild(ctx, ng, c, child, visit)
if err != nil {
return false, err
}
if has {
return has, nil
}
}
}
return false, nil
}
func (p *RcPinner) index(recursive bool) *index {
if recursive {
return p.cidRIdx
}
return p.cidDIdx
}