Added client.StopTime(), to expose disconnected (#400)

* 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.
This commit is contained in:
Jens Alfke 2024-05-19 11:11:24 -07:00 committed by GitHub
parent 5966c7fe0d
commit cc3f827fc1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 9 additions and 2 deletions

View File

@ -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

View File

@ -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())
}

View File

@ -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
}