...

Source file src/github.com/sassoftware/relic/lib/pkcs9/ratelimit/ratelimit.go

Documentation: github.com/sassoftware/relic/lib/pkcs9/ratelimit

     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  	"log"
    19  	"time"
    20  
    21  	"github.com/sassoftware/relic/lib/pkcs7"
    22  	"github.com/sassoftware/relic/lib/pkcs9"
    23  	"golang.org/x/time/rate"
    24  )
    25  
    26  type limiter struct {
    27  	Timestamper pkcs9.Timestamper
    28  	Limit       *rate.Limiter
    29  }
    30  
    31  func New(t pkcs9.Timestamper, r float64, burst int) pkcs9.Timestamper {
    32  	if r == 0 {
    33  		return t
    34  	}
    35  	if burst < 1 {
    36  		burst = 1
    37  	}
    38  	return &limiter{t, rate.NewLimiter(rate.Limit(r), burst)}
    39  }
    40  
    41  func (l *limiter) Timestamp(ctx context.Context, req *pkcs9.Request) (*pkcs7.ContentInfoSignedData, error) {
    42  	start := time.Now()
    43  	if err := l.Limit.Wait(ctx); err != nil {
    44  		return nil, err
    45  	}
    46  	if waited := time.Now().Sub(start); waited > 50*time.Millisecond {
    47  		log.Printf("timestamper: waited %s due to rate limit", waited)
    48  	}
    49  	return l.Timestamper.Timestamp(ctx, req)
    50  }
    51  

View as plain text