Skip to content

Commit 578bfff

Browse files
authored
fix: avoid panic on re-register timer (#23)
1 parent cec980a commit 578bfff

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

tunnelsdk/tunnel.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@ package tunnelsdk
22

33
import (
44
"context"
5+
"crypto/rand"
56
"crypto/sha512"
67
"encoding/hex"
78
"errors"
89
"fmt"
10+
"math/big"
911
"net"
1012
"net/netip"
1113
"net/url"
@@ -194,6 +196,9 @@ func (c *Client) LaunchTunnel(ctx context.Context, cfg TunnelConfig) (*Tunnel, e
194196
if len(res.TunnelURLs) == 0 {
195197
return nil, xerrors.Errorf("no tunnel urls returned from server")
196198
}
199+
if res.ReregisterWait <= 0 {
200+
return nil, xerrors.Errorf("invalid reregister wait time: %s", res.ReregisterWait)
201+
}
197202

198203
primaryURL, err := url.Parse(res.TunnelURLs[0])
199204
if err != nil {
@@ -247,6 +252,17 @@ func (c *Client) LaunchTunnel(ctx context.Context, cfg TunnelConfig) (*Tunnel, e
247252
cfg.Log.Warn(ctx, "periodically re-register tunnel", slog.Error(err))
248253
}
249254

255+
// If we failed to re-register, try again in 30 seconds plus a
256+
// random amount of time between 0 and 30 seconds.
257+
if res.ReregisterWait <= 0 {
258+
res.ReregisterWait = 30 * time.Second
259+
i, err := rand.Int(rand.Reader, big.NewInt(30))
260+
if err != nil {
261+
i = big.NewInt(30)
262+
}
263+
res.ReregisterWait += time.Duration(i.Int64()) * time.Second
264+
}
265+
250266
ticker.Reset(res.ReregisterWait)
251267
cancel()
252268
}

0 commit comments

Comments
 (0)