-
Notifications
You must be signed in to change notification settings - Fork 142
/
service_events.go
88 lines (72 loc) · 2.12 KB
/
service_events.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
package db
import (
"fmt"
"github.com/michaelquigley/pfxlog"
"github.com/openziti/foundation/v2/cowslice"
)
type ServiceEventType byte
func (self ServiceEventType) String() string {
if self == ServiceDialAccessGained {
return "dial-gained"
}
if self == ServiceDialAccessLost {
return "dial-lost"
}
if self == ServiceBindAccessGained {
return "bind-gained"
}
if self == ServiceBindAccessLost {
return "bind-lost"
}
if self == ServiceUpdated {
return "service-updated"
}
return "unknown"
}
const (
ServiceDialAccessGained ServiceEventType = 1
ServiceDialAccessLost ServiceEventType = 2
ServiceBindAccessGained ServiceEventType = 3
ServiceBindAccessLost ServiceEventType = 4
ServiceUpdated ServiceEventType = 5
)
var ServiceEvents = &ServiceEventsRegistry{
handlers: cowslice.NewCowSlice(make([]ServiceEventHandler, 0)),
}
func init() {
ServiceEvents.AddServiceEventHandler(func(event *ServiceEvent) {
pfxlog.Logger().Tracef("identity %v -> service %v %v", event.IdentityId, event.ServiceId, event.Type.String())
})
}
type ServiceEvent struct {
Type ServiceEventType
IdentityId string
ServiceId string
}
func (self *ServiceEvent) String() string {
return fmt.Sprintf("service event [identity %v -> service %v %v]", self.IdentityId, self.ServiceId, self.Type.String())
}
type ServiceEventHandler func(event *ServiceEvent)
type ServiceEventsRegistry struct {
handlers *cowslice.CowSlice
}
func (self *ServiceEventsRegistry) AddServiceEventHandler(listener ServiceEventHandler) {
cowslice.Append(self.handlers, listener)
}
func (self *ServiceEventsRegistry) RemoveServiceEventHandler(listener ServiceEventHandler) {
cowslice.Delete(self.handlers, listener)
}
func (self *ServiceEventsRegistry) dispatchEventsAsync(events []*ServiceEvent) {
go self.dispatchEvents(events)
}
func (self *ServiceEventsRegistry) dispatchEvents(events []*ServiceEvent) {
for _, event := range events {
self.dispatchEvent(event)
}
}
func (self *ServiceEventsRegistry) dispatchEvent(event *ServiceEvent) {
handlers := self.handlers.Value().([]ServiceEventHandler)
for _, handler := range handlers {
handler(event)
}
}