-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
93 lines (81 loc) · 2.47 KB
/
proxy.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
package customer
import (
"context"
"errors"
"time"
"github.com/go-kit/kit/circuitbreaker"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/ratelimit"
"github.com/go-kit/kit/tracing/opentracing"
grpctransport "github.com/go-kit/kit/transport/grpc"
"github.com/ngray1747/dvd-rental/dvd/pb"
stdopentracing "github.com/opentracing/opentracing-go"
"github.com/sony/gobreaker"
"golang.org/x/time/rate"
"google.golang.org/grpc"
)
type ProxyMiddleware func(ProxyService) ProxyService
type ProxyService interface {
UpdateDVDStatus(ctx context.Context, DVDID string) error
}
type proxymw struct {
context.Context
ProxyService
UpdateDVDStatusEndpoint endpoint.Endpoint
}
type updateDVDStatusRequest struct {
ID string
}
type updateDVDStatusResponse struct {
Err error
}
func encodeRentDVDRequest(_ context.Context, request interface{}) (interface{}, error) {
req := request.(updateDVDStatusRequest)
return &pb.RentDVDRequest{Id: req.ID}, nil
}
func decodeRentDVDResponse(_ context.Context, response interface{}) (interface{}, error) {
resp := response.(*pb.RentDVDResponse)
return updateDVDStatusResponse{Err: strToError(resp.Err)}, nil
}
func strToError(err string) error {
if err == "" {
return nil
}
return errors.New(err)
}
func (pm proxymw) UpdateDVDStatus(ctx context.Context, DVDID string) error {
response, err := pm.UpdateDVDStatusEndpoint(ctx, updateDVDStatusRequest{
ID: DVDID,
})
if err != nil {
return err
}
resp := response.(updateDVDStatusResponse)
return resp.Err
}
func NewProxyMiddleware(conn *grpc.ClientConn, ctx context.Context, ot stdopentracing.Tracer, logger log.Logger) ProxyMiddleware {
return func(svc ProxyService) ProxyService {
limiter := ratelimit.NewErroringLimiter(rate.NewLimiter(rate.Every(time.Second), 10))
var opts []grpctransport.ClientOption
var rentDVDEndpoint endpoint.Endpoint
{
rentDVDEndpoint = grpctransport.NewClient(
conn,
"pb.DVDRental",
"RentDVD",
encodeRentDVDRequest,
decodeRentDVDResponse,
pb.RentDVDResponse{},
append(opts, grpctransport.ClientBefore(opentracing.ContextToGRPC(ot, logger)))...,
).Endpoint()
rentDVDEndpoint = opentracing.TraceClient(ot, "RentDVD")(rentDVDEndpoint)
rentDVDEndpoint = limiter(rentDVDEndpoint)
rentDVDEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{
Name: "RentDVD",
Timeout: 10 * time.Second,
}))(rentDVDEndpoint)
}
return proxymw{ctx, svc, rentDVDEndpoint}
}
}