/
registry.go
175 lines (139 loc) · 3.83 KB
/
registry.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
package event
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/tierklinik-dobersberg/cis/pkg/pkglog"
"github.com/tierklinik-dobersberg/logger"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
)
var log = pkglog.New("event")
type subscription struct {
topic string
subscriber string
ch chan<- *Event
}
// Type describes an avaialble event type.
type Type struct {
// ID is the name of the event type
ID string
// Description is a human readable descriptin of
// the event type.
Description string
}
type TypeRef struct {
reg *Registry
Type
}
func (ref *TypeRef) Fire(ctx context.Context, payload Data) {
ctx, sp := otel.Tracer("").Start(ctx, "cis_event_fire")
defer sp.End()
sp.SetAttributes(
attribute.String("id", ref.ID),
)
ref.reg.Fire(ctx, ref.ID, payload)
}
type Registry struct {
l sync.RWMutex
subscribers []subscription
types map[string]Type
}
func (reg *Registry) RegisterType(eventType Type) (*TypeRef, error) {
reg.l.Lock()
defer reg.l.Unlock()
if reg.types == nil {
reg.types = make(map[string]Type)
}
if _, ok := reg.types[strings.ToLower(eventType.ID)]; ok {
return nil, fmt.Errorf("event-type: name taken")
}
reg.types[strings.ToLower(eventType.ID)] = eventType
return &TypeRef{Type: eventType, reg: reg}, nil
}
func (reg *Registry) ListTypes() []Type {
reg.l.RLock()
defer reg.l.RUnlock()
result := make([]Type, 0, len(reg.types))
for _, t := range reg.types {
result = append(result, t)
}
return result
}
// Fire fires a new event of the given ID to all subscribers.
func (reg *Registry) Fire(ctx context.Context, id string, payload Data) {
reg.l.RLock()
defer reg.l.RUnlock()
log := log.From(ctx).WithFields(logger.Fields{
"eventID": id,
})
log.Infof("fireing event")
evt := &Event{
ID: id,
Data: payload,
Created: time.Now(),
}
for _, sub := range reg.subscribers {
l := log.WithFields(logger.Fields{
"subscriber": sub.subscriber,
"subscription": sub.topic,
})
if !MatchSubscription(id, sub.topic) {
// l.Infof("skipping subscriber %s, topic %s does not match %s.", sub.subscriber, sub.topic, id)
continue
}
start := time.Now()
go func(sub subscription) {
select {
case sub.ch <- evt:
l.V(7).Logf("notified subscriber after %s", time.Since(start))
case <-time.After(time.Second):
l.Errorf("failed to notify event subscriber")
}
}(sub)
}
}
// Subscribe subscribes to events of the given eventID. All events
// fired on the registry that match the subscribed ID are published
// to the returned channel. Note that the order of events is not
// guaranteed.
func (reg *Registry) Subscribe(client, eventID string) <-chan *Event {
reg.l.Lock()
defer reg.l.Unlock()
ch := make(chan *Event)
reg.subscribers = append(reg.subscribers, subscription{
topic: eventID,
subscriber: client,
ch: ch,
})
return ch
}
// Unsubscribe removes a previous subscription from client on eventID.
func (reg *Registry) Unsubscribe(client, eventID string) {
reg.l.Lock()
defer reg.l.Unlock()
for idx, subscription := range reg.subscribers {
if subscription.subscriber == client && subscription.topic == eventID {
reg.subscribers = append(reg.subscribers[:idx], reg.subscribers[idx+1:]...)
}
}
}
// Subscribe subscribes to events on the DefaultRegistry.
func Subscribe(client, eventID string) <-chan *Event {
return DefaultRegistry.Subscribe(client, eventID)
}
// Fire fires an event on the DefaultRegistry.
func Fire(ctx context.Context, id string, payload Data) {
DefaultRegistry.Fire(ctx, id, payload)
}
// DefaultRegistry is the event registry used by package level functions.
var DefaultRegistry = new(Registry)
func MustRegisterType(t Type) *TypeRef {
tref, err := DefaultRegistry.RegisterType(t)
if err != nil {
panic(fmt.Sprintf("%s: %s", t.ID, err))
}
return tref
}