...

Source file src/github.com/google/certificate-transparency-go/jsonclient/backoff.go

Documentation: github.com/google/certificate-transparency-go/jsonclient

     1  // Copyright 2017 Google LLC. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package jsonclient
    16  
    17  import (
    18  	"sync"
    19  	"time"
    20  )
    21  
    22  type backoff struct {
    23  	mu         sync.RWMutex
    24  	multiplier uint
    25  	notBefore  time.Time
    26  }
    27  
    28  const (
    29  	// maximum backoff is 2^(maxMultiplier-1) = 128 seconds
    30  	maxMultiplier = 8
    31  )
    32  
    33  func (b *backoff) set(override *time.Duration) time.Duration {
    34  	b.mu.Lock()
    35  	defer b.mu.Unlock()
    36  	if b.notBefore.After(time.Now()) {
    37  		if override != nil {
    38  			// If existing backoff is set but override would be longer than
    39  			// it then set it to that.
    40  			notBefore := time.Now().Add(*override)
    41  			if notBefore.After(b.notBefore) {
    42  				b.notBefore = notBefore
    43  			}
    44  		}
    45  		return time.Until(b.notBefore)
    46  	}
    47  	var wait time.Duration
    48  	if override != nil {
    49  		wait = *override
    50  	} else {
    51  		if b.multiplier < maxMultiplier {
    52  			b.multiplier++
    53  		}
    54  		wait = time.Second * time.Duration(1<<(b.multiplier-1))
    55  	}
    56  	b.notBefore = time.Now().Add(wait)
    57  	return wait
    58  }
    59  
    60  func (b *backoff) decreaseMultiplier() {
    61  	b.mu.Lock()
    62  	defer b.mu.Unlock()
    63  	if b.multiplier > 0 {
    64  		b.multiplier--
    65  	}
    66  }
    67  
    68  func (b *backoff) until() time.Time {
    69  	b.mu.RLock()
    70  	defer b.mu.RUnlock()
    71  	return b.notBefore
    72  }
    73  

View as plain text