github.com/cilium/cilium@v1.16.2/pkg/api/helpers/delay_simulator.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package helpers 5 6 import ( 7 "time" 8 9 "github.com/cilium/cilium/pkg/lock" 10 ) 11 12 // Operation represents an API operation 13 type Operation interface{} 14 15 // DelaySimulator simulates delays in API calls 16 type DelaySimulator struct { 17 mutex lock.RWMutex 18 delays map[Operation]time.Duration 19 } 20 21 // NewDelaySimulator returns a new DelaySimulator 22 func NewDelaySimulator() *DelaySimulator { 23 return &DelaySimulator{ 24 delays: map[Operation]time.Duration{}, 25 } 26 } 27 28 func (d *DelaySimulator) setDelayLocked(op Operation, delay time.Duration) { 29 if delay == time.Duration(0) { 30 delete(d.delays, op) 31 } else { 32 d.delays[op] = delay 33 } 34 } 35 36 // SetDelay specifies the delay to be simulated for an individual API operation 37 func (d *DelaySimulator) SetDelay(op Operation, delay time.Duration) { 38 d.mutex.Lock() 39 d.setDelayLocked(op, delay) 40 d.mutex.Unlock() 41 } 42 43 // Delay delays an API operation according to the configuration 44 func (d *DelaySimulator) Delay(op Operation) { 45 d.mutex.RLock() 46 delay, ok := d.delays[op] 47 d.mutex.RUnlock() 48 if ok { 49 time.Sleep(delay) 50 } 51 }