istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/test/loadbalancersim/network/helper.go (about) 1 // Copyright Istio Authors 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 network 16 17 import ( 18 "time" 19 20 "go.uber.org/atomic" 21 22 "istio.io/istio/pkg/test/loadbalancersim/timeseries" 23 ) 24 25 type ConnectionHelper struct { 26 name string 27 hist timeseries.Instance 28 active *atomic.Uint64 29 total *atomic.Uint64 30 } 31 32 func NewConnectionHelper(name string) *ConnectionHelper { 33 return &ConnectionHelper{ 34 active: atomic.NewUint64(0), 35 total: atomic.NewUint64(0), 36 name: name, 37 } 38 } 39 40 func (c *ConnectionHelper) Name() string { 41 return c.name 42 } 43 44 func (c *ConnectionHelper) TotalRequests() uint64 { 45 return c.total.Load() 46 } 47 48 func (c *ConnectionHelper) ActiveRequests() uint64 { 49 return c.active.Load() 50 } 51 52 func (c *ConnectionHelper) Latency() *timeseries.Instance { 53 return &c.hist 54 } 55 56 func (c *ConnectionHelper) Request(request func(onDone func()), onDone func()) { 57 start := time.Now() 58 c.total.Inc() 59 c.active.Inc() 60 61 wrappedDone := func() { 62 // Calculate the latency for this request. 63 latency := time.Since(start) 64 65 // Add the latency observation. 66 c.hist.AddObservation(latency.Seconds(), time.Now()) 67 68 c.active.Dec() 69 70 // Invoke the caller's handler. 71 onDone() 72 } 73 74 request(wrappedDone) 75 }