-
Notifications
You must be signed in to change notification settings - Fork 0
/
stage.go
67 lines (52 loc) · 1.4 KB
/
stage.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
// Copyright © 2024 Timothy E. Peoples
package pipeline
import (
"context"
"github.com/go-sage/synctools/pkg/errgroupx"
"github.com/go-sage/synctools/pkg/waypoint"
)
type stage struct {
name string
capacity int
sfunc StageFunc
waypt *waypoint.Waypoint
}
// runner returns an [errgroupx.ContextFunc] as expected by the [GoContext] method
// on type *errgroupx.Group.
func (s *stage) runner(inch <-chan any, outch chan<- any) errgroupx.ContextFunc {
return func(ctx context.Context) error {
defer close(outch)
s.waypt = waypoint.New(s.capacity)
eg, ctx, cancel := errgroupx.WithCancel(ctx)
defer cancel()
const errInputDone = errstr("no more input")
runloop := func() error {
for {
in, ok, err := Recv[any](ctx, inch)
if err != nil {
return err
} else if !ok {
return errInputDone
}
w, err := s.waypt.Wait(ctx)
if err != nil {
return err
}
eg.Go(func() (err error) {
defer w.Done()
var out any
if out, err = s.sfunc(ctx, in); err != nil {
return err
}
return Send(ctx, out, outch)
})
}
}
if err := runloop(); err != nil && err != errInputDone {
return err
}
return eg.Wait()
}
}
// [errgroupx.ContextFunc]: https://pkg.go.dev/github.com/go-sage/synctools@v0.1.0/pkg/errgroupx#ContextFunc
// [GoContext]: https://pkg.go.dev/github.com/go-sage/synctools@v0.1.0/pkg/errgroupx#Group.GoContext