Skip to content

Modern Docker Management, Designed for Everyone

7.3 KB
Raw Blame
package edge

import (
	"bytes"
	"context"
	"encoding/json/v2"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net/http"
	"strings"
	"time"

	"github.com/cenkalti/backoff/v5"

	"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
)

const (
	defaultTunnelPollRequestTimeout = 15 * time.Second
	tunnelPollPath                  = "/api/tunnel/poll"
)

var defaultPollManagedSessionStopTimeout = 5 * time.Second

var errPollManagedSessionStopTimeout = errors.New("timed out waiting for poll-managed websocket session to stop")

func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {
	if c.cfg == nil {
		return errors.New("manager base URL is empty")
	}
	managerBaseURL := strings.TrimRight(strings.TrimSpace(httpx.ManagerBaseURL(c.cfg.ManagerApiUrl)), "/")
	if managerBaseURL == "" {
		return errors.New("manager base URL is empty")
	}
	httpClient, err := NewManagerHTTPClient(c.cfg, 0)
	if err != nil {
		return fmt.Errorf("failed to configure edge poll client: %w", err)
	}
	pollURL := managerBaseURL + tunnelPollPath
	interval := DefaultTunnelPollInterval
	// Failed polls back off exponentially; success restores the advertised interval. No jitter: polls are
	// already phase-spread across agents, so the first retry is exactly the poll interval.
	retryBackoff := backoff.NewExponentialBackOff()
	retryBackoff.InitialInterval = interval
	retryBackoff.RandomizationFactor = 0
	retryBackoff.MaxInterval = maxPollRetryInterval
	var session *pollManagedTunnelSession
	defer func() {
		shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultPollManagedSessionStopTimeout)
		defer cancel()

		if stopPollManagedSessionErr := c.stopPollManagedSession(shutdownCtx, session); stopPollManagedSessionErr != nil {
			slog.WarnContext(ctx, "Failed to stop poll-managed websocket session during shutdown", "error", stopPollManagedSessionErr)
		}
	}()

	for {
		var operationErr error
		session, operationErr = consumePollManagedSession(session)
		if operationErr != nil {
			return operationErr
		}

		if ctx.Err() != nil {
			return ctx.Err()
		}

		status, operationErr := c.pollTunnelControl(ctx, httpClient, pollURL, session != nil)
		if operationErr != nil {
			if ctx.Err() != nil {
				return ctx.Err()
			}

			retryInterval := retryBackoff.NextBackOff()
			slog.WarnContext(ctx, "Poll control request failed, retrying after interval",
				"error", operationErr,
				"interval", retryInterval,
			)

			session, operationErr = waitForNextPollCycle(ctx, session, retryInterval)
			if operationErr != nil {
				return operationErr
			}
			continue
		}

		if status.PollIntervalSeconds > 0 {
			interval = time.Duration(status.PollIntervalSeconds) * time.Second
		}
		// Reset copies InitialInterval into the current interval, so the
		// manager-advertised value must be applied before resetting.
		retryBackoff.InitialInterval = interval
		retryBackoff.Reset()

		session, operationErr = c.syncPollManagedSession(ctx, session, status.Status)
		if operationErr != nil {
			if !errors.Is(operationErr, errPollManagedSessionStopTimeout) {
				return operationErr
			}
			slog.WarnContext(ctx, "Poll-managed tunnel is still draining; replacement remains fenced", "error", operationErr)
		}

		session, operationErr = waitForNextPollCycle(ctx, session, interval)
		if operationErr != nil {
			return operationErr
		}
	}
}

func consumePollManagedSession(session *pollManagedTunnelSession) (*pollManagedTunnelSession, error) {
	if session == nil {
		return nil, nil
	}

	select {
	case err := <-session.done:
		if err != nil {
			return nil, fmt.Errorf("poll-managed websocket session ended: %w", err)
		}
		return nil, nil
	default:
		return session, nil
	}
}

func (c *TunnelClient) syncPollManagedSession(ctx context.Context, session *pollManagedTunnelSession, status string) (*pollManagedTunnelSession, error) {
	switch status {
	case TunnelStatusRequired, TunnelStatusActive:
		if session != nil {
			return session, nil
		}

		slog.InfoContext(ctx, "Poll control plane requested edge tunnel",
			"status", status,
			"managerGrpcAddr", c.managerGRPCAddr,
			"managerWsUrl", c.managerWebSocketURL(),
		)
		return c.startPollManagedSession(ctx), nil
	case TunnelStatusIdle:
		if session == nil {
			return nil, nil
		}
		if session.stopping {
			return session, nil
		}

		slog.InfoContext(ctx, "Poll control plane marked edge tunnel idle; closing session")
		session.stopping = true
		idleCtx, idleCancel := context.WithTimeout(ctx, defaultPollManagedSessionStopTimeout)
		err := c.stopPollManagedSession(idleCtx, session)
		idleCancel()
		if err != nil {
			return session, err
		}
		return nil, nil
	default:
		slog.WarnContext(ctx, "Received unknown poll control status", "status", status)
		return session, nil
	}
}

func waitForNextPollCycle(ctx context.Context, session *pollManagedTunnelSession, interval time.Duration) (*pollManagedTunnelSession, error) {
	waitTimer := time.NewTimer(interval)
	defer waitTimer.Stop()

	var sessionDone <-chan error
	if session != nil {
		sessionDone = session.done
	}

	select {
	case <-ctx.Done():
		return session, ctx.Err()
	case err := <-sessionDone:
		if err != nil {
			return nil, fmt.Errorf("poll-managed websocket session ended: %w", err)
		}
		return nil, nil
	case <-waitTimer.C:
		return session, nil
	}
}

func (c *TunnelClient) pollTunnelControl(ctx context.Context, httpClient *http.Client, pollURL string, connected bool) (*TunnelPollResponse, error) {
	pollReq := TunnelPollRequest{
		Transport: EdgeTransportPoll,
		Connected: connected,
	}

	body, err := json.Marshal(pollReq)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal poll request: %w", err)
	}

	reqCtx, cancel := context.WithTimeout(ctx, defaultTunnelPollRequestTimeout)
	defer cancel()

	req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pollURL, bytes.NewReader(body))
	if err != nil {
		return nil, fmt.Errorf("failed to create poll request: %w", err)
	}
	req.Header.Set("Content-Type", "application/json")
	for header, value := range agentAuthCredentials(c.cfg.AgentToken) {
		req.Header.Set(header, value)
	}

	resp, err := httpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("poll request failed: %w", err)
	}
	defer func() { _ = resp.Body.Close() }()

	if resp.StatusCode != http.StatusOK {
		respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
		return nil, fmt.Errorf("poll request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(respBody)))
	}

	var pollResp TunnelPollResponse
	if unmarshalReadErr := json.UnmarshalRead(resp.Body, &pollResp); unmarshalReadErr != nil {
		return nil, fmt.Errorf("failed to decode poll response: %w", unmarshalReadErr)
	}
	return &pollResp, nil
}

func (c *TunnelClient) startPollManagedSession(ctx context.Context) *pollManagedTunnelSession {
	sessionCtx, cancel := context.WithCancel(ctx)
	done := make(chan error, 1)

	go func() {
		err := c.connectAndServeManagedTunnel(sessionCtx)
		if sessionCtx.Err() != nil {
			err = nil
		}
		done <- err
		close(done)
	}()

	return &pollManagedTunnelSession{cancel: cancel, done: done}
}

func (c *TunnelClient) stopPollManagedSession(ctx context.Context, session *pollManagedTunnelSession) error {
	if session == nil {
		return nil
	}
	session.stopping = true
	session.cancel()

	select {
	case err := <-session.done:
		return err
	case <-ctx.Done():
		if errors.Is(ctx.Err(), context.DeadlineExceeded) {
			return errPollManagedSessionStopTimeout
		}
		return ctx.Err()
	}
}