-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathfirst.go
82 lines (73 loc) · 1.72 KB
/
first.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
package main
import (
"context"
"errors"
"sync"
"sync/atomic"
"golang.org/x/sync/errgroup"
)
// FirstResponse is a helper to get the first non-null result or error from a set of goroutines.
type FirstResponse struct {
result chan any
wg *errgroup.Group
waitWg chan struct{}
resultOnce sync.Once
ctx context.Context
gotResult *atomic.Bool
}
func NewFirstResponse(ctx context.Context, concurrency int) *FirstResponse {
fr := &FirstResponse{
result: make(chan any, 1),
waitWg: make(chan struct{}),
gotResult: new(atomic.Bool),
}
fr.wg, ctx = errgroup.WithContext(ctx)
if concurrency > 0 {
fr.wg.SetLimit(concurrency)
}
fr.ctx = ctx
return fr
}
// Spawn spawns a goroutine that executes the given function.
func (w *FirstResponse) Spawn(f func() (any, error)) (ok bool) {
if w.gotResult.Load() {
return false
}
w.wg.Go(func() error {
result, err := f()
if err != nil {
return w.send(err) // stop the errgroup
} else {
if result != nil {
return w.send(result) // stop the errgroup
}
}
return nil
})
return true
}
var errGotFirstResult = errors.New("got first result")
// send sends the result to the channel, but only once.
// If the result is already sent, it does nothing.
// The result can be something, or an error.
func (w *FirstResponse) send(result any) error {
w.gotResult.Store(true)
w.resultOnce.Do(func() {
w.result <- result
close(w.result)
})
return errGotFirstResult
}
// Wait waits for all goroutines to finish, and returns the first non-null result or error.
func (w *FirstResponse) Wait() any {
go func() {
w.wg.Wait()
w.waitWg <- struct{}{}
}()
select {
case result := <-w.result:
return result
case <-w.waitWg:
return nil
}
}