-
Notifications
You must be signed in to change notification settings - Fork 2
/
reactor.go
89 lines (77 loc) · 1.59 KB
/
reactor.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
package facade
import (
"context"
"gopkg.in/workanator/vuego.v1/app/event"
)
const (
eventQueueSize = 64
)
// Reactor implements event.Bus interface and establishes event processing.
type Reactor struct {
outEvents chan event.Event
}
func NewReactor() *Reactor {
return &Reactor{
outEvents: make(chan event.Event, eventQueueSize),
}
}
// Implement event.Consumer interface. The enter point of inbound events.
func (r *Reactor) Consume(buf []event.Event, ctx context.Context) error {
// Marshal events
for _, ev := range buf {
// Deliver system events directly to outbound queue
if ev.Category.IsSystem() {
r.outEvents <- ev
}
// Test if context is terminated
if ctx != nil {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
}
}
return nil
}
// Implement event.Producer interface. The leave point of outbound events.
func (r *Reactor) Produce(buf []event.Event, ctx context.Context) (n int, err error) {
// Return immediately if buf is of zero length
if len(buf) == 0 {
return 0, nil
}
// Read the first event in blocking mode
if ctx != nil {
select {
case buf[n] = <-r.outEvents:
n++
case <-ctx.Done():
return 0, ctx.Err()
}
} else {
buf[n] = <-r.outEvents
n++
}
// Read as much events as possible from the queue
hasMore := true
for n < len(buf) && hasMore {
if ctx != nil {
select {
case buf[n] = <-r.outEvents:
n++
case <-ctx.Done():
return n, ctx.Err()
default:
hasMore = false
}
} else {
select {
case buf[n] = <-r.outEvents:
n++
default:
hasMore = false
}
}
}
return n, nil
}