-
Notifications
You must be signed in to change notification settings - Fork 66
/
tchannel_server.go
268 lines (232 loc) · 7.64 KB
/
tchannel_server.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
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
// Copyright (c) 2024 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package zanzibar
import (
"context"
"fmt"
"strings"
"sync"
"github.com/opentracing/opentracing-go"
"github.com/pborman/uuid"
"github.com/uber-go/tally"
"github.com/uber/tchannel-go"
"go.uber.org/zap"
netContext "golang.org/x/net/context"
)
// PostResponseCB registers a callback that is run after a response has been
// completely processed (e.g. written to the channel).
// This gives the server a chance to clean up resources from the response object
type PostResponseCB func(ctx context.Context, method string, response RWTStruct)
// TChannelEndpoint wraps over a TChannelHandler and can be registered to a TChannelRouter
// to handle tchannel inbound call. It only has one Handle method which is delegated to the
// embedded TChannelHandler.
type TChannelEndpoint struct {
TChannelHandler
EndpointID string
HandlerID string
Method string
callback PostResponseCB
}
// TChannelRouter handles incoming TChannel calls and routes them to the matching TChannelHandler.
type TChannelRouter struct {
sync.RWMutex
registrar tchannel.Registrar
endpoints map[string]*TChannelEndpoint
contextLogger ContextLogger
scope tally.Scope
extractor ContextExtractor
requestUUIDHeaderKey string
}
// netContextRouter implements the Handle interface that consumes netContext instead of stdlib context
type netContextRouter struct {
router *TChannelRouter
}
func (ncr netContextRouter) Handle(ctx netContext.Context, call *tchannel.InboundCall) {
ncr.router.Handle(ctx, call)
}
// NewTChannelEndpoint creates a new tchannel endpoint to handle an incoming
// call for its method.
func NewTChannelEndpoint(
endpointID, handlerID, method string,
handler TChannelHandler,
) *TChannelEndpoint {
return NewTChannelEndpointWithPostResponseCB(
endpointID, handlerID, method,
handler, nil,
)
}
// NewTChannelEndpointWithPostResponseCB creates a new tchannel endpoint,
// with or without a post response callback function.
func NewTChannelEndpointWithPostResponseCB(
endpointID, handlerID, method string,
handler TChannelHandler,
callback PostResponseCB,
) *TChannelEndpoint {
return &TChannelEndpoint{
TChannelHandler: handler,
EndpointID: endpointID,
HandlerID: handlerID,
Method: method,
callback: callback,
}
}
// NewTChannelRouter returns a TChannel router that can serve thrift services over TChannel.
func NewTChannelRouter(registrar tchannel.Registrar, g *Gateway) *TChannelRouter {
return &TChannelRouter{
registrar: registrar,
endpoints: map[string]*TChannelEndpoint{},
contextLogger: g.ContextLogger,
scope: g.RootScope,
extractor: g.ContextExtractor,
requestUUIDHeaderKey: g.requestUUIDHeaderKey,
}
}
// Register registers the given TChannelEndpoint.
func (s *TChannelRouter) Register(e *TChannelEndpoint) error {
s.RLock()
if _, ok := s.endpoints[e.Method]; ok {
s.RUnlock()
return fmt.Errorf("handler for '%s' is already registered", e.Method)
}
s.RUnlock()
s.Lock()
s.endpoints[e.Method] = e
s.Unlock()
ncr := netContextRouter{router: s}
s.registrar.Register(ncr, e.Method)
return nil
}
// Handle handles an incoming TChannel call and forwards it to the correct handler.
func (s *TChannelRouter) Handle(ctx context.Context, call *tchannel.InboundCall) {
method := call.MethodString()
if sep := strings.Index(method, "::"); sep == -1 {
s.contextLogger.Error(ctx, "Handle got call for which does not match the expected call format", zap.String(logFieldRequestMethod, method))
return
}
s.RLock()
e, ok := s.endpoints[method]
s.RUnlock()
if !ok {
s.contextLogger.Error(ctx, "Handle got call for method which is not registered",
zap.String(logFieldRequestMethod, method),
)
return
}
// put log fields on the context
logFields := []zap.Field{
zap.String(logFieldEndpointID, e.EndpointID),
zap.String(logFieldEndpointHandler, e.HandlerID),
zap.String(logFieldRequestMethod, e.Method),
}
ctx = WithLogFields(ctx, logFields...)
// put scope tags on the context
scopeTags := map[string]string{
scopeTagEndpoint: e.EndpointID,
scopeTagHandler: e.HandlerID,
scopeTagEndpointMethod: e.Method,
scopeTagProtocol: scopeTagTChannel,
}
ctx = WithScopeTagsDefault(ctx, scopeTags, s.scope)
var err error
c := &tchannelInboundCall{
call: call,
endpoint: e,
contextLogger: s.contextLogger,
scope: s.scope.Tagged(scopeTags),
}
c.start()
ctx, err = s.handleHeader(ctx, c)
defer func() { c.finish(ctx, err) }()
if err != nil {
return
}
errc := make(chan error, 1)
go func() { errc <- s.handleBody(ctx, c) }()
select {
case <-ctx.Done():
err = ctx.Err()
if err == context.Canceled {
// check if context was Canceled due to handle response
if c.responded {
err = <-errc
}
}
case err = <-errc:
}
}
func (s *TChannelRouter) handleHeader(
ctx context.Context,
c *tchannelInboundCall,
) (context.Context, error) {
if err := c.readReqHeaders(ctx); err != nil {
return ctx, err
}
reqUUID, ok := c.reqHeaders[s.requestUUIDHeaderKey]
if !ok {
reqUUID = uuid.New()
}
ctx = withRequestUUID(ctx, reqUUID)
// put request headers on context so that user-provided extractor
// functions can choose to have certain headers as metric tags or
// log fields
ctx = WithEndpointRequestHeadersField(ctx, c.reqHeaders)
// use user-provided extractor function to decide metric tags
scopeTags := make(map[string]string)
for k, v := range s.extractor.ExtractScopeTags(ctx) {
scopeTags[k] = v
}
ctx = WithScopeTagsDefault(ctx, scopeTags, c.scope)
if len(scopeTags) != 0 {
c.scope = c.scope.Tagged(scopeTags)
}
// use user-provided extractor function to decide log fields
logFields := s.extractor.ExtractLogFields(ctx)
logFields = append(logFields, zap.String(logFieldRequestUUID, reqUUID))
ctx = WithLogFields(ctx, logFields...)
return ctx, nil
}
func (s *TChannelRouter) handleBody(
ctx context.Context,
c *tchannelInboundCall,
) (err error) {
wireValue, err := c.readReqBody(ctx)
if err != nil {
return err
}
// trace request
tracer := tchannel.TracerFromRegistrar(s.registrar)
ctx = tchannel.ExtractInboundSpan(ctx, c.call, c.reqHeaders, tracer)
ctx = WithLogFields(ctx, extractSpanLogFields(opentracing.SpanFromContext(ctx))...)
// handle request
resp, err := c.handle(ctx, &wireValue)
if err != nil {
return err
}
// TODO: put response headers on ctx for final metrics and logs
//ctx = WithEndpointResponseHeadersField(ctx, c.resHeaders)
// write response
if err = c.writeResHeaders(ctx); err != nil {
return err
}
if err = c.writeResBody(ctx, resp); err != nil {
return err
}
return err
}