-
Notifications
You must be signed in to change notification settings - Fork 0
/
monza.go
108 lines (86 loc) · 1.91 KB
/
monza.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
package monza
import (
"context"
"encoding/json"
"time"
)
type Destination interface{
Setup(ctx context.Context) error
Record(ctx context.Context, event Event)
Teardown(ctx context.Context)
}
type ServiceID string
type Event struct {
Event string `json:"event,omitempty"`
Data interface{} `json:"data,omitempty"`
ID int64 `json:"id,omitempty"`
ClientTime time.Time `json:"client_time,omitempty"`
IPAddr string `json:"ip_addr"`
ServiceID ServiceID `json:"service_id"`
}
func (e Event) JSON() []byte {
eventAsJSONStringBytes, err := json.Marshal(e)
if err != nil {
return nil
}
return eventAsJSONStringBytes
}
type Client interface {
RegisterDestination(ctx context.Context, destination Destination) error
Record(events Event)
Teardown(ctx context.Context)
}
var instance Client
func Get(ctx context.Context, config Config) Client {
if instance != nil {
return instance
}
c := &client{
Config: config,
listener: make(chan Event),
quit: make(chan interface{}),
}
go c.startListening(ctx)
instance = c
return instance
}
type Config struct {
IpAddress string
Destinations []Destination
}
type client struct {
listener chan Event
Config
quit chan interface{}
}
func (c *client) RegisterDestination(ctx context.Context, destination Destination) error {
err := destination.Setup(ctx)
if err != nil {
return err
}
c.Destinations = append(c.Destinations, destination)
return nil
}
func (c *client) Record(event Event) {
c.listener <- event
}
// Teardown implements Client.
func (c *client) Teardown(ctx context.Context) {
c.quit <- nil
for _, destination := range c.Destinations{
destination.Teardown(ctx)
}
}
func (c *client) startListening(ctx context.Context) {
for {
select {
case <- c.quit:
return
default:
events := <-c.listener
for _, destination := range c.Destinations {
destination.Record(ctx, events)
}
}
}
}