forked from envoyproxy/ratelimit
/
ratelimit_legacy.go
99 lines (82 loc) · 2.61 KB
/
ratelimit_legacy.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
package ratelimit
import (
"github.com/golang/protobuf/jsonpb"
"github.com/lyft/gostats"
pb "github.com/lyft/ratelimit/proto/envoy/service/ratelimit/v2"
pb_legacy "github.com/lyft/ratelimit/proto/ratelimit"
"golang.org/x/net/context"
)
type RateLimitLegacyServiceServer interface {
pb_legacy.RateLimitServiceServer
}
// legacyService is used to implement ratelimit.proto (https://github.com/lyft/ratelimit/blob/0ded92a2af8261d43096eba4132e45b99a3b8b14/proto/ratelimit/ratelimit.proto)
// the legacyService receives RateLimitRequests, converts the request, and calls the service's ShouldRateLimit method.
type legacyService struct {
s *service
shouldRateLimitLegacyStats shouldRateLimitLegacyStats
}
type shouldRateLimitLegacyStats struct {
reqConversionError stats.Counter
respConversionError stats.Counter
shouldRateLimitError stats.Counter
}
func newShouldRateLimitLegacyStats(scope stats.Scope) shouldRateLimitLegacyStats {
s := scope.Scope("call.should_rate_limit_legacy")
return shouldRateLimitLegacyStats{
reqConversionError: s.NewCounter("req_conversion_error"),
respConversionError: s.NewCounter("resp_conversion_error"),
shouldRateLimitError: s.NewCounter("should_rate_limit_error"),
}
}
func (this *legacyService) ShouldRateLimit(
ctx context.Context,
legacyRequest *pb_legacy.RateLimitRequest) (finalResponse *pb_legacy.RateLimitResponse, finalError error) {
request, err := ConvertLegacyRequest(legacyRequest)
if err != nil {
this.shouldRateLimitLegacyStats.reqConversionError.Inc()
return nil, err
}
resp, err := this.s.ShouldRateLimit(ctx, request)
if err != nil {
this.shouldRateLimitLegacyStats.shouldRateLimitError.Inc()
return nil, err
}
legacyResponse, err := ConvertResponse(resp)
if err != nil {
this.shouldRateLimitLegacyStats.respConversionError.Inc()
return nil, err
}
return legacyResponse, nil
}
func ConvertLegacyRequest(legacyRequest *pb_legacy.RateLimitRequest) (*pb.RateLimitRequest, error) {
if legacyRequest == nil {
return nil, nil
}
m := &jsonpb.Marshaler{}
s, err := m.MarshalToString(legacyRequest)
if err != nil {
return nil, err
}
req := &pb.RateLimitRequest{}
err = jsonpb.UnmarshalString(s, req)
if err != nil {
return nil, err
}
return req, nil
}
func ConvertResponse(response *pb.RateLimitResponse) (*pb_legacy.RateLimitResponse, error) {
if response == nil {
return nil, nil
}
m := &jsonpb.Marshaler{}
s, err := m.MarshalToString(response)
if err != nil {
return nil, err
}
resp := &pb_legacy.RateLimitResponse{}
err = jsonpb.UnmarshalString(s, resp)
if err != nil {
return nil, err
}
return resp, nil
}