forked from micro/micro
/
wrapper.go
320 lines (268 loc) · 9.31 KB
/
wrapper.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package wrapper
import (
"context"
"encoding/base64"
"reflect"
"strings"
"time"
"github.com/crazybber/micro/v3/service/auth"
"github.com/crazybber/micro/v3/service/client"
"github.com/crazybber/micro/v3/service/context/metadata"
"github.com/crazybber/micro/v3/service/debug"
"github.com/crazybber/micro/v3/service/debug/trace"
"github.com/crazybber/micro/v3/service/errors"
"github.com/crazybber/micro/v3/service/logger"
"github.com/crazybber/micro/v3/service/metrics"
"github.com/crazybber/micro/v3/service/server"
inauth "github.com/crazybber/micro/v3/util/auth"
"github.com/crazybber/micro/v3/util/cache"
)
type authWrapper struct {
client.Client
}
func (a *authWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
ctx = a.wrapContext(ctx, opts...)
return a.Client.Call(ctx, req, rsp, opts...)
}
func (a *authWrapper) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
ctx = a.wrapContext(ctx, opts...)
return a.Client.Stream(ctx, req, opts...)
}
func (a *authWrapper) wrapContext(ctx context.Context, opts ...client.CallOption) context.Context {
// parse the options
var options client.CallOptions
for _, o := range opts {
o(&options)
}
// set the namespace header if it has not been set (e.g. on a service to service request)
authOpts := auth.DefaultAuth.Options()
if _, ok := metadata.Get(ctx, "Micro-Namespace"); !ok {
ctx = metadata.Set(ctx, "Micro-Namespace", authOpts.Issuer)
}
// We dont't override the header unless the AuthToken option has been specified
if !options.AuthToken {
return ctx
}
// check to see if we have a valid access token
if authOpts.Token != nil && !authOpts.Token.Expired() {
ctx = metadata.Set(ctx, "Authorization", inauth.BearerScheme+authOpts.Token.AccessToken)
return ctx
}
// call without an auth token
return ctx
}
// AuthClient wraps requests with the auth header
func AuthClient(c client.Client) client.Client {
return &authWrapper{c}
}
// AuthHandler wraps a server handler to perform auth
func AuthHandler() server.HandlerWrapper {
return func(h server.HandlerFunc) server.HandlerFunc {
return func(ctx context.Context, req server.Request, rsp interface{}) error {
// Extract the token if the header is present. We will inspect the token regardless of if it's
// present or not since noop auth will return a blank account upon Inspecting a blank token.
var token string
if header, ok := metadata.Get(ctx, "Authorization"); ok {
// Ensure the correct scheme is being used
switch {
case strings.HasPrefix(header, inauth.BearerScheme):
// Strip the bearer scheme prefix
token = strings.TrimPrefix(header, inauth.BearerScheme)
case strings.HasPrefix(header, "Basic "):
b, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(header, "Basic "))
if err != nil {
return errors.Unauthorized(req.Service(), "invalid authorization header. Incorrect format")
}
parts := strings.SplitN(string(b), ":", 2)
if len(parts) != 2 {
return errors.Unauthorized(req.Service(), "invalid authorization header. Incorrect format")
}
token = parts[1]
default:
return errors.Unauthorized(req.Service(), "invalid authorization header. Expected Bearer or Basic schema")
}
}
// Determine the namespace
ns := auth.DefaultAuth.Options().Issuer
var acc *auth.Account
if a, err := auth.Inspect(token); err == nil {
ctx = auth.ContextWithAccount(ctx, a)
acc = a
}
// construct the resource
res := &auth.Resource{
Type: "service",
Name: req.Service(),
Endpoint: req.Endpoint(),
}
// Verify the caller has access to the resource.
err := auth.Verify(acc, res, auth.VerifyNamespace(ns))
if err == auth.ErrForbidden && acc != nil {
return errors.Forbidden(req.Service(), "Forbidden call made to %v:%v by %v", req.Service(), req.Endpoint(), acc.ID)
} else if err == auth.ErrForbidden {
return errors.Unauthorized(req.Service(), "Unauthorized call made to %v:%v", req.Service(), req.Endpoint())
} else if err != nil {
return errors.InternalServerError(req.Service(), "Error authorizing request: %v", err)
}
// The user is authorised, allow the call
return h(ctx, req, rsp)
}
}
}
type logWrapper struct {
client.Client
}
func (l *logWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
logger.Debugf("Calling service %s endpoint %s", req.Service(), req.Endpoint())
return l.Client.Call(ctx, req, rsp, opts...)
}
func (l *logWrapper) Stream(ctx context.Context, req client.Request, opts ...client.CallOption) (client.Stream, error) {
logger.Debugf("Streaming service %s endpoint %s", req.Service(), req.Endpoint())
return l.Client.Stream(ctx, req, opts...)
}
func LogClient(c client.Client) client.Client {
return &logWrapper{c}
}
func LogHandler() server.HandlerWrapper {
// return a handler wrapper
return func(h server.HandlerFunc) server.HandlerFunc {
// return a function that returns a function
return func(ctx context.Context, req server.Request, rsp interface{}) error {
logger.Debugf("Serving request for service %s endpoint %s", req.Service(), req.Endpoint())
return h(ctx, req, rsp)
}
}
}
// HandlerStats wraps a server handler to generate request/error stats
func HandlerStats() server.HandlerWrapper {
// return a handler wrapper
return func(h server.HandlerFunc) server.HandlerFunc {
// return a function that returns a function
return func(ctx context.Context, req server.Request, rsp interface{}) error {
// execute the handler
err := h(ctx, req, rsp)
// record the stats
debug.DefaultStats.Record(err)
// return the error
return err
}
}
}
type traceWrapper struct {
client.Client
}
func (c *traceWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
newCtx, s := debug.DefaultTracer.Start(ctx, req.Service()+"."+req.Endpoint())
s.Type = trace.SpanTypeRequestOutbound
err := c.Client.Call(newCtx, req, rsp, opts...)
if err != nil {
s.Metadata["error"] = err.Error()
}
// finish the trace
debug.DefaultTracer.Finish(s)
return err
}
// TraceCall is a call tracing wrapper
func TraceCall(c client.Client) client.Client {
return &traceWrapper{
Client: c,
}
}
// TraceHandler wraps a server handler to perform tracing
func TraceHandler() server.HandlerWrapper {
// return a handler wrapper
return func(h server.HandlerFunc) server.HandlerFunc {
// return a function that returns a function
return func(ctx context.Context, req server.Request, rsp interface{}) error {
// don't store traces for debug
if strings.HasPrefix(req.Endpoint(), "Debug.") {
return h(ctx, req, rsp)
}
// get the span
newCtx, s := debug.DefaultTracer.Start(ctx, req.Service()+"."+req.Endpoint())
s.Type = trace.SpanTypeRequestInbound
err := h(newCtx, req, rsp)
if err != nil {
s.Metadata["error"] = err.Error()
}
// finish
debug.DefaultTracer.Finish(s)
return err
}
}
}
type cacheWrapper struct {
Cache *cache.Cache
client.Client
}
// Call executes the request. If the CacheExpiry option was set, the response will be cached using
// a hash of the metadata and request as the key.
func (c *cacheWrapper) Call(ctx context.Context, req client.Request, rsp interface{}, opts ...client.CallOption) error {
// parse the options
var options client.CallOptions
for _, o := range opts {
o(&options)
}
// if the client doesn't have a cacbe setup don't continue
if c.Cache == nil {
return c.Client.Call(ctx, req, rsp, opts...)
}
cacheOpts, ok := cache.GetOptions(options.Context)
if !ok {
return c.Client.Call(ctx, req, rsp, opts...)
}
// if the cache expiry is not set, execute the call without the cache
if cacheOpts.Expiry == 0 || rsp == nil {
return c.Client.Call(ctx, req, rsp, opts...)
}
// check to see if there is a response cached, if there is assign it
if r, ok := c.Cache.Get(ctx, req); ok {
val := reflect.ValueOf(rsp).Elem()
val.Set(reflect.ValueOf(r).Elem())
return nil
}
// don't cache the result if there was an error
if err := c.Client.Call(ctx, req, rsp, opts...); err != nil {
return err
}
// set the result in the cache
c.Cache.Set(ctx, req, rsp, cacheOpts.Expiry)
return nil
}
// CacheClient wraps requests with the cache wrapper
func CacheClient(c client.Client) client.Client {
return &cacheWrapper{
Cache: cache.New(),
Client: c,
}
}
// MetricsHandler wraps a server handler to instrument calls
func MetricsHandler() server.HandlerWrapper {
// return a handler wrapper
return func(h server.HandlerFunc) server.HandlerFunc {
// return a function that returns a function
return func(ctx context.Context, req server.Request, rsp interface{}) error {
// Don't instrument debug calls:
if strings.HasPrefix(req.Endpoint(), "Debug.") {
return h(ctx, req, rsp)
}
// Build some tags to describe the call:
tags := metrics.Tags{
"method": req.Method(),
}
// Start the clock:
callTime := time.Now()
// Run the handlerFunction:
err := h(ctx, req, rsp)
// Add a result tag:
if err != nil {
tags["result"] = "failure"
} else {
tags["result"] = "success"
}
// Instrument the result (if the DefaultClient has been configured):
metrics.Timing("service.handler", time.Since(callTime), tags)
return err
}
}
}