-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcompparallel.go
323 lines (293 loc) · 7.93 KB
/
compparallel.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
package routinghelpers
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/hashicorp/go-multierror"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/core/routing"
"github.com/multiformats/go-multihash"
)
var _ routing.Routing = &composableParallel{}
var _ ProvideManyRouter = &composableParallel{}
type composableParallel struct {
routers []*ParallelRouter
}
// NewComposableParallel creates a Router that will execute methods from provided Routers in parallel.
// On all methods, If IgnoreError flag is set, that Router will not stop the entire execution.
// On all methods, If ExecuteAfter is set, that Router will be executed after the timer.
// Router specific timeout will start counting AFTER the ExecuteAfter timer.
func NewComposableParallel(routers []*ParallelRouter) *composableParallel {
return &composableParallel{
routers: routers,
}
}
// Provide will call all Routers in parallel.
func (r *composableParallel) Provide(ctx context.Context, cid cid.Cid, provide bool) error {
return executeParallel(ctx, r.routers,
func(ctx context.Context, r routing.Routing) error {
return r.Provide(ctx, cid, provide)
},
)
}
// ProvideMany will call all supported Routers in parallel.
func (r *composableParallel) ProvideMany(ctx context.Context, keys []multihash.Multihash) error {
return executeParallel(ctx, r.routers,
func(ctx context.Context, r routing.Routing) error {
pm, ok := r.(ProvideManyRouter)
if !ok {
return nil
}
return pm.ProvideMany(ctx, keys)
},
)
}
// Ready will call all supported ProvideMany Routers SEQUENTIALLY.
// If some of them are not ready, this method will return false.
func (r *composableParallel) Ready() bool {
for _, ro := range r.routers {
pm, ok := ro.Router.(ProvideManyRouter)
if !ok {
continue
}
if !pm.Ready() {
return false
}
}
return true
}
// FindProvidersAsync will execute all Routers in parallel, iterating results from them in unspecified order.
// If count is set, only that amount of elements will be returned without any specification about from what router is obtained.
// To gather providers from a set of Routers first, you can use the ExecuteAfter timer to delay some Router execution.
func (r *composableParallel) FindProvidersAsync(ctx context.Context, cid cid.Cid, count int) <-chan peer.AddrInfo {
var totalCount int64
ch, _ := getChannelOrErrorParallel(
ctx,
r.routers,
func(ctx context.Context, r routing.Routing) (<-chan peer.AddrInfo, error) {
return r.FindProvidersAsync(ctx, cid, count), nil
},
func() bool {
return atomic.AddInt64(&totalCount, 1) > int64(count) && count != 0
},
)
return ch
}
// FindPeer will execute all Routers in parallel, getting the first AddrInfo found and cancelling all other Router calls.
func (r *composableParallel) FindPeer(ctx context.Context, id peer.ID) (peer.AddrInfo, error) {
return getValueOrErrorParallel(ctx, r.routers,
func(ctx context.Context, r routing.Routing) (peer.AddrInfo, bool, error) {
addr, err := r.FindPeer(ctx, id)
return addr, addr.ID == "", err
},
)
}
// PutValue will execute all Routers in parallel. If a Router fails and IgnoreError flag is not set, the whole execution will fail.
// Some Puts before the failure might be successful, even if we return an error.
func (r *composableParallel) PutValue(ctx context.Context, key string, val []byte, opts ...routing.Option) error {
return executeParallel(ctx, r.routers,
func(ctx context.Context, r routing.Routing) error {
return r.PutValue(ctx, key, val, opts...)
},
)
}
// GetValue will execute all Routers in parallel. The first value found will be returned, cancelling all other executions.
func (r *composableParallel) GetValue(ctx context.Context, key string, opts ...routing.Option) ([]byte, error) {
return getValueOrErrorParallel(ctx, r.routers,
func(ctx context.Context, r routing.Routing) ([]byte, bool, error) {
val, err := r.GetValue(ctx, key, opts...)
return val, len(val) == 0, err
})
}
func (r *composableParallel) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
return getChannelOrErrorParallel(
ctx,
r.routers,
func(ctx context.Context, r routing.Routing) (<-chan []byte, error) {
return r.SearchValue(ctx, key, opts...)
},
func() bool { return false },
)
}
func (r *composableParallel) Bootstrap(ctx context.Context) error {
return executeParallel(ctx, r.routers,
func(ctx context.Context, r routing.Routing) error {
return r.Bootstrap(ctx)
})
}
func getValueOrErrorParallel[T any](
ctx context.Context,
routers []*ParallelRouter,
f func(context.Context, routing.Routing) (T, bool, error),
) (value T, err error) {
outCh := make(chan T)
errCh := make(chan error)
// global cancel context to stop early other router's execution.
ctx, cancelAll := context.WithCancel(ctx)
defer cancelAll()
var wg sync.WaitGroup
for _, r := range routers {
wg.Add(1)
go func(r *ParallelRouter) {
defer wg.Done()
tim := time.NewTimer(r.ExecuteAfter)
defer tim.Stop()
select {
case <-ctx.Done():
case <-tim.C:
ctx, cancel := context.WithTimeout(ctx, r.Timeout)
defer cancel()
value, empty, err := f(ctx, r.Router)
if err != nil &&
!errors.Is(err, routing.ErrNotFound) &&
!r.IgnoreError {
select {
case <-ctx.Done():
case errCh <- err:
}
return
}
if empty {
return
}
select {
case <-ctx.Done():
return
case outCh <- value:
}
}
}(r)
}
// goroutine closing everything when finishing execution
go func() {
wg.Wait()
close(outCh)
close(errCh)
}()
select {
case out, ok := <-outCh:
if !ok {
return value, routing.ErrNotFound
}
return out, nil
case err, ok := <-errCh:
if !ok {
return value, routing.ErrNotFound
}
return value, err
case <-ctx.Done():
return value, ctx.Err()
}
}
func executeParallel(
ctx context.Context,
routers []*ParallelRouter,
f func(context.Context, routing.Routing,
) error) error {
var wg sync.WaitGroup
errCh := make(chan error)
for _, r := range routers {
wg.Add(1)
go func(r *ParallelRouter) {
defer wg.Done()
tim := time.NewTimer(r.ExecuteAfter)
defer tim.Stop()
select {
case <-ctx.Done():
if !r.IgnoreError {
errCh <- ctx.Err()
}
case <-tim.C:
ctx, cancel := context.WithTimeout(ctx, r.Timeout)
defer cancel()
err := f(ctx, r.Router)
if err != nil &&
!r.IgnoreError {
errCh <- err
}
}
}(r)
}
go func() {
wg.Wait()
close(errCh)
}()
var errOut error
for err := range errCh {
errOut = multierror.Append(errOut, err)
}
return errOut
}
func getChannelOrErrorParallel[T any](
ctx context.Context,
routers []*ParallelRouter,
f func(context.Context, routing.Routing) (<-chan T, error),
shouldStop func() bool,
) (chan T, error) {
outCh := make(chan T)
errCh := make(chan error)
var wg sync.WaitGroup
ctx, cancelAll := context.WithCancel(ctx)
for _, r := range routers {
wg.Add(1)
go func(r *ParallelRouter) {
defer wg.Done()
tim := time.NewTimer(r.ExecuteAfter)
defer tim.Stop()
select {
case <-ctx.Done():
return
case <-tim.C:
ctx, cancel := context.WithTimeout(ctx, r.Timeout)
defer cancel()
valueChan, err := f(ctx, r.Router)
if err != nil && !r.IgnoreError {
select {
case <-ctx.Done():
case errCh <- err:
}
return
}
for {
select {
case <-ctx.Done():
return
case val, ok := <-valueChan:
if !ok {
return
}
if shouldStop() {
return
}
select {
case <-ctx.Done():
return
case outCh <- val:
}
}
}
}
}(r)
}
// goroutine closing everything when finishing execution
go func() {
wg.Wait()
close(outCh)
close(errCh)
cancelAll()
}()
select {
case err, ok := <-errCh:
if !ok {
return nil, routing.ErrNotFound
}
return nil, err
case <-ctx.Done():
return nil, ctx.Err()
default:
return outCh, nil
}
}