github.com/chenbh/concourse/v6@v6.4.2/worker/runtime/timeout_lock.go (about)

     1  package runtime
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"golang.org/x/sync/semaphore"
     8  )
     9  
    10  type TimeoutWithByPassLock struct {
    11  	semaphore *semaphore.Weighted
    12  	timeout   time.Duration
    13  	enabled   bool
    14  }
    15  
    16  // NewTimeoutLimitLock returns a lock that allows only 1 entity to hold the lock at a time
    17  //    Lock acquisition will block until the lock is acquired or the configured `timeout` elapses
    18  //    Lock can be bypassed by specifying setting `enabled` to false
    19  
    20  func NewTimeoutLimitLock(timeout time.Duration, enabled bool) TimeoutWithByPassLock {
    21  	return TimeoutWithByPassLock{
    22  		semaphore: semaphore.NewWeighted(1),
    23  		timeout:   timeout,
    24  		enabled:   enabled,
    25  	}
    26  }
    27  
    28  func (tl TimeoutWithByPassLock) Acquire(ctx context.Context) error {
    29  	if !tl.enabled {
    30  		return nil
    31  	}
    32  	ctx, cancel := context.WithTimeout(ctx, tl.timeout)
    33  	defer cancel()
    34  
    35  	return tl.semaphore.Acquire(ctx, 1)
    36  }
    37  
    38  func (tl TimeoutWithByPassLock) Release() {
    39  	if tl.enabled {
    40  		tl.semaphore.Release(1)
    41  	}
    42  }