forked from cloudfoundry/routing-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_source.go
127 lines (98 loc) · 2.33 KB
/
event_source.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
package routing_api
import (
"encoding/json"
"code.cloudfoundry.org/routing-api/models"
trace "code.cloudfoundry.org/trace-logger"
"github.com/vito/go-sse/sse"
)
//go:generate counterfeiter -o fake_routing_api/fake_event_source.go . EventSource
type EventSource interface {
Next() (Event, error)
Close() error
}
type RawEventSource interface {
Next() (sse.Event, error)
Close() error
}
type eventSource struct {
rawEventSource RawEventSource
}
type Event struct {
Route models.Route
Action string
}
func NewEventSource(raw RawEventSource) EventSource {
return &eventSource{
rawEventSource: raw,
}
}
//go:generate counterfeiter -o fake_routing_api/fake_tcp_event_source.go . TcpEventSource
type TcpEventSource interface {
Next() (TcpEvent, error)
Close() error
}
type TcpEvent struct {
TcpRouteMapping models.TcpRouteMapping
Action string
}
type tcpEventSource struct {
rawEventSource RawEventSource
}
func NewTcpEventSource(raw RawEventSource) TcpEventSource {
return &tcpEventSource{
rawEventSource: raw,
}
}
func (e *eventSource) Next() (Event, error) {
rawEvent, err := e.rawEventSource.Next()
if err != nil {
return Event{}, err
}
trace.DumpJSON("EVENT", rawEvent)
event, err := convertRawEvent(rawEvent)
if err != nil {
return Event{}, err
}
return event, nil
}
func (e *eventSource) Close() error {
return doClose(e.rawEventSource)
}
func (e *tcpEventSource) Next() (TcpEvent, error) {
rawEvent, err := e.rawEventSource.Next()
if err != nil {
return TcpEvent{}, err
}
trace.DumpJSON("EVENT", rawEvent)
event, err := convertRawToTcpEvent(rawEvent)
if err != nil {
return TcpEvent{}, err
}
return event, nil
}
func (e *tcpEventSource) Close() error {
return doClose(e.rawEventSource)
}
func doClose(rawEventSource RawEventSource) error {
err := rawEventSource.Close()
if err != nil {
return err
}
return nil
}
func convertRawEvent(event sse.Event) (Event, error) {
var route models.Route
err := json.Unmarshal(event.Data, &route)
if err != nil {
return Event{}, err
}
return Event{Action: event.Name, Route: route}, nil
}
func convertRawToTcpEvent(event sse.Event) (TcpEvent, error) {
var route models.TcpRouteMapping
err := json.Unmarshal(event.Data, &route)
if err != nil {
return TcpEvent{}, err
}
return TcpEvent{Action: event.Name, TcpRouteMapping: route}, nil
}