/
workers.go
104 lines (93 loc) · 2.27 KB
/
workers.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
package etl
import (
"context"
"golang.org/x/sync/errgroup"
)
type W[To any] struct {
Iter
ID int
yield Y[To]
}
func (w W[To]) Yield(v To) error {
return w.yield(v)
}
// Workers iterates over a slice of values and calls a worker func for each value.
func Workers[To any](it Iter, workers int, fn func(context.Context, W[To]) error) Iter {
return MakeGen(Gen[To]{
Run: func(ctx context.Context, yield Y[To]) error {
itval := make(chan any)
eg, ctx := errgroup.WithContext(ctx)
for i := 0; i < workers; i++ {
w := W[To]{
Iter: Chan(itval),
ID: i,
yield: yield,
}
eg.Go(func() error {
return fn(ctx, w)
})
}
eg.Go(func() error {
defer close(itval)
return Consume(it, func(v any) error {
select {
case itval <- v:
case <-ctx.Done():
return ctx.Err()
}
return nil
})
})
return eg.Wait()
},
Close: it.Close,
})
}
// WorkersValue is a convinitent func that calls fn for every consumed value, it will yield any value
// by calling the yield func.
func WorkersValue[Ti, To any](it Iter, workers int, fn func(context.Context, Ti, Y[To]) error) Iter {
return Workers(it, workers, func(ctx context.Context, w W[To]) error {
return ConsumeContext(ctx, w, func(v Ti) error {
return fn(ctx, v, w.Yield)
})
})
}
// WorkersConsume creates a pool of workers that call fn for every iteration value.
// this will close the consumed Iter upon finish.
func WorkersConsume[Ti any](it Iter, workers int, fn func(context.Context, Ti) error) error {
return WorkersConsumeContext(context.Background(), it, workers, fn)
}
func WorkersConsumeContext[Ti any](ctx context.Context, it Iter, workers int, fn func(context.Context, Ti) error) error {
defer it.Close()
eg, ctx := errgroup.WithContext(ctx)
itval := make(chan Ti)
for i := 0; i < workers; i++ {
eg.Go(func() error {
for {
select {
case v, ok := <-itval:
if !ok {
return nil
}
if err := fn(ctx, v); err != nil {
return err
}
case <-ctx.Done():
return ctx.Err()
}
}
})
}
eg.Go(func() error {
defer close(itval)
return ConsumeContext(ctx, it, func(v Ti) error {
select {
case itval <- v:
case <-ctx.Done():
return ctx.Err()
}
return nil
})
})
return eg.Wait()
}