Skip to content

Commit

Permalink
Add custom JSON-RPC error code for rate limiting (#219)
Browse files Browse the repository at this point in the history
  • Loading branch information
wanliqun authored Aug 21, 2024
1 parent 6149e82 commit f69d88e
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions util/rpc/middlewares/rate_limit.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import (
"github.com/pkg/errors"
)

const (
ratelimitErrorCode = -32005
)

func QpsRateLimit(next rpc.HandleCallMsgFunc) rpc.HandleCallMsgFunc {
return func(ctx context.Context, msg *rpc.JsonRpcMessage) *rpc.JsonRpcMessage {
registry, ok := ctx.Value(handlers.CtxKeyRateRegistry).(*rate.Registry)
Expand All @@ -33,7 +37,10 @@ func QpsRateLimit(next rpc.HandleCallMsgFunc) rpc.HandleCallMsgFunc {
}

func errQpsRateLimited(err error) error {
return errors.WithMessage(err, "allowed qps exceeded")
return &rpc.JsonError{
Code: ratelimitErrorCode,
Message: errors.WithMessage(err, "request rate exceeded").Error(),
}
}

func DailyMaxReqRateLimit(next rpc.HandleCallMsgFunc) rpc.HandleCallMsgFunc {
Expand All @@ -53,5 +60,8 @@ func DailyMaxReqRateLimit(next rpc.HandleCallMsgFunc) rpc.HandleCallMsgFunc {
}

func errDailyMaxReqRateLimited(err error) error {
return errors.WithMessage(err, "daily request limit exceeded")
return &rpc.JsonError{
Code: ratelimitErrorCode,
Message: errors.WithMessage(err, "daily request count exceeded").Error(),
}
}

0 comments on commit f69d88e

Please sign in to comment.