forked from CyCoreSystems/ari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bus.go
90 lines (75 loc) · 1.73 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
package ari
import (
"context"
"sync"
)
// Bus is an event bus for ARI events. It receives and
// redistributes events based on a subscription model.
type Bus interface {
Close()
Sender
Subscriber
}
// A Sender is an entity which can send event bus messages
type Sender interface {
Send(e Event)
}
// A Subscriber is an entity which can create ARI event subscriptions
type Subscriber interface {
Subscribe(key *Key, n ...string) Subscription
}
// A Subscription is a subscription on series of ARI events
type Subscription interface {
// Events returns a channel on which events related to this subscription are sent.
Events() <-chan Event
// Cancel terminates the subscription
Cancel()
}
// Once listens for the first event of the provided types,
// returning a channel which supplies that event.
func Once(ctx context.Context, bus Bus, key *Key, eTypes ...string) <-chan Event {
s := bus.Subscribe(key, eTypes...)
ret := make(chan Event)
// Stop subscription after one event
go func() {
select {
case ret <- <-s.Events():
case <-ctx.Done():
}
close(ret)
s.Cancel()
}()
return ret
}
// NewNullSubscription returns a subscription which never returns any events
func NewNullSubscription() *NullSubscription {
return &NullSubscription{
ch: make(chan Event),
}
}
// NullSubscription is a subscription which never returns any events.
type NullSubscription struct {
ch chan Event
closed bool
mu sync.RWMutex
}
func (n *NullSubscription) Events() <-chan Event {
if n.ch == nil {
n.mu.Lock()
n.closed = false
n.ch = make(chan Event)
n.mu.Unlock()
}
return n.ch
}
func (n *NullSubscription) Cancel() {
if n.closed {
return
}
n.mu.Lock()
n.closed = true
if n.ch != nil {
close(n.ch)
}
n.mu.Unlock()
}