Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Commit f337897

Browse files
authored
feat: Add ActiveConnections function to track usage (#390)
* feat: Add ActiveConnections function tto track usage * Fix linting errors * Fix syntax err
1 parent 4de99d5 commit f337897

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

wsnet/dial.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,17 @@ func (d *Dialer) Closed() <-chan struct{} {
232232
return d.closedChan
233233
}
234234

235+
// ActiveConnections returns the amount of active connections.
236+
// DialContext opens a connection, and close will end it.
237+
func (d *Dialer) ActiveConnections() int {
238+
stats, ok := d.rtc.GetStats().GetConnectionStats(d.rtc)
239+
if !ok {
240+
return -1
241+
}
242+
// Subtract 1 for the control channel.
243+
return int(stats.DataChannelsRequested-stats.DataChannelsClosed) - 1
244+
}
245+
235246
// Close closes the RTC connection.
236247
// All data channels dialed will be closed.
237248
func (d *Dialer) Close() error {

wsnet/dial_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,38 @@ func TestDial(t *testing.T) {
243243
t.Error("didn't close in time")
244244
}
245245
})
246+
247+
t.Run("Active Connections", func(t *testing.T) {
248+
t.Parallel()
249+
250+
listener, err := net.Listen("tcp", "0.0.0.0:0")
251+
if err != nil {
252+
t.Error(err)
253+
return
254+
}
255+
go func() {
256+
_, _ = listener.Accept()
257+
}()
258+
connectAddr, listenAddr := createDumbBroker(t)
259+
_, err = Listen(context.Background(), slogtest.Make(t, nil), listenAddr, "")
260+
if err != nil {
261+
t.Error(err)
262+
return
263+
}
264+
dialer, err := DialWebsocket(context.Background(), connectAddr, nil)
265+
if err != nil {
266+
t.Error(err)
267+
}
268+
conn, _ := dialer.DialContext(context.Background(), listener.Addr().Network(), listener.Addr().String())
269+
assert.Equal(t, 1, dialer.ActiveConnections())
270+
_ = conn.Close()
271+
assert.Equal(t, 0, dialer.ActiveConnections())
272+
_, _ = dialer.DialContext(context.Background(), listener.Addr().Network(), listener.Addr().String())
273+
conn, _ = dialer.DialContext(context.Background(), listener.Addr().Network(), listener.Addr().String())
274+
assert.Equal(t, 2, dialer.ActiveConnections())
275+
_ = conn.Close()
276+
assert.Equal(t, 1, dialer.ActiveConnections())
277+
})
246278
}
247279

248280
func BenchmarkThroughput(b *testing.B) {

0 commit comments

Comments
 (0)