Skip to content

Commit

Permalink
Added client.StopTime(), to expose disconnected (#400)
Browse files Browse the repository at this point in the history
* Added client.StopTime() to expose `disconnected`

* Added a test of Client.StopTime()

I added a check to TestClientStop(), both before and after stopping.

I also noticed a race condition in the test (comparing a time against
time.Now) and fixed it to allow a one-second discrepancy.
  • Loading branch information
snej authored May 19, 2024
1 parent 5966c7f commit cc3f827
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 2 deletions.
5 changes: 5 additions & 0 deletions clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,11 @@ func (cl *Client) StopCause() error {
return cl.State.stopCause.Load().(error)
}

// StopTime returns the the time the client disconnected in unix time, else zero.
func (cl *Client) StopTime() int64 {
return atomic.LoadInt64(&cl.State.disconnected)
}

// Closed returns true if client connection is closed.
func (cl *Client) Closed() bool {
return cl.State.open == nil || cl.State.open.Err() != nil
Expand Down
4 changes: 3 additions & 1 deletion clients_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -583,9 +583,11 @@ func TestClientReadDone(t *testing.T) {

func TestClientStop(t *testing.T) {
cl, _, _ := newTestClient()
require.Equal(t, int64(0), cl.StopTime())
cl.Stop(nil)
require.Equal(t, nil, cl.State.stopCause.Load())
require.Equal(t, time.Now().Unix(), cl.State.disconnected)
require.InDelta(t, time.Now().Unix(), cl.State.disconnected, 1.0)
require.Equal(t, cl.State.disconnected, cl.StopTime())
require.True(t, cl.Closed())
require.Equal(t, nil, cl.StopCause())
}
Expand Down
2 changes: 1 addition & 1 deletion server.go
Original file line number Diff line number Diff line change
Expand Up @@ -1689,7 +1689,7 @@ func (s *Server) loadRetained(v []storage.Message) {
// than their given expiry intervals.
func (s *Server) clearExpiredClients(dt int64) {
for id, client := range s.Clients.GetAll() {
disconnected := atomic.LoadInt64(&client.State.disconnected)
disconnected := client.StopTime()
if disconnected == 0 {
continue
}
Expand Down

0 comments on commit cc3f827

Please sign in to comment.