-
Notifications
You must be signed in to change notification settings - Fork 2
/
limiter.go
49 lines (39 loc) · 1.2 KB
/
limiter.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
package limiter
import (
"context"
"path"
"github.com/alexfalkowski/go-service/limiter"
"github.com/alexfalkowski/go-service/transport/strings"
l "github.com/sethvargo/go-limiter"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// UnaryServerInterceptor for gRPC.
func UnaryServerInterceptor(limiter l.Store, key limiter.KeyFunc) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
p := path.Dir(info.FullMethod)[1:]
if strings.IsObservable(p) {
return handler(ctx, req)
}
if err := limit(ctx, limiter, key); err != nil {
return nil, err
}
return handler(ctx, req)
}
}
func limit(ctx context.Context, store l.Store, key limiter.KeyFunc) error {
ok, info, err := limiter.Take(ctx, store, key)
if err != nil {
return internalError(err)
}
grpc.SetHeader(ctx, metadata.Pairs("ratelimit", info))
if !ok {
return status.Errorf(codes.ResourceExhausted, "limiter: resource exhausted, %s", info)
}
return nil
}
func internalError(err error) error {
return status.Errorf(codes.Internal, "limiter: %s", err.Error())
}