-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.go
More file actions
291 lines (224 loc) · 6.94 KB
/
router.go
File metadata and controls
291 lines (224 loc) · 6.94 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package platform
import (
"errors"
"fmt"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/golang/protobuf/proto"
)
var RequestTimeout = errors.New("Request timed out")
type Router interface {
Route(request *Request) (*Request, error)
Stream(request *Request) (chan *Request, chan interface{})
SetHeartbeatTimeout(heartbeatTimeout time.Duration)
}
type TracingRouter struct {
parentRouter Router
tracer Tracer
parentTrace *Trace
}
func (r *TracingRouter) Route(request *Request) (*Request, error) {
trace := r.tracer.Start(r.parentTrace, request.GetRouting().GetRouteTo()[0].GetUri())
defer r.tracer.End(trace)
request.Trace = trace
return r.parentRouter.Route(request)
}
func (r *TracingRouter) Stream(request *Request) (chan *Request, chan interface{}) {
trace := r.tracer.Start(r.parentTrace, request.GetRouting().GetRouteTo()[0].GetUri())
request.Trace = trace
internalResponses, internalTimeout := r.parentRouter.Stream(request)
returnedResponses := make(chan *Request)
returnedTimeout := make(chan interface{})
go func() {
defer r.tracer.End(trace)
for {
select {
case response := <-internalResponses:
returnedResponses <- response
if response.GetCompleted() {
return
}
case <-internalTimeout:
close(returnedTimeout)
return
}
}
}()
return returnedResponses, returnedTimeout
}
func (r *TracingRouter) SetHeartbeatTimeout(heartbeatTimeout time.Duration) {
r.parentRouter.SetHeartbeatTimeout(heartbeatTimeout)
}
func NewTracingRouter(parentRouter Router, tracer Tracer, parentTrace *Trace) *TracingRouter {
return &TracingRouter{
parentRouter: parentRouter,
tracer: tracer,
parentTrace: parentTrace,
}
}
type StandardRouter struct {
publisher Publisher
subscriber Subscriber
heartbeatTimeout time.Duration
topic string
pendingResponses map[string]chan *Request
mu sync.Mutex
}
func createResponseChanWithError(request *Request, err *Error) chan *Request {
responses := make(chan *Request, 1)
errorBytes, _ := Marshal(err)
responses <- generateResponse(request, &Request{
Routing: RouteToUri("resource:///platform/reply/error"),
Payload: errorBytes,
Completed: Bool(true),
})
return responses
}
func (r *StandardRouter) Route(originalRequest *Request) (*Request, error) {
responses, streamTimeout := r.Stream(originalRequest)
for {
select {
case response := <-responses:
if response.GetCompleted() {
return response, nil
}
case <-streamTimeout:
return nil, RequestTimeout
}
}
return nil, RequestTimeout
}
func (r *StandardRouter) Stream(originalRequest *Request) (chan *Request, chan interface{}) {
request := proto.Clone(originalRequest).(*Request)
if request.Uuid == nil {
request.Uuid = String("request-" + CreateUUID())
}
requestUUIDSuffix := "::" + strconv.Itoa(int(time.Now().UnixNano()))
request.Uuid = String(request.GetUuid() + requestUUIDSuffix)
requestUUID := request.GetUuid()
requestURI := ""
if len(request.GetRouting().GetRouteTo()) > 0 {
requestURI = request.GetRouting().GetRouteTo()[0].GetUri()
}
parsedURI, err := url.Parse(requestURI)
if err != nil {
return createResponseChanWithError(request, &Error{
Message: String(fmt.Sprintf("Failed to parse the RouteTo URI: %s", err)),
}), nil
}
if request.Routing != nil {
request.Routing.RouteFrom = append(request.Routing.RouteFrom, &Route{
Uri: String(r.topic),
})
}
requestBytes, err := Marshal(request)
if err != nil {
return createResponseChanWithError(request, &Error{
Message: String(fmt.Sprintf("Failed to marshal the request: %s", err)),
}), nil
}
internalResponses := make(chan *Request, 5)
responses := make(chan *Request, 5)
streamTimeout := make(chan interface{})
r.mu.Lock()
r.pendingResponses[requestUUID] = internalResponses
r.mu.Unlock()
timer := time.NewTimer(r.heartbeatTimeout * 2)
go func() {
defer timer.Stop()
for {
select {
case response := <-internalResponses:
responseUri := ""
if len(response.GetRouting().GetRouteTo()) > 0 {
responseUri = response.GetRouting().GetRouteTo()[0].GetUri()
}
// Internal requests shouldn't have to deal with heartbeats from other services
if IsInternalRequest(request) && responseUri == "resource:///heartbeat" {
continue
}
// Remove the request uuid suffix to ensure proper routing on the response
response.Uuid = String(strings.Replace(response.GetUuid(), requestUUIDSuffix, "", 1))
select {
case responses <- response:
case <-time.After(5 * time.Second):
logger.Errorf("[StandardRouter.Stream] %s - %s - %s - failed to notify client of the response", requestUUID, requestURI, responseUri)
}
if response.GetCompleted() {
return
}
case <-timer.C:
close(streamTimeout)
r.mu.Lock()
delete(r.pendingResponses, requestUUID)
r.mu.Unlock()
return
}
timer.Reset(r.heartbeatTimeout)
}
}()
if err := r.publisher.Publish(parsedURI.Scheme+"-"+parsedURI.Path, requestBytes); err != nil {
return createResponseChanWithError(request, &Error{
Message: String(fmt.Sprintf("Failed to publish request to microservices: %s", err)),
}), nil
}
timer.Reset(r.heartbeatTimeout)
return responses, streamTimeout
}
func (r *StandardRouter) SetHeartbeatTimeout(heartbeatTimeout time.Duration) {
r.heartbeatTimeout = heartbeatTimeout
}
func (r *StandardRouter) subscribe() {
r.subscriber.Subscribe(r.topic, ConsumerHandlerFunc(func(body []byte) error {
response := &Request{}
if err := Unmarshal(body, response); err != nil {
return err
}
responseUuid := response.GetUuid()
responseUri := ""
if len(response.GetRouting().GetRouteTo()) > 0 {
responseUri = response.GetRouting().GetRouteTo()[0].GetUri()
}
r.mu.Lock()
if responses, exists := r.pendingResponses[response.GetUuid()]; exists {
select {
case responses <- response:
default:
logger.Printf("[StandardRouter.Subscriber] %s - %s - reply chan was not available", responseUuid, responseUri)
}
if response.GetCompleted() {
delete(r.pendingResponses, response.GetUuid())
}
} else {
logger.Errorf("[StandardRouter.Subscriber] %s - %s - pending response channel did not exist, it may have been deleted", responseUuid, responseUri)
}
r.mu.Unlock()
return nil
}))
r.subscriber.Run()
}
func NewStandardRouter(publisher Publisher, subscriber Subscriber) *StandardRouter {
router := &StandardRouter{
publisher: publisher,
subscriber: subscriber,
heartbeatTimeout: time.Second * 10,
topic: "router-" + CreateUUID(),
pendingResponses: map[string]chan *Request{},
}
router.subscribe()
return router
}
func NewStandardRouterWithTopic(publisher Publisher, subscriber Subscriber, topic string) *StandardRouter {
router := &StandardRouter{
publisher: publisher,
subscriber: subscriber,
heartbeatTimeout: time.Second * 10,
topic: topic,
pendingResponses: map[string]chan *Request{},
}
router.subscribe()
return router
}