forked from berty/go-ipfs-log
/
fetcher.go
282 lines (227 loc) · 6.48 KB
/
fetcher.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
package entry
import (
"context"
"sync"
"time"
"github.com/stateless-minds/go-ipfs-log/identityprovider"
"github.com/stateless-minds/go-ipfs-log/iface"
"github.com/stateless-minds/go-ipfs-log/io/cbor"
core_iface "github.com/ipfs/boxo/coreiface"
"github.com/ipfs/go-cid"
"golang.org/x/sync/semaphore"
)
type taskKind int
const (
taskKindAdded = iota
taskKindInProgress
taskKindDone
)
func noopShouldExclude(hash cid.Cid) bool {
return false
}
type Fetcher struct {
length int
maxClock int // keep track of the latest clock time during load
minClock int // keep track of the minimum clock time during load
muClock sync.Mutex
timeout time.Duration
io iface.IO
provider identityprovider.Interface
shouldExclude iface.ExcludeFunc
tasksCache map[cid.Cid]taskKind
condProcess *sync.Cond
muProcess *sync.RWMutex
sem *semaphore.Weighted
ipfs core_iface.CoreAPI
progressChan chan iface.IPFSLogEntry
}
func NewFetcher(ipfs core_iface.CoreAPI, options *FetchOptions) *Fetcher {
// set default
length := -1
if options.Length != nil {
length = *options.Length
}
if options.Concurrency <= 0 {
options.Concurrency = 32
}
if options.IO == nil {
io, err := cbor.IO(&Entry{}, &LamportClock{})
if err != nil {
return nil
}
options.IO = io
}
if options.ShouldExclude == nil {
options.ShouldExclude = noopShouldExclude
}
muProcess := sync.RWMutex{}
// create Fetcher
return &Fetcher{
io: options.IO,
length: length,
timeout: options.Timeout,
shouldExclude: options.ShouldExclude,
sem: semaphore.NewWeighted(int64(options.Concurrency)),
ipfs: ipfs,
progressChan: options.ProgressChan,
muProcess: &muProcess,
condProcess: sync.NewCond(&muProcess),
maxClock: 0,
minClock: 0,
tasksCache: make(map[cid.Cid]taskKind),
}
}
func (f *Fetcher) Fetch(ctx context.Context, hashes []cid.Cid) []iface.IPFSLogEntry {
if f.timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, f.timeout)
defer cancel()
}
return f.processQueue(ctx, hashes)
}
func (f *Fetcher) processQueue(ctx context.Context, hashes []cid.Cid) []iface.IPFSLogEntry {
results := []iface.IPFSLogEntry{}
queue := newProcessQueue()
f.muProcess.Lock()
f.addHashesToQueue(queue, hashes...)
taskInProgress := 0
for queue.Len() > 0 {
// acquire a process slot limited by concurrency limit
if err := f.acquireProcessSlot(ctx); err != nil {
// @FIXME(gfanton): log this
// fmt.Printf("error while process next: %s\n", err.Error())
break
}
// get next hash
hash := queue.Next()
f.tasksCache[hash] = taskKindInProgress
// run process
go func(hash cid.Cid) {
entry, err := f.fetchEntry(ctx, hash)
if err != nil { // nolint:staticcheck
// @FIXME(gfanton): log this
// fmt.Printf("unable to fetch entry: %s\n", err.Error())
}
// free process slot
f.processDone()
f.muProcess.Lock()
if entry != nil {
entryHash := entry.GetHash()
var lastEntry iface.IPFSLogEntry
if len(results) > 0 {
lastEntry = results[len(results)-1]
}
// update clock
f.updateClock(ctx, entry, lastEntry)
// if we don't know this hash yet, add it to result
cache := f.tasksCache[entryHash]
if cache == taskKindAdded || cache == taskKindInProgress {
ts := entry.GetClock().GetTime()
isLater := len(results) >= f.length && ts >= f.minClock
if f.length < 0 || len(results) < f.length || isLater {
results = append(results, entry)
// signal progress
if f.progressChan != nil {
f.progressChan <- entry
}
}
f.tasksCache[entryHash] = taskKindDone
// add next elems to queue
f.addNextEntry(ctx, queue, entry, results)
}
}
// mark this process as done
taskInProgress--
// signal that a slot is available
f.condProcess.Signal()
f.muProcess.Unlock()
}(hash)
// increase in progress task counter
taskInProgress++
// wait until a task is added or that no running task is in progress
for queue.Len() == 0 && taskInProgress > 0 {
f.condProcess.Wait()
}
}
// wait until all process are done/canceled
for taskInProgress > 0 {
f.condProcess.Wait()
}
f.muProcess.Unlock()
return results
}
func (f *Fetcher) updateClock(ctx context.Context, entry, lastEntry iface.IPFSLogEntry) {
f.muClock.Lock()
ts := entry.GetClock().GetTime()
// Update min/max clocks
if f.maxClock < ts {
f.maxClock = ts
}
if lastEntry != nil {
if ts := lastEntry.GetClock().GetTime(); ts < f.minClock {
f.minClock = ts
}
} else {
f.minClock = f.maxClock
}
f.muClock.Unlock()
}
func (f *Fetcher) exclude(hash cid.Cid) (yes bool) {
if yes = !hash.Defined(); yes {
return
}
// do we have it in the internal cache ?
if _, yes = f.tasksCache[hash]; yes {
return
}
// should the caller want it ?
yes = f.shouldExclude(hash)
return
}
func (f *Fetcher) addNextEntry(ctx context.Context, queue processQueue, entry iface.IPFSLogEntry, results []iface.IPFSLogEntry) {
ts := entry.GetClock().GetTime()
if f.length < 0 {
// If we're fetching all entries (length === -1), adds nexts and refs to the queue
f.addHashesToQueue(queue, entry.GetNext()...)
f.addHashesToQueue(queue, entry.GetRefs()...)
return
}
// If we're fetching entries up to certain length,
// fetch the next if result is filled up, to make sure we "check"
// the next entry if its clock is later than what we have in the result
if len(results) < f.length || ts > f.minClock || ts == f.minClock {
for _, h := range entry.GetNext() {
f.addHashToQueue(queue, f.maxClock-ts, h)
}
}
if len(results)+len(entry.GetRefs()) <= f.length {
for i, h := range entry.GetRefs() {
f.addHashToQueue(queue, f.maxClock-ts+((i+1)*i), h)
}
}
}
func (f *Fetcher) fetchEntry(ctx context.Context, hash cid.Cid) (entry iface.IPFSLogEntry, err error) {
// Load the entry
return FromMultihashWithIO(ctx, f.ipfs, hash, f.provider, f.io)
}
func (f *Fetcher) addHashesToQueue(queue processQueue, hashes ...cid.Cid) (added int) {
for i, h := range hashes {
added += f.addHashToQueue(queue, i, h)
}
return
}
func (f *Fetcher) addHashToQueue(queue processQueue, index int, hash cid.Cid) (added int) {
if f.exclude(hash) {
return
}
queue.Add(index, hash)
f.tasksCache[hash] = taskKindAdded
return 1
}
func (f *Fetcher) acquireProcessSlot(ctx context.Context) error {
return f.sem.Acquire(ctx, 1)
}
func (f *Fetcher) processDone() {
// signal that a process slot is available
f.sem.Release(1)
}