github.com/cilium/cilium@v1.16.2/pkg/api/metrics/mock/mock.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package mock 5 6 import ( 7 "fmt" 8 "time" 9 10 "github.com/cilium/cilium/pkg/lock" 11 ) 12 13 // MockMetrics is a mock implementation of pkg/api/metrics 14 type MockMetrics struct { 15 mutex lock.RWMutex 16 apiCall map[string]float64 17 rateLimit map[string]time.Duration 18 } 19 20 // NewMockMetrics returns a new metrics implementation with a mocked backend 21 func NewMockMetrics() *MockMetrics { 22 return &MockMetrics{ 23 apiCall: map[string]float64{}, 24 rateLimit: map[string]time.Duration{}, 25 } 26 } 27 28 // APICall returns the sum of all durations of all API for a given operation 29 // and status 30 func (m *MockMetrics) APICall(operation, status string) float64 { 31 m.mutex.RLock() 32 defer m.mutex.RUnlock() 33 return m.apiCall[fmt.Sprintf("operation=%s, status=%s", operation, status)] 34 } 35 36 // ObserveAPICall must be called on every API call made with the operation 37 // performed, the status code received and the duration of the call. The 38 // duration of the API call will be observed. The total can be retrieved with 39 // APICall(). 40 func (m *MockMetrics) ObserveAPICall(operation, status string, duration float64) { 41 m.mutex.Lock() 42 m.apiCall[fmt.Sprintf("operation=%s, status=%s", operation, status)] += duration 43 m.mutex.Unlock() 44 } 45 46 // RateLimit returns the sum of all rate limited durations of all API for a 47 // given operation 48 func (m *MockMetrics) RateLimit(operation string) time.Duration { 49 m.mutex.RLock() 50 defer m.mutex.RUnlock() 51 return m.rateLimit[operation] 52 } 53 54 // ObserveRateLimit must be called in case an API call was subject to rate 55 // limiting. The duration of the rate-limiting will be observed. The taotal of 56 // all durations can be retrieve with RateLimit(). 57 func (m *MockMetrics) ObserveRateLimit(operation string, delay time.Duration) { 58 m.mutex.Lock() 59 m.rateLimit[operation] += delay 60 m.mutex.Unlock() 61 }