-
Notifications
You must be signed in to change notification settings - Fork 66
/
baz_simpleservice_method_call_tchannel.go
240 lines (212 loc) · 8.55 KB
/
baz_simpleservice_method_call_tchannel.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
// Code generated by zanzibar
// @generated
// Copyright (c) 2018 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 baztchannelendpoint
import (
"context"
"runtime/debug"
"strings"
"time"
"github.com/pkg/errors"
tchannel "github.com/uber/tchannel-go"
zanzibar "github.com/uber/zanzibar/runtime"
"go.uber.org/thriftrw/wire"
"go.uber.org/zap"
endpointsIDlEndpointsTchannelBazBaz "github.com/uber/zanzibar/examples/example-gateway/build/gen-code/endpoints-idl/endpoints/tchannel/baz/baz"
customBaz "github.com/uber/zanzibar/examples/example-gateway/endpoints/tchannel/baz"
defaultExampleTchannel "github.com/uber/zanzibar/examples/example-gateway/middlewares/default/default_example_tchannel"
exampleTchannel "github.com/uber/zanzibar/examples/example-gateway/middlewares/example_tchannel"
module "github.com/uber/zanzibar/examples/example-gateway/build/endpoints/tchannel/baz/module"
)
// NewSimpleServiceCallHandler creates a handler to be registered with a thrift server.
func NewSimpleServiceCallHandler(deps *module.Dependencies) *SimpleServiceCallHandler {
handler := &SimpleServiceCallHandler{
Deps: deps,
}
handler.endpoint = zanzibar.NewTChannelEndpoint(
"bazTChannel", "call", "SimpleService::Call",
zanzibar.NewTchannelStack([]zanzibar.MiddlewareTchannelHandle{
deps.Middleware.DefaultExampleTchannel.NewMiddlewareHandle(
defaultExampleTchannel.Options{},
),
deps.Middleware.ExampleTchannel.NewMiddlewareHandle(
exampleTchannel.Options{
Foo: "test",
},
),
}, handler),
)
return handler
}
// SimpleServiceCallHandler is the handler for "SimpleService::Call".
type SimpleServiceCallHandler struct {
Deps *module.Dependencies
endpoint *zanzibar.TChannelEndpoint
}
// Register adds the tchannel handler to the gateway's tchannel router
func (h *SimpleServiceCallHandler) Register(g *zanzibar.Gateway) error {
return g.ServerTChannelRouter.Register(h.endpoint)
}
// Handle handles RPC call of "SimpleService::Call".
func (h *SimpleServiceCallHandler) Handle(
ctx context.Context,
reqHeaders map[string]string,
wireValue *wire.Value,
) (ctxRes context.Context, isSuccessful bool, response zanzibar.RWTStruct, headers map[string]string, e error) {
defer func() {
if r := recover(); r != nil {
stacktrace := string(debug.Stack())
e = errors.Errorf("enpoint panic: %v, stacktrace: %v", r, stacktrace)
ctx = h.Deps.Default.ContextLogger.ErrorZ(
ctx,
"Endpoint failure: endpoint panic",
zap.Error(e),
zap.String("stacktrace", stacktrace),
zap.String("endpoint", h.endpoint.EndpointID))
h.Deps.Default.ContextMetrics.IncCounter(ctx, zanzibar.MetricEndpointPanics, 1)
isSuccessful = false
response = nil
headers = nil
}
}()
wfReqHeaders := zanzibar.ServerTChannelHeader(reqHeaders)
if err := wfReqHeaders.EnsureContext(ctx, []string{"x-uuid", "x-token"}, h.Deps.Default.ContextLogger); err != nil {
return ctx, false, nil, nil, errors.Wrapf(
err, "%s.%s (%s) missing request headers",
h.endpoint.EndpointID, h.endpoint.HandlerID, h.endpoint.Method,
)
}
var res endpointsIDlEndpointsTchannelBazBaz.SimpleService_Call_Result
var req endpointsIDlEndpointsTchannelBazBaz.SimpleService_Call_Args
if err := req.FromWire(*wireValue); err != nil {
ctx = h.Deps.Default.ContextLogger.ErrorZ(ctx, "Endpoint failure: error converting request from wire", zap.Error(err))
return ctx, false, nil, nil, errors.Wrapf(
err, "Error converting %s.%s (%s) request from wire",
h.endpoint.EndpointID, h.endpoint.HandlerID, h.endpoint.Method,
)
}
if hostPort, ok := reqHeaders["x-deputy-forwarded"]; ok {
if hostPort != "" {
return h.redirectToDeputy(ctx, reqHeaders, hostPort, &req, &res)
}
}
workflow := customBaz.NewSimpleServiceCallWorkflow(h.Deps)
ctx, wfResHeaders, err := workflow.Handle(ctx, wfReqHeaders, &req)
resHeaders := map[string]string{}
if wfResHeaders != nil {
for _, key := range wfResHeaders.Keys() {
resHeaders[key], _ = wfResHeaders.Get(key)
}
}
if err != nil {
switch v := err.(type) {
case *endpointsIDlEndpointsTchannelBazBaz.AuthErr:
ctxWithError := zanzibar.WithScopeTags(ctx, map[string]string{
"app-error": "endpointsIDlEndpointsTchannelBazBaz.AuthErr",
})
h.Deps.Default.ContextMetrics.IncCounter(ctxWithError, zanzibar.MetricEndpointAppErrors, 1)
if v == nil {
ctx = h.Deps.Default.ContextLogger.ErrorZ(
ctx,
"Endpoint failure: handler returned non-nil error type *endpointsIDlEndpointsTchannelBazBaz.AuthErr but nil value",
zap.Error(err),
)
return ctx, false, nil, resHeaders, errors.Errorf(
"%s.%s (%s) handler returned non-nil error type *endpointsIDlEndpointsTchannelBazBaz.AuthErr but nil value",
h.endpoint.EndpointID, h.endpoint.HandlerID, h.endpoint.Method,
)
}
res.AuthErr = v
default:
ctxWithError := zanzibar.WithScopeTags(ctx, map[string]string{
"app-error": "unknown",
})
h.Deps.Default.ContextMetrics.IncCounter(ctxWithError, zanzibar.MetricEndpointAppErrors, 1)
ctx = h.Deps.Default.ContextLogger.ErrorZ(ctx, "Endpoint failure: handler returned error", zap.Error(err))
return ctx, false, nil, resHeaders, errors.Wrapf(
err, "%s.%s (%s) handler returned error",
h.endpoint.EndpointID, h.endpoint.HandlerID, h.endpoint.Method,
)
}
}
if wfResHeaders == nil {
return ctx, false, nil, nil, errors.Wrapf(
errors.Errorf(
"Missing mandatory headers: %s",
strings.Join([]string{"some-res-header"}, ", "),
),
"%s.%s (%s) missing response headers",
h.endpoint.EndpointID, h.endpoint.HandlerID, h.endpoint.Method,
)
}
if err := wfResHeaders.EnsureContext(ctx, []string{"some-res-header"}, h.Deps.Default.ContextLogger); err != nil {
return ctx, false, nil, nil, errors.Wrapf(
err, "%s.%s (%s) missing response headers",
h.endpoint.EndpointID, h.endpoint.HandlerID, h.endpoint.Method,
)
}
return ctx, err == nil, &res, resHeaders, nil
}
// redirectToDeputy sends the request to deputy hostPort
func (h *SimpleServiceCallHandler) redirectToDeputy(
ctx context.Context,
reqHeaders map[string]string,
hostPort string,
req *endpointsIDlEndpointsTchannelBazBaz.SimpleService_Call_Args,
res *endpointsIDlEndpointsTchannelBazBaz.SimpleService_Call_Result,
) (context.Context, bool, zanzibar.RWTStruct, map[string]string, error) {
var routingKey string
if h.Deps.Default.Config.ContainsKey("tchannel.routingKey") {
routingKey = h.Deps.Default.Config.MustGetString("tchannel.routingKey")
}
serviceName := h.Deps.Default.Config.MustGetString("tchannel.serviceName")
timeout := time.Millisecond * time.Duration(
h.Deps.Default.Config.MustGetInt("tchannel.deputy.timeout"),
)
timeoutPerAttempt := time.Millisecond * time.Duration(
h.Deps.Default.Config.MustGetInt("tchannel.deputy.timeoutPerAttempt"),
)
methodNames := map[string]string{
"SimpleService::Call": "Call",
}
deputyChannel, err := tchannel.NewChannel(serviceName, nil)
if err != nil {
ctx = h.Deps.Default.ContextLogger.ErrorZ(ctx, "Deputy Failure", zap.Error(err))
}
defer deputyChannel.Close()
deputyChannel.Peers().Add(hostPort)
client := zanzibar.NewTChannelClientContext(
deputyChannel,
h.Deps.Default.ContextLogger,
h.Deps.Default.ContextMetrics,
h.Deps.Default.ContextExtractor,
&zanzibar.TChannelClientOption{
ServiceName: serviceName,
ClientID: "",
MethodNames: methodNames,
Timeout: timeout,
TimeoutPerAttempt: timeoutPerAttempt,
RoutingKey: &routingKey,
},
)
success, respHeaders, err := client.Call(ctx, "SimpleService", "Call", reqHeaders, req, res)
return ctx, success, res, respHeaders, err
}