-
Notifications
You must be signed in to change notification settings - Fork 14
/
sync_adapter_source.go
59 lines (48 loc) · 1.24 KB
/
sync_adapter_source.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
package substrate
import (
"context"
"github.com/uw-labs/sync/rungroup"
)
// NewSynchronousMessageSource returns a new synchronous message source, given
// an AsyncMessageSource. When Close is called on the SynchronousMessageSource,
// this is also propogated to the underlying SynchronousMessageSource.
func NewSynchronousMessageSource(ams AsyncMessageSource) SynchronousMessageSource {
return &synchronousMessageSourceAdapter{
ams,
}
}
type synchronousMessageSourceAdapter struct {
ac AsyncMessageSource
}
func (a *synchronousMessageSourceAdapter) ConsumeMessages(ctx context.Context, handler ConsumerMessageHandler) error {
rg, ctx := rungroup.New(ctx)
messages := make(chan Message)
acks := make(chan Message)
rg.Go(func() error {
return a.ac.ConsumeMessages(ctx, messages, acks)
})
rg.Go(func() error {
for {
select {
case msg := <-messages:
if err := handler(ctx, msg); err != nil {
return err
}
select {
case acks <- msg:
case <-ctx.Done():
return nil
}
case <-ctx.Done():
return nil
}
}
})
return rg.Wait()
}
func (a *synchronousMessageSourceAdapter) Close() error {
return a.ac.Close()
}
func (a *synchronousMessageSourceAdapter) Status() (*Status, error) {
return a.ac.Status()
}