Skip to content

Commit

Permalink
Add OnConnectionDown callback in autopaho
Browse files Browse the repository at this point in the history
Provides callback that is called when an established conneciton is dropped. Presents an opportunity to prevent future attempts to connect.
  • Loading branch information
MattBrittan authored Nov 26, 2024
2 parents 32af1f8 + 1fb922c commit a13d64c
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions autopaho/auto.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ type ClientConfig struct {
// To fix, use packets.NewThreadSafeConn wrapper or extend the custom net.Conn struct with sync.Locker.
AttemptConnection func(context.Context, ClientConfig, *url.URL) (net.Conn, error)

OnConnectionUp func(*ConnectionManager, *paho.Connack) // Called when a connection is made (including reconnection). Connection Manager passed to simplify subscriptions. Supplied function must not block.
OnConnectError func(error) // Called (within a goroutine) whenever a connection attempt fails. Will wrap autopaho.ConnackError on server deny.
OnConnectionUp func(*ConnectionManager, *paho.Connack) // Called when a connection is made (including reconnection). Connection Manager passed to simplify subscriptions. Supplied function must not block.
OnConnectionDown func() bool // Only called after the connection that resulted in OnConnectionUp is dropped. Returning false will cause autopaho to cease attempting to connect. Supplied function must not block.
OnConnectError func(error) // Called (within a goroutine) whenever a connection attempt fails. Will wrap autopaho.ConnackError on server deny.

Debug log.Logger // By default set to NOOPLogger{},set to a logger for debugging info
Errors log.Logger // By default set to NOOPLogger{},set to a logger for errors
Expand Down Expand Up @@ -359,6 +360,11 @@ func NewConnection(ctx context.Context, cfg ClientConfig) (*ConnectionManager, e
close(c.connDown)
c.connUp = make(chan struct{})
c.mu.Unlock()

if cfg.OnConnectionDown != nil && !cfg.OnConnectionDown() {
cfg.Debug.Printf("mainLoop: connection to server lost (%s); OnConnectionDown aborts reconnect\n", err)
break mainLoop
}
cfg.Debug.Printf("mainLoop: connection to server lost (%s); will reconnect\n", err)
}
cfg.Debug.Println("mainLoop: connection manager has terminated")
Expand Down

0 comments on commit a13d64c

Please sign in to comment.