@@ -16,25 +16,25 @@ package event
1616
1717import (
1818 "slices"
19+ "sync"
1920
2021 "github.com/blinklabs-io/adder/event"
2122 "github.com/blinklabs-io/adder/plugin"
2223)
2324
2425type Event struct {
25- errorChan chan <- error
26+ errorChan chan error
2627 inputChan chan event.Event
2728 outputChan chan event.Event
29+ doneChan chan struct {}
30+ stopOnce sync.Once
2831 logger plugin.Logger
2932 filterTypes []string
3033}
3134
3235// New returns a new Event object with the specified options applied
3336func New (options ... EventOptionFunc ) * Event {
34- e := & Event {
35- inputChan : make (chan event.Event , 10 ),
36- outputChan : make (chan event.Event , 10 ),
37- }
37+ e := & Event {}
3838 for _ , option := range options {
3939 option (e )
4040 }
@@ -43,37 +43,58 @@ func New(options ...EventOptionFunc) *Event {
4343
4444// Start the event filter
4545func (e * Event ) Start () error {
46+ e .errorChan = make (chan error )
47+ e .inputChan = make (chan event.Event , 10 )
48+ e .outputChan = make (chan event.Event , 10 )
49+ e .doneChan = make (chan struct {})
50+ e .stopOnce = sync.Once {}
4651 go func () {
4752 for {
48- evt , ok := <- e .inputChan
49- // Channel has been closed, which means we're shutting down
50- if ! ok {
53+ select {
54+ case <- e .doneChan :
5155 return
52- }
53- // Drop events if we have a type filter configured and the event doesn't match
54- if len (e .filterTypes ) > 0 {
55- matched := slices .Contains (e .filterTypes , evt .Type )
56- if ! matched {
57- continue
56+ case evt , ok := <- e .inputChan :
57+ // Channel has been closed, which means we're shutting down
58+ if ! ok {
59+ return
5860 }
61+ // Drop events if we have a type filter configured and the event doesn't match
62+ if len (e .filterTypes ) > 0 {
63+ matched := slices .Contains (e .filterTypes , evt .Type )
64+ if ! matched {
65+ continue
66+ }
67+ }
68+ // Send event along
69+ e .outputChan <- evt
5970 }
60- // Send event along
61- e .outputChan <- evt
6271 }
6372 }()
6473 return nil
6574}
6675
6776// Stop the event filter
6877func (e * Event ) Stop () error {
69- close (e .inputChan )
70- close (e .outputChan )
78+ e .stopOnce .Do (func () {
79+ if e .doneChan != nil {
80+ close (e .doneChan )
81+ }
82+ if e .inputChan != nil {
83+ close (e .inputChan )
84+ }
85+ if e .outputChan != nil {
86+ close (e .outputChan )
87+ }
88+ if e .errorChan != nil {
89+ close (e .errorChan )
90+ }
91+ })
7192 return nil
7293}
7394
74- // SetErrorChan sets the error channel
75- func (e * Event ) SetErrorChan ( ch chan <- error ) {
76- e .errorChan = ch
95+ // ErrorChan returns the filter error channel
96+ func (e * Event ) ErrorChan () chan error {
97+ return e .errorChan
7798}
7899
79100// InputChan returns the input event channel
0 commit comments