Skip to content

Modern Docker Management, Designed for Everyone

fix: crashes, goroutine leaks, and hot-path performance in the backend (#3425)

Kyle Mendell97b9e9c83053
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index e7b2f80c0..b3c91fb2d 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -465,11 +465,51 @@ func (h *EnvironmentHandler) visibleEnvironmentsForInternal(ctx context.Context,
return filtered, nil
}
+// fingerprintEnvironmentsInternal hashes every field of the visible environment
+// list. This runs on every stream tick for every connected client, so it hashes
+// the fields directly rather than marshalling the payload to JSON and retaining
+// the bytes for comparison — most ticks change nothing and the encoded snapshot
+// was thrown away immediately.
+func fingerprintEnvironmentsInternal(envs []environment.Environment) uint64 {
+ return utils.FingerprintOf(envs, func(f *utils.Fingerprint, env *environment.Environment) {
+ f.String(env.ID).
+ String(env.Name).
+ String(env.ApiUrl).
+ String(env.Status).
+ Bool(env.Enabled).
+ Bool(env.IsEdge).
+ OptTime(env.LastSeen).
+ OptString(env.EdgeTransport).
+ OptString(env.LastEdgeTransport).
+ OptString(env.EdgeSecurityMode).
+ OptString(env.EdgeSessionID).
+ OptString(env.EdgeAgentInstance).
+ Strings(env.EdgeCapabilities).
+ OptBool(env.Connected).
+ OptTime(env.ConnectedAt).
+ OptTime(env.LastHeartbeat).
+ OptTime(env.LastPollAt).
+ OptString(env.ApiKey)
+
+ cert := env.EdgeMTLSCertificate
+ f.Present(cert != nil)
+ if cert == nil {
+ return
+ }
+ f.OptString(cert.CommonName).
+ OptTime(cert.ExpiresAt).
+ OptInt(cert.DaysRemaining).
+ Bool(cert.Expired).
+ Bool(cert.ExpiringSoon)
+ })
+}
+
func (h *EnvironmentHandler) runEnvironmentStreamProducerInternal(ctx context.Context, ps *authz.PermissionSet, events chan<- environment.StreamEvent) {
changes, unsubscribe := h.environmentService.SubscribeRuntimeChanges()
defer unsubscribe()
- var lastFingerprint []byte
+ var lastFingerprint uint64
+ var haveFingerprint bool
var lastSentAt time.Time
send := func() bool {
@@ -482,17 +522,14 @@ func (h *EnvironmentHandler) runEnvironmentStreamProducerInternal(ctx context.Co
return ctx.Err() == nil
}
- fingerprint, err := json.Marshal(envs)
- if err != nil {
- slog.WarnContext(ctx, "environment stream failed to encode environments", "error", err)
- return ctx.Err() == nil
- }
+ fingerprint := fingerprintEnvironmentsInternal(envs)
// Re-send unchanged state on a floor so relative timestamps in the UI
// ("last seen 2 minutes ago") keep advancing.
- if bytes.Equal(fingerprint, lastFingerprint) && time.Since(lastSentAt) < environmentStreamRefreshFloor {
+ if haveFingerprint && fingerprint == lastFingerprint && time.Since(lastSentAt) < environmentStreamRefreshFloor {
return true
}
lastFingerprint = fingerprint
+ haveFingerprint = true
lastSentAt = time.Now()
return agg.Send(ctx, events, environment.StreamEvent{
diff --git a/backend/api/handlers/environments_test.go b/backend/api/handlers/environments_test.go
index b6270d1df..32303023c 100644
--- a/backend/api/handlers/environments_test.go
+++ b/backend/api/handlers/environments_test.go
@@ -5,6 +5,7 @@ import (
"net/http"
"net/http/httptest"
"os"
+ "reflect"
"testing"
"time"
@@ -268,3 +269,22 @@ func TestEnvironmentHandlerApplyEdgeRuntimeState(t *testing.T) {
assert.NotNil(t, env.LastPollAt)
})
}
+
+// The environment stream suppresses redundant sends by comparing a fingerprint
+// of the visible list. A field added to Environment but not to the fingerprint
+// would stop propagating to connected clients until the 30s floor, so pin the
+// field count: if this fails, add the new field to
+// fingerprintEnvironmentsInternal and bump the constant.
+func TestEnvironmentFingerprintCoversEveryField(t *testing.T) {
+ const environmentFingerprintFieldCount = 19
+ require.Equal(t, environmentFingerprintFieldCount, reflect.TypeOf(envtypes.Environment{}).NumField(),
+ "environment.Environment gained or lost a field; update fingerprintEnvironmentsInternal to match")
+}
+
+func TestFingerprintEnvironmentsDetectsFieldChange(t *testing.T) {
+ base := []envtypes.Environment{{ID: "1", Name: "prod", Status: "online", Enabled: true}}
+ renamed := []envtypes.Environment{{ID: "1", Name: "production", Status: "online", Enabled: true}}
+
+ assert.Equal(t, fingerprintEnvironmentsInternal(base), fingerprintEnvironmentsInternal(base))
+ assert.NotEqual(t, fingerprintEnvironmentsInternal(base), fingerprintEnvironmentsInternal(renamed))
+}
diff --git a/backend/api/handlers/events.go b/backend/api/handlers/events.go
index 81e7978b7..2d20363f5 100644
--- a/backend/api/handlers/events.go
+++ b/backend/api/handlers/events.go
@@ -2,6 +2,7 @@ package handlers
import (
"context"
+ "crypto/subtle"
"encoding/json/v2"
"log/slog"
"net/http"
@@ -133,7 +134,13 @@ func validAgentEventIngestionTokenInternal(r *http.Request, cfg *config.Config)
return false
}
token := r.Header.Get(pkgutils.HeaderAgentToken)
- return token != "" && token == cfg.AgentToken
+ if token == "" || cfg.AgentToken == "" {
+ return false
+ }
+ // Constant time, matching agentTokenMatchesInternal in the auth middleware:
+ // this endpoint is unauthenticated apart from the token, so a byte-by-byte
+ // comparison is directly probeable.
+ return subtle.ConstantTimeCompare([]byte(token), []byte(cfg.AgentToken)) == 1
}
// RegisterEvents registers all event management endpoints.
diff --git a/backend/api/handlers/oidc.go b/backend/api/handlers/oidc.go
index 780ac4aab..814934508 100644
--- a/backend/api/handlers/oidc.go
+++ b/backend/api/handlers/oidc.go
@@ -317,8 +317,10 @@ func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlI
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to generate OIDC auth URL").Error())
}
- // Build state cookie (600 seconds = 10 minutes)
- stateCookie := cookie.BuildOidcStateCookieString(stateCookieValue, 600, false)
+ // Build state cookie (600 seconds = 10 minutes). Secure is resolved from the
+ // request the same way the session token cookie resolves it, rather than
+ // being hard-coded off.
+ stateCookie := cookie.BuildOidcStateCookieString(stateCookieValue, 600, cookie.SecureCookieFromContext(ctx))
return &GetOidcAuthUrlOutput{
SetCookie: stateCookie,
@@ -365,7 +367,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
// Build cookies: clear the state cookie always; only set the session
// token cookie for browser flows (mobile clients use Bearer tokens from
// the JSON body and never consume the cookie).
- clearStateCookie := cookie.BuildClearOidcStateCookieString(false)
+ clearStateCookie := cookie.BuildClearOidcStateCookieString(cookie.SecureCookieFromContext(ctx))
setCookies := []string{clearStateCookie}
if mobileRedirectURI == "" {
maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
diff --git a/backend/api/ws/diagnostics.go b/backend/api/ws/diagnostics.go
index e76c96764..1133766ad 100644
--- a/backend/api/ws/diagnostics.go
+++ b/backend/api/ws/diagnostics.go
@@ -20,6 +20,17 @@ import (
// diagnosticsStreamInterval is how often the live diagnostics stream pushes a snapshot.
const diagnosticsStreamInterval = 2 * time.Second
+// Keepalive/liveness bounds for the diagnostics sockets, mirroring the system
+// stats stream. Without them a silently dead peer wedges WriteMessage forever,
+// which also strands the writer's deferred cleanup (log subscription, conn).
+const (
+ diagnosticsReadLimit = 512
+ diagnosticsPongWait = 60 * time.Second
+ diagnosticsWriteWait = 10 * time.Second
+ diagnosticsPingWriteWait = 1 * time.Second
+ diagnosticsPingPeriod = diagnosticsPongWait * 9 / 10
+)
+
// BuildDiagnostics assembles a full diagnostics snapshot: runtime/memory/GC from
// the DiagnosticsService plus this package's WebSocket metrics and worker-goroutine
// count. Shared by the REST endpoint (via handlers) and the live WebSocket stream.
@@ -77,6 +88,7 @@ func (h *WebSocketHandler) DiagnosticsStream(c *echo.Context) error {
if marshalErr != nil {
return true
}
+ _ = conn.SetWriteDeadline(time.Now().Add(diagnosticsWriteWait))
return conn.WriteMessage(websocket.TextMessage, b) == nil
}
@@ -85,6 +97,8 @@ func (h *WebSocketHandler) DiagnosticsStream(c *echo.Context) error {
}
ticker := time.NewTicker(diagnosticsStreamInterval)
defer ticker.Stop()
+ pingTicker := time.NewTicker(diagnosticsPingPeriod)
+ defer pingTicker.Stop()
for {
select {
case <-done:
@@ -93,6 +107,11 @@ func (h *WebSocketHandler) DiagnosticsStream(c *echo.Context) error {
if !write() {
return nil
}
+ case <-pingTicker.C:
+ _ = conn.SetWriteDeadline(time.Now().Add(diagnosticsPingWriteWait))
+ if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
+ return nil
+ }
}
}
}
@@ -120,6 +139,7 @@ func (h *WebSocketHandler) ServerLogsStream(c *echo.Context) error {
if marshalErr != nil {
return true
}
+ _ = conn.SetWriteDeadline(time.Now().Add(diagnosticsWriteWait))
return conn.WriteMessage(websocket.TextMessage, b) == nil
}
@@ -128,6 +148,8 @@ func (h *WebSocketHandler) ServerLogsStream(c *echo.Context) error {
return nil
}
}
+ pingTicker := time.NewTicker(diagnosticsPingPeriod)
+ defer pingTicker.Stop()
for {
select {
case <-done:
@@ -139,13 +161,27 @@ func (h *WebSocketHandler) ServerLogsStream(c *echo.Context) error {
if !write(e) {
return nil
}
+ case <-pingTicker.C:
+ _ = conn.SetWriteDeadline(time.Now().Add(diagnosticsPingWriteWait))
+ if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
+ return nil
+ }
}
}
}
// diagnosticsReadLoopInternal drains incoming frames; the returned channel closes
-// when the peer disconnects, signaling the writer loop to stop.
+// when the peer disconnects, signaling the writer loop to stop. The read deadline
+// is what makes a half-open connection observable: pongs from the writer's pings
+// extend it, and a peer that stops answering trips it within diagnosticsPongWait.
func diagnosticsReadLoopInternal(conn *websocket.Conn) <-chan struct{} {
+ conn.SetReadLimit(diagnosticsReadLimit)
+ _ = conn.SetReadDeadline(time.Now().Add(diagnosticsPongWait))
+ conn.SetPongHandler(func(string) error {
+ _ = conn.SetReadDeadline(time.Now().Add(diagnosticsPongWait))
+ return nil
+ })
+
done := make(chan struct{})
go func() {
defer close(done)
diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.go
index d4333a4d9..167b86001 100644
--- a/backend/api/ws/handler.go
+++ b/backend/api/ws/handler.go
@@ -308,13 +308,21 @@ func (h *WebSocketHandler) serveLogStreamInternal(
return hubBuilder(streamKey, onEmpty)
})
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, kind, resourceID))
+ release := func() {
+ h.wsMetrics.UnregisterConnection(connID)
+ h.releaseLogStreamInternal(streamKey, stream)
+ }
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
// which triggers when all clients disconnect.
- wshub.ServeClientWithOnRemove(context.Background(), stream.hub, conn, func() {
- h.wsMetrics.UnregisterConnection(connID)
- h.releaseLogStreamInternal(streamKey, stream)
- })
+ if !wshub.ServeClientWithOnRemove(context.Background(), stream.hub, conn, release) {
+ // The stream refcount normally keeps this hub alive, so a stopped hub
+ // here means it was torn down out from under us; drop our reference
+ // rather than leaking the connection and the metrics entry.
+ slog.Debug("log stream hub stopped before client registration", "streamKey", streamKey)
+ _ = conn.Close()
+ release()
+ }
}
// broadcastLogStreamErrorInternal emits an error message to every client of a log stream.
@@ -649,13 +657,28 @@ func (h *WebSocketHandler) ContainerStats(c *echo.Context) error {
}
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindContainerStats, containerID))
- hub := h.getOrCreateContainerStatsHubInternal(containerID)
onRemove := func() {
h.wsMetrics.UnregisterConnection(connID)
}
+
+ // A reconnect can land exactly on the 5s idle-teardown boundary and load a
+ // hub whose Run has already exited. Drop that hub and retry once so the
+ // client gets a live producer instead of a silent socket.
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled by the shared hub when it idles.
- wshub.ServeClientWithOnRemove(context.Background(), hub, conn, onRemove)
+ for attempt := range 2 {
+ hub := h.getOrCreateContainerStatsHubInternal(containerID)
+ if wshub.ServeClientWithOnRemove(context.Background(), hub, conn, onRemove) {
+ return nil
+ }
+ h.containerStatsHubs.CompareAndDelete(containerID, hub)
+ slog.DebugContext(c.Request().Context(), "container stats hub stopped before client registration; retrying",
+ "containerID", containerID, "attempt", attempt+1)
+ }
+
+ slog.WarnContext(c.Request().Context(), "failed to register container stats client", "containerID", containerID)
+ _ = conn.Close()
+ onRemove()
return nil
}
@@ -681,6 +704,10 @@ func (h *WebSocketHandler) getOrCreateContainerStatsHubInternal(containerID stri
return hub
}
+// containerStatsErrorDrainGrace is how long a failed stats hub stays alive after
+// broadcasting its error frame, so clients receive it before the hub shuts down.
+const containerStatsErrorDrainGrace = 2 * time.Second
+
func (h *WebSocketHandler) runContainerStatsHubInternal(containerID string, hub *wshub.Hub) {
ctx, cancel := context.WithCancel(context.Background())
var cleanupTimer *time.Timer
@@ -722,7 +749,29 @@ func (h *WebSocketHandler) runContainerStatsHubInternal(containerID string, hub
statsChan := make(chan any, 64)
go func(ctx context.Context) {
defer close(statsChan)
- _ = h.containerService.StreamStats(ctx, containerID, statsChan)
+
+ err := h.containerService.StreamStats(ctx, containerID, statsChan)
+ if err == nil || errors.Is(err, context.Canceled) || ctx.Err() != nil {
+ return
+ }
+
+ // The producer died but the hub stayed cached, so clients kept an open
+ // socket that would never emit another sample. Tell them why, then drop
+ // the hub so the next connect rebuilds a producer instead of attaching
+ // to this dead one.
+ slog.Warn("container stats stream failed", "containerID", containerID, "error", err)
+ if b, marshalErr := json.Marshal(map[string]any{
+ "error": "Failed to stream container stats: " + err.Error(),
+ "timestamp": wshub.NowRFC3339(),
+ }); marshalErr == nil {
+ hub.Broadcast(b)
+ }
+ h.containerStatsHubs.CompareAndDelete(containerID, hub)
+
+ // Cancelling immediately would race hub.Run between ctx.Done and the
+ // queued error frame, dropping the very message clients need. Give the
+ // broadcast a moment to drain, then tear the hub down.
+ time.AfterFunc(containerStatsErrorDrainGrace, cancel)
}(ctx)
go func() {
@@ -923,7 +972,10 @@ func (h *WebSocketHandler) checkRateLimitInternal(clientIP string) (*int32, bool
func (h *WebSocketHandler) releaseRateLimitInternal(clientIP string, count *int32) {
newCount := atomic.AddInt32(count, -1)
if newCount <= 0 {
- h.activeConnections.Delete(clientIP)
+ // CompareAndDelete, not Delete: a plain delete removed whatever counter
+ // was stored for this IP, which after a racing reconnect is a live one —
+ // wiping its count and letting that IP exceed the limit.
+ h.activeConnections.CompareAndDelete(clientIP, count)
}
}
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index 0ed0508ed..018be93d4 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -24,6 +24,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"
+ httputil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
"github.com/getarcaneapp/arcane/types/v2"
"go.uber.org/fx"
)
@@ -208,6 +209,12 @@ func newRouter(p RouterParams) (*echo.Echo, *edge.TunnelServer) {
apiGroup.Use(middleware.PerIPRateLimitForPaths(
[]string{"/api/webhooks/trigger/:token"}, 60, 10,
))
+ // Agent event ingestion authenticates on the agent token alone and sits
+ // outside the auth middleware, so it needs its own brute-force ceiling.
+ // The allowance is generous because busy agents legitimately batch events.
+ apiGroup.Use(middleware.PerIPRateLimitForPaths(
+ []string{"/api/events"}, 60, 30,
+ ))
handlerAppCtx := handlers.NewActivityAppContext(ctx)
tunnelRegistry := edge.NewTunnelRegistry()
@@ -233,6 +240,10 @@ func newRouter(p RouterParams) (*echo.Echo, *edge.TunnelServer) {
envResolver,
createAuthValidatorInternal(deps),
permissionMatcher,
+ // Proxied WebSocket upgrades enforce the same Origin policy as the local
+ // endpoints, so a cross-origin page cannot ride a session cookie into a
+ // remote environment.
+ httputil.ValidateWebSocketOrigin(cfg.GetAppURL()),
)
apiGroup.Use(envProxyMiddleware)
diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go
index f5afff74b..43a9d9605 100644
--- a/backend/internal/database/database.go
+++ b/backend/internal/database/database.go
@@ -18,6 +18,7 @@ import (
"github.com/libtnb/sqlite"
"github.com/pressly/goose/v3"
+ "github.com/pressly/goose/v3/lock"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
@@ -238,7 +239,20 @@ func newGooseProviderInternal(db *sql.DB, dbProvider string) (*goose.Provider, e
return nil, err
}
- return goose.NewProvider(dialect, db, migrationsFS)
+ // Two Arcane processes pointed at the same Postgres (a rolling deploy, or a
+ // replica set) would otherwise run migrations concurrently and race on the
+ // same DDL. A session-level advisory lock serializes them; SQLite needs no
+ // equivalent because it is single-writer by construction.
+ var options []goose.ProviderOption
+ if dialect == goose.DialectPostgres {
+ sessionLocker, err := lock.NewPostgresSessionLocker()
+ if err != nil {
+ return nil, errors.WrapIf(err, "failed to create Postgres migration session locker")
+ }
+ options = append(options, goose.WithSessionLocker(sessionLocker))
+ }
+
+ return goose.NewProvider(dialect, db, migrationsFS, options...)
}
func embeddedMigrationFSInternal(dbProvider string) (fs.FS, error) {
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index ea51d580b..38e77ffc1 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -3,7 +3,6 @@ package middleware
import (
"github.com/samber/mo"
- "bytes"
"context"
"io"
"log/slog"
@@ -65,11 +64,16 @@ type EnvironmentMiddleware struct {
httpClient *http.Client
registry *edge.TunnelRegistry
matcher *authz.PermissionMatcher
+ // checkOrigin is the same Origin validator the local WebSocket endpoints
+ // use. Proxied upgrades previously accepted any Origin, so a cross-origin
+ // page could ride the caller's session cookie into a remote environment's
+ // terminal or log stream.
+ checkOrigin func(*http.Request) bool
}
// NewEnvProxyMiddlewareWithParam creates middleware that proxies requests to remote environments.
-func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, authValidator AuthValidator, matcher *authz.PermissionMatcher) echo.MiddlewareFunc {
- return NewEnvProxyMiddlewareWithParamAndRegistry(localID, paramName, resolver, authValidator, matcher, edge.GetRegistry())
+func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, authValidator AuthValidator, matcher *authz.PermissionMatcher, checkOrigin func(*http.Request) bool) echo.MiddlewareFunc {
+ return NewEnvProxyMiddlewareWithParamAndRegistry(localID, paramName, resolver, authValidator, matcher, edge.GetRegistry(), checkOrigin)
}
// NewEnvProxyMiddlewareWithParamAndRegistry creates middleware with an injected tunnel registry.
@@ -80,6 +84,7 @@ func NewEnvProxyMiddlewareWithParamAndRegistry(
authValidator AuthValidator,
matcher *authz.PermissionMatcher,
registry *edge.TunnelRegistry,
+ checkOrigin func(*http.Request) bool,
) echo.MiddlewareFunc {
if registry == nil {
registry = edge.NewTunnelRegistry()
@@ -93,6 +98,7 @@ func NewEnvProxyMiddlewareWithParamAndRegistry(
httpClient: &http.Client{Timeout: proxyTimeout},
registry: registry,
matcher: matcher,
+ checkOrigin: checkOrigin,
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
@@ -253,7 +259,7 @@ func (m *EnvironmentMiddleware) setProxyContextHeadersInternal(c *echo.Context,
func (m *EnvironmentMiddleware) proxyThroughTunnelInternal(c *echo.Context, tunnel *edge.AgentTunnel, envID string) error {
proxyPath := m.buildProxyPath(c, envID)
if m.isWebSocketUpgrade(c) {
- return edge.ProxyWebSocketRequest(c, tunnel, proxyPath)
+ return edge.ProxyWebSocketRequest(c, tunnel, proxyPath, m.checkOrigin)
}
return edge.ProxyHTTPRequest(c, tunnel, proxyPath)
}
@@ -431,7 +437,7 @@ func (m *EnvironmentMiddleware) proxyWebSocket(c *echo.Context, target string, a
wsTarget := edge.HTTPToWebSocketURL(target)
headers := edge.BuildWebSocketHeaders(c, accessToken)
- if err := wsutil.ProxyHTTP(c.Response(), c.Request(), wsTarget, headers); err != nil {
+ if err := wsutil.ProxyHTTP(c.Response(), c.Request(), wsTarget, headers, m.checkOrigin); err != nil {
slog.Error("websocket proxy failed", "err", err)
}
return nil
@@ -477,34 +483,39 @@ func (m *EnvironmentMiddleware) createProxyRequest(c *echo.Context, target strin
return nil, common.Classify(common.ErrEnvironmentInvalidProxyTarget, errors.WrapIf(err, "Invalid proxy target URL"))
}
- var bodyBytes []byte
- if srcReq.Body != nil {
- var err error
- bodyBytes, err = io.ReadAll(srcReq.Body)
+ // The body is streamed straight through rather than buffered: volume backup
+ // and image import uploads run to gigabytes, and reading them into memory
+ // cost roughly twice their size per in-flight request. This drops GetBody,
+ // so the transport can no longer replay the body across a redirect or an
+ // idle-connection retry; a proxied API call has no legitimate need for
+ // either, and a failure surfaces as a 502 rather than silent corruption.
+ //
+ // A server request's ContentLength is 0 only when there is genuinely no
+ // body (-1 means chunked/unknown), so it is the safe signal for whether to
+ // forward one at all.
+ var requestBody io.ReadCloser
+ var contentLength int64
+ switch {
+ case srcReq.Body == nil:
+ case srcReq.ContentLength != 0:
+ requestBody, contentLength = srcReq.Body, srcReq.ContentLength
+ default:
_ = srcReq.Body.Close()
- if err != nil {
- return nil, errors.WrapIf(err, "failed to read request body")
- }
}
- slog.DebugContext(srcReq.Context(), "Creating proxy request", "method", srcReq.Method, "target", target, "contentLength", srcReq.ContentLength, "contentType", srcReq.Header.Get("Content-Type"), "bodyLength", len(bodyBytes), "body", string(bodyBytes))
+ // The body is deliberately not logged: at debug level it would put compose
+ // files and registry credentials into the ring buffer served by
+ // /api/diagnostics/logs, and stringifying it allocated even when debug was off.
+ slog.DebugContext(srcReq.Context(), "Creating proxy request", "method", srcReq.Method, "target", target, "contentLength", srcReq.ContentLength, "contentType", srcReq.Header.Get("Content-Type"))
- var requestBody io.ReadCloser
- var getBody func() (io.ReadCloser, error)
- if len(bodyBytes) > 0 {
- requestBody = io.NopCloser(bytes.NewReader(bodyBytes))
- getBody = func() (io.ReadCloser, error) {
- return io.NopCloser(bytes.NewReader(bodyBytes)), nil
- }
- }
requestURL := *validatedTarget
req := (&http.Request{
- Method: srcReq.Method,
- URL: &requestURL,
- Host: requestURL.Host,
- Header: make(http.Header),
- Body: requestBody,
- GetBody: getBody,
+ Method: srcReq.Method,
+ URL: &requestURL,
+ Host: requestURL.Host,
+ Header: make(http.Header),
+ Body: requestBody,
+ ContentLength: contentLength,
}).WithContext(srcReq.Context())
skip := edge.GetSkipHeaders()
@@ -513,10 +524,6 @@ func (m *EnvironmentMiddleware) createProxyRequest(c *echo.Context, target strin
edge.SetAgentToken(req, accessToken)
edge.SetForwardedHeaders(req, c.RealIP(), srcReq.Host)
- if len(bodyBytes) > 0 {
- req.ContentLength = int64(len(bodyBytes))
- }
-
return req, nil
}
diff --git a/backend/internal/services/build_workspace_service.go b/backend/internal/services/build_workspace_service.go
index 6ac3ec108..8b582263d 100644
--- a/backend/internal/services/build_workspace_service.go
+++ b/backend/internal/services/build_workspace_service.go
@@ -313,19 +313,13 @@ func sanitizeUploadFilename(filename string) (string, error) {
func joinBuildRoot(root, cleaned string) (string, error) {
rel := strings.TrimPrefix(cleaned, "/")
fullPath := filepath.Join(root, filepath.FromSlash(rel))
- if !isWithinRoot(root, fullPath) {
+ if !utils.IsWithinRoot(root, fullPath) {
return "", errors.New("invalid path: outside builds directory")
}
- return fullPath, nil
-}
-
-func isWithinRoot(root, target string) bool {
- rootClean := filepath.Clean(root)
- targetClean := filepath.Clean(target)
- if targetClean == rootClean {
- return true
+ if _, err := utils.ResolveWithinRoot(root, fullPath); err != nil {
+ return "", errors.WrapIf(err, "invalid path: outside builds directory")
}
- return strings.HasPrefix(targetClean, rootClean+string(os.PathSeparator))
+ return fullPath, nil
}
func resolveLinkTarget(root, target string) string {
@@ -334,7 +328,7 @@ func resolveLinkTarget(root, target string) string {
}
if filepath.IsAbs(target) {
targetClean := filepath.Clean(target)
- if isWithinRoot(root, targetClean) {
+ if utils.IsWithinRoot(root, targetClean) {
rel, err := filepath.Rel(root, targetClean)
if err != nil {
return "(external)"
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index 048c785ad..f231853a7 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -94,17 +94,38 @@ func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGet
kvService: kvService,
}
backgroundLoader := func(imageRefs []string) (map[string]string, error) {
- ctx, cancel := context.WithTimeout(context.Background(), timeouts.DefaultRegistry)
- defer cancel()
digests := make(map[string]string, len(imageRefs))
+ var firstErr error
for _, imageRef := range imageRefs {
- result, err := service.inspectImageDigestInternal(ctx, imageRef, nil)
+ // Per-ref timeout: a single deadline shared across the whole
+ // sequential batch left later refs with whatever the earlier ones
+ // had not already spent, so one slow registry starved the tail.
+ result, err := func() (*registryDigestResult, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), timeouts.DefaultRegistry)
+ defer cancel()
+ return service.inspectImageDigestInternal(ctx, imageRef, nil)
+ }()
if err != nil {
- return nil, err
+ slog.Debug("registry revalidation failed for image", "imageRef", imageRef, "error", err)
+ if firstErr == nil {
+ firstErr = err
+ }
+ continue
}
digests[imageRef] = result.Digest
}
- return digests, nil
+
+ // Returning an error alongside results makes hot discard the whole map,
+ // so report success whenever anything resolved: one unreachable registry
+ // used to throw away every digest already fetched, forcing the entire
+ // batch to be refetched on the next tick. Refs that failed are simply
+ // left uncached (this cache has no missing-key cache) and retried on
+ // next access; only a fully failed batch surfaces the error, which
+ // KeepOnError turns into "retain the previous digests".
+ if len(digests) > 0 {
+ return digests, nil
+ }
+ return nil, firstErr
}
service.cache = hot.NewHotCache[string, string](hot.LRU, 4096).
WithTTL(registryCacheTTL).
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 97a72d6e2..30b35a516 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -1285,7 +1285,7 @@ func (s *ContainerService) getCachedProjectIconMetadataInternal(ctx context.Cont
meta := projects.ArcaneComposeMetadata{ServiceIconSets: map[string]projects.IconSet{}}
proj, err := s.projectService.GetProjectByComposeName(ctx, projectName)
if err == nil && proj != nil {
- meta = s.projectService.getProjectMetadataForProject(ctx, *proj)
+ meta = s.projectService.getProjectMetadataForProject(ctx, *proj, nil)
}
if s.iconMetaCache != nil {
s.iconMetaCache.Set(projectName, meta)
diff --git a/backend/internal/services/dashboard_service.go b/backend/internal/services/dashboard_service.go
index 9620ac628..9affe1eed 100644
--- a/backend/internal/services/dashboard_service.go
+++ b/backend/internal/services/dashboard_service.go
@@ -13,6 +13,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/types/v2/base"
containertypes "github.com/getarcaneapp/arcane/types/v2/container"
dashboardtypes "github.com/getarcaneapp/arcane/types/v2/dashboard"
@@ -149,7 +150,7 @@ func (s *DashboardService) GetSnapshot(ctx context.Context, options DashboardAct
volumeUsageCounts = &counts
}
- actionItems, err := s.buildActionItemsForSnapshotInternal(ctx, options, filteredContainers, dockerImages)
+ actionItems, err := s.buildActionItemsForSnapshotInternal(ctx, options, filteredContainers, dockerContainers)
if err != nil {
return nil, err
}
@@ -177,11 +178,14 @@ func (s *DashboardService) GetSnapshot(ctx context.Context, options DashboardAct
}, nil
}
+// buildActionItemsForSnapshotInternal derives the dashboard's action badges.
+// filteredContainers drives the stopped-container badge; allContainers is the raw
+// snapshot list, passed to the update count so it need not re-list containers.
func (s *DashboardService) buildActionItemsForSnapshotInternal(
ctx context.Context,
options DashboardActionItemsOptions,
- containers []dockercontainer.Summary,
- _ any,
+ filteredContainers []dockercontainer.Summary,
+ allContainers []dockercontainer.Summary,
) (*dashboardtypes.ActionItems, error) {
if options.DebugAllGood {
return &dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}}, nil
@@ -195,8 +199,10 @@ func (s *DashboardService) buildActionItemsForSnapshotInternal(
g, groupCtx := errgroup.WithContext(ctx)
- g.Go(func() error {
- count, err := s.getPendingResourceUpdatesCountInternal(groupCtx)
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "dashboard action item worker")
+
+ count, err := s.getPendingResourceUpdatesCountInternal(groupCtx, allContainers)
if err != nil {
return err
}
@@ -204,7 +210,9 @@ func (s *DashboardService) buildActionItemsForSnapshotInternal(
return nil
})
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "dashboard action item worker")
+
count, err := s.getActionableVulnerabilitiesCountInternal(groupCtx)
if err != nil {
return err
@@ -213,7 +221,9 @@ func (s *DashboardService) buildActionItemsForSnapshotInternal(
return nil
})
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "dashboard action item worker")
+
count, err := s.getExpiringAPIKeysCountInternal(groupCtx)
if err != nil {
return err
@@ -227,7 +237,7 @@ func (s *DashboardService) buildActionItemsForSnapshotInternal(
}
stoppedContainers := 0
- for _, container := range containers {
+ for _, container := range filteredContainers {
if container.State != "running" {
stoppedContainers++
}
@@ -279,24 +289,23 @@ func buildDashboardActionItemsInternal(
return &dashboardtypes.ActionItems{Items: actionItems}
}
-func (s *DashboardService) getPendingResourceUpdatesCountInternal(ctx context.Context) (int, error) {
+// getPendingResourceUpdatesCountInternal counts standalone containers and projects
+// with a pending image update. allContainers is the snapshot's container list,
+// reused rather than re-listed: this used to issue its own GetAllContainers on
+// top of the two the project count triggered, for a single badge number.
+func (s *DashboardService) getPendingResourceUpdatesCountInternal(ctx context.Context, allContainers []dockercontainer.Summary) (int, error) {
if s.db == nil || s.dockerService == nil {
return 0, nil
}
- containers, _, _, _, err := s.dockerService.GetAllContainers(ctx)
- if err != nil {
- return 0, errors.WrapIf(err, "failed to load containers for update counts")
- }
-
- filteredContainers := filterInternalContainers(containers, false)
+ filteredContainers := filterInternalContainers(allContainers, false)
standaloneContainers := filterStandaloneDockerContainersInternal(filteredContainers)
containerCount, err := s.getPendingContainerUpdatesCountForImageIDsInternal(ctx, collectImageIDs(standaloneContainers))
if err != nil {
return 0, err
}
- projectCount, err := s.getPendingProjectUpdatesCountInternal(ctx)
+ projectCount, err := s.getPendingProjectUpdatesCountInternal(ctx, allContainers)
if err != nil {
return 0, err
}
@@ -332,12 +341,12 @@ func (s *DashboardService) getPendingContainerUpdatesCountForImageIDsInternal(ct
return int(count), nil
}
-func (s *DashboardService) getPendingProjectUpdatesCountInternal(ctx context.Context) (int, error) {
+func (s *DashboardService) getPendingProjectUpdatesCountInternal(ctx context.Context, allContainers []dockercontainer.Summary) (int, error) {
if s.projectService == nil {
return 0, nil
}
- count, err := s.projectService.countProjectsByUpdateStatusInternal(ctx, "has_update")
+ count, err := s.projectService.countProjectsWithPendingUpdatesInternal(ctx, allContainers)
if err != nil {
return 0, errors.WrapIf(err, "failed to count projects with updates")
}
diff --git a/backend/internal/services/docker_client_service.go b/backend/internal/services/docker_client_service.go
index a426413e0..51aafd5d4 100644
--- a/backend/internal/services/docker_client_service.go
+++ b/backend/internal/services/docker_client_service.go
@@ -16,6 +16,7 @@ import (
docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
dashboardtypes "github.com/getarcaneapp/arcane/types/v2/dashboard"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/events"
@@ -209,6 +210,10 @@ func (s *DockerClientService) EventBus() *bus.DockerEventBus {
return s.eventBus
}
+// dockerEventStreamHealthyAfter is how long an event stream must survive before
+// the reconnect backoff is considered recovered and reset.
+const dockerEventStreamHealthyAfter = 30 * time.Second
+
func (s *DockerClientService) WatchEvents(ctx context.Context) {
eventBackoff := backoff.NewExponentialBackOff()
eventBackoff.InitialInterval = 500 * time.Millisecond
@@ -224,13 +229,22 @@ func (s *DockerClientService) WatchEvents(ctx context.Context) {
continue
}
- eventBackoff.Reset()
result := dockerClient.Events(ctx, client.EventsListOptions{})
s.publishImageStateResyncInternal()
+ streamStart := time.Now()
err = s.consumeEventsInternal(ctx, result.Messages, result.Err)
if err != nil && !errors.Is(err, context.Canceled) && !errors.Is(err, io.EOF) {
slog.WarnContext(ctx, "Docker event stream stopped", "error", err)
}
+
+ // Only a stream that actually stayed up counts as recovery. Resetting
+ // unconditionally before Events() meant a daemon that accepts the
+ // connection and drops it immediately was reconnected at the floor
+ // interval forever, purging the container update-info cache each time.
+ if time.Since(streamStart) >= dockerEventStreamHealthyAfter {
+ eventBackoff.Reset()
+ }
+
if !sleepDockerEventBackoffInternal(ctx, eventBackoff) {
return
}
@@ -351,17 +365,23 @@ func (s *DockerClientService) GetSnapshot(ctx context.Context, envID string) (*d
var networks []network.Summary
var volumes *client.VolumeListResult
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "docker snapshot worker")
+
var err error
containers, err = s.listContainersInternal(groupCtx)
return err
})
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "docker snapshot worker")
+
var err error
images, err = s.listImagesInternal(groupCtx)
return err
})
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "docker snapshot worker")
+
var err error
networks, err = s.listNetworksInternal(groupCtx)
if err != nil {
@@ -369,7 +389,9 @@ func (s *DockerClientService) GetSnapshot(ctx context.Context, envID string) (*d
}
return nil
})
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "docker snapshot worker")
+
var err error
volumes, err = s.listVolumesInternal(groupCtx)
if err != nil {
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index c45fc3fc6..7cd8d63d8 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -16,6 +16,7 @@ import (
dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
systemtypes "github.com/getarcaneapp/arcane/types/v2/system"
@@ -70,7 +71,9 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetyp
g, gctx := errgroup.WithContext(ctx)
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "image worker")
+
var err error
inspectResult, err := dockerClient.ImageInspect(gctx, id)
if err != nil {
@@ -80,7 +83,9 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetyp
return nil
})
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "image worker")
+
imageList, err := dockerClient.ImageList(gctx, client.ImageListOptions{})
if err != nil {
return errors.WrapIf(err, "failed to list images")
@@ -674,7 +679,9 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
g, groupCtx := errgroup.WithContext(ctx)
// Fetch Docker images
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "image worker")
+
var err error
imageList, err := s.dockerService.listImagesInternal(groupCtx)
if err != nil {
@@ -685,7 +692,9 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
})
// Fetch containers to determine usage
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "image worker")
+
var err error
containerList, err := s.dockerService.listContainersInternal(groupCtx)
if err != nil {
diff --git a/backend/internal/services/network_service.go b/backend/internal/services/network_service.go
index fdb1651cd..d3d0369ca 100644
--- a/backend/internal/services/network_service.go
+++ b/backend/internal/services/network_service.go
@@ -13,6 +13,7 @@ import (
dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
networktypes "github.com/getarcaneapp/arcane/types/v2/network"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/network"
@@ -81,7 +82,9 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.
for i := range networkList.Items {
rawNetwork := networkList.Items[i]
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "network worker")
+
inspected, err := libarcane.NetworkInspectWithCompatibility(groupCtx, dockerClient, rawNetwork.ID, client.NetworkInspectOptions{})
if err != nil {
return errors.WrapIff(err, "failed to inspect network %s", rawNetwork.Name)
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index 300f3d7ac..e6fd25f03 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -64,11 +64,32 @@ type ProjectService struct {
config *config.Config
registryCredentialsProvider registryCredentialsProviderInternal
+ // syncMu serializes SyncProjectsFromFileSystem: its discovery walk and its
+ // cleanup pass must not interleave with another run's.
+ syncMu sync.Mutex
+
composeNameCacheMu sync.RWMutex
composeNameToProjID map[string]string
composeCache *hot.HotCache[string, composeCacheEntry]
+ // metaCache holds per-project icon/URL metadata, keyed by project ID. Deriving
+ // it costs a full compose load (interpolation plus .env reads) and, for GitOps
+ // projects, a gitops_syncs lookup — per project, on every list request. Mirrors
+ // ContainerService.iconMetaCache.
+ metaCache *hot.HotCache[string, projects.ArcaneComposeMetadata]
+}
+
+// projectMetadataEnvInternal carries the inputs ParseArcaneComposeMetadata needs
+// beyond the project itself. Resolving them costs a settings clone and a stat
+// syscall each, so list paths resolve once and reuse across every project.
+type projectMetadataEnvInternal struct {
+ projectsDirectory string
+ autoInjectEnv bool
}
+// projectMetadataTTL bounds how stale cached compose metadata can be. It matches
+// containerIconMetadataTTL so icons resolved from either service agree.
+const projectMetadataTTL = 5 * time.Second
+
type registryCredentialsProviderInternal func(context.Context) ([]containerregistry.Credential, error)
type composeCacheEntry struct {
@@ -90,6 +111,10 @@ func NewProjectService(db *database.DB, settingsService *SettingsService, eventS
containerRegistryService: containerRegistryService,
config: cfg,
composeCache: hot.NewHotCache[string, composeCacheEntry](hot.LRU, 2048).Build(),
+ metaCache: hot.NewHotCache[string, projects.ArcaneComposeMetadata](hot.LRU, 1024).
+ WithTTL(projectMetadataTTL).
+ WithJanitor().
+ Build(),
}
}
@@ -976,7 +1001,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string
resp.DirName = mo.PointerToOption(proj.DirName).OrEmpty()
resp.RelativePath = s.getProjectRelativePathInternal(projectsDir, proj.Path)
resp.GitOpsManagedBy = proj.GitOpsManagedBy
- meta := s.getProjectMetadataForProject(ctx, *proj)
+ meta := s.getProjectMetadataForProject(ctx, *proj, nil)
applyResolvedProjectIconInternal(&resp, s.resolveIconSetInternal(ctx, meta.ProjectIcon))
resp.URLs = meta.ProjectURLS
@@ -1149,30 +1174,20 @@ func readProjectIncludeFileContentInternal(projectPath string, inc projects.Incl
return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))
}
- resolvedProjectPath, err := filepath.EvalSymlinks(projectPath)
+ resolvedPath, err := utils.ResolveWithinRoot(projectPath, validatedPath)
if err != nil {
- return project.IncludeFile{}, errors.WrapIf(err, "failed to resolve project path")
- }
- resolvedPath, err := filepath.EvalSymlinks(validatedPath)
- if err != nil {
- if os.IsNotExist(err) {
- return project.IncludeFile{
- Path: validatedPath,
- RelativePath: inc.RelativePath,
- Content: "# This file will be created when you save changes\nservices:\n",
- }, nil
- }
- return project.IncludeFile{}, errors.WrapIf(err, "failed to resolve include file")
- }
- if !projects.IsSafeSubdirectory(resolvedProjectPath, resolvedPath) {
- return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.New("Forbidden project file path: include resolves outside project directory"))
+ return project.IncludeFile{}, common.Classify(common.ErrProjectFileForbidden, errors.WrapIf(err, "Forbidden project file path"))
}
info, err := os.Stat(resolvedPath)
+ if os.IsNotExist(err) {
+ return project.IncludeFile{
+ Path: validatedPath,
+ RelativePath: inc.RelativePath,
+ Content: "# This file will be created when you save changes\nservices:\n",
+ }, nil
+ }
if err != nil {
- if os.IsNotExist(err) {
- return project.IncludeFile{}, common.Classify(common.ErrProjectFileNotFound, errors.New("Project file not found"))
- }
return project.IncludeFile{}, errors.WrapIf(err, "failed to stat include file")
}
if info.IsDir() {
@@ -1466,6 +1481,13 @@ func (s *ProjectService) enrichWithComposeServiceConfigs(ctx context.Context, pr
}
func (s *ProjectService) SyncProjectsFromFileSystem(ctx context.Context) error {
+ // Serialized because the walk and the cleanup are two halves of one
+ // decision: overlapping syncs let an older walk's cleanup delete a project a
+ // newer walk had just upserted, because the older walk's `seen` set predates
+ // it. Filesystem-watcher debounces fire these back to back.
+ s.syncMu.Lock()
+ defer s.syncMu.Unlock()
+
followProjectSymlinks := s.settingsService.GetBoolSetting(ctx, "followProjectSymlinks", false)
projectsDir, err := s.getProjectsDirectoryInternal(ctx)
if err != nil {
@@ -4101,6 +4123,12 @@ func (s *ProjectService) StreamProjectLogs(ctx context.Context, projectID string
// Reader goroutine: forward lines to channel
go func() {
+ // Closing the read half unblocks any pending pw.Write in ComposeLogs.
+ // Without it, an abandoned tail (ctx cancel, or a >1MiB line tripping
+ // bufio.ErrTooLong) wedges the writer goroutine forever and this
+ // function never collects its second done value.
+ defer func() { _ = pr.CloseWithError(io.ErrClosedPipe) }()
+
sc := bufio.NewScanner(pr)
sc.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for sc.Scan() {
@@ -4611,25 +4639,70 @@ func getProjectUpdateStatusInternal(updateInfo *project.UpdateInfo) string {
return updateInfo.Status
}
-func (s *ProjectService) countProjectsByUpdateStatusInternal(ctx context.Context, status string) (int, error) {
- if strings.TrimSpace(status) == "" {
+// countProjectsWithPendingUpdatesInternal counts non-archived projects with at
+// least one image update pending, plus compose projects running on the daemon
+// that Arcane does not track. It deliberately avoids the project-list pipeline:
+// that path builds full project DTOs (live status, icons, URLs, GitOps lookups)
+// and then throws all of them away for a single number, costing several full
+// container lists and a compose parse per project on every dashboard load.
+//
+// allContainers is the caller's already-fetched container list; pass nil to have
+// it fetched here.
+func (s *ProjectService) countProjectsWithPendingUpdatesInternal(ctx context.Context, allContainers []container.Summary) (int, error) {
+ if s.db == nil {
return 0, nil
}
- result, err := s.filterProjectsWithDerivedFiltersInternal(ctx, pagination.QueryParams{
- Filters: map[string]string{
- "updates": status,
- },
- Params: pagination.Params{
- Start: 0,
- Limit: 0,
- },
- }, s.db.WithContext(ctx).Model(&models.Project{}).Where("is_archived = ?", false))
- if err != nil {
- return 0, err
+ var projectsArray []models.Project
+ if err := s.db.WithContext(ctx).Where("is_archived = ?", false).Find(&projectsArray).Error; err != nil {
+ return 0, errors.WrapIf(err, "failed to list projects for update count")
+ }
+
+ // enrichProjectsWithUpdateInfoInternal keys off Details.ID, so the summaries
+ // only need identity — no status, icons or URLs are read here.
+ details := make([]project.Details, len(projectsArray))
+ for i, proj := range projectsArray {
+ details[i].ID = proj.ID
+ }
+ s.enrichProjectsWithUpdateInfoInternal(ctx, projectsArray, details)
+
+ count := 0
+ for i := range details {
+ if details[i].UpdateInfo != nil && details[i].UpdateInfo.HasUpdate {
+ count++
+ }
+ }
+
+ return count + s.countDiscoveredComposeProjectUpdatesInternal(ctx, projectsArray, allContainers), nil
+}
+
+// countDiscoveredComposeProjectUpdatesInternal counts compose projects running on
+// the daemon that Arcane does not track but that have a pending image update, so
+// the dashboard badge matches the projects table. Errors are logged and counted
+// as zero: a missing container list should degrade the badge, not fail the load.
+func (s *ProjectService) countDiscoveredComposeProjectUpdatesInternal(ctx context.Context, projectsArray []models.Project, allContainers []container.Summary) int {
+ if allContainers == nil {
+ var err error
+ allContainers, err = projects.ListGlobalComposeContainers(ctx)
+ if err != nil {
+ slog.WarnContext(ctx, "failed to list compose containers for project update count", "error", err)
+ return 0
+ }
}
- return int(result.TotalCount), nil
+ composeContainers := make([]container.Summary, 0, len(allContainers))
+ for _, c := range allContainers {
+ if dockerutil.ComposeProjectLabel(c.Labels) != "" {
+ composeContainers = append(composeContainers, c)
+ }
+ }
+ if len(composeContainers) == 0 {
+ return 0
+ }
+
+ knownProjectNames := s.buildKnownComposeProjectNameSetInternal(ctx, projectsArray)
+ // Only rows with a pending update are returned, so the length is the count.
+ return len(buildDiscoveredComposeProjectUpdateRowsInternal(ctx, composeContainers, knownProjectNames, s.imageService, iconCatalogForContextInternal(ctx)))
}
// fetchProjectStatusConcurrently fetches live Docker status for multiple projects in parallel
@@ -4640,6 +4713,13 @@ func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, pro
slog.WarnContext(ctx, "failed to resolve projects directory for relative project paths", "error", err)
}
+ // Resolved once for the whole list: getProjectMetadataForProject would
+ // otherwise re-stat the projects directory and re-clone settings per project.
+ metaEnv := &projectMetadataEnvInternal{
+ projectsDirectory: projectsDir,
+ autoInjectEnv: s.settingsService.GetBoolSetting(ctx, "autoInjectEnv", false),
+ }
+
// 1. Fetch all compose containers in one go
containers, err := projects.ListGlobalComposeContainers(ctx)
if err != nil {
@@ -4653,7 +4733,7 @@ func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, pro
results[i].DirName = mo.PointerToOption(p.DirName).OrEmpty()
results[i].RelativePath = s.getProjectRelativePathInternal(projectsDir, p.Path)
results[i].GitOpsManagedBy = p.GitOpsManagedBy
- meta := s.getProjectMetadataForProject(ctx, p)
+ meta := s.getProjectMetadataForProject(ctx, p, metaEnv)
applyResolvedProjectIconInternal(&results[i], s.resolveIconSetInternal(ctx, meta.ProjectIcon))
results[i].URLs = meta.ProjectURLS
results[i].Status = string(models.ProjectStatusUnknown)
@@ -4668,13 +4748,13 @@ func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, pro
results := make([]project.Details, len(projectsList))
currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
for i, p := range projectsList {
- results[i] = s.mapProjectToDto(ctx, projectsDir, p, containersByProject, currentContainerID, currentContainerErr)
+ results[i] = s.mapProjectToDto(ctx, projectsDir, p, containersByProject, currentContainerID, currentContainerErr, metaEnv)
}
return results
}
-func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string, p models.Project, containersByProject map[string][]container.Summary, currentContainerID string, currentContainerErr error) project.Details {
+func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string, p models.Project, containersByProject map[string][]container.Summary, currentContainerID string, currentContainerErr error, metaEnv *projectMetadataEnvInternal) project.Details {
var resp project.Details
_ = mapper.MapStruct(p, &resp)
@@ -4685,7 +4765,7 @@ func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string
resp.DirName = mo.PointerToOption(p.DirName).OrEmpty()
resp.RelativePath = s.getProjectRelativePathInternal(projectsDir, p.Path)
resp.GitOpsManagedBy = p.GitOpsManagedBy
- meta := s.getProjectMetadataForProject(ctx, p)
+ meta := s.getProjectMetadataForProject(ctx, p, metaEnv)
applyResolvedProjectIconInternal(&resp, s.resolveIconSetInternal(ctx, meta.ProjectIcon))
resp.URLs = meta.ProjectURLS
@@ -4796,22 +4876,47 @@ func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string
return resp
}
-func (s *ProjectService) getProjectMetadataForProject(ctx context.Context, p models.Project) projects.ArcaneComposeMetadata {
+// getProjectMetadataForProject resolves a project's icon sets and service URLs.
+// Results are cached for projectMetadataTTL because deriving them is expensive
+// (compose load with interpolation and .env reads, plus a gitops_syncs query for
+// GitOps-managed projects) and every project row on the list page needs it.
+//
+// env may be nil, in which case the projects directory and autoInjectEnv setting
+// are resolved here; callers iterating over many projects should resolve them
+// once and pass them in.
+func (s *ProjectService) getProjectMetadataForProject(ctx context.Context, p models.Project, env *projectMetadataEnvInternal) projects.ArcaneComposeMetadata {
+ if s.metaCache != nil && p.ID != "" {
+ if meta, ok, _ := s.metaCache.Get(p.ID); ok {
+ return meta
+ }
+ }
+
+ empty := projects.ArcaneComposeMetadata{ServiceIconSets: map[string]projects.IconSet{}}
+
composeFile, err := s.resolveProjectComposeFileInternal(ctx, &p)
if err != nil {
- return projects.ArcaneComposeMetadata{ServiceIconSets: map[string]projects.IconSet{}}
+ return empty
}
- projectsDirectory, projectsDirErr := s.getProjectsDirectoryInternal(ctx)
- if projectsDirErr != nil {
- slog.WarnContext(ctx, "failed to resolve projects directory for Arcane compose metadata", "path", composeFile, "error", projectsDirErr)
+ if env == nil {
+ projectsDirectory, projectsDirErr := s.getProjectsDirectoryInternal(ctx)
+ if projectsDirErr != nil {
+ slog.WarnContext(ctx, "failed to resolve projects directory for Arcane compose metadata", "path", composeFile, "error", projectsDirErr)
+ }
+ env = &projectMetadataEnvInternal{
+ projectsDirectory: projectsDirectory,
+ autoInjectEnv: s.settingsService.GetBoolSetting(ctx, "autoInjectEnv", false),
+ }
}
- autoInjectEnv := s.settingsService.GetBoolSetting(ctx, "autoInjectEnv", false)
- meta, err := projects.ParseArcaneComposeMetadata(ctx, composeFile, projectsDirectory, autoInjectEnv)
+ meta, err := projects.ParseArcaneComposeMetadata(ctx, composeFile, env.projectsDirectory, env.autoInjectEnv)
if err != nil {
slog.WarnContext(ctx, "failed to parse Arcane compose metadata", "path", composeFile, "error", err)
- return projects.ArcaneComposeMetadata{ServiceIconSets: map[string]projects.IconSet{}}
+ return empty
+ }
+
+ if s.metaCache != nil && p.ID != "" {
+ s.metaCache.Set(p.ID, meta)
}
return meta
diff --git a/backend/internal/services/project_service_test.go b/backend/internal/services/project_service_test.go
index e61f4839b..ff895e1ce 100644
--- a/backend/internal/services/project_service_test.go
+++ b/backend/internal/services/project_service_test.go
@@ -4297,7 +4297,7 @@ func TestProjectService_MapProjectToDto_SetsRedeployDisabledFromRuntimeServices(
Labels: tt.labels,
},
},
- }, tt.currentContainerID, tt.currentErr)
+ }, tt.currentContainerID, tt.currentErr, nil)
require.Equal(t, tt.wantProject, details.RedeployDisabled)
require.Len(t, details.RuntimeServices, 1)
diff --git a/backend/internal/services/swarm_service.go b/backend/internal/services/swarm_service.go
index a71f0cd70..862987a85 100644
--- a/backend/internal/services/swarm_service.go
+++ b/backend/internal/services/swarm_service.go
@@ -26,6 +26,7 @@ import (
libswarm "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/swarm"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
appfs "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"
networktypes "github.com/moby/moby/api/types/network"
"github.com/moby/moby/api/types/swarm"
@@ -700,7 +701,9 @@ func (s *SwarmService) resolveNodeAgentCoverageInternal(ctx context.Context, env
g.SetLimit(swarmNodeIdentityProbeConcurrency)
for _, candidate := range probeEnvsByID {
env := candidate
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "swarm worker")
+
runtime := s.resolveSwarmNodeAgentRuntimeInternal(groupCtx, &env)
runtimeMu.Lock()
runtimeByEnvID[env.ID] = runtime
@@ -913,7 +916,9 @@ func (s *SwarmService) JoinEnvironments(ctx context.Context, managerEnvironmentI
if target.Role != swarmtypes.SwarmJoinEnvironmentRoleWorker {
continue
}
- group.Go(func() error {
+ group.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "swarm worker")
+
if groupCtx.Err() == nil {
processTargetInternal(index)
}
diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.go
index 9fd6c46ba..6dc511527 100644
--- a/backend/internal/services/system_service.go
+++ b/backend/internal/services/system_service.go
@@ -150,7 +150,9 @@ func (s *SystemService) runSystemPruneInternal(ctx context.Context, req system.P
g, groupCtx := errgroup.WithContext(ctx)
if req.Images != nil && req.Images.Mode != system.PruneImageModeNone {
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "system info worker")
+
s.appendSystemPruneActivityMessageInternal(groupCtx, activityID, "Pruning images", 40)
slog.InfoContext(groupCtx, "Pruning images...", "mode", req.Images.Mode, "until", req.Images.Until)
localResult := &system.PruneAllResult{}
@@ -171,7 +173,9 @@ func (s *SystemService) runSystemPruneInternal(ctx context.Context, req system.P
}
if req.BuildCache != nil && req.BuildCache.Mode != system.PruneBuildCacheModeNone {
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "system info worker")
+
s.appendSystemPruneActivityMessageInternal(groupCtx, activityID, "Pruning build cache", 45)
slog.InfoContext(groupCtx, "Pruning build cache...", "mode", req.BuildCache.Mode, "until", req.BuildCache.Until)
localResult := &system.PruneAllResult{}
@@ -194,7 +198,9 @@ func (s *SystemService) runSystemPruneInternal(ctx context.Context, req system.P
}
if req.Volumes != nil && req.Volumes.Mode != system.PruneVolumeModeNone {
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "system info worker")
+
s.appendSystemPruneActivityMessageInternal(groupCtx, activityID, "Pruning volumes", 55)
slog.InfoContext(groupCtx, "Pruning volumes...", "mode", req.Volumes.Mode)
localResult := &system.PruneAllResult{}
@@ -215,7 +221,9 @@ func (s *SystemService) runSystemPruneInternal(ctx context.Context, req system.P
}
if req.Networks != nil && req.Networks.Mode != system.PruneNetworkModeNone {
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "system info worker")
+
s.appendSystemPruneActivityMessageInternal(groupCtx, activityID, "Pruning networks", 65)
slog.InfoContext(groupCtx, "Pruning networks...", "mode", req.Networks.Mode, "until", req.Networks.Until)
localResult := &system.PruneAllResult{}
@@ -318,7 +326,9 @@ func (s *SystemService) performBatchContainerAction(ctx context.Context, contain
continue
}
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "system info worker")
+
err := action(groupCtx, c.ID)
mu.Lock()
diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.go
index 28de43c96..53b595380 100644
--- a/backend/internal/services/template_service.go
+++ b/backend/internal/services/template_service.go
@@ -578,7 +578,9 @@ func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]models.Com
continue
}
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "template worker")
+
remoteTemplates, err := s.fetchRegistryTemplates(groupCtx, &reg)
if err != nil {
slog.WarnContext(groupCtx, "failed to fetch templates from registry", "registry", reg.Name, "url", reg.URL, "error", err)
@@ -781,7 +783,9 @@ func (s *TemplateService) enrichRemoteTemplateIcons(ctx context.Context, templat
for i := range templates {
idx := i
- group.Go(func() error {
+ group.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "template worker")
+
composeContent, envContent, err := s.fetchRemoteTemplateFiles(groupCtx, &templates[idx])
if err != nil {
slog.WarnContext(groupCtx, "failed to fetch remote template content for icon extraction", "templateID", templates[idx].ID, "error", err)
@@ -820,13 +824,24 @@ func (s *TemplateService) newSafeRequestInternal(ctx context.Context, method, ra
return nil, nil, err
}
+ // Double-checked under registryMu: the lazy init ran unsynchronized, so
+ // concurrent template downloads raced on s.safeHTTPClient — a data race, and
+ // each loser silently built and leaked its own client.
+ s.registryMu.RLock()
client := s.safeHTTPClient
+ s.registryMu.RUnlock()
+
if client == nil {
- client = s.newSafeHTTPClientInternal()
+ s.registryMu.Lock()
+ if s.safeHTTPClient == nil {
+ s.safeHTTPClient = s.newSafeHTTPClientInternal()
+ }
+ client = s.safeHTTPClient
+ s.registryMu.Unlock()
+
if client == nil {
return nil, nil, errors.New("failed to configure safe HTTP client")
}
- s.safeHTTPClient = client
}
req, err := http.NewRequestWithContext(ctx, method, parsedURL.String(), nil)
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index c2d1da51b..50eae6247 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -34,6 +34,7 @@ import (
"github.com/moby/moby/api/types/volume"
"github.com/moby/moby/client"
"github.com/samber/mo"
+ "golang.org/x/sync/singleflight"
)
type VolumeService struct {
@@ -46,13 +47,21 @@ type VolumeService struct {
backupVolumeName string
helperMu sync.Mutex
helperByVolume map[string]*volumeHelper
+ // helperGroup deduplicates concurrent read-only helper creation per volume.
+ // Without it two simultaneous browse requests each create a helper and the
+ // second overwrites the first in helperByVolume, orphaning a `sleep infinity`
+ // container that pins the volume until restart.
+ helperGroup singleflight.Group
}
// volumeHelper tracks a reused read-only browse helper container and the last
-// time it serviced a request, so idle helpers can be reaped.
+// time it serviced a request, so idle helpers can be reaped. inUse counts the
+// requests currently holding the helper: the reaper must not remove a helper
+// mid-download just because it was acquired longer ago than the idle timeout.
type volumeHelper struct {
id string
lastUsedAt time.Time
+ inUse int
}
const volumeHelperImage = volumehelper.DefaultToolsImage
@@ -723,12 +732,109 @@ func (s *VolumeService) createTempContainerInternal(ctx context.Context, volumeN
return "", nil, err
}
- if readOnly {
+ if !readOnly {
+ return s.startHelperContainerInternal(ctx, dockerClient, volumeName, false)
+ }
+
+ // Read-only helpers are shared and reaped when idle; the caller's cleanup
+ // releases its in-use hold instead of removing the container. The resolve →
+ // acquire gap is racy against the reaper, so retry a resolve whose helper
+ // was reaped before this caller could take its hold.
+ for range 3 {
+ containerID, err := s.resolveReadOnlyHelperInternal(ctx, dockerClient, volumeName)
+ if err != nil {
+ return "", nil, err
+ }
+ if release, ok := s.acquireHelperInternal(volumeName, containerID); ok {
+ return containerID, release, nil
+ }
+ }
+ return "", nil, errors.New("failed to acquire volume helper container")
+}
+
+// resolveReadOnlyHelperInternal returns the shared read-only helper container ID
+// for volumeName, creating it if needed. singleflight collapses concurrent
+// misses: without it both requests create a helper and the loser is orphaned,
+// holding the volume mount with no cleanup path until Arcane restarts. The
+// creation itself can pull an image, so it must not run under helperMu.
+func (s *VolumeService) resolveReadOnlyHelperInternal(ctx context.Context, dockerClient *client.Client, volumeName string) (string, error) {
+ resultCh := s.helperGroup.DoChan(volumeName, func() (any, error) {
if containerID, ok := s.getReusableReadOnlyContainerInternal(ctx, dockerClient, volumeName).Get(); ok {
- return containerID, func() {}, nil
+ return containerID, nil
+ }
+
+ // Detached from the caller's context so a client that walks away
+ // mid-create doesn't abort the helper the other waiters are blocked on,
+ // but still bounded: WithoutCancel alone would let a hung daemon or
+ // image pull wedge this singleflight key forever, queueing every later
+ // browse of the volume behind it with no recovery until restart.
+ createCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeouts.DefaultDockerImagePull)
+ defer cancel()
+
+ containerID, _, createErr := s.startHelperContainerInternal(createCtx, dockerClient, volumeName, true)
+ if createErr != nil {
+ return nil, createErr
+ }
+
+ s.helperMu.Lock()
+ s.helperByVolume[volumeName] = &volumeHelper{id: containerID, lastUsedAt: time.Now()}
+ s.helperMu.Unlock()
+ return containerID, nil
+ })
+
+ // DoChan instead of Do so a caller whose request is canceled unblocks
+ // immediately; the shared create keeps running for the remaining waiters
+ // (and lands in helperByVolume for the next request even if none remain).
+ var shared any
+ select {
+ case <-ctx.Done():
+ return "", errors.WrapIf(ctx.Err(), "canceled waiting for volume helper container")
+ case result := <-resultCh:
+ if result.Err != nil {
+ return "", result.Err
}
+ shared = result.Val
}
+ containerID, ok := shared.(string)
+ if !ok || containerID == "" {
+ return "", errors.New("failed to resolve volume helper container")
+ }
+ return containerID, nil
+}
+
+// acquireHelperInternal takes an in-use hold on volumeName's helper, reporting
+// false when the helper has been removed (e.g. reaped) since it was resolved.
+// The returned release drops the hold and refreshes the idle clock, so the idle
+// timeout is measured from the end of the last request, not its start — a
+// download running longer than the timeout used to have its helper reaped out
+// from under it, truncating the stream.
+func (s *VolumeService) acquireHelperInternal(volumeName, containerID string) (func(), bool) {
+ s.helperMu.Lock()
+ defer s.helperMu.Unlock()
+
+ helper := s.helperByVolume[volumeName]
+ if helper == nil || helper.id != containerID {
+ return nil, false
+ }
+
+ helper.inUse++
+ helper.lastUsedAt = time.Now()
+
+ return func() {
+ s.helperMu.Lock()
+ defer s.helperMu.Unlock()
+ if current := s.helperByVolume[volumeName]; current == helper {
+ helper.inUse--
+ helper.lastUsedAt = time.Now()
+ }
+ }, true
+}
+
+// startHelperContainerInternal creates and starts a volume helper container and
+// returns a cleanup that removes it. Tracking of reusable read-only helpers is
+// the caller's responsibility.
+func (s *VolumeService) startHelperContainerInternal(ctx context.Context, dockerClient *client.Client, volumeName string, readOnly bool) (string, func(), error) {
helperImage, err := getVolumeHelperImageInternal(ctx, s.dockerService, s.imageService, dockerClient)
if err != nil {
return "", nil, err
@@ -764,14 +870,7 @@ func (s *VolumeService) createTempContainerInternal(ctx context.Context, volumeN
}
cleanup := func() {
- _, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())
- }
-
- if readOnly {
- s.helperMu.Lock()
- s.helperByVolume[volumeName] = &volumeHelper{id: resp.ID, lastUsedAt: time.Now()}
- s.helperMu.Unlock()
- return resp.ID, func() {}, nil
+ _, _ = dockerClient.ContainerRemove(context.WithoutCancel(ctx), resp.ID, volumehelper.RemoveOptions())
}
return resp.ID, cleanup, nil
@@ -875,6 +974,12 @@ func (s *VolumeService) collectStaleHelperIDsInternal(now time.Time, idleTimeout
delete(s.helperByVolume, volumeName)
continue
}
+ // A helper with active holds is serving a request right now (e.g. a
+ // download streaming for longer than the idle timeout); it becomes
+ // reapable once released, since release refreshes lastUsedAt.
+ if helper.inUse > 0 {
+ continue
+ }
if now.Sub(helper.lastUsedAt) >= idleTimeout {
staleIDs = append(staleIDs, helper.id)
delete(s.helperByVolume, volumeName)
diff --git a/backend/internal/services/volume_service_test.go b/backend/internal/services/volume_service_test.go
index 7b29c0687..c77311f6d 100644
--- a/backend/internal/services/volume_service_test.go
+++ b/backend/internal/services/volume_service_test.go
@@ -432,6 +432,36 @@ func TestCollectStaleHelperIDsInternal(t *testing.T) {
require.Contains(t, s.helperByVolume, "fresh")
}
+// A helper serving a request longer than the idle timeout (e.g. a slow download)
+// must not be reaped mid-stream; it becomes collectible once released, with the
+// idle clock measured from the release.
+func TestCollectStaleHelperIDsInternalSkipsInUseHelpers(t *testing.T) {
+ now := time.Now()
+ s := &VolumeService{
+ helperByVolume: map[string]*volumeHelper{
+ "vol-a": {id: "c-a", lastUsedAt: now.Add(-30 * time.Minute)},
+ },
+ }
+
+ release, ok := s.acquireHelperInternal("vol-a", "c-a")
+ require.True(t, ok)
+
+ require.Empty(t, s.collectStaleHelperIDsInternal(now, 10*time.Minute),
+ "an in-use helper must survive the reaper regardless of lastUsedAt")
+ require.Contains(t, s.helperByVolume, "vol-a")
+
+ release()
+ require.Empty(t, s.collectStaleHelperIDsInternal(now, 10*time.Minute),
+ "release refreshes the idle clock, so the helper is fresh again")
+ stale := s.collectStaleHelperIDsInternal(now.Add(11*time.Minute), 10*time.Minute)
+ require.Equal(t, []string{"c-a"}, stale)
+
+ // Acquiring a helper that was reaped (or replaced) since resolve must fail
+ // so the caller re-resolves instead of using a dead container.
+ _, ok = s.acquireHelperInternal("vol-a", "c-a")
+ require.False(t, ok)
+}
+
func TestTakeHelperIDInternal(t *testing.T) {
s := &VolumeService{
helperByVolume: map[string]*volumeHelper{
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
index f18cb9a94..384a4b72c 100644
--- a/backend/internal/services/vulnerability_service.go
+++ b/backend/internal/services/vulnerability_service.go
@@ -92,9 +92,9 @@ type VulnerabilityService struct {
notificationService *NotificationService
activityService *ActivityService
registryService *ContainerRegistryService
- // scanLocks provides per-image locking to allow concurrent scans of different images
- // while preventing duplicate scans of the same image
- scanLocks sync.Map // map[string]*sync.Mutex
+ // scanLocks provides per-image locking to allow concurrent scans of different
+ // images while preventing duplicate scans of the same image.
+ scanLocks utils.KeyedMutex
// trivyScanSlots limits concurrent Trivy scans (manual + scheduled) and
// provides deterministic slot IDs for shared-cache sharding.
trivyScanSlots chan int
@@ -103,15 +103,6 @@ type VulnerabilityService struct {
scanPhases sync.Map // map[string]vulnerability.ScanPhase
}
-// getImageLock returns a mutex for the given image ID, creating one if needed
-func (s *VulnerabilityService) getImageLock(imageID string) *sync.Mutex {
- lock, _ := s.scanLocks.LoadOrStore(imageID, &sync.Mutex{})
- if mu, ok := lock.(*sync.Mutex); ok {
- return mu
- }
- return &sync.Mutex{}
-}
-
func (s *VulnerabilityService) setScanPhaseInternal(imageID string, phase vulnerability.ScanPhase) {
if imageID == "" || phase == "" {
return
@@ -3287,9 +3278,7 @@ func (s *VulnerabilityService) runTrivyScan(ctx context.Context, trivyImage stri
defer releaseSlot()
// Use per-image locking to allow concurrent scans of different images
- lock := s.getImageLock(imageID)
- lock.Lock()
- defer lock.Unlock()
+ defer s.scanLocks.Lock(imageID)()
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
diff --git a/backend/pkg/fswatch/watcher.go b/backend/pkg/fswatch/watcher.go
index 5b7111f2f..199161975 100644
--- a/backend/pkg/fswatch/watcher.go
+++ b/backend/pkg/fswatch/watcher.go
@@ -84,6 +84,16 @@ func (fw *Watcher) Start(ctx context.Context) error {
}
if err := fw.watcher.Add(fw.watchedPath); err != nil {
+ // The underlying fsnotify watcher already holds an inotify/kqueue
+ // descriptor. A caller whose Start failed has no reason to call Stop, so
+ // release it here and mark the watcher spent. fsnotify's Close is
+ // idempotent, so a later Stop remains safe.
+ fw.stopped = true
+ if closeErr := fw.watcher.Close(); closeErr != nil {
+ slog.WarnContext(ctx, "Failed to close filesystem watcher after failed start",
+ "path", fw.watchedPath,
+ "error", closeErr)
+ }
return err
}
diff --git a/backend/pkg/libarcane/edge/client.go b/backend/pkg/libarcane/edge/client.go
index e59764a9b..c12c09eb2 100644
--- a/backend/pkg/libarcane/edge/client.go
+++ b/backend/pkg/libarcane/edge/client.go
@@ -13,11 +13,24 @@ import (
"emperror.dev/errors"
+ "github.com/cenkalti/backoff/v5"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/samber/mo"
)
+const (
+ // maxReconnectInterval caps the exponential reconnect backoff so a long-dead
+ // manager is still retried at a sane cadence.
+ maxReconnectInterval = 60 * time.Second
+ // healthyTunnelSessionDuration is how long a tunnel session must survive
+ // before the reconnect backoff is treated as recovered.
+ healthyTunnelSessionDuration = 60 * time.Second
+ // maxPollRetryInterval caps the exponential backoff applied to failed poll
+ // control requests. Successful polls return to the manager-advertised interval.
+ maxPollRetryInterval = 60 * time.Second
+)
+
const (
// DefaultHeartbeatInterval is how often the client sends heartbeats
DefaultHeartbeatInterval = 30 * time.Second
@@ -113,6 +126,14 @@ func (c *TunnelClient) StartWithErrorChan(ctx context.Context, errCh chan error)
defer close(errCh)
}
+ // A fixed reconnect interval meant a permanently broken or unauthorized agent
+ // hammered the manager's auth and DB path forever. Back off exponentially
+ // (with jitter) up to maxReconnectInterval, and reset only once a session has
+ // stayed up long enough to count as healthy.
+ reconnectBackoff := backoff.NewExponentialBackOff()
+ reconnectBackoff.InitialInterval = c.reconnectInterval
+ reconnectBackoff.MaxInterval = maxReconnectInterval
+
for {
select {
case <-ctx.Done():
@@ -122,6 +143,7 @@ func (c *TunnelClient) StartWithErrorChan(ctx context.Context, errCh chan error)
slog.InfoContext(ctx, "Edge tunnel client stopped")
return
default:
+ sessionStart := time.Now()
if err := c.connectAndServe(ctx); err != nil {
if errCh != nil {
select {
@@ -133,14 +155,23 @@ func (c *TunnelClient) StartWithErrorChan(ctx context.Context, errCh chan error)
}
}
+ if time.Since(sessionStart) >= healthyTunnelSessionDuration {
+ reconnectBackoff.Reset()
+ }
+
// Wait before reconnecting
+ delay := reconnectBackoff.NextBackOff()
+ reconnectTimer := time.NewTimer(delay)
select {
case <-ctx.Done():
+ reconnectTimer.Stop()
return
case <-c.stopCh:
+ reconnectTimer.Stop()
return
- case <-time.After(c.reconnectInterval):
- slog.InfoContext(ctx, "Attempting to reconnect edge tunnel")
+ case <-reconnectTimer.C:
+ reconnectTimer.Stop()
+ slog.InfoContext(ctx, "Attempting to reconnect edge tunnel", "delay", delay)
}
}
}
@@ -743,7 +774,7 @@ func (c *TunnelClient) handleRequest(ctx context.Context, conn TunnelConnection,
return
}
- reqCtx, cancel := context.WithTimeout(ctx, c.requestTimeout)
+ reqCtx, cancel := context.WithTimeout(ctx, c.requestTimeoutInternal())
defer cancel()
reqCtx = withInternalTunnelRequestInternal(reqCtx)
@@ -795,7 +826,7 @@ func isGRPCConnection(conn TunnelConnection) bool {
}
func (c *TunnelClient) handleRequestStreaming(ctx context.Context, conn TunnelConnection, msg *TunnelMessage) {
- reqCtx, cancel := context.WithTimeout(ctx, c.requestTimeout)
+ reqCtx, cancel := context.WithTimeout(ctx, c.requestTimeoutInternal())
defer cancel()
reqCtx = withInternalTunnelRequestInternal(reqCtx)
diff --git a/backend/pkg/libarcane/edge/client_test.go b/backend/pkg/libarcane/edge/client_test.go
index c979f2fab..8e6895a00 100644
--- a/backend/pkg/libarcane/edge/client_test.go
+++ b/backend/pkg/libarcane/edge/client_test.go
@@ -1285,7 +1285,7 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
if !ok || tunnel == nil {
return c.NoContent(http.StatusServiceUnavailable)
}
- return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
+ return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats", func(*http.Request) bool { return true })
})
proxyServer := httptest.NewServer(router)
diff --git a/backend/pkg/libarcane/edge/client_transport_poll.go b/backend/pkg/libarcane/edge/client_transport_poll.go
index 4c16846a3..2be6b6d04 100644
--- a/backend/pkg/libarcane/edge/client_transport_poll.go
+++ b/backend/pkg/libarcane/edge/client_transport_poll.go
@@ -11,6 +11,8 @@ import (
"time"
"emperror.dev/errors"
+
+ "github.com/cenkalti/backoff/v5"
)
const defaultTunnelPollRequestTimeout = 15 * time.Second
@@ -30,6 +32,17 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {
pollURL := managerBaseURL + "/api/tunnel/poll"
interval := DefaultTunnelPollInterval
+ // Failed polls back off exponentially instead of retrying every 2s forever;
+ // a successful poll restores the manager-advertised interval. No jitter: the
+ // default randomization lets the very first retry exceed the advertised
+ // interval by up to 50%, and poll cycles are already phase-spread across
+ // agents (each notices an outage at its own next tick), so there is no
+ // synchronized herd for jitter to break up. The first retry is therefore
+ // deterministically the poll interval itself.
+ 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)
@@ -57,12 +70,13 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {
return ctx.Err()
}
+ retryInterval := retryBackoff.NextBackOff()
slog.WarnContext(ctx, "Poll control request failed, retrying after interval",
"error", err,
- "interval", interval,
+ "interval", retryInterval,
)
- session, err = waitForNextPollCycleInternal(ctx, session, interval)
+ session, err = waitForNextPollCycleInternal(ctx, session, retryInterval)
if err != nil {
return err
}
@@ -72,6 +86,10 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {
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, err = c.syncPollManagedSessionInternal(ctx, session, status.Status)
if err != nil {
diff --git a/backend/pkg/libarcane/edge/commands_test.go b/backend/pkg/libarcane/edge/commands_test.go
index 3bc6c7506..7b4187afa 100644
--- a/backend/pkg/libarcane/edge/commands_test.go
+++ b/backend/pkg/libarcane/edge/commands_test.go
@@ -75,7 +75,7 @@ func TestCollectCommandResponse(t *testing.T) {
pending.ResponseCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandAck}
pending.ResponseCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandOutput, Body: []byte("hello ")}
pending.ResponseCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandComplete, Status: 200, Headers: map[string]string{"Content-Type": "text/plain"}, Body: []byte("world")}
- require.NoError(t, tunnel.Close())
+ require.NoError(t, tunnel.CloseWithReason(""))
status, headers, body, err := collectCommandResponseInternal(context.Background(), tunnel, pending, "")
require.NoError(t, err)
diff --git a/backend/pkg/libarcane/edge/proxy_test.go b/backend/pkg/libarcane/edge/proxy_test.go
index 988f4bc96..250927062 100644
--- a/backend/pkg/libarcane/edge/proxy_test.go
+++ b/backend/pkg/libarcane/edge/proxy_test.go
@@ -86,7 +86,7 @@ func TestProxyRequest(t *testing.T) {
}
})
defer server.Close()
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
@@ -110,7 +110,7 @@ func TestProxyHTTPRequest(t *testing.T) {
}
})
defer server.Close()
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
e := echo.New()
w := httptest.NewRecorder()
@@ -251,7 +251,7 @@ func TestDoRequest(t *testing.T) {
}
})
defer server.Close()
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
// Register tunnel globally
registry := GetRegistry()
@@ -314,7 +314,7 @@ func TestHasActiveTunnel(t *testing.T) {
assert.True(t, HasActiveTunnel("env-active"))
assert.False(t, HasActiveTunnel("non-existent"))
- _ = tunnel.Close()
+ _ = tunnel.CloseWithReason("")
assert.False(t, HasActiveTunnel("env-active"))
}
@@ -371,7 +371,7 @@ func TestProxyHTTPRequest_StripsBrowserHeaders(t *testing.T) {
}
})
defer server.Close()
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
e := echo.New()
w := httptest.NewRecorder()
@@ -429,7 +429,7 @@ func TestProxyHTTPRequest_ForwardsBodyCorrectly(t *testing.T) {
}
})
defer server.Close()
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
requestBody := `{"name":"My Project"}`
@@ -569,7 +569,7 @@ func TestProxyHTTPRequest_EndToEnd_BrowserOriginStripped(t *testing.T) {
server, tunnel := setupMockAgentServer(t, agentHandler)
defer server.Close()
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
e := echo.New()
w := httptest.NewRecorder()
@@ -633,7 +633,7 @@ func TestProxyHTTPRequest_BodyPreservation_WebSocket(t *testing.T) {
}
tunnel := newWebSocketAgentTunnel("env-body-test", wsConn)
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
go func() {
for {
diff --git a/backend/pkg/libarcane/edge/registry.go b/backend/pkg/libarcane/edge/registry.go
index 0c9f36f05..30e212d87 100644
--- a/backend/pkg/libarcane/edge/registry.go
+++ b/backend/pkg/libarcane/edge/registry.go
@@ -35,12 +35,41 @@ func (t *AgentTunnel) GetLastHeartbeat() time.Time {
return t.LastHeartbeat
}
-// Close closes the tunnel connection
-func (t *AgentTunnel) Close() error {
- return t.CloseWithReason("")
+// TunnelMetadataSnapshot is a consistent copy of a tunnel's mutable metadata.
+type TunnelMetadataSnapshot struct {
+ ConnectedAt time.Time
+ LastHeartbeat time.Time
+ SessionID string
+ AgentInstance string
+ SecurityMode string
+ Capabilities []string
+ State string
}
-// CloseWithReason closes the tunnel connection and records the disconnect reason.
+// MetadataSnapshot returns the tunnel's mutable metadata under one read lock.
+// Reading the fields directly races with the writers that take t.mu (heartbeats,
+// registration, CloseWithReason) and can mix state from either side of a close.
+func (t *AgentTunnel) MetadataSnapshot() TunnelMetadataSnapshot {
+ if t == nil {
+ return TunnelMetadataSnapshot{}
+ }
+
+ t.mu.RLock()
+ defer t.mu.RUnlock()
+
+ return TunnelMetadataSnapshot{
+ ConnectedAt: t.ConnectedAt,
+ LastHeartbeat: t.LastHeartbeat,
+ SessionID: t.SessionID,
+ AgentInstance: t.AgentInstance,
+ SecurityMode: t.SecurityMode,
+ Capabilities: append([]string(nil), t.Capabilities...),
+ State: t.State,
+ }
+}
+
+// CloseWithReason closes the tunnel connection and records the disconnect
+// reason. Pass "" when there is no reason to record.
func (t *AgentTunnel) CloseWithReason(reason string) error {
if t == nil {
return nil
@@ -85,7 +114,7 @@ func (r *TunnelRegistry) Register(envID string, tunnel *AgentTunnel) {
// Close existing tunnel if any
if existing, ok := r.tunnels[envID]; ok {
slog.Info("Replacing existing edge tunnel")
- _ = existing.Close()
+ _ = existing.CloseWithReason("")
}
r.tunnels[envID] = tunnel
@@ -135,7 +164,7 @@ func (r *TunnelRegistry) Unregister(envID string) {
defer r.mu.Unlock()
if tunnel, ok := r.tunnels[envID]; ok {
- _ = tunnel.Close()
+ _ = tunnel.CloseWithReason("")
delete(r.tunnels, envID)
slog.Info("Edge agent tunnel unregistered")
}
@@ -160,7 +189,7 @@ func (r *TunnelRegistry) UnregisterCurrent(envID string, current *AgentTunnel) (
return false, false
}
- _ = existing.Close()
+ _ = existing.CloseWithReason("")
delete(r.tunnels, envID)
slog.Info("Edge agent tunnel unregistered", "environment_id", envID, "session_id", current.SessionID)
return true, false
diff --git a/backend/pkg/libarcane/edge/remenv_test.go b/backend/pkg/libarcane/edge/remenv_test.go
index 3b438ea1c..a33658405 100644
--- a/backend/pkg/libarcane/edge/remenv_test.go
+++ b/backend/pkg/libarcane/edge/remenv_test.go
@@ -310,7 +310,7 @@ func TestRemenvClient_EdgeWithTunnel(t *testing.T) {
}
})
defer server.Close()
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
envID := "env-edge-1"
GetRegistry().Register(envID, tunnel)
diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.go
index 9c23b3c42..9a7533642 100644
--- a/backend/pkg/libarcane/edge/server.go
+++ b/backend/pkg/libarcane/edge/server.go
@@ -430,7 +430,7 @@ func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx co
DrainPrevious: drainPrevious,
}); err != nil {
slog.WarnContext(ctx, "Failed to send register response", "environment_id", tunnel.EnvironmentID, "error", err)
- _ = tunnel.Close()
+ _ = tunnel.CloseWithReason("")
removed, active := s.registry.UnregisterCurrent(tunnel.EnvironmentID, tunnel)
if removed && !active {
s.updateConnectionStatusInternal(callbackCtx, tunnel, false)
@@ -456,6 +456,14 @@ func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx co
// messageLoop processes incoming messages from the agent.
func (s *TunnelServer) messageLoop(ctx context.Context, tunnel *AgentTunnel) {
+ // One reusable timer for stream delivery deadlines. time.After per message
+ // left a live 5s runtime timer for every frame, so a chatty log tail through
+ // a tunnel accumulated thousands of them. This loop is the only user, so the
+ // timer is never touched concurrently.
+ deliveryTimer := time.NewTimer(streamDeliveryTimeout)
+ deliveryTimer.Stop()
+ defer deliveryTimer.Stop()
+
for {
select {
case <-ctx.Done():
@@ -469,12 +477,12 @@ func (s *TunnelServer) messageLoop(ctx context.Context, tunnel *AgentTunnel) {
return
}
- s.handleTunnelMessage(ctx, tunnel, msg)
+ s.handleTunnelMessage(ctx, tunnel, msg, deliveryTimer)
}
}
}
-func (s *TunnelServer) handleTunnelMessage(ctx context.Context, tunnel *AgentTunnel, msg *TunnelMessage) {
+func (s *TunnelServer) handleTunnelMessage(ctx context.Context, tunnel *AgentTunnel, msg *TunnelMessage, deliveryTimer *time.Timer) {
switch msg.Type {
case MessageTypeHeartbeat:
s.handleHeartbeat(ctx, tunnel, msg)
@@ -485,7 +493,7 @@ func (s *TunnelServer) handleTunnelMessage(ctx context.Context, tunnel *AgentTun
case MessageTypeEvent:
s.handleEvent(ctx, tunnel, msg)
case MessageTypeStreamData, MessageTypeStreamEnd, MessageTypeWebSocketData, MessageTypeWebSocketClose, MessageTypeStreamClose:
- s.deliverStream(ctx, tunnel, msg)
+ s.deliverStream(ctx, tunnel, msg, deliveryTimer)
case MessageTypeRequest, MessageTypeHeartbeatAck, MessageTypeWebSocketStart, MessageTypeRegisterResponse, MessageTypeCommandRequest, MessageTypeStreamOpen, MessageTypeCancelRequest:
slog.DebugContext(ctx, "Ignoring message type from agent", "type", msg.Type, "environment_id", tunnel.EnvironmentID)
case MessageTypeRegister:
@@ -525,17 +533,23 @@ func (s *TunnelServer) deliverResponse(ctx context.Context, tunnel *AgentTunnel,
slog.WarnContext(ctx, "Received response for unknown request", "id", msg.ID)
}
-func (s *TunnelServer) deliverStream(ctx context.Context, tunnel *AgentTunnel, msg *TunnelMessage) {
+func (s *TunnelServer) deliverStream(ctx context.Context, tunnel *AgentTunnel, msg *TunnelMessage, deliveryTimer *time.Timer) {
if req, ok := tunnel.Pending.Load(msg.ID); ok {
pending, isPending := req.(*PendingRequest)
if !isPending {
return
}
+
+ // Go 1.23+ timers drop any stale value on Stop/Reset, so no drain is needed.
+ deliveryTimer.Stop()
+ deliveryTimer.Reset(streamDeliveryTimeout)
+ defer deliveryTimer.Stop()
+
select {
case pending.ResponseCh <- msg:
case <-ctx.Done():
return
- case <-time.After(streamDeliveryTimeout):
+ case <-deliveryTimer.C:
err := errors.Errorf("stream delivery timed out for pending request %s", msg.ID)
tunnel.Pending.Delete(msg.ID)
pending.failureCh <- err
diff --git a/backend/pkg/libarcane/edge/server_test.go b/backend/pkg/libarcane/edge/server_test.go
index 64350756a..ae26a704f 100644
--- a/backend/pkg/libarcane/edge/server_test.go
+++ b/backend/pkg/libarcane/edge/server_test.go
@@ -574,13 +574,16 @@ func TestTunnelServer_HandleEventCallback(t *testing.T) {
})
tunnel := NewAgentTunnelWithConn("env-edge", &fakeServerTunnelConn{})
+ deliveryTimer := time.NewTimer(streamDeliveryTimeout)
+ deliveryTimer.Stop()
+ defer deliveryTimer.Stop()
server.handleTunnelMessage(context.Background(), tunnel, &TunnelMessage{
Type: MessageTypeEvent,
Event: &TunnelEvent{
Type: "container.start",
Title: "Container started",
},
- })
+ }, deliveryTimer)
select {
case <-called:
diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.go
index bf9b319b5..e675ec03a 100644
--- a/backend/pkg/libarcane/edge/tls.go
+++ b/backend/pkg/libarcane/edge/tls.go
@@ -20,13 +20,13 @@ import (
"regexp"
"strconv"
"strings"
- "sync"
"syscall"
"time"
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
"go.getarcane.app/sys/atomic"
libcrypto "go.getarcane.app/sys/crypto"
@@ -54,7 +54,7 @@ const (
var generatedAssetNameSanitizer = regexp.MustCompile(`[^a-zA-Z0-9._-]+`)
-var managerCALocks sync.Map
+var managerCALocks utils.KeyedMutex
// BuildManagerServerTLSConfig returns the manager TLS configuration needed to
// support optional edge mTLS on the shared Arcane listener.
@@ -1066,15 +1066,11 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string)
}
lockPath := filepath.Join(absDir, lockName)
- muValue, _ := managerCALocks.LoadOrStore(lockPath, &sync.Mutex{})
- mu, ok := muValue.(*sync.Mutex)
- if !ok {
- return nil, errors.New("manager CA lock value is not *sync.Mutex")
- }
deadline := time.Now().Add(managerCALockTimeout)
for {
- if !mu.TryLock() {
+ unlock, held := managerCALocks.TryLock(lockPath)
+ if !held {
if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {
return nil, err
}
@@ -1086,22 +1082,26 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string)
_ = file.Close()
return func() {
_ = os.Remove(lockPath)
- mu.Unlock()
+ unlock()
}, nil
}
if !os.IsExist(err) {
- mu.Unlock()
+ unlock()
return nil, errors.WrapIf(err, "failed to acquire edge mTLS CA lock")
}
if time.Now().After(deadline) {
if removeStaleEdgeMTLSLockInternal(lockPath) {
+ // Retake the lock from the top; continuing while still holding it
+ // makes the next TryLock fail against ourselves and spin until the
+ // context is cancelled.
+ unlock()
deadline = time.Now().Add(managerCALockTimeout)
continue
}
- mu.Unlock()
+ unlock()
return nil, errors.Errorf("timed out waiting for edge mTLS CA lock %s", lockPath)
}
- mu.Unlock()
+ unlock()
if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {
return nil, err
}
diff --git a/backend/pkg/libarcane/edge/transport.go b/backend/pkg/libarcane/edge/transport.go
index 67d234dbc..ce1e76c71 100644
--- a/backend/pkg/libarcane/edge/transport.go
+++ b/backend/pkg/libarcane/edge/transport.go
@@ -142,16 +142,18 @@ func GetTunnelRuntimeState(envID string) mo.Option[*TunnelRuntimeState] {
return mo.None[*TunnelRuntimeState]()
}
- state := &TunnelRuntimeState{}
- state.Transport = tunnel.Conn.Transport()
-
- state.ConnectedAt = new(tunnel.ConnectedAt)
- state.LastHeartbeat = new(tunnel.GetLastHeartbeat())
- state.SessionID = tunnel.SessionID
- state.AgentInstance = tunnel.AgentInstance
- state.SecurityMode = tunnel.SecurityMode
- state.Capabilities = append([]string(nil), tunnel.Capabilities...)
- state.State = tunnel.State
-
- return mo.Some(state)
+ // One snapshot under a single read lock, so the reported fields all describe
+ // the same moment and none of them race the tunnel's writers.
+ meta := tunnel.MetadataSnapshot()
+
+ return mo.Some(&TunnelRuntimeState{
+ Transport: tunnel.Conn.Transport(),
+ ConnectedAt: new(meta.ConnectedAt),
+ LastHeartbeat: new(meta.LastHeartbeat),
+ SessionID: meta.SessionID,
+ AgentInstance: meta.AgentInstance,
+ SecurityMode: meta.SecurityMode,
+ Capabilities: meta.Capabilities,
+ State: meta.State,
+ })
}
diff --git a/backend/pkg/libarcane/edge/transport_test.go b/backend/pkg/libarcane/edge/transport_test.go
index 55f84c482..87b89c90f 100644
--- a/backend/pkg/libarcane/edge/transport_test.go
+++ b/backend/pkg/libarcane/edge/transport_test.go
@@ -391,7 +391,7 @@ func setupWebSocketBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel,
}()
return tunnel, func() {
- _ = tunnel.Close()
+ _ = tunnel.CloseWithReason("")
server.Close()
<-dispatchDone
}
diff --git a/backend/pkg/libarcane/edge/ws_proxy.go b/backend/pkg/libarcane/edge/ws_proxy.go
index 807d46b8d..59795c3ad 100644
--- a/backend/pkg/libarcane/edge/ws_proxy.go
+++ b/backend/pkg/libarcane/edge/ws_proxy.go
@@ -27,16 +27,28 @@ var wsUpgraderForProxy = websocket.Upgrader{
ReadBufferSize: 64 * 1024,
WriteBufferSize: 64 * 1024,
EnableCompression: true,
- CheckOrigin: func(r *http.Request) bool { return true },
}
// ProxyWebSocketRequest proxies a WebSocket upgrade through an edge tunnel.
// This handles logs, stats, and other streaming endpoints.
-func ProxyWebSocketRequest(c *echo.Context, tunnel *AgentTunnel, targetPath string) error {
+//
+// checkOrigin must be the same Origin validator the local WebSocket endpoints
+// use. It is required: the caller's session cookie has already been validated by
+// the time this runs, so accepting any Origin would let an attacker-controlled
+// page open a terminal or log stream in the tunnelled environment.
+func ProxyWebSocketRequest(c *echo.Context, tunnel *AgentTunnel, targetPath string, checkOrigin func(*http.Request) bool) error {
req := c.Request()
ctx := req.Context()
- clientWS, err := wsUpgraderForProxy.Upgrade(c.Response(), req, nil)
+ if checkOrigin == nil {
+ slog.ErrorContext(ctx, "Refusing edge WebSocket proxy without an origin validator", "path", targetPath)
+ return echo.NewHTTPError(http.StatusForbidden, "websocket origin validation unavailable")
+ }
+
+ proxyUpgrader := wsUpgraderForProxy
+ proxyUpgrader.CheckOrigin = checkOrigin
+
+ clientWS, err := proxyUpgrader.Upgrade(c.Response(), req, nil)
if err != nil {
slog.ErrorContext(ctx, "Failed to upgrade WebSocket for edge proxy", "error", err)
return nil
diff --git a/backend/pkg/libarcane/edge/ws_proxy_test.go b/backend/pkg/libarcane/edge/ws_proxy_test.go
index d64e4cfef..66390187f 100644
--- a/backend/pkg/libarcane/edge/ws_proxy_test.go
+++ b/backend/pkg/libarcane/edge/ws_proxy_test.go
@@ -70,7 +70,7 @@ func TestProxyWebSocketRequest(t *testing.T) {
}
tunnel := newWebSocketAgentTunnel("env-ws-proxy", agentConn)
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
// Start receiving on tunnel
go func() {
@@ -93,7 +93,7 @@ func TestProxyWebSocketRequest(t *testing.T) {
// Setup Manager
router := echo.New()
router.GET("/proxy-ws", func(c *echo.Context) error {
- return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
+ return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats", func(*http.Request) bool { return true })
})
proxyServer := httptest.NewServer(router)
@@ -148,7 +148,7 @@ func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
}
tunnel := newWebSocketAgentTunnel("env-ws-close", agentConn)
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
go func() {
for {
@@ -160,7 +160,7 @@ func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
router := echo.New()
router.GET("/proxy-ws", func(c *echo.Context) error {
- return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats")
+ return ProxyWebSocketRequest(c, tunnel, "/api/environments/0/ws/system/stats", func(*http.Request) bool { return true })
})
proxyServer := httptest.NewServer(router)
defer proxyServer.Close()
@@ -219,7 +219,7 @@ func TestSendWebSocketData(t *testing.T) {
defer func() { _ = conn.Close() }()
tunnel := newWebSocketAgentTunnel("env-helper", conn)
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
err = sendWebSocketData(tunnel, "test-stream", websocket.TextMessage, []byte("payload"))
require.NoError(t, err)
@@ -254,7 +254,7 @@ func TestSendWebSocketClose(t *testing.T) {
}
tunnel := newWebSocketAgentTunnel("env-helper-close", conn)
- defer func() { _ = tunnel.Close() }()
+ defer func() { _ = tunnel.CloseWithReason("") }()
sendWebSocketClose(tunnel, "test-stream")
}
diff --git a/backend/pkg/libarcane/ws/bridge.go b/backend/pkg/libarcane/ws/bridge.go
index 24560a35d..473d2d1b2 100644
--- a/backend/pkg/libarcane/ws/bridge.go
+++ b/backend/pkg/libarcane/ws/bridge.go
@@ -17,6 +17,8 @@ type LogMessage struct {
// ForwardLines forwards plain text lines to the hub.
func ForwardLines(ctx context.Context, hub *Hub, lines <-chan string) {
+ defer trackWorkerGoroutine()()
+
for {
select {
case <-ctx.Done():
@@ -32,6 +34,8 @@ func ForwardLines(ctx context.Context, hub *Hub, lines <-chan string) {
// ForwardLogJSON sends each LogMessage as its own JSON object frame.
func ForwardLogJSON(ctx context.Context, hub *Hub, logs <-chan LogMessage) {
+ defer trackWorkerGoroutine()()
+
for {
select {
case <-ctx.Done():
@@ -54,9 +58,12 @@ func ForwardLogJSON(ctx context.Context, hub *Hub, logs <-chan LogMessage) {
// Flushes when maxBatch reached or flushInterval elapsed.
func ForwardLogJSONBatched(ctx context.Context, hub *Hub, logs <-chan LogMessage, maxBatch int, flushInterval time.Duration) {
if maxBatch <= 1 {
+ // Delegates to ForwardLogJSON, which does its own accounting.
ForwardLogJSON(ctx, hub, logs)
return
}
+ defer trackWorkerGoroutine()()
+
ticker := time.NewTicker(flushInterval)
defer ticker.Stop()
diff --git a/backend/pkg/libarcane/ws/client.go b/backend/pkg/libarcane/ws/client.go
index 3d0cac90f..f94421e31 100644
--- a/backend/pkg/libarcane/ws/client.go
+++ b/backend/pkg/libarcane/ws/client.go
@@ -40,13 +40,28 @@ func NewClient(conn *websocket.Conn, sendBuffer int) *Client {
// ServeClientWithOnRemove registers the client with the hub and starts read/write pumps.
// Caller is responsible for creating/closing the websocket.Conn.
// If onRemove is non-nil, it is invoked when the client is removed from the hub.
-func ServeClientWithOnRemove(ctx context.Context, hub *Hub, conn *websocket.Conn, onRemove func()) {
+//
+// It reports whether registration succeeded. Registration fails when the hub's
+// Run has already exited (or ctx is done) — landing on that boundary used to
+// block forever on the unbuffered register channel, leaking the caller's
+// goroutine and the socket. On failure nothing is registered and onRemove is
+// never invoked, so the caller can retry against a fresh hub with the same
+// connection, or close it and release its own bookkeeping.
+func ServeClientWithOnRemove(ctx context.Context, hub *Hub, conn *websocket.Conn, onRemove func()) bool {
c := NewClient(conn, clientSendBuffer)
c.onRemove = onRemove
- hub.register <- c
+
+ select {
+ case hub.register <- c:
+ case <-hub.stopped:
+ return false
+ case <-ctx.Done():
+ return false
+ }
go c.writePump(ctx, hub)
go c.readPump(ctx, hub)
+ return true
}
func (c *Client) safeRemove(hub *Hub) {
@@ -59,6 +74,7 @@ func (c *Client) safeRemove(hub *Hub) {
}
func (c *Client) readPump(ctx context.Context, hub *Hub) {
+ defer trackWorkerGoroutine()()
// Ensure client is removed from hub without sending on a potentially
// unserviced channel. Use hub.remove which is safe when the hub has exited.
defer c.safeRemove(hub)
@@ -87,6 +103,8 @@ func (c *Client) readPump(ctx context.Context, hub *Hub) {
}
func (c *Client) writePump(ctx context.Context, hub *Hub) {
+ defer trackWorkerGoroutine()()
+
// Timer instead of Ticker: no drain-after-Stop, and we can reset after each ping
// so shutdown sees ctx.Done() without waiting for an extra tick.
pingTimer := time.NewTimer(pingPeriod)
diff --git a/backend/pkg/libarcane/ws/client_test.go b/backend/pkg/libarcane/ws/client_test.go
index f31a6ecee..00cdb20fc 100644
--- a/backend/pkg/libarcane/ws/client_test.go
+++ b/backend/pkg/libarcane/ws/client_test.go
@@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
"time"
@@ -252,3 +253,43 @@ func TestServeClient_MultipleMessages(t *testing.T) {
assert.Equal(t, expected, string(msg))
}
}
+
+// A reconnect can land on a hub whose Run has already exited (e.g. the idle
+// teardown fired between lookup and registration). That used to block forever
+// on the unbuffered register channel, leaking the caller's goroutine and the
+// socket; registration must now fail so the caller can retry with a fresh hub.
+func TestServeClient_StoppedHubDoesNotBlock(t *testing.T) {
+ h := NewHub(10)
+ ctx, cancel := context.WithCancel(t.Context())
+ stopped := make(chan struct{})
+ go func() {
+ defer close(stopped)
+ h.Run(ctx)
+ }()
+
+ cancel()
+ <-stopped
+
+ _, serverConn, cleanup := newTestWSPair(t)
+ defer cleanup()
+
+ var onRemoveCalled atomic.Bool
+ done := make(chan bool, 1)
+ go func() {
+ done <- ServeClientWithOnRemove(t.Context(), h, serverConn, func() {
+ onRemoveCalled.Store(true)
+ })
+ }()
+
+ select {
+ case registered := <-done:
+ assert.False(t, registered, "registration against a stopped hub must fail")
+ case <-time.After(2 * time.Second):
+ t.Fatal("ServeClientWithOnRemove blocked on a stopped hub")
+ }
+
+ // The caller owns the connection and its bookkeeping on failure, so it can
+ // retry the same conn against a fresh hub.
+ assert.False(t, onRemoveCalled.Load(), "onRemove must not run when registration fails")
+ assert.Equal(t, 0, h.ClientCount())
+}
diff --git a/backend/pkg/libarcane/ws/diagnostics.go b/backend/pkg/libarcane/ws/diagnostics.go
index e480ecb59..d037936d8 100644
--- a/backend/pkg/libarcane/ws/diagnostics.go
+++ b/backend/pkg/libarcane/ws/diagnostics.go
@@ -1,64 +1,28 @@
package ws
-import (
- "runtime"
- "strings"
- "time"
-
- "github.com/samber/hot"
-)
-
-const wsPkgPath = "internal/utils/ws"
-
-const workerGoroutineCountTTL = 5 * time.Second
-
-var workerGoroutineCountCache = hot.NewHotCache[struct{}, int](hot.LRU, 1).
- WithTTL(workerGoroutineCountTTL).
- Build()
+import "sync/atomic"
+
+// workerGoroutines tracks how many websocket worker goroutines this package is
+// currently running (hub loops, read/write pumps and log forwarders).
+//
+// This used to be derived by scanning a full runtime.Stack(buf, true) dump on a
+// 5s timer whenever a diagnostics client was connected — a stop-the-world pause
+// of up to 8MB plus a string split, just to produce one integer. It also matched
+// frames against a package path that no longer exists, so the reported number
+// had been zero regardless. Workers now account for themselves.
+var workerGoroutines atomic.Int64
+
+// trackWorkerGoroutine marks the calling goroutine as an active worker and
+// returns the function that releases it. Intended to be deferred immediately:
+//
+// defer trackWorkerGoroutine()()
+func trackWorkerGoroutine() func() {
+ workerGoroutines.Add(1)
+ return func() { workerGoroutines.Add(-1) }
+}
-// CountWorkerGoroutines returns a best-effort count of websocket worker goroutines
+// CountWorkerGoroutines returns the number of websocket worker goroutines
// belonging to this package. Intended for diagnostics endpoints only.
func CountWorkerGoroutines() int {
- count, found, err := workerGoroutineCountCache.GetWithLoaders(struct{}{}, func(_ []struct{}) (map[struct{}]int, error) {
- return map[struct{}]int{{}: countWorkerGoroutinesInternal()}, nil
- })
- if err != nil || !found {
- return countWorkerGoroutinesInternal()
- }
- return count
-}
-
-func countWorkerGoroutinesInternal() int {
- buf := make([]byte, 1<<20)
- for {
- n := runtime.Stack(buf, true)
- if n < len(buf) {
- buf = buf[:n]
- break
- }
- if len(buf) >= 8<<20 {
- buf = buf[:n]
- break
- }
- buf = make([]byte, len(buf)*2)
- }
-
- s := string(buf)
- blocks := strings.Split(s, "\n\n")
- count := 0
- for _, block := range blocks {
- if block == "" || !strings.Contains(block, wsPkgPath) {
- continue
- }
- if strings.Contains(block, ".Run(") ||
- strings.Contains(block, "readPump") ||
- strings.Contains(block, "writePump") ||
- strings.Contains(block, "ForwardLines") ||
- strings.Contains(block, "ForwardLogJSON") ||
- strings.Contains(block, "ForwardLogJSONBatched") {
- count++
- }
- }
-
- return count
+ return int(workerGoroutines.Load())
}
diff --git a/backend/pkg/libarcane/ws/hub.go b/backend/pkg/libarcane/ws/hub.go
index 4aa8abe53..49663411e 100644
--- a/backend/pkg/libarcane/ws/hub.go
+++ b/backend/pkg/libarcane/ws/hub.go
@@ -16,11 +16,16 @@ type Hub struct {
register chan *Client
unregister chan *Client
broadcast chan []byte
- onFirst func()
- onActive func()
- onEmpty func()
- dropped atomic.Uint64
- lastWarned atomic.Int64
+ // stopped is closed when Run returns, so registration attempts against a
+ // torn-down hub fail fast instead of blocking forever on the unbuffered
+ // register channel.
+ stopped chan struct{}
+ stoppedOnce sync.Once
+ onFirst func()
+ onActive func()
+ onEmpty func()
+ dropped atomic.Uint64
+ lastWarned atomic.Int64
}
func NewHub(buffer int) *Hub {
@@ -29,6 +34,7 @@ func NewHub(buffer int) *Hub {
register: make(chan *Client),
unregister: make(chan *Client),
broadcast: make(chan []byte, buffer),
+ stopped: make(chan struct{}),
}
}
@@ -51,7 +57,12 @@ func (h *Hub) SetOnEmpty(fn func()) {
}
func (h *Hub) Run(ctx context.Context) {
+ defer trackWorkerGoroutine()()
defer h.closeAll()
+ // Signalled before closeAll so a registration racing this shutdown fails fast
+ // instead of joining a hub that is already draining. stoppedOnce keeps it safe
+ // if Run is ever (incorrectly) started twice.
+ defer func() { h.stoppedOnce.Do(func() { close(h.stopped) }) }()
for {
select {
diff --git a/backend/pkg/libarcane/ws/proxy.go b/backend/pkg/libarcane/ws/proxy.go
index 252b7075f..cb31efe03 100644
--- a/backend/pkg/libarcane/ws/proxy.go
+++ b/backend/pkg/libarcane/ws/proxy.go
@@ -6,6 +6,7 @@ import (
"net/http"
"time"
+ "emperror.dev/errors"
"github.com/gorilla/websocket"
)
@@ -13,12 +14,23 @@ var upgrader = websocket.Upgrader{
ReadBufferSize: 32 * 1024,
WriteBufferSize: 32 * 1024,
EnableCompression: true,
- CheckOrigin: func(r *http.Request) bool { return true },
}
// ProxyHTTP upgrades the incoming client connection and bridges it to remoteWS.
-func ProxyHTTP(w http.ResponseWriter, r *http.Request, remoteWS string, header http.Header) error {
- clientConn, err := upgrader.Upgrade(w, r, nil)
+//
+// checkOrigin must be the same Origin validator the local WebSocket endpoints
+// use. It is required: this upgrade is reached with the caller's session cookie
+// already validated, so accepting any Origin would let an attacker-controlled
+// page open a terminal or log stream in a remote environment.
+func ProxyHTTP(w http.ResponseWriter, r *http.Request, remoteWS string, header http.Header, checkOrigin func(*http.Request) bool) error {
+ if checkOrigin == nil {
+ return errors.New("websocket proxy requires an origin validator")
+ }
+
+ proxyUpgrader := upgrader
+ proxyUpgrader.CheckOrigin = checkOrigin
+
+ clientConn, err := proxyUpgrader.Upgrade(w, r, nil)
if err != nil {
slog.Error("failed to upgrade client connection", "remoteWS", remoteWS, "err", err)
return err
diff --git a/backend/pkg/libarcane/ws/proxy_test.go b/backend/pkg/libarcane/ws/proxy_test.go
index 28bf4d8ed..12018429c 100644
--- a/backend/pkg/libarcane/ws/proxy_test.go
+++ b/backend/pkg/libarcane/ws/proxy_test.go
@@ -12,6 +12,15 @@ import (
"github.com/stretchr/testify/require"
)
+// allowAnyOriginForTest stands in for the caller-supplied Origin validator;
+// these tests exercise the proxy bridge, not the Origin policy.
+func allowAnyOriginForTest(*http.Request) bool { return true }
+
+func TestProxyHTTP_RequiresOriginValidator(t *testing.T) {
+ err := ProxyHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil), "ws://127.0.0.1:1", nil, nil)
+ require.Error(t, err, "proxy must refuse to upgrade without an origin validator")
+}
+
func TestProxyHTTP_BidirectionalMessages(t *testing.T) {
// 1. Create a "remote" WebSocket server that echoes messages
remoteServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -43,7 +52,7 @@ func TestProxyHTTP_BidirectionalMessages(t *testing.T) {
// 2. Create a "proxy" server that uses ProxyHTTP
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- _ = ProxyHTTP(w, r, remoteWS, nil)
+ _ = ProxyHTTP(w, r, remoteWS, nil, allowAnyOriginForTest)
}))
defer proxyServer.Close()
@@ -92,7 +101,7 @@ func TestProxyHTTP_RemoteClose(t *testing.T) {
proxyDone := make(chan error, 1)
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- proxyDone <- ProxyHTTP(w, r, remoteWS, nil)
+ proxyDone <- ProxyHTTP(w, r, remoteWS, nil, allowAnyOriginForTest)
}))
defer proxyServer.Close()
@@ -118,7 +127,7 @@ func TestProxyHTTP_RemoteClose(t *testing.T) {
func TestProxyHTTP_InvalidRemoteURL(t *testing.T) {
proxyDone := make(chan error, 1)
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- proxyDone <- ProxyHTTP(w, r, "ws://127.0.0.1:1", nil)
+ proxyDone <- ProxyHTTP(w, r, "ws://127.0.0.1:1", nil, allowAnyOriginForTest)
}))
defer proxyServer.Close()
@@ -169,7 +178,7 @@ func TestProxyHTTP_BinaryMessages(t *testing.T) {
remoteWS := "ws" + strings.TrimPrefix(remoteServer.URL, "http")
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- _ = ProxyHTTP(w, r, remoteWS, nil)
+ _ = ProxyHTTP(w, r, remoteWS, nil, allowAnyOriginForTest)
}))
defer proxyServer.Close()
@@ -217,7 +226,7 @@ func TestProxyHTTP_HeadersForwarded(t *testing.T) {
}
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- _ = ProxyHTTP(w, r, remoteWS, customHeaders)
+ _ = ProxyHTTP(w, r, remoteWS, customHeaders, allowAnyOriginForTest)
}))
defer proxyServer.Close()
diff --git a/backend/pkg/pagination/reflect.go b/backend/pkg/pagination/reflect.go
index 9ef4376e9..209c39317 100644
--- a/backend/pkg/pagination/reflect.go
+++ b/backend/pkg/pagination/reflect.go
@@ -43,9 +43,11 @@ func PaginateAndSortDB(params QueryParams, query *gorm.DB, result any) (Response
limit = 100
}
- page := (params.Start / limit) + 1
-
- return paginateDB(page, limit, query, result, params.SkipCount)
+ // The caller's offset is passed through as-is. Converting it to a page number
+ // and back rounded it down to a page boundary, so ?start=25&limit=20 returned
+ // rows 20-39 instead of 25-44 — and clamping limit above skewed it further,
+ // since the clamped limit divided a start computed from the requested one.
+ return paginateDB(params.Start, limit, query, result, params.SkipCount)
}
// paginateDBAll returns all results without pagination limits.
@@ -83,12 +85,18 @@ func paginateDBAll(query *gorm.DB, result any, skipCount bool) (Response, error)
// paginateDB applies offset/limit pagination. When skipCount is true the COUNT(*) is elided
// and TotalItems/TotalPages are returned as UnknownTotal.
// Count runs before Find so it sees a clean session (Find sets Statement.Dest in GORM v2).
-func paginateDB(page int, pageSize int, query *gorm.DB, result any, skipCount bool) (Response, error) {
- if page < 1 {
- page = 1
+func paginateDB(offset int, pageSize int, query *gorm.DB, result any, skipCount bool) (Response, error) {
+ if offset < 0 {
+ offset = 0
+ }
+ if pageSize < 1 {
+ pageSize = 1
}
- offset := (page - 1) * pageSize
+ // CurrentPage is a display value derived from the offset; the query itself
+ // uses the exact offset, so an offset that does not land on a page boundary
+ // is honoured rather than rounded.
+ page := (offset / pageSize) + 1
var totalItems int64
if !skipCount {
diff --git a/backend/pkg/pagination/skipcount_test.go b/backend/pkg/pagination/skipcount_test.go
index 3893f6a4d..a76538e20 100644
--- a/backend/pkg/pagination/skipcount_test.go
+++ b/backend/pkg/pagination/skipcount_test.go
@@ -68,3 +68,20 @@ func TestPaginateAndSortDB_SkipCountShowAll(t *testing.T) {
require.Equal(t, UnknownTotal, resp.TotalItems)
require.Equal(t, UnknownTotal, resp.TotalPages)
}
+
+// A start that does not land on a page boundary used to be rounded down to the
+// containing page: ?start=3&limit=2 returned rows 2-3 rather than 3-4.
+func TestPaginateAndSortDB_HonoursUnalignedStart(t *testing.T) {
+ db := newSkipCountTestDB(t)
+
+ var got []widget
+ resp, err := PaginateAndSortDB(QueryParams{
+ Params: Params{Start: 3, Limit: 2},
+ SortParams: SortParams{Sort: "Name", Order: "asc"},
+ }, db.Model(&widget{}), &got)
+ require.NoError(t, err)
+ require.Len(t, got, 2)
+ require.Equal(t, "D", got[0].Name, "offset 3 must return the 4th row, not the start of its page")
+ require.Equal(t, "E", got[1].Name)
+ require.Equal(t, int64(5), resp.TotalItems)
+}
diff --git a/backend/pkg/scheduler/auto_heal_job.go b/backend/pkg/scheduler/auto_heal_job.go
index 3fb72f819..116c3d191 100644
--- a/backend/pkg/scheduler/auto_heal_job.go
+++ b/backend/pkg/scheduler/auto_heal_job.go
@@ -3,8 +3,10 @@ package scheduler
import (
"context"
"log/slog"
+ "slices"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/moby/moby/api/types/container"
@@ -16,6 +18,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"go.getarcane.app/sys/cgroup"
)
@@ -33,6 +36,11 @@ type AutoHealJob struct {
eventService *services.EventService
notificationService *services.NotificationService
+ // running guards against overlapping cron ticks: inspecting every candidate
+ // can outlast the (as low as 30s) interval, and stacked runs re-evaluate the
+ // same unhealthy containers concurrently.
+ running atomic.Bool
+
mu sync.Mutex
restarts map[string]*restartRecord
@@ -91,6 +99,12 @@ func (j *AutoHealJob) Run(ctx context.Context) {
return
}
+ if !j.running.CompareAndSwap(false, true) {
+ slog.WarnContext(ctx, "auto-heal run still in progress; skipping overlapping run")
+ return
+ }
+ defer j.running.Store(false)
+
dockerClient, err := j.getDockerClientInternal(ctx)
if err != nil {
slog.ErrorContext(ctx, "auto-heal failed to get Docker client", "error", err)
@@ -116,7 +130,9 @@ func (j *AutoHealJob) Run(ctx context.Context) {
g.SetLimit(autoHealInspectConcurrency)
for _, candidate := range candidates {
- g.Go(func() error {
+ g.Go(func() (workerErr error) {
+ defer utils.RecoverToError(&workerErr, "auto-heal worker")
+
j.processCandidateInternal(groupCtx, dockerClient, candidate, maxRestarts, restartWindow, restartWindowMinutes)
return nil
})
@@ -195,7 +211,8 @@ func (j *AutoHealJob) processCandidateInternal(
return
}
- if !j.canRestart(containerID, maxRestarts, restartWindow) {
+ releaseSlot, reserved := j.reserveRestartSlotInternal(containerID, maxRestarts, restartWindow)
+ if !reserved {
slog.WarnContext(ctx, "auto-heal restart-loop protection: skipping container",
"container", containerName,
"max_restarts", maxRestarts,
@@ -205,11 +222,11 @@ func (j *AutoHealJob) processCandidateInternal(
}
if err := j.restartContainerInternal(ctx, dockerClient, containerID); err != nil {
+ releaseSlot()
slog.ErrorContext(ctx, "auto-heal failed to restart container", "container", containerName, "error", err)
return
}
- j.recordRestart(containerID)
j.postRestartActionsInternal(ctx, containerID, containerName)
slog.InfoContext(ctx, "auto-heal restarted unhealthy container", "container", containerName, "container_id", containerID)
@@ -243,21 +260,79 @@ func (j *AutoHealJob) Reschedule(ctx context.Context) error {
return nil
}
-// canRestart checks if a container can be restarted within the rate limit.
-func (j *AutoHealJob) canRestart(containerID string, maxRestarts int, window time.Duration) bool {
+// pruneRecordLockedInternal prunes expired timestamps for containerID and drops
+// the entry entirely when nothing recent remains, so restarts does not grow
+// without bound as containers come and go. Callers must hold j.mu.
+func (j *AutoHealJob) pruneRecordLockedInternal(containerID string, cutoff time.Time) *restartRecord {
+ record, exists := j.restarts[containerID]
+ if !exists {
+ return nil
+ }
+
+ record.timestamps = j.pruneTimestamps(record.timestamps, cutoff)
+ if len(record.timestamps) == 0 {
+ delete(j.restarts, containerID)
+ return nil
+ }
+ return record
+}
+
+// reserveRestartSlotInternal atomically checks the rate limit and claims a slot.
+// Checking and recording separately let two workers inspecting the same
+// container both pass the check and restart it past the configured limit.
+//
+// The returned release undoes the reservation, so a restart that fails does not
+// consume a slot — matching the previous behaviour of only counting restarts
+// that actually happened.
+func (j *AutoHealJob) reserveRestartSlotInternal(containerID string, maxRestarts int, window time.Duration) (func(), bool) {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+
+ record := j.pruneRecordLockedInternal(containerID, time.Now().Add(-window))
+ if record != nil && len(record.timestamps) >= maxRestarts {
+ return nil, false
+ }
+ if record == nil {
+ record = &restartRecord{}
+ j.restarts[containerID] = record
+ }
+
+ reserved := time.Now()
+ record.timestamps = append(record.timestamps, reserved)
+
+ return func() { j.releaseRestartSlotInternal(containerID, reserved) }, true
+}
+
+func (j *AutoHealJob) releaseRestartSlotInternal(containerID string, reserved time.Time) {
j.mu.Lock()
defer j.mu.Unlock()
record, exists := j.restarts[containerID]
if !exists {
- return true
+ return
+ }
+ for i, ts := range slices.Backward(record.timestamps) {
+ if ts.Equal(reserved) {
+ record.timestamps = append(record.timestamps[:i], record.timestamps[i+1:]...)
+ break
+ }
}
+ if len(record.timestamps) == 0 {
+ delete(j.restarts, containerID)
+ }
+}
- cutoff := time.Now().Add(-window)
- recent := j.pruneTimestamps(record.timestamps, cutoff)
- record.timestamps = recent
+// canRestart checks if a container can be restarted within the rate limit.
+func (j *AutoHealJob) canRestart(containerID string, maxRestarts int, window time.Duration) bool {
+ j.mu.Lock()
+ defer j.mu.Unlock()
+
+ record := j.pruneRecordLockedInternal(containerID, time.Now().Add(-window))
+ if record == nil {
+ return true
+ }
- return len(recent) < maxRestarts
+ return len(record.timestamps) < maxRestarts
}
// recordRestart records a restart timestamp for a container.
diff --git a/backend/pkg/scheduler/filesystem_watcher_job.go b/backend/pkg/scheduler/filesystem_watcher_job.go
index c1b3732f7..d17341d5e 100644
--- a/backend/pkg/scheduler/filesystem_watcher_job.go
+++ b/backend/pkg/scheduler/filesystem_watcher_job.go
@@ -61,13 +61,33 @@ func (j *FilesystemWatcherJob) Start(ctx context.Context) error {
followProjectSymlinks := settings.FollowProjectSymlinks.IsTrue()
j.logRecursiveProjectsWatchLimitWarningInternal(ctx, projectsDirectory)
- sw, err := fswatch.NewWatcher(projectsDirectory, j.projectWatcherOptionsInternal(followProjectSymlinks))
+ // Watchers are held locally until both are running, then published under the
+ // lock: assigning to j.projectsWatcher/j.templatesWatcher as they were built
+ // raced with Stop and RestartProjectsWatcher, and left every watcher created
+ // on a path that later failed holding its inotify/kqueue descriptors.
+ var projectsWatcher, templatesWatcher *fswatch.Watcher
+ published := false
+ defer func() {
+ if published {
+ return
+ }
+ // Startup failed somewhere below; release whatever was built. The job
+ // never took ownership of these, so nothing else will free them.
+ for _, watcher := range []*fswatch.Watcher{projectsWatcher, templatesWatcher} {
+ if watcher == nil {
+ continue
+ }
+ if stopErr := watcher.Stop(); stopErr != nil {
+ slog.ErrorContext(ctx, "Failed to stop watcher after startup error", "error", stopErr)
+ }
+ }
+ }()
+
+ projectsWatcher, err = fswatch.NewWatcher(projectsDirectory, j.projectWatcherOptionsInternal(followProjectSymlinks))
if err != nil {
return err
}
- j.projectsWatcher = sw
-
templatesDir, err := projects.GetTemplatesDirectory(ctx, settings.TemplatesDirectory.Value)
if err != nil {
return err
@@ -80,7 +100,7 @@ func (j *FilesystemWatcherJob) Start(ctx context.Context) error {
"projectsDirectory", projectsDirectory,
"templatesDirectory", templatesDir)
} else {
- tw, err := fswatch.NewWatcher(templatesDir, fswatch.WatcherOptions{
+ templatesWatcher, err = fswatch.NewWatcher(templatesDir, fswatch.WatcherOptions{
Debounce: 3 * time.Second,
OnChange: j.handleTemplatesChange,
MaxDepth: 1,
@@ -88,25 +108,27 @@ func (j *FilesystemWatcherJob) Start(ctx context.Context) error {
if err != nil {
return err
}
- j.templatesWatcher = tw
}
}
- if err := j.projectsWatcher.Start(ctx); err != nil {
+ if err := projectsWatcher.Start(ctx); err != nil {
return err
}
- if j.templatesWatcher != nil {
- if err := j.templatesWatcher.Start(ctx); err != nil {
- if stopErr := j.projectsWatcher.Stop(); stopErr != nil {
- slog.ErrorContext(ctx, "Failed to stop projects watcher after templates watcher start error", "error", stopErr)
- }
+ if templatesWatcher != nil {
+ if err := templatesWatcher.Start(ctx); err != nil {
return err
}
}
+ j.mu.Lock()
+ j.projectsWatcher = projectsWatcher
+ j.templatesWatcher = templatesWatcher
+ j.mu.Unlock()
+ published = true
+
slog.InfoContext(ctx, "Filesystem watcher started for projects directory",
"path", projectsDirectory)
- if j.templatesWatcher != nil {
+ if templatesWatcher != nil {
slog.InfoContext(ctx, "Filesystem watcher started for templates directory",
"path", templatesDir)
}
@@ -213,6 +235,9 @@ func (j *FilesystemWatcherJob) RestartProjectsWatcher(ctx context.Context) error
// Start the new watcher
if err := sw.Start(ctx); err != nil {
+ if stopErr := sw.Stop(); stopErr != nil {
+ slog.ErrorContext(ctx, "Failed to stop projects watcher after restart error", "error", stopErr)
+ }
return err
}
diff --git a/backend/pkg/scheduler/scheduler.go b/backend/pkg/scheduler/scheduler.go
index b71f654a1..2c7ee3e64 100644
--- a/backend/pkg/scheduler/scheduler.go
+++ b/backend/pkg/scheduler/scheduler.go
@@ -7,6 +7,7 @@ import (
"time"
"emperror.dev/errors"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"
"github.com/robfig/cron/v3"
"github.com/samber/mo"
@@ -78,6 +79,9 @@ func (js *JobScheduler) RegisterBusWatcher(watcher schedulertypes.BusWatcher, ca
}
js.watcherWG.Go(func() {
+ // A panic in a watcher goroutine would crash the process; contain it the
+ // same way scheduled job runs are contained.
+ defer utils.RecoverToError(nil, "bus watcher", "name", watcher.Name())
if err := watcher.Start(js.context); err != nil {
slog.ErrorContext(js.context, "Bus watcher failed", "name", watcher.Name(), "error", err)
}
@@ -275,6 +279,10 @@ func (js *JobScheduler) upsertJobInternal(ctx context.Context, job schedulertype
// lifecycle context. Callers must hold js.mu.
func (js *JobScheduler) addCronEntryInternal(job schedulertypes.Job, schedule string, parsedSchedule cron.Schedule) (cron.EntryID, *time.Time) {
entryID := js.cron.Schedule(parsedSchedule, cron.FuncJob(func() {
+ // robfig/cron has no default panic recovery, so a panic in any job would
+ // otherwise take down the whole process. Recovering here covers every
+ // scheduled job in one place.
+ defer utils.RecoverToError(nil, "scheduled job", "name", job.Name(), "schedule", schedule)
slog.InfoContext(js.context, "Job starting", "name", job.Name(), "schedule", schedule)
job.Run(js.context)
slog.InfoContext(js.context, "Job finished", "name", job.Name())
diff --git a/backend/pkg/utils/fingerprint.go b/backend/pkg/utils/fingerprint.go
new file mode 100644
index 000000000..68c579053
--- /dev/null
+++ b/backend/pkg/utils/fingerprint.go
@@ -0,0 +1,118 @@
+package utils
+
+import (
+ "encoding/binary"
+ "hash"
+ "hash/fnv"
+ "time"
+)
+
+// Fingerprint accumulates an order-sensitive 64-bit hash of arbitrary field
+// values. It exists for change detection: a poller that must decide "did
+// anything change since the last tick?" can hash the fields it cares about
+// instead of marshalling the whole payload to JSON and retaining the bytes just
+// to compare them on the next tick.
+//
+// Every method returns the receiver so a struct's fields read as one chain.
+// Opt* variants tag presence, keeping nil distinct from the zero value so
+// clearing a field is observed as a change.
+//
+// It is a change detector, not a checksum. FNV-1a is not collision resistant and
+// must never back a security or correctness decision.
+type Fingerprint struct {
+ h hash.Hash64
+}
+
+func NewFingerprint() *Fingerprint {
+ return &Fingerprint{h: fnv.New64a()}
+}
+
+// String hashes s followed by a separator, so adjacent fields cannot be
+// re-split ("ab"+"c" must not match "a"+"bc").
+func (f *Fingerprint) String(s string) *Fingerprint {
+ _, _ = f.h.Write([]byte(s))
+ _, _ = f.h.Write([]byte{0})
+ return f
+}
+
+func (f *Fingerprint) OptString(s *string) *Fingerprint {
+ if s == nil {
+ return f.Bool(false)
+ }
+ return f.Bool(true).String(*s)
+}
+
+// Strings hashes a string slice including its length, so resizing or reordering
+// changes the result.
+func (f *Fingerprint) Strings(items []string) *Fingerprint {
+ f.Int(int64(len(items)))
+ for _, item := range items {
+ f.String(item)
+ }
+ return f
+}
+
+func (f *Fingerprint) Bool(b bool) *Fingerprint {
+ if b {
+ _, _ = f.h.Write([]byte{1})
+ return f
+ }
+ _, _ = f.h.Write([]byte{0})
+ return f
+}
+
+func (f *Fingerprint) OptBool(b *bool) *Fingerprint {
+ if b == nil {
+ return f.Bool(false)
+ }
+ return f.Bool(true).Bool(*b)
+}
+
+func (f *Fingerprint) Int(v int64) *Fingerprint {
+ // Varint keeps the encoding signed end to end; a fixed-width write would
+ // need an int64→uint64 reinterpretation.
+ var buf [binary.MaxVarintLen64]byte
+ n := binary.PutVarint(buf[:], v)
+ _, _ = f.h.Write(buf[:n])
+ return f
+}
+
+func (f *Fingerprint) OptInt(v *int) *Fingerprint {
+ if v == nil {
+ return f.Bool(false)
+ }
+ return f.Bool(true).Int(int64(*v))
+}
+
+func (f *Fingerprint) Time(t time.Time) *Fingerprint {
+ return f.Int(t.UnixNano())
+}
+
+func (f *Fingerprint) OptTime(t *time.Time) *Fingerprint {
+ if t == nil {
+ return f.Bool(false)
+ }
+ return f.Bool(true).Time(*t)
+}
+
+// Present tags whether an optional nested value follows. Hash its fields only
+// when it reports true.
+func (f *Fingerprint) Present(ok bool) *Fingerprint {
+ return f.Bool(ok)
+}
+
+func (f *Fingerprint) Sum() uint64 {
+ return f.h.Sum64()
+}
+
+// FingerprintOf hashes a slice of items with a per-item writer, including the
+// slice length so resizing or reordering changes the result. The writer receives
+// a pointer so large structs are not copied per item.
+func FingerprintOf[T any](items []T, write func(*Fingerprint, *T)) uint64 {
+ f := NewFingerprint()
+ f.Int(int64(len(items)))
+ for i := range items {
+ write(f, &items[i])
+ }
+ return f.Sum()
+}
diff --git a/backend/pkg/utils/keyedmutex.go b/backend/pkg/utils/keyedmutex.go
new file mode 100644
index 000000000..c1ed1a790
--- /dev/null
+++ b/backend/pkg/utils/keyedmutex.go
@@ -0,0 +1,81 @@
+package utils
+
+import "sync"
+
+// KeyedMutex hands out one mutex per key, so unrelated keys proceed
+// concurrently while work on the same key is serialized.
+//
+// Entries are reference counted and dropped once nobody holds or awaits them.
+// The naive version of this — a sync.Map of *sync.Mutex — either grows one
+// entry per key ever seen, or, if entries are deleted on release, hands two
+// callers different mutexes for the same key and silently loses mutual
+// exclusion. The reference count is taken under the map lock, so a key with
+// waiters is never removed.
+//
+// The zero value is ready to use.
+type KeyedMutex struct {
+ mu sync.Mutex
+ locks map[string]*keyedMutexEntry
+}
+
+type keyedMutexEntry struct {
+ mu sync.Mutex
+ refs int
+}
+
+// reserve returns the entry for key with its reference count incremented.
+func (k *KeyedMutex) reserve(key string) *keyedMutexEntry {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+
+ if k.locks == nil {
+ k.locks = make(map[string]*keyedMutexEntry)
+ }
+ entry, ok := k.locks[key]
+ if !ok {
+ entry = &keyedMutexEntry{}
+ k.locks[key] = entry
+ }
+ entry.refs++
+ return entry
+}
+
+// release drops one reference and removes the entry when it reaches zero.
+func (k *KeyedMutex) release(key string, entry *keyedMutexEntry) {
+ k.mu.Lock()
+ defer k.mu.Unlock()
+
+ entry.refs--
+ if entry.refs == 0 && k.locks[key] == entry {
+ delete(k.locks, key)
+ }
+}
+
+// Lock blocks until the key's mutex is held and returns its unlock function.
+// Intended to be deferred at the point of acquisition:
+//
+// defer locks.Lock(id)()
+func (k *KeyedMutex) Lock(key string) func() {
+ entry := k.reserve(key)
+ entry.mu.Lock()
+
+ return func() {
+ entry.mu.Unlock()
+ k.release(key, entry)
+ }
+}
+
+// TryLock acquires the key's mutex without blocking. It reports whether the
+// lock was taken; the unlock function is only valid when it was.
+func (k *KeyedMutex) TryLock(key string) (func(), bool) {
+ entry := k.reserve(key)
+ if !entry.mu.TryLock() {
+ k.release(key, entry)
+ return nil, false
+ }
+
+ return func() {
+ entry.mu.Unlock()
+ k.release(key, entry)
+ }, true
+}
diff --git a/backend/pkg/utils/keyedmutex_test.go b/backend/pkg/utils/keyedmutex_test.go
new file mode 100644
index 000000000..843ffaa85
--- /dev/null
+++ b/backend/pkg/utils/keyedmutex_test.go
@@ -0,0 +1,61 @@
+package utils
+
+import (
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// The whole point of the reference count: releasing a key must not remove an
+// entry another goroutine is waiting on, or the two end up on different mutexes
+// and both enter the critical section.
+func TestKeyedMutexSerializesSameKey(t *testing.T) {
+ var locks KeyedMutex
+
+ inside := 0
+ maxInside := 0
+ var guard sync.Mutex
+
+ var wg sync.WaitGroup
+ for range 50 {
+ wg.Go(func() {
+ defer locks.Lock("image-1")()
+
+ guard.Lock()
+ inside++
+ if inside > maxInside {
+ maxInside = inside
+ }
+ guard.Unlock()
+
+ guard.Lock()
+ inside--
+ guard.Unlock()
+ })
+ }
+ wg.Wait()
+
+ require.Equal(t, 1, maxInside, "two goroutines held the same key at once")
+ require.Empty(t, locks.locks, "released keys must not accumulate")
+}
+
+func TestKeyedMutexTryLockDoesNotBlockOnHeldKey(t *testing.T) {
+ var locks KeyedMutex
+
+ unlock := locks.Lock("a")
+ if _, ok := locks.TryLock("a"); ok {
+ t.Fatal("TryLock acquired a key that is already held")
+ }
+
+ // A different key is unaffected.
+ otherUnlock, ok := locks.TryLock("b")
+ require.True(t, ok)
+ otherUnlock()
+
+ unlock()
+ retaken, ok := locks.TryLock("a")
+ require.True(t, ok, "key must be acquirable once released")
+ retaken()
+ require.Empty(t, locks.locks)
+}
diff --git a/backend/pkg/utils/path_util.go b/backend/pkg/utils/path_util.go
index f61999f84..82f0f66cd 100644
--- a/backend/pkg/utils/path_util.go
+++ b/backend/pkg/utils/path_util.go
@@ -1,12 +1,58 @@
package utils
import (
+ "os"
"path"
+ "path/filepath"
"strings"
"emperror.dev/errors"
)
+// IsWithinRoot reports whether target is root or lies beneath it. Both paths are
+// cleaned first; neither is resolved, so this only proves the *spelling* of the
+// path stays inside root. Use ResolveWithinRoot when a symlink could redirect it.
+func IsWithinRoot(root, target string) bool {
+ rootClean := filepath.Clean(root)
+ targetClean := filepath.Clean(target)
+ if targetClean == rootClean {
+ return true
+ }
+ return strings.HasPrefix(targetClean, rootClean+string(os.PathSeparator))
+}
+
+// ResolveWithinRoot resolves symlinks in both root and target and returns the
+// resolved target, verifying it stays inside root. A target that does not exist
+// yet is allowed: its parent is resolved instead, so create/write paths work.
+//
+// This is the check that makes containment real. A lexical test alone accepts a
+// symlink that sits inside root but points at /etc, which is then read, written
+// or removed through as if it were an in-root file.
+func ResolveWithinRoot(root, target string) (string, error) {
+ resolvedRoot, err := filepath.EvalSymlinks(filepath.Clean(root))
+ if err != nil {
+ return "", errors.WrapIff(err, "failed to resolve root directory %q", root)
+ }
+
+ cleanTarget := filepath.Clean(target)
+ resolved, err := filepath.EvalSymlinks(cleanTarget)
+ if err != nil {
+ if !os.IsNotExist(err) {
+ return "", errors.WrapIff(err, "failed to resolve path %q", target)
+ }
+ resolvedParent, parentErr := filepath.EvalSymlinks(filepath.Dir(cleanTarget))
+ if parentErr != nil {
+ return "", errors.WrapIff(parentErr, "failed to resolve parent directory of %q", target)
+ }
+ resolved = filepath.Join(resolvedParent, filepath.Base(cleanTarget))
+ }
+
+ if !IsWithinRoot(resolvedRoot, resolved) {
+ return "", errors.Errorf("path %q resolves outside %q", target, root)
+ }
+ return resolved, nil
+}
+
// SanitizeBrowsePath normalizes a path within a rooted file browser.
func SanitizeBrowsePath(input string) (string, error) {
trimmed := strings.TrimSpace(input)
diff --git a/backend/pkg/utils/recover.go b/backend/pkg/utils/recover.go
new file mode 100644
index 000000000..fea0a0387
--- /dev/null
+++ b/backend/pkg/utils/recover.go
@@ -0,0 +1,34 @@
+package utils
+
+import (
+ "log/slog"
+
+ "emperror.dev/emperror"
+ "emperror.dev/errors"
+)
+
+// RecoverToError converts a panic in the calling goroutine into an error and
+// logs it. x/sync's errgroup does not recover worker panics — they crash the
+// whole process — so every worker defers this as its first statement:
+//
+// g.Go(func() (workerErr error) {
+// defer utils.RecoverToError(&workerErr, "image list worker")
+// ...
+// })
+//
+// It must be deferred directly (not wrapped in another closure) for recover()
+// to observe the panic. errPtr may be nil when the caller has no error to
+// report into (e.g. a fire-and-forget goroutine); the panic is still logged.
+// args are extra slog attributes appended to the log record.
+func RecoverToError(errPtr *error, label string, args ...any) {
+ panicErr := emperror.Recover(recover())
+ if panicErr == nil {
+ return
+ }
+
+ err := errors.WrapIf(panicErr, label+" panicked")
+ slog.Error(label+" panicked", append([]any{"error", err}, args...)...)
+ if errPtr != nil {
+ *errPtr = err
+ }
+}