| 1 | // Copyright © SAS Institute Inc. |
| 2 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | // you may not use this file except in compliance with the License. |
| 4 | // You may obtain a copy of the License at |
| 5 | // |
| 6 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | // |
| 8 | // Unless required by applicable law or agreed to in writing, software |
| 9 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | // See the License for the specific language governing permissions and |
| 12 | // limitations under the License. |
| 13 | |
| 14 | package ratelimit |
| 15 | |
| 16 | import ( |
| 17 | "context" |
| 18 | "time" |
| 19 | |
| 20 | "golang.org/x/time/rate" |
| 21 | |
| 22 | "github.com/prometheus/client_golang/prometheus" |
| 23 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 24 | "github.com/sassoftware/relic/v7/lib/pkcs7" |
| 25 | "github.com/sassoftware/relic/v7/lib/pkcs9" |
| 26 | ) |
| 27 | |
| 28 | var metricRateLimited = promauto.NewCounter(prometheus.CounterOpts{ |
| 29 | Name: "timestamper_rate_limited_seconds", |
| 30 | Help: "Cumulative number of seconds waiting for rate limits", |
| 31 | }) |
| 32 | |
| 33 | type limiter struct { |
| 34 | Timestamper pkcs9.Timestamper |
| 35 | Limit *rate.Limiter |
| 36 | } |
| 37 | |
| 38 | func New(t pkcs9.Timestamper, r float64, burst int) pkcs9.Timestamper { |
| 39 | if r == 0 { |
| 40 | return t |
| 41 | } |
| 42 | if burst < 1 { |
| 43 | burst = 1 |
| 44 | } |
| 45 | return &limiter{t, rate.NewLimiter(rate.Limit(r), burst)} |
| 46 | } |
| 47 | |
| 48 | func (l *limiter) Timestamp(ctx context.Context, req *pkcs9.Request) (*pkcs7.ContentInfoSignedData, error) { |
| 49 | start := time.Now() |
| 50 | if err := l.Limit.Wait(ctx); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | if waited := time.Since(start); waited > 1*time.Millisecond { |
| 54 | metricRateLimited.Add(time.Since(start).Seconds()) |
| 55 | } |
| 56 | return l.Timestamper.Timestamp(ctx, req) |
| 57 | } |