-
Notifications
You must be signed in to change notification settings - Fork 0
/
bus.go
97 lines (77 loc) · 2.16 KB
/
bus.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
package events
import (
"fmt"
"github.com/spellshape/cli/spellshape/pkg/cliui/colors"
)
// DefaultBufferSize defines the default maximum number
// of events that the bus can cache before they are handled.
const DefaultBufferSize = 50
// Provider defines an interface for event providers.
type Provider interface {
// Events returns a read only channel to read the events.
Events() <-chan Event
}
type (
// Bus defines a bus to send and receive events.
Bus struct {
evChan chan Event
stopped bool
}
// BusOption configures the Bus.
BusOption func(*Bus)
)
// WithBufferSize assigns the size of the buffer to use for buffering events.
func WithBufferSize(size int) BusOption {
return func(bus *Bus) {
bus.evChan = make(chan Event, size)
}
}
// NewBus creates a new event bus.
func NewBus(options ...BusOption) Bus {
bus := Bus{
evChan: make(chan Event, DefaultBufferSize),
}
for _, apply := range options {
apply(&bus)
}
return bus
}
// Send sends a new event to bus.
// This method will block if the event bus buffer is full.
func (b Bus) Send(message string, options ...Option) {
if b.evChan == nil || b.stopped {
return
}
b.evChan <- New(message, options...)
}
// Sendf sends a new event with a formatted message to bus.
func (b Bus) Sendf(format string, a ...any) {
b.Send(fmt.Sprintf(format, a...))
}
// SendInfo sends an info event to the bus.
func (b Bus) SendInfo(message string, options ...Option) {
b.Send(colors.Info(message), options...)
}
// SendError sends an error event to the bus.
func (b Bus) SendError(err error, options ...Option) {
b.Send(colors.Error(err.Error()), options...)
}
// SendView sends a new event for a view to the bus.
// Views are types that implement the `fmt.Stringer` interface
// which allow events with complex message formats.
func (b Bus) SendView(s fmt.Stringer, options ...Option) {
b.Send(s.String(), options...)
}
// Events returns a read only channel to read the events.
func (b Bus) Events() <-chan Event {
return b.evChan
}
// Stop stops the event bus.
// All new events are ignored once the event bus is stopped.
func (b *Bus) Stop() {
if b.evChan == nil {
return
}
b.stopped = true
close(b.evChan)
}