diff --git a/supervisor/supervisor.go b/supervisor/supervisor.go index cc2d42e545f..a5cc4c4e857 100644 --- a/supervisor/supervisor.go +++ b/supervisor/supervisor.go @@ -63,6 +63,9 @@ var errEarlyShutdown = errors.New("shutdown started") type tunnelError struct { index int err error + // served reports whether the connection registered and stayed up for at + // least tunnelRetryDuration before it ended. + served bool } func NewSupervisor(config *TunnelConfig, orchestrator *orchestration.Orchestrator, gracefulShutdownC <-chan struct{}) (*Supervisor, error) { @@ -284,6 +287,15 @@ func (s *Supervisor) runConnections(ctx context.Context, connectedSignal *signal if _, retry := s.tunnelsProtocolFallback[tunnelError.index].GetMaxBackoffDuration(ctx); !retry { continue } + if tunnelError.served { + // The edge keeps routing requests to this connection until it registers + // again, so reconnect a connection that was serving right away. Serve has + // already waited its per-connection backoff, and a reconnect that fails + // before registering goes through the shared backoff below. + go s.startTunnel(ctx, tunnelError.index, s.newConnectedTunnelSignal(tunnelError.index)) + tunnelsActive++ + continue + } tunnelsWaiting = append(tunnelsWaiting, tunnelError.index) s.waitForNextTunnel(tunnelError.index) @@ -381,15 +393,21 @@ func (s *Supervisor) startFirstTunnel( connectedSignal *signal.Signal, ) { var err error + var started time.Time const firstConnIndex = 0 isStaticEdge := len(s.config.EdgeAddrs) > 0 defer func() { - s.tunnelErrors <- tunnelError{index: firstConnIndex, err: err} + s.tunnelErrors <- tunnelError{index: firstConnIndex, err: err, served: served(connectedSignal, started)} }() + // Read the fallback before the first connection can register: initialize + // adds the other connections' entries to the map once it has. + protocolFallback := s.tunnelsProtocolFallback[firstConnIndex] + // If the first tunnel disconnects, keep restarting it. for { - err = s.edgeTunnelServer.Serve(ctx, firstConnIndex, s.tunnelsProtocolFallback[firstConnIndex], connectedSignal) + started = time.Now() + err = s.edgeTunnelServer.Serve(ctx, firstConnIndex, protocolFallback, connectedSignal) if ctx.Err() != nil { return } @@ -402,7 +420,7 @@ func (s *Supervisor) startFirstTunnel( return } // Make sure we don't continue if there is no more fallback allowed - if _, retry := s.tunnelsProtocolFallback[firstConnIndex].GetMaxBackoffDuration(ctx); !retry { + if _, retry := protocolFallback.GetMaxBackoffDuration(ctx); !retry { return } // Try again for Unauthorized errors because we hope them to be @@ -467,9 +485,22 @@ func (s *Supervisor) startTunnel( index int, connectedSignal *signal.Signal, ) { + started := time.Now() // nolint: gosec err := s.edgeTunnelServer.Serve(ctx, uint8(index), s.tunnelsProtocolFallback[index], connectedSignal) - s.tunnelErrors <- tunnelError{index: index, err: err} + s.tunnelErrors <- tunnelError{index: index, err: err, served: served(connectedSignal, started)} +} + +// served reports whether a connection started at started registered and lasted +// at least tunnelRetryDuration. This limits immediate reconnects of a connection +// to one per tunnelRetryDuration, as with region changes. +func served(connectedSignal *signal.Signal, started time.Time) bool { + select { + case <-connectedSignal.Wait(): + return time.Since(started) >= tunnelRetryDuration + default: + return false + } } func (s *Supervisor) newConnectedTunnelSignal(index int) *signal.Signal { diff --git a/supervisor/supervisor_test.go b/supervisor/supervisor_test.go index 7728e9680bd..f627a7aa364 100644 --- a/supervisor/supervisor_test.go +++ b/supervisor/supervisor_test.go @@ -3,6 +3,7 @@ package supervisor import ( "context" "crypto/tls" + "errors" "fmt" "sync/atomic" "testing" @@ -301,3 +302,68 @@ func TestRegionChangeGracefulShutdownInterruptsRestartDelay(t *testing.T) { require.Equal(t, 2, starts, "graceful shutdown must prevent another connection") }) } + +func TestReconnectAfterServedConnectionCloses(t *testing.T) { + t.Parallel() + + errEdgeClosed := errors.New("connection with edge closed") + for _, test := range []struct { + name string + index uint8 + registers bool + servesFor time.Duration + wantImmediate bool + }{ + {"served connection reconnects at once", 1, true, time.Hour, true}, + {"served first connection reconnects at once", 0, true, time.Hour, true}, + {"short-lived connection waits for the backoff", 1, true, time.Second, false}, + {"unregistered connection waits for the backoff", 1, false, time.Hour, false}, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + s := newTestSupervisor(t, nil) + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + var closed, restarted time.Time + var calls atomic.Int32 + s.edgeTunnelServer = regionChangeTunnelServer(func(ctx context.Context, index uint8, connected *signal.Signal) error { + if index != test.index { + connected.Notify() + <-ctx.Done() + return ctx.Err() + } + switch calls.Add(1) { + case 1: + if test.registers { + connected.Notify() + } + time.Sleep(test.servesFor) + closed = time.Now() + return errEdgeClosed + default: + restarted = time.Now() + cancel() + return ctx.Err() + } + }) + // Channels the supervisor selects on must belong to the bubble, or + // the fake clock never advances past a connection's lifetime. + s.tunnelErrors = make(chan tunnelError) + s.tunnelsConnecting = make(map[int]chan struct{}) + s.config.HAConnections = 2 + selector, err := connection.NewProtocolSelector("http2", s.log.Logger()) + require.NoError(t, err) + s.config.ProtocolSelector = selector + + require.NoError(t, s.runConnections(ctx, signal.New(make(chan struct{})))) + require.Equal(t, int32(2), calls.Load(), "the closed connection must be started again") + if test.wantImmediate { + require.Equal(t, closed, restarted, "a connection that was serving must reconnect without the shared backoff") + } else { + require.Greater(t, restarted.Sub(closed), time.Duration(0), "the reconnect must wait for the shared backoff") + } + }) + }) + } +}