mirror of
https://github.com/strukturag/nextcloud-spreed-signaling
synced 2024-06-08 00:42:25 +02:00
Reuse backoff waiting code in NATS client.
This commit is contained in:
parent
fe53c32714
commit
f6fe960534
|
@ -22,6 +22,7 @@
|
||||||
package signaling
|
package signaling
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
@ -74,33 +75,27 @@ func NewNatsClient(url string) (NatsClient, error) {
|
||||||
return NewLoopbackNatsClient()
|
return NewLoopbackNatsClient()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
backoff, err := NewExponentialBackoff(initialConnectInterval, maxConnectInterval)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
client := &natsClient{}
|
client := &natsClient{}
|
||||||
|
|
||||||
var err error
|
|
||||||
client.nc, err = nats.Connect(url,
|
client.nc, err = nats.Connect(url,
|
||||||
nats.ClosedHandler(client.onClosed),
|
nats.ClosedHandler(client.onClosed),
|
||||||
nats.DisconnectHandler(client.onDisconnected),
|
nats.DisconnectHandler(client.onDisconnected),
|
||||||
nats.ReconnectHandler(client.onReconnected))
|
nats.ReconnectHandler(client.onReconnected))
|
||||||
|
|
||||||
interrupt := make(chan os.Signal, 1)
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||||
signal.Notify(interrupt, os.Interrupt)
|
defer stop()
|
||||||
defer signal.Stop(interrupt)
|
|
||||||
|
|
||||||
delay := initialConnectInterval
|
|
||||||
timer := time.NewTimer(delay)
|
|
||||||
// The initial connect must succeed, so we retry in the case of an error.
|
// The initial connect must succeed, so we retry in the case of an error.
|
||||||
for err != nil {
|
for err != nil {
|
||||||
log.Printf("Could not create connection (%s), will retry in %s", err, delay)
|
log.Printf("Could not create connection (%s), will retry in %s", err, backoff.NextWait())
|
||||||
timer.Reset(delay)
|
backoff.Wait(ctx)
|
||||||
select {
|
if ctx.Err() != nil {
|
||||||
case <-interrupt:
|
|
||||||
return nil, fmt.Errorf("interrupted")
|
return nil, fmt.Errorf("interrupted")
|
||||||
case <-timer.C:
|
|
||||||
// Retry connection
|
|
||||||
delay = delay * 2
|
|
||||||
if delay > maxConnectInterval {
|
|
||||||
delay = maxConnectInterval
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
client.nc, err = nats.Connect(url)
|
client.nc, err = nats.Connect(url)
|
||||||
|
|
Loading…
Reference in a new issue