Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: use go.getarcane.app for common utilities (#4223)
Kyle Mendellbd98dbd289c0
diff --git a/.github/.golangci.yml b/.github/.golangci.ymlindex e85b65e63..d3648e4c5 100644--- a/.github/.golangci.yml+++ b/.github/.golangci.yml@@ -1,4 +1,4 @@-version: '2'+version: "2"run:tests: falsetimeout: 5m@@ -88,6 +88,8 @@ linters:- whitespace- zerologlintsettings:+ grouper:+ const-require-single-const: truecustom:shimbad:type: module@@ -117,13 +119,13 @@ linters:rules:- linters:- revive- text: 'var-naming:'+ text: "var-naming:"- linters:- revive- text: 'unused-parameter:'+ text: "unused-parameter:"- linters:- revive- text: 'exported:'+ text: "exported:"- linters:- forbidigopath: cli/@@ -131,22 +133,11 @@ linters:- linters:- shimbadpath: internal/types/endpoints\.go- paths:- - '.*\.pb\.go$'- - third_party$- - builtin$- - examples$issues:max-issues-per-linter: 0max-same-issues: 0formatters:enable:- - gofmt- - goimports+ - gofumptexclusions:generated: lax- paths:- - '.*\.pb\.go$'- - third_party$- - builtin$- - examples$diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 8fe2ddbb4..22917f97c 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -1,6 +1,8 @@{"go.buildTags": "playwright,buildables",+ "go.useLanguageServer": true,"gopls": {+ "formatting.gofumpt": true,"ui.diagnostic.analyses": {"stdversion": false}diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex fef782b15..5a388a173 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -17,9 +17,17 @@ Thanks for helping make Arcane better! We've built a modern, streamlined develop### Prerequisites-- **Docker & Docker Compose** (that's it! π)+- **Docker & Docker Compose**- **VS Code** based IDE (recommended for the best developer experience)- **[Vite+](https://viteplus.dev)** (`curl -fsSL https://vite.plus | bash`) β manages the Node toolchain, formatting, linting, and pre-commit hooks when working outside Docker+- **[goimports-reviser](https://github.com/incu6us/goimports-reviser) and [gofumpt](https://github.com/mvdan/gofumpt)** β required for Go import grouping and code formatting. Install both with Go:++ ```bash+ go install github.com/incu6us/goimports-reviser/v3@latest+ go install mvdan.cc/gofumpt@latest+ ```++ Make sure your Go binary directory is on `PATH`.> **π‘ Working Directory**: Unless otherwise specified, all commands in this guide should be run from the project root directory (`arcane/`).diff --git a/Justfile b/Justfileindex 21dbf37f2..2e0f58002 100644--- a/Justfile+++ b/Justfile@@ -5,6 +5,7 @@set working-directory := './'edge_proto_dir := 'backend/proto'+modules := './backend ./cli ./types'_default:@just --list@@ -233,7 +234,7 @@ test target="all":# Quality: format, lint, and fixes# ------------------------------------------------------------------------------# Format frontend/test/email TypeScript with vp fmt (Vite+) and Go modules with gofmt+# Format frontend/test/email TypeScript with vp fmt (Vite+) and Go modules with goimports-reviser and gofumpt[group('quality')]_format-frontend:vp fmt frontend@@ -245,9 +246,13 @@ _format-js:[group('quality')]_format-go:- cd backend && gofmt -s -w .- cd cli && gofmt -s -w .- cd types && gofmt -s -w .+ #!/usr/bin/env bash+ set -euo pipefail+ for module in {{ modules }}; do+ # A non-matching project name keeps all non-stdlib imports in one group.+ (cd "$module" && goimports-reviser -project-name . ./...)+ gofumpt -w -extra "$module"+ done[group('quality')]_format-just:@@ -267,7 +272,7 @@ _format-check-go:#!/usr/bin/env bashset -euo pipefail- unformatted=$(gofmt -l backend cli types)+ unformatted=$(gofumpt -l -extra {{ modules }})if [ -n "$unformatted" ]; thenecho "Unformatted Go files:"echo "$unformatted"@@ -277,7 +282,7 @@ _format-check-go:[group('quality')]_format-all:#!/usr/bin/env bash- # Run every formatter even if one fails, so e.g. a vp/pnpm hiccup can't skip gofmt+ # Run every formatter even if one fails, so e.g. a vp/pnpm hiccup can't skip gofumptfailed=0for target in frontend js go just; dojust "_format-${target}" || failed=1diff --git a/backend/api/api.go b/backend/api/api.goindex 3e683d631..dfdd0175e 100644--- a/backend/api/api.go+++ b/backend/api/api.go@@ -9,12 +9,18 @@ import ("reflect""strings"+ "github.com/danielgtaylor/huma/v2"+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"+ "github.com/getarcaneapp/arcane/backend/v2/api/handlers""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/apns""github.com/getarcaneapp/arcane/backend/v2/internal/appimages""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/build"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/dashboard""github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment"@@ -27,6 +33,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/imagepatch""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/job"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/network""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/oidc"@@ -39,33 +46,49 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/search""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/swarm"+ "github.com/getarcaneapp/arcane/backend/v2/internal/system""github.com/getarcaneapp/arcane/backend/v2/internal/systembackup""github.com/getarcaneapp/arcane/backend/v2/internal/template"+ "github.com/getarcaneapp/arcane/backend/v2/internal/updater"+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/internal/variable""github.com/getarcaneapp/arcane/backend/v2/internal/version"- "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"-- "github.com/danielgtaylor/huma/v2"- "github.com/danielgtaylor/huma/v2/adapters/humaecho"- "github.com/getarcaneapp/arcane/backend/v2/api/handlers"- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/container"- "github.com/getarcaneapp/arcane/backend/v2/internal/dashboard"- "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/system"- "github.com/getarcaneapp/arcane/backend/v2/internal/updater"- "github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/internal/volume"+ "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability""github.com/getarcaneapp/arcane/backend/v2/internal/webhook""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/labstack/echo/v5"+ kit "go.getarcane.app/kit/pkg""go.uber.org/fx")const (arcaneTypesPrefix = "github.com/getarcaneapp/arcane/types/v2/"dockerSDKPrefix = "github.com/moby/moby"++ // scalarDocsHTML returns the HTML template for Scalar API documentation.+ scalarDocsHTML = `<!doctype html>+<html>+ <head>+ <title>Arcane API Reference</title>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ </head>+ <body>+ <script+ id="api-reference"+ data-url="/api/openapi.json"+ data-configuration='{+ "theme": "purple",+ "darkMode": true,+ "layout": "modern",+ "hiddenClients": ["unirest"],+ "defaultHttpClient": { "targetKey": "shell", "clientKey": "curl" }+ }'></script>+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>+ </body>+</html>`)var dockerSchemaPrefixes = map[string]string{@@ -120,11 +143,7 @@ func packagePathForType(t reflect.Type) string {func shortPackageFromTypeString(typeStr string) string {before, _, ok := strings.Cut(typeStr, ".")- if !ok {- return ""- }-- return before+ return kit.Ternary(!ok, "", before)}func arcanePackageName(pkgPath string) (string, bool) {@@ -142,7 +161,7 @@ func arcanePackageName(pkgPath string) (string, bool) {return "", false}- return strings.ToUpper(pkg[:1]) + pkg[1:], true+ return kit.Capitalize(pkg), true}func dockerSchemaPrefix(pkgPath, shortPkg string) (string, bool) {@@ -201,7 +220,7 @@ func qualifyGenericArcaneArgumentsInternal(pkgPath, typeName, schemaName string)replacement := ""if innerPackage != outerPackage {- replacement = strings.ToUpper(innerPackage[:1]) + innerPackage[1:]+ replacement = kit.Capitalize(innerPackage)}argumentTypeIndex := prefixIndex + len(arcaneTypesPrefix) + separator + 1@@ -330,29 +349,6 @@ func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlerutil.ActivityAppreturn api}-// scalarDocsHTML returns the HTML template for Scalar API documentation.-const scalarDocsHTML = `<!doctype html>-<html>- <head>- <title>Arcane API Reference</title>- <meta charset="utf-8" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- </head>- <body>- <script- id="api-reference"- data-url="/api/openapi.json"- data-configuration='{- "theme": "purple",- "darkMode": true,- "layout": "modern",- "hiddenClients": ["unirest"],- "defaultHttpClient": { "targetKey": "shell", "clientKey": "curl" }- }'></script>- <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>- </body>-</html>`-// registerScalarDocs adds the Scalar API documentation endpoint.func registerScalarDocs(apiGroup *echo.Group) {apiGroup.GET("/docs", func(c *echo.Context) error {diff --git a/backend/api/api_test.go b/backend/api/api_test.goindex c64ea223c..6ff56f7ae 100644--- a/backend/api/api_test.go+++ b/backend/api/api_test.go@@ -87,7 +87,6 @@ func TestCustomSchemaNamer_PrefixesArcaneTypesByPackage(t *testing.T) {require.Equal(t, "EnvSummary", envName,"expected EnvSummary, got %q", envName)-}func TestCustomSchemaNamer_PointerMatchesValue(t *testing.T) {@@ -102,7 +101,6 @@ func TestCustomSchemaNamer_PointerMatchesValue(t *testing.T) {require.Equal(t, genericPointerName, genericValueName,"expected generic pointer and value names to match, got %q and %q", genericValueName, genericPointerName)-}func TestCustomSchemaNamer_PrefixesDockerTypes(t *testing.T) {@@ -110,7 +108,6 @@ func TestCustomSchemaNamer_PrefixesDockerTypes(t *testing.T) {require.True(t, strings.HasPrefix(name, "DockerNetwork"),"expected DockerNetwork prefix, got %q", name)-}func TestCustomSchemaNamer_DisambiguatesGenericDomainTypes(t *testing.T) {@@ -152,7 +149,6 @@ func TestCustomSchemaNamer_DisambiguatesGenericDomainTypes(t *testing.T) {require.Equal(t, "BasePaginatedWithCountsSummaryImageSummary", mixedPackages,"expected only the Arcane argument to be qualified in place, got %q", mixedPackages)-}func TestHandlerDeps_ZeroValue(t *testing.T) {@@ -172,7 +168,6 @@ func TestSetupAPIForSpec_DefaultSecurity(t *testing.T) {require.True(t, reflect.DeepEqual(api.OpenAPI().Security, expectedSecurity),"expected default API security %v, got %v", expectedSecurity, api.OpenAPI().Security)-}func TestSetupAPIForSpecUsesV2JSONFormats(t *testing.T) {@@ -196,7 +191,6 @@ func TestSetupAPIForSpecUsesV2JSONFormats(t *testing.T) {require.Equal(t, want, got,"marshal %s = %s, want %s", contentType, got, want)}-})}}@@ -219,7 +213,6 @@ func TestSetupAPIForSpecPreservesDurationNanoseconds(t *testing.T) {require.Equal(t, want, got,"marshal duration = %s, want %s", got, want)}-}func TestSetupAPIForSpec_PublicRoutesOverrideSecurity(t *testing.T) {@@ -282,7 +275,6 @@ func TestSetupAPIForSpec_PublicRoutesOverrideSecurity(t *testing.T) {require.Empty(t, operation.Security,"expected operation %s %s to be public, got security %v", testCase.method, testCase.path, operation.Security)-})}}@@ -316,7 +308,6 @@ func TestSetupAPIForSpec_TemplateReadRoutesProtected(t *testing.T) {require.True(t, reflect.DeepEqual(api.OpenAPI().Security, expectedSecurity),"expected API security %v, got %v", expectedSecurity, api.OpenAPI().Security)-})}}@@ -331,7 +322,6 @@ func TestSetupAPIForSpec_DoesNotRegisterPublicCreateEvent(t *testing.T) {require.Nil(t, pathItem.Post,"expected POST /events to be absent from the public API")-}func TestVariableMaterializationRoutesAreAgentOnly(t *testing.T) {diff --git a/backend/api/buildables.go b/backend/api/buildables.goindex adb7ef827..a62c763bc 100644--- a/backend/api/buildables.go+++ b/backend/api/buildables.go@@ -7,15 +7,14 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/buildables""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"authtypes "github.com/getarcaneapp/arcane/types/v2/auth""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/user""github.com/labstack/echo/v5"+ "go.getarcane.app/kit/pkg/mapping")// SetupBuildablesRoutes registers buildable feature routes based on EnabledFeatures.@@ -81,7 +80,7 @@ func registerAutoLoginRoutes(apiGroup *echo.Group, authService *auth.AuthService}var userResp user.User- if mapErr := mapper.MapStruct(userModel, &userResp); mapErr != nil {+ if mapErr := mapping.MapStruct(userModel, &userResp); mapErr != nil {return c.JSON(http.StatusInternalServerError, base.ErrorResponse{Error: "Failed to map user"})}diff --git a/backend/api/handlers/diagnostics.go b/backend/api/handlers/diagnostics.goindex fd66cb351..d080af530 100644--- a/backend/api/handlers/diagnostics.go+++ b/backend/api/handlers/diagnostics.go@@ -6,7 +6,6 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"diff --git a/backend/api/json_serializer.go b/backend/api/json_serializer.goindex 4ad52e4dc..1e3130b81 100644--- a/backend/api/json_serializer.go+++ b/backend/api/json_serializer.go@@ -8,7 +8,6 @@ import ("net/http""emperror.dev/errors"-"github.com/labstack/echo/v5""go.getarcane.app/kit/normalization")diff --git a/backend/api/json_serializer_test.go b/backend/api/json_serializer_test.goindex cb3237c08..fb2bc7382 100644--- a/backend/api/json_serializer_test.go+++ b/backend/api/json_serializer_test.go@@ -32,7 +32,6 @@ func TestJSONV2SerializerUsesV2ResponseSemantics(t *testing.T) {require.Equal(t, want, got,"serialized response = %s, want %s", got, want)}-}func TestJSONV2SerializerPreservesDurationNanoseconds(t *testing.T) {@@ -54,7 +53,6 @@ func TestJSONV2SerializerPreservesDurationNanoseconds(t *testing.T) {require.Equal(t, want, got,"serialized response = %s, want %s", got, want)}-}func TestJSONV2SerializerUsesStrictV2Decoding(t *testing.T) {@@ -74,7 +72,6 @@ func TestJSONV2SerializerUsesStrictV2Decoding(t *testing.T) {require.Empty(t, body.Name,"case-variant field populated Name with %q", body.Name)-})for _, test := range []struct {@@ -98,7 +95,6 @@ func TestJSONV2SerializerUsesStrictV2Decoding(t *testing.T) {require.Equal(t, http.StatusBadRequest, httpErr.StatusCode(),"HTTP status = %d, want %d", httpErr.StatusCode(), http.StatusBadRequest)-})}}diff --git a/backend/api/normalization_test.go b/backend/api/normalization_test.goindex df2d159c6..fe46f1140 100644--- a/backend/api/normalization_test.go+++ b/backend/api/normalization_test.go@@ -233,7 +233,8 @@ func TestNormalizationRejectsInvalidTagsAtRegistration(t *testing.T) {Body struct {Name string `json:"name" unorm:"invalid"`}- }) (*struct{}, error) {+ },+ ) (*struct{}, error) {return nil, nil})})diff --git a/backend/api/webhooks_trigger.go b/backend/api/webhooks_trigger.goindex 157f34c48..58ce90472 100644--- a/backend/api/webhooks_trigger.go+++ b/backend/api/webhooks_trigger.go@@ -4,7 +4,6 @@ import ("net/http""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/webhook""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/api/ws/container_stats.go b/backend/api/ws/container_stats.goindex 89c92c37c..8bd731a80 100644--- a/backend/api/ws/container_stats.go+++ b/backend/api/ws/container_stats.go@@ -10,10 +10,9 @@ import ("time""emperror.dev/errors"- "github.com/labstack/echo/v5"-wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"systemtypes "github.com/getarcaneapp/arcane/types/v2/system"+ "github.com/labstack/echo/v5")// ============================================================================diff --git a/backend/api/ws/diagnostics.go b/backend/api/ws/diagnostics.goindex 482f80320..87fdff629 100644--- a/backend/api/ws/diagnostics.go+++ b/backend/api/ws/diagnostics.go@@ -8,10 +8,9 @@ import ("net/http/pprof""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics"-"github.com/coder/websocket""github.com/getarcaneapp/arcane/backend/v2/internal/auth"+ "github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"@@ -20,13 +19,13 @@ import ("go.getarcane.app/streams/logs")-// 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 the writer forever,-// which also strands the writer's deferred cleanup (log subscription, conn).const (+ // diagnosticsStreamInterval is how often the live diagnostics stream pushes a snapshot.+ diagnosticsStreamInterval = 2 * time.Second++ // Keepalive/liveness bounds for the diagnostics sockets, mirroring the system+ // stats stream. Without them a silently dead peer wedges the writer forever,+ // which also strands the writer's deferred cleanup (log subscription, conn).diagnosticsReadLimit = 512diagnosticsWriteWait = 10 * time.SeconddiagnosticsPingWait = 10 * time.Seconddiff --git a/backend/api/ws/exec.go b/backend/api/ws/exec.goindex 337098200..b1d476b8d 100644--- a/backend/api/ws/exec.go+++ b/backend/api/ws/exec.go@@ -12,10 +12,9 @@ import ("emperror.dev/errors""github.com/coder/websocket"- "github.com/labstack/echo/v5"-wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"systemtypes "github.com/getarcaneapp/arcane/types/v2/system"+ "github.com/labstack/echo/v5")// ============================================================================diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.goindex 449c6a409..75bc1d1cf 100644--- a/backend/api/ws/handler.go+++ b/backend/api/ws/handler.go@@ -9,9 +9,6 @@ import ("time""github.com/coder/websocket"- "github.com/labstack/echo/v5"- "github.com/samber/hot"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -25,6 +22,8 @@ import (wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"httputil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"systemtypes "github.com/getarcaneapp/arcane/types/v2/system"+ "github.com/labstack/echo/v5"+ "github.com/samber/hot""go.getarcane.app/sys/cgroup")diff --git a/backend/api/ws/log_streams.go b/backend/api/ws/log_streams.goindex ed4c0a48e..e3a4a6067 100644--- a/backend/api/ws/log_streams.go+++ b/backend/api/ws/log_streams.go@@ -12,10 +12,9 @@ import ("time""emperror.dev/errors"- "github.com/labstack/echo/v5"-wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"systemtypes "github.com/getarcaneapp/arcane/types/v2/system"+ "github.com/labstack/echo/v5")// ============================================================================@@ -171,7 +170,7 @@ func (h *WebSocketHandler) serveLogStreamInternal(// broadcastLogStreamErrorInternal emits an error message to every client of a log stream.// resourceLabel is the human-readable noun used in slog/error text (e.g. "project log stream").// errorPrefix is the user-facing message prefix (e.g. "Failed to stream project logs: ").-func broadcastLogStreamErrorInternal(resourceLabel, errorPrefix string, resourceID string, format string, err error, ls *wsLogStream) {+func broadcastLogStreamErrorInternal(resourceLabel, errorPrefix, resourceID, format string, err error, ls *wsLogStream) {slog.Warn(resourceLabel+" failed", "resourceID", resourceID, "error", err)if format == "json" {diff --git a/backend/api/ws/proxy_permissions.go b/backend/api/ws/proxy_permissions.goindex a6c07589d..2f2357f00 100644--- a/backend/api/ws/proxy_permissions.go+++ b/backend/api/ws/proxy_permissions.go@@ -3,9 +3,8 @@ package wsimport ("net/http"- "github.com/labstack/echo/v5"-"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/labstack/echo/v5")// proxiedWSRoute couples a proxied WebSocket route (relative to thediff --git a/backend/api/ws/system_stats.go b/backend/api/ws/system_stats.goindex 0f1c4db44..65f1bcac2 100644--- a/backend/api/ws/system_stats.go+++ b/backend/api/ws/system_stats.go@@ -11,15 +11,15 @@ import ("time""github.com/coder/websocket"+ httputil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+ systemtypes "github.com/getarcaneapp/arcane/types/v2/system""github.com/labstack/echo/v5""github.com/samber/hot""github.com/shirou/gopsutil/v4/cpu""github.com/shirou/gopsutil/v4/disk""github.com/shirou/gopsutil/v4/host""github.com/shirou/gopsutil/v4/mem"-- httputil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"- systemtypes "github.com/getarcaneapp/arcane/types/v2/system"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup")@@ -515,8 +515,5 @@ func (h *WebSocketHandler) getDiskUsagePath(ctx context.Context) string {}return map[struct{}]string{{}: path}, nil})- if err != nil || !found {- return "/"- }- return path+ return kit.Ternary(err != nil || !found, "/", path)}diff --git a/backend/api/ws/system_stats_test.go b/backend/api/ws/system_stats_test.goindex fa105efe8..7d16040d1 100644--- a/backend/api/ws/system_stats_test.go+++ b/backend/api/ws/system_stats_test.go@@ -6,9 +6,8 @@ import ("testing""time"- "github.com/stretchr/testify/require"-systemtypes "github.com/getarcaneapp/arcane/types/v2/system"+ "github.com/stretchr/testify/require")func TestApplyCPUAffinityLimitInternal(t *testing.T) {diff --git a/backend/cli/admin/reset_mfa.go b/backend/cli/admin/reset_mfa.goindex de1859356..7842fe6fa 100644--- a/backend/cli/admin/reset_mfa.go+++ b/backend/cli/admin/reset_mfa.go@@ -8,13 +8,12 @@ import ("strings""emperror.dev/errors"- "github.com/spf13/cobra"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/passkey""github.com/getarcaneapp/arcane/backend/v2/internal/user"+ "github.com/spf13/cobra")var resetMFAUsername stringdiff --git a/backend/cli/admin/reset_mfa_test.go b/backend/cli/admin/reset_mfa_test.goindex a07eb180c..dcf862dc7 100644--- a/backend/cli/admin/reset_mfa_test.go+++ b/backend/cli/admin/reset_mfa_test.go@@ -1,23 +1,20 @@package adminimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"bytes""context""testing""time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/passkey""github.com/getarcaneapp/arcane/backend/v2/internal/session"-+ "github.com/getarcaneapp/arcane/types/v2/auth""github.com/libtnb/sqlite""github.com/stretchr/testify/require""gorm.io/gorm"-- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/types/v2/auth")func newResetMFATestDBInternal(t *testing.T) *database.DB {diff --git a/backend/cli/admin/reset_password.go b/backend/cli/admin/reset_password.goindex 0ea6d99ed..82fd4d659 100644--- a/backend/cli/admin/reset_password.go+++ b/backend/cli/admin/reset_password.go@@ -1,8 +1,6 @@package adminimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"context""fmt""io"@@ -11,15 +9,16 @@ import ("strings""emperror.dev/errors"- "github.com/spf13/cobra"- "golang.org/x/term"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"+ "github.com/spf13/cobra"+ kit "go.getarcane.app/kit/pkg"+ "golang.org/x/term")const defaultAdminUsername = "arcane"@@ -141,10 +140,7 @@ func validatePasswordPairInternal(password, confirmation, policy string) error {func passwordPolicyFromDBInternal(ctx context.Context, db *database.DB) string {var setting settings.SettingVariableerr := db.WithContext(ctx).First(&setting, "key = ?", "authPasswordPolicy").Error- if err != nil || strings.TrimSpace(setting.Value) == "" {- return validation.PasswordPolicyStrong- }- return setting.Value+ return kit.Ternary(err != nil || strings.TrimSpace(setting.Value) == "", validation.PasswordPolicyStrong, setting.Value)}func resetPasswordInternal(ctx context.Context, db *database.DB, username, password, policy string) error {diff --git a/backend/cli/admin/reset_password_test.go b/backend/cli/admin/reset_password_test.goindex 5b4aff201..c44ab2ed9 100644--- a/backend/cli/admin/reset_password_test.go+++ b/backend/cli/admin/reset_password_test.go@@ -1,16 +1,11 @@package adminimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role"@@ -19,6 +14,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation""github.com/getarcaneapp/arcane/types/v2/auth"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm")func newResetPasswordTestDBInternal(t *testing.T) *database.DB {diff --git a/backend/cli/generate/api_key_test.go b/backend/cli/generate/api_key_test.goindex cf7e533e0..806c1242e 100644--- a/backend/cli/generate/api_key_test.go+++ b/backend/cli/generate/api_key_test.go@@ -27,5 +27,4 @@ func TestAPIKeyCommandAvailableInBackendCLI(t *testing.T) {require.NotContains(t, out, "ADMIN_STATIC_API_KEY","expected raw arc_ key in output, got: %q", out)-}diff --git a/backend/cli/generate/secret_test.go b/backend/cli/generate/secret_test.goindex 885727d7a..28943875c 100644--- a/backend/cli/generate/secret_test.go+++ b/backend/cli/generate/secret_test.go@@ -99,10 +99,8 @@ func TestSecretAllFormatContainsSections(t *testing.T) {"HEX",}for _, s := range mustContain {-require.Contains(t, out, s,"expected section %q not found in output:\n%s", s, out)-}// verify the hex value decodes to 32 bytesdiff --git a/backend/cli/health.go b/backend/cli/health.goindex fde7ccfa8..1992417d9 100644--- a/backend/cli/health.go+++ b/backend/cli/health.go@@ -1,6 +1,7 @@package cliimport (+ "cmp""context""net""net/http"@@ -10,7 +11,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/spf13/cobra")@@ -47,10 +47,7 @@ func buildHealthURLInternal(cfg *config.Config) (string, error) {return "", errors.New("health config is nil")}- port := strings.TrimSpace(cfg.Port)- if port == "" {- port = defaultHealthPort- }+ port := cmp.Or(strings.TrimSpace(cfg.Port), defaultHealthPort)if _, err := strconv.Atoi(port); err != nil {return "", errors.WrapIff(err, "invalid health port %q", port)}diff --git a/backend/cli/health_test.go b/backend/cli/health_test.goindex 87c1661ea..83ac350b2 100644--- a/backend/cli/health_test.go+++ b/backend/cli/health_test.go@@ -28,7 +28,6 @@ func TestBuildHealthURLInternalDefaults(t *testing.T) {require.True(t, strings.HasSuffix(healthURL, "/api/health"),"expected health URL path /api/health, got: %s", healthURL)-})t.Run("explicit_port", func(t *testing.T) {@@ -40,7 +39,6 @@ func TestBuildHealthURLInternalDefaults(t *testing.T) {require.True(t, strings.HasPrefix(healthURL, "http://127.0.0.1:8443"),"unexpected health URL: %s", healthURL)-})}@@ -50,7 +48,6 @@ func TestBuildHealthURLInternalInvalidPort(t *testing.T) {require.Error(t, err,"expected invalid health URL port to fail")-}func TestRunHealthCommandInternal(t *testing.T) {@@ -88,7 +85,6 @@ func TestRunHealthCommandInternal(t *testing.T) {require.NoError(t, err,"health command failed: %v", err)}-}func TestRunHealthCommandInternalNon2xx(t *testing.T) {@@ -114,7 +110,6 @@ func TestRunHealthCommandInternalNon2xx(t *testing.T) {require.Contains(t, err.Error(), "health check failed with status","unexpected error: %v", err)-}func TestRunHealthCommandInternalConnectionFailure(t *testing.T) {@@ -122,7 +117,6 @@ func TestRunHealthCommandInternalConnectionFailure(t *testing.T) {require.Error(t, err,"expected connection failure")-}func TestRunHealthCommandInternalDefaultTimeoutFallback(t *testing.T) {@@ -138,5 +132,4 @@ func TestRunHealthCommandInternalDefaultTimeoutFallback(t *testing.T) {require.Contains(t, fmt.Sprint(defaultHealthTimeout), "5s","unexpected default timeout: %s", defaultHealthTimeout)-}diff --git a/backend/cli/recovery/recovery.go b/backend/cli/recovery/recovery.goindex b9ca4fa32..33e6f32eb 100644--- a/backend/cli/recovery/recovery.go+++ b/backend/cli/recovery/recovery.go@@ -1,6 +1,7 @@package recoveryimport (+ "cmp""context""encoding/json/v2""fmt"@@ -10,16 +11,12 @@ import ("time""emperror.dev/errors"- "gorm.io/gorm"- "gorm.io/gorm/clause"-"github.com/getarcaneapp/arcane/backend/v2/cli/upgrade""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/systembackup"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"rusticruntime "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/rustic"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"@@ -29,6 +26,9 @@ import ("github.com/moby/moby/api/types/mount""github.com/moby/moby/client""github.com/spf13/cobra"+ "go.getarcane.app/docker/compat"+ "gorm.io/gorm"+ "gorm.io/gorm/clause")const rusticImage = rusticruntime.DefaultImage@@ -65,7 +65,7 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {return fmt.Errorf("connect to Docker: %w", err)}defer func() { _ = dockerClient.Close() }()- inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, request.ContainerID, client.ContainerInspectOptions{})+ inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, request.ContainerID, client.ContainerInspectOptions{})if err != nil {return fmt.Errorf("inspect Arcane container: %w", err)}@@ -117,9 +117,7 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {}// Projects were restored into the current directory, so the recovered// configuration must keep pointing there rather than at the backup-time path.- if request.ProjectsSetting != "" {- manifest.Environment["PROJECTS_DIRECTORY"] = request.ProjectsSetting- }+ manifest.Environment["PROJECTS_DIRECTORY"] = cmp.Or(request.ProjectsSetting, manifest.Environment["PROJECTS_DIRECTORY"])if err := finalizeRestoredBackupInternal(ctx, manifest.Environment["DATABASE_URL"], manifest.BackupID, manifest.ActivityID, request); err != nil {restart()return fmt.Errorf("finalize restored system backup: %w", err)diff --git a/backend/cli/root.go b/backend/cli/root.goindex fa8083cc7..7bf427f77 100644--- a/backend/cli/root.go+++ b/backend/cli/root.go@@ -5,21 +5,20 @@ import ("log/slog""os"- "github.com/spf13/cobra"-"github.com/getarcaneapp/arcane/backend/v2/cli/admin""github.com/getarcaneapp/arcane/backend/v2/cli/generate""github.com/getarcaneapp/arcane/backend/v2/cli/recovery""github.com/getarcaneapp/arcane/backend/v2/cli/upgrade""github.com/getarcaneapp/arcane/backend/v2/internal/bootstrap""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/signals"+ "github.com/spf13/cobra"+ "go.getarcane.app/kit/pkg/signals")var rootCmd = &cobra.Command{Use: "arcane",Long: "Arcane - Modern Docker Management, Designed for Everyone.",- Version: getVersion(),+ Version: config.Version,Run: func(cmd *cobra.Command, args []string) {err := bootstrap.Bootstrap(cmd.Context())if err != nil {@@ -45,7 +44,3 @@ func init() {rootCmd.AddCommand(recovery.RestoreCmd)rootCmd.AddCommand(generate.GenerateCmd)}--func getVersion() string {- return config.Version-}diff --git a/backend/cli/upgrade/logfile.go b/backend/cli/upgrade/logfile.goindex c26caa1fb..7d523476c 100644--- a/backend/cli/upgrade/logfile.go+++ b/backend/cli/upgrade/logfile.go@@ -14,6 +14,7 @@ import ("time""go.getarcane.app/acfs/atomic"+ kit "go.getarcane.app/kit/pkg")const logFilePerm = 0o644@@ -59,7 +60,7 @@ func (w *LogWriter) Name() string { return w.path }// output to a timestamped file under dataDir. Every entry is persisted as it is// logged, so the returned writer needs no closing -- it is returned so the// caller can report where the log landed.-func SetupMessageOnlyLogFile(dataDir string, filePrefix string, minLevel slog.Level) (*LogWriter, error) {+func SetupMessageOnlyLogFile(dataDir, filePrefix string, minLevel slog.Level) (*LogWriter, error) {if strings.TrimSpace(dataDir) == "" {return nil, errors.New("dataDir is required")}@@ -171,10 +172,7 @@ func formatSlogValue(v slog.Value) string {case slog.KindDuration:return strconv.Quote(v.Duration().String())case slog.KindBool:- if v.Bool() {- return "true"- }- return "false"+ return kit.Ternary(v.Bool(), "true", "false")case slog.KindGroup:return strconv.Quote(fmt.Sprint(v.Group()))case slog.KindLogValuer:diff --git a/backend/cli/upgrade/logfile_test.go b/backend/cli/upgrade/logfile_test.goindex a33b19be8..3ccbdb202 100644--- a/backend/cli/upgrade/logfile_test.go+++ b/backend/cli/upgrade/logfile_test.go@@ -33,5 +33,4 @@ func TestSetupMessageOnlyLogFile(t *testing.T) {require.False(t, !strings.Contains(got, "container updated") || !strings.Contains(got, `container="web"`),"log file content = %q, want message-only entry with attrs", got)-}diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.goindex 6906569f4..f0c0c30d6 100644--- a/backend/cli/upgrade/upgrade.go+++ b/backend/cli/upgrade/upgrade.go@@ -1,6 +1,7 @@package upgradeimport (+ "cmp""context""fmt""log/slog"@@ -10,15 +11,14 @@ import ("time""emperror.dev/errors"-+ docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/network""github.com/moby/moby/client""github.com/spf13/cobra"-- docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"- "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""go.getarcane.app/updater/labels")@@ -85,7 +85,7 @@ func runUpgrade(cmd *cobra.Command, args []string) error {containerName = strings.TrimPrefix(targetContainer.Name, "/")slog.Info("Found Arcane container", "name", containerName, "id", targetContainer.ID[:12])} else {- inspectResult, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerName, client.ContainerInspectOptions{})+ inspectResult, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerName, client.ContainerInspectOptions{})if inspectErr != nil {return errors.WrapIff(inspectErr, "failed to inspect container %s", containerName)}@@ -144,7 +144,7 @@ func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (contcontinue}- inspectResult, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})+ inspectResult, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})if err != nil {continue}@@ -356,7 +356,7 @@ func determineImageName(ctx context.Context, dockerClient *client.Client, cont c// Default to :latest if still no tagif !hasExplicitTag(imageName) {- imageName = ensureDefaultTag(imageName)+ imageName = kit.Ternary(imageName == "", "ghcr.io/getarcaneapp/arcane:latest", imageName+":latest")}return imageName@@ -406,9 +406,7 @@ func inferImageNameFromDocker(ctx context.Context, dockerClient *client.Client,t = stripDigest(t)if strings.Contains(t, "arcane") {- if arcaneAny == "" {- arcaneAny = t- }+ arcaneAny = cmp.Or(arcaneAny, t)if !strings.HasSuffix(t, ":latest") && arcaneNonLatest == "" {arcaneNonLatest = t}@@ -416,18 +414,7 @@ func inferImageNameFromDocker(ctx context.Context, dockerClient *client.Client,}// Prefer non-latest tags- if arcaneNonLatest != "" {- return arcaneNonLatest- }- return arcaneAny-}--// ensureDefaultTag adds :latest tag if no tag is present-func ensureDefaultTag(imageName string) string {- if imageName == "" {- return "ghcr.io/getarcaneapp/arcane:latest"- }- return imageName + ":latest"+ return kit.Ternary(arcaneNonLatest != "", arcaneNonLatest, arcaneAny)}// pulledImageAlreadyRunning reports whether the freshly pulled reference resolves to@@ -477,7 +464,7 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldContaconfig.Labels = refreshRecreatedContainerLabelsInternal(ctx, dockerClient, config.Labels, oldContainer.Image, newImage)- hostConfig, sanitizedMemorySwappiness, engineInfo, err := libarcane.PrepareRecreateHostConfigForEngine(ctx, dockerClient, oldContainer.HostConfig)+ hostConfig, sanitizedMemorySwappiness, engineInfo, err := compat.PrepareRecreateHostConfigForEngine(ctx, dockerClient, oldContainer.HostConfig)if err != nil {return errors.WrapIf(err, "prepare host config")}@@ -530,11 +517,11 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldContanetworkConfig *network.NetworkingConfig)if !nm.IsContainer() {- apiVersion = libarcane.DetectDockerAPIVersion(ctx, dockerClient)- if apiVersion != "" && !libarcane.IsDockerAPIVersionAtLeast(apiVersion, libarcane.NetworkScopedMacAddressMinAPIVersion) {+ apiVersion = compat.DetectDockerAPIVersion(ctx, dockerClient)+ if apiVersion != "" && !compat.IsDockerAPIVersionAtLeast(apiVersion, compat.NetworkScopedMacAddressMinAPIVersion) {slog.Info("daemon API does not support per-network mac-address on create; stripping endpoint mac addresses","dockerAPIVersion", apiVersion,- "minimumRequiredAPIVersion", libarcane.NetworkScopedMacAddressMinAPIVersion,+ "minimumRequiredAPIVersion", compat.NetworkScopedMacAddressMinAPIVersion,)}@@ -544,7 +531,7 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta}networkConfig = &network.NetworkingConfig{- EndpointsConfig: libarcane.SanitizeContainerCreateEndpointSettingsForDockerAPI(endpoints, apiVersion),+ EndpointsConfig: compat.SanitizeContainerCreateEndpointSettingsForDockerAPI(endpoints, apiVersion),}}@@ -563,7 +550,7 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldContafmt.Println("PROGRESS:75:Creating new container")slog.Info("Creating new container", "name", originalName)- resp, err := libarcane.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{+ resp, err := compat.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{Config: &config,HostConfig: hostConfig,NetworkingConfig: networkConfig,diff --git a/backend/cli/upgrade/upgrade_test.go b/backend/cli/upgrade/upgrade_test.goindex 1832cd55e..17f35b6b1 100644--- a/backend/cli/upgrade/upgrade_test.go+++ b/backend/cli/upgrade/upgrade_test.go@@ -132,7 +132,6 @@ func TestRefreshRecreatedImageLabelsInternalKeepsNilWhenNoLabelsExist(t *testingfunc TestRefreshRecreatedContainerLabelsInternalPreservesLabelsWhenTargetInspectFails(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {-assert.Contains(t, r.URL.Path, "/images/target:latest/json","unexpected Docker API request: %s %s", r.Method, r.URL.Path)diff --git a/backend/cli/version.go b/backend/cli/version.goindex 7ff3f5ff3..98b00bcb6 100644--- a/backend/cli/version.go+++ b/backend/cli/version.go@@ -4,9 +4,8 @@ import ("fmt""runtime"- "github.com/spf13/cobra"-"github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/spf13/cobra")var versionCmd = &cobra.Command{diff --git a/backend/frontend/frontend.go b/backend/frontend/frontend.goindex fd9b33b2f..a85e2f7e0 100644--- a/backend/frontend/frontend.go+++ b/backend/frontend/frontend.go@@ -3,6 +3,7 @@package frontendimport (+ "cmp""embed""io/fs""mime"@@ -10,7 +11,6 @@ import ("strings""emperror.dev/errors"-"github.com/labstack/echo/v5""github.com/labstack/echo/v5/middleware")@@ -59,10 +59,7 @@ func RegisterFrontend(e *echo.Echo) error {return next(c)}- p := strings.TrimPrefix(c.Request().URL.Path, "/")- if p == "" {- p = indexHtmlFileConstant- }+ p := cmp.Or(strings.TrimPrefix(c.Request().URL.Path, "/"), indexHtmlFileConstant)if _, statErr := fs.Stat(distFS, p); statErr != nil && !strings.HasPrefix(p, "_app/") {p = indexHtmlFileConstant}diff --git a/backend/go.mod b/backend/go.modindex 3ca229081..c12f2a4a4 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -41,7 +41,6 @@ require (github.com/gofrs/flock v0.13.1github.com/google/go-containerregistry v0.22.1github.com/google/uuid v1.6.0- github.com/jinzhu/copier v0.4.0github.com/jwx-go/jwkfetch/v4 v4.0.4github.com/klauspost/compress v1.20.1github.com/labstack/echo/v5 v5.3.1@@ -71,8 +70,9 @@ require (github.com/wneessen/go-mail v0.8.1go.getarcane.app/acfs v0.6.1go.getarcane.app/builds v0.4.2+ go.getarcane.app/docker/compat v0.1.0go.getarcane.app/docker/convert v0.3.2- go.getarcane.app/kit v0.2.0+ go.getarcane.app/kit v0.3.1go.getarcane.app/streams v0.4.3go.getarcane.app/sys/cgroup v0.2.3go.getarcane.app/sys/crypto v0.2.2@@ -190,6 +190,7 @@ require (github.com/jackc/pgx/v5 v5.10.0 // indirectgithub.com/jackc/puddle/v2 v2.2.2 // indirectgithub.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect+ github.com/jinzhu/copier v0.4.0 // indirectgithub.com/jinzhu/inflection v1.0.0 // indirectgithub.com/jinzhu/now v1.1.5 // indirectgithub.com/jonboulle/clockwork v0.5.0 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 1f02faf83..6a6b01b2c 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -736,10 +736,12 @@ go.getarcane.app/acfs v0.6.1 h1:xPDfof8Tbr3ZQ6ATcyFM4EtyUh+K657CThpGdg+dz50=go.getarcane.app/acfs v0.6.1/go.mod h1:Z+0Gs4LGNjvGMLq+TKv/oGKh29FRbAH6mcVPwY5KhFI=go.getarcane.app/builds v0.4.2 h1:pWrNrJ4pjLm2Dpwii4bkf0ptKrlE9N8j/EL1F6o15mA=go.getarcane.app/builds v0.4.2/go.mod h1:sOgXeqAcEUeblqdUOSPGZLYz3rlTJpTMXaSy0aQhmlQ=+go.getarcane.app/docker/compat v0.1.0 h1:GIycV+Pn/kEIXlqhmjfSGuDgw5OhECYudRdHZgmHIdo=+go.getarcane.app/docker/compat v0.1.0/go.mod h1:lSGOgKO2ikdy8WzFGHLtkT05L7Amak8HCtnudV6Deow=go.getarcane.app/docker/convert v0.3.2 h1:4y2zEpkdv6CfWqzdz3whxWSpF9cKbhihcNBwWK4cXVM=go.getarcane.app/docker/convert v0.3.2/go.mod h1:iZ3vyiTnj7/K70aDSY/G689YnvqOYtZle9IVPFlnM24=-go.getarcane.app/kit v0.2.0 h1:3PPHo5nHuns1vjqmCMFPFdnmbH/qQOserONCba/gBi4=-go.getarcane.app/kit v0.2.0/go.mod h1:TGqQCbAJs3ldzkFncXZ93wTVSDhAMQlqyNdVO2CNjIk=+go.getarcane.app/kit v0.3.1 h1:fuSl8ZMshuFPUvJl/9QwoI/ds1+zsfpixZYqk/hFLUE=+go.getarcane.app/kit v0.3.1/go.mod h1:KTjbXTEeC3i9e1QxZowDJWjFyABlD6UF3ISVtoIZs10=go.getarcane.app/streams v0.4.3 h1:Rzg6xCWzYmD4IN+GiKYmAc8HqCgVIq/sQ4DC3OxiZ1o=go.getarcane.app/streams v0.4.3/go.mod h1:SC/7A3pR8RanF5DqdX99A40qEw13TbmmbEtJK3yPuy4=go.getarcane.app/sys/cgroup v0.2.3 h1:+eGLUC+3Ct+BNcPBQwC/g/psDOzjWN2vUr6KhKyNWgI=diff --git a/backend/internal/activity/handler.go b/backend/internal/activity/handler.goindex 05a4d1ced..068834168 100644--- a/backend/internal/activity/handler.go+++ b/backend/internal/activity/handler.go@@ -1,11 +1,9 @@package activityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-+ "cmp""context""fmt"- "hash/fnv""maps""net/http""net/url"@@ -14,8 +12,8 @@ import ("time""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -25,6 +23,7 @@ import (activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/base""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/streams/agg""gorm.io/gorm")@@ -369,34 +368,6 @@ func activityStreamEnvironmentVersionInternal(environment environment.Environmenreturn environment.ID + ":" + environment.UpdatedAt.UTC().Format(time.RFC3339Nano)}-// activitySnapshotFingerprintInternal hashes the fields that affect what the-// client renders, so a poller can skip re-sending a snapshot identical to the-// previous one.-func activitySnapshotFingerprintInternal(items []activitytypes.Activity) string {- hash := fnv.New64a()- writeField := func(value string) {- _, _ = hash.Write([]byte(value))- _, _ = hash.Write([]byte{0})- }- for _, item := range items {- writeField(item.ID)- writeField(string(item.Status))- if item.Progress != nil {- writeField(strconv.Itoa(*item.Progress))- }- writeField(item.Step)- writeField(item.LatestMessage)- if item.UpdatedAt != nil {- writeField(item.UpdatedAt.UTC().Format(time.RFC3339Nano))- }- if item.EndedAt != nil {- writeField(item.EndedAt.UTC().Format(time.RFC3339Nano))- }- writeField("|")- }- return strconv.FormatUint(hash.Sum64(), 16)-}-func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Context, environment environment.Environment, limit int, publish func(activitytypes.StreamEvent)) {environmentID := environment.IDlastError := ""@@ -422,7 +393,7 @@ func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Contreturn}if output != nil {- fingerprint := activitySnapshotFingerprintInternal(output.Body.Data)+ fingerprint := strconv.FormatUint(kit.Fingerprint(output.Body.Data), 16)if fingerprint != lastFingerprint {publish(activitytypes.StreamEvent{Type: "snapshot",@@ -451,7 +422,7 @@ func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.ContlastFingerprint = ""}lastError = ""- fingerprint := activitySnapshotFingerprintInternal(output.Body.Data)+ fingerprint := strconv.FormatUint(kit.Fingerprint(output.Body.Data), 16)if fingerprint == lastFingerprint {return}@@ -530,17 +501,12 @@ func applyActivitySourceLabelsForEnvironmentInternal(environmentModel environmen}func activitySourceFromEnvironmentInternal(environmentModel environment.Environment) (string, string) {- environmentID := environmentModel.ID- if environmentID == "" {- environmentID = environment.LocalEnvironmentID- }+ environmentID := cmp.Or(environmentModel.ID, environment.LocalEnvironmentID)return environmentID, environment.DisplayName(environmentID, environmentModel.Name)}func (h *ActivityHandler) resolveActivitySourceInternal(ctx context.Context, environmentID string) (string, string) {- if environmentID == "" {- environmentID = environment.LocalEnvironmentID- }+ environmentID = cmp.Or(environmentID, environment.LocalEnvironmentID)if h.environment.ResolveEnvironmentName != nil {return environmentID, h.environment.ResolveEnvironmentName(ctx, environmentID)}@@ -589,10 +555,7 @@ func resolveActivityStreamLimitInternal(limit int) int {if limit <= 0 {return 50}- if limit > 100 {- return 100- }- return limit+ return kit.Ternary(limit > 100, 100, limit)}func activityListParamsInternal(input *ListActivitiesInput) pagination.QueryParams {@@ -649,7 +612,8 @@ func (h *ActivityHandler) listRemoteActivitiesInternal(ctx context.Context, inpuparams := normalizeRemoteActivityParamsInternal(activityListParamsInternal(input))// The agent only ships the newest window the merged page can use, not its// whole history; the stream poller repeats this every few seconds.- remoteActivities, remoteTotal, remoteErr := collectActivityWindowInternal(remoteActivityWindowInternal(params), func(start, limit int) ([]activitytypes.Activity, int64, error) {+ window := kit.Ternary(params.Limit == -1, -1, params.Start+params.Limit)+ remoteActivities, remoteTotal, remoteErr := collectActivityWindowInternal(window, func(start, limit int) ([]activitytypes.Activity, int64, error) {page := *inputpage.Start, page.Limit = start, limitremote, err := fetch("/api/environments/0/activities?" + activityListQueryInternal(&page).Encode())diff --git a/backend/internal/activity/job.go b/backend/internal/activity/job.goindex 489ffdf85..d5a56f7a3 100644--- a/backend/internal/activity/job.go+++ b/backend/internal/activity/job.go@@ -1,6 +1,7 @@package activityimport (+ "cmp""context""time"@@ -82,10 +83,7 @@ func jobActivityInternal(run st.Run, name string) Activity {status = activitytypes.StatusCancelledcase st.Queued, st.Waiting, st.Retrying:}- message := run.Outcome.Message- if message == "" {- message = name + ": " + string(run.Status)- }+ message := cmp.Or(run.Outcome.Message, name+": "+string(run.Status))model := Activity{ID: run.ActivityID, CreatedAt: run.CreatedAt, UpdatedAt: new(run.UpdatedAt),EnvironmentID: run.EnvironmentID, BatchID: new(run.ID), Type: activitytypes.TypeJobRun, Status: status,diff --git a/backend/internal/activity/job_test.go b/backend/internal/activity/job_test.goindex 8c75795d3..7b7479d26 100644--- a/backend/internal/activity/job_test.go+++ b/backend/internal/activity/job_test.go@@ -2,14 +2,14 @@ package activityimport ("context"- "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"- "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""os""strings""testing""time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/stretchr/testify/require"diff --git a/backend/internal/activity/model.go b/backend/internal/activity/model.goindex 1737ce4ab..5344b89ee 100644--- a/backend/internal/activity/model.go+++ b/backend/internal/activity/model.go@@ -1,10 +1,9 @@package activityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity")diff --git a/backend/internal/activity/module.go b/backend/internal/activity/module.goindex 735d39fbc..5a06e4d75 100644--- a/backend/internal/activity/module.go+++ b/backend/internal/activity/module.go@@ -4,7 +4,6 @@ package activityimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings")diff --git a/backend/internal/activity/remote.go b/backend/internal/activity/remote.goindex 2e8459ff7..280b82eb6 100644--- a/backend/internal/activity/remote.go+++ b/backend/internal/activity/remote.go@@ -8,6 +8,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/samber/lo"+ kit "go.getarcane.app/kit/pkg")// remoteActivityPageCeiling mirrors the agent's page clamp in PaginateAndSortDB.@@ -27,16 +28,6 @@ func normalizeRemoteActivityParamsInternal(params pagination.QueryParams) paginareturn params}-// remoteActivityWindowInternal is how many newest rows each source must supply-// for the merged page to be exact: every row in the global top start+limit is-// in its own source's top start+limit under the shared sort order.-func remoteActivityWindowInternal(params pagination.QueryParams) int {- if params.Limit == -1 {- return -1- }- return params.Start + params.Limit-}-// collectActivityWindowInternal reads window rows from a source in pages the// agent accepts, stopping early when the source runs out. -1 reads everything.func collectActivityWindowInternal(window int, fetchPage func(start, limit int) ([]activitytypes.Activity, int64, error)) ([]activitytypes.Activity, int64, error) {@@ -65,7 +56,8 @@ func collectActivityWindowInternal(window int, fetchPage func(start, limit int)// and be the agent's newest window; remoteTotal is the agent's filtered count.func (s *ActivityService) ListRemoteActivities(ctx context.Context, environmentID string, remote []activitytypes.Activity, remoteTotal int64, params pagination.QueryParams) ([]activitytypes.Activity, pagination.Response, error) {params = normalizeRemoteActivityParamsInternal(params)- activities, localTotal, err := collectActivityWindowInternal(remoteActivityWindowInternal(params), func(start, limit int) ([]activitytypes.Activity, int64, error) {+ window := kit.Ternary(params.Limit == -1, -1, params.Start+params.Limit)+ activities, localTotal, err := collectActivityWindowInternal(window, func(start, limit int) ([]activitytypes.Activity, int64, error) {local := paramslocal.Start, local.Limit = start, limitrows, page, err := s.ListActivitiesPaginated(ctx, environmentID, local)@@ -96,10 +88,7 @@ func compareActivitiesInternal(a, b activitytypes.Activity, params pagination.QuaActive := a.Status == activitytypes.StatusQueued || a.Status == activitytypes.StatusRunningbActive := b.Status == activitytypes.StatusQueued || b.Status == activitytypes.StatusRunningif aActive != bActive {- if aActive {- return -1- }- return 1+ return kit.Ternary(aActive, -1, 1)}aTime, bTime := a.CreatedAt, b.CreatedAtif a.EndedAt != nil {diff --git a/backend/internal/activity/service.go b/backend/internal/activity/service.goindex 5ac022c51..14cfd982a 100644--- a/backend/internal/activity/service.go+++ b/backend/internal/activity/service.go@@ -1,6 +1,7 @@package activityimport (+ "cmp""context"stderrors "errors""hash/fnv"@@ -35,6 +36,24 @@ const (// must be before the periodic sweep fails it. It covers the window between// StartActivity's row creation and the worker's Track call.abandonedActivityGrace = 2 * time.Minute++ // terminalPublishRetention bounds how long a terminal publish suppresses+ // stale non-terminal snapshots for the same activity. Stale publishers are+ // goroutines already past their commit, so they publish within moments; the+ // retention only has to outlive that gap while keeping the latch map small.+ terminalPublishRetention = 10 * time.Minute++ // ErrActivityNotCancelable indicates the activity has already reached a terminal+ // state and can no longer be cancelled.+ ErrActivityNotCancelable = errors.Sentinel("activity is not cancelable")++ // subscriberMessageQueueLimit bounds the per-subscriber backlog of "message"+ // events; the oldest message is dropped (and flagged as missed) on overflow.+ subscriberMessageQueueLimit = 256++ cancelledMessageInternal = "Cancelled by user"++ deleteActivitiesBatchSize = 500)type ActivityService struct {@@ -74,20 +93,6 @@ type ActivityService struct {publishLocks [64]sync.Mutex}-// terminalPublishRetention bounds how long a terminal publish suppresses-// stale non-terminal snapshots for the same activity. Stale publishers are-// goroutines already past their commit, so they publish within moments; the-// retention only has to outlive that gap while keeping the latch map small.-const terminalPublishRetention = 10 * time.Minute--// ErrActivityNotCancelable indicates the activity has already reached a terminal-// state and can no longer be cancelled.-const ErrActivityNotCancelable = errors.Sentinel("activity is not cancelable")--// subscriberMessageQueueLimit bounds the per-subscriber backlog of "message"-// events; the oldest message is dropped (and flagged as missed) on overflow.-const subscriberMessageQueueLimit = 256-// activitySubscriber buffers stream events between publishers and one stream// consumer. "activity" events are coalesced in place per activity ID (only the// latest pending state matters to the UI), so bulk operations emitting rapid@@ -204,9 +209,11 @@ func (sub *activitySubscriber) pump() {}}-type StartActivityRequest = activitylib.StartRequest-type UpdateActivityRequest = activitylib.UpdateRequest-type AppendActivityMessageRequest = activitylib.AppendMessageRequest+type (+ StartActivityRequest = activitylib.StartRequest+ UpdateActivityRequest = activitylib.UpdateRequest+ AppendActivityMessageRequest = activitylib.AppendMessageRequest+)func NewActivityService(db *database.DB, settingsService *settings.SettingsService) *ActivityService {return &ActivityService{@@ -295,10 +302,7 @@ func (s *ActivityService) StartActivity(ctx context.Context, req StartActivityRe}now := time.Now()- environmentID := strings.TrimSpace(req.EnvironmentID)- if environmentID == "" {- environmentID = "0"- }+ environmentID := cmp.Or(strings.TrimSpace(req.EnvironmentID), "0")var startedByUserID, startedByUsername, startedByDisplayName *stringif req.StartedBy != nil {@@ -425,10 +429,7 @@ func (s *ActivityService) AwaitActivitySlot(ctx context.Context, activityID, envif activityID == "" {return errors.New("activity id is required")}- environmentID = strings.TrimSpace(environmentID)- if environmentID == "" {- environmentID = "0"- }+ environmentID = cmp.Or(strings.TrimSpace(environmentID), "0")s.slotMu.Lock()_, held := s.slotReleases[activityID]@@ -600,10 +601,7 @@ func buildAppendBatchInternal(activityID string, reqs []AppendActivityMessageReqmessageText = messageText[:8192]}- level := req.Level- if level == "" {- level = activitytypes.MessageLevelInfo- }+ level := cmp.Or(req.Level, activitytypes.MessageLevelInfo)messages = append(messages, &ActivityMessage{ActivityID: activityID,@@ -690,9 +688,7 @@ func (s *ActivityService) CompleteActivity(ctx context.Context, activityID strinif err := s.checkInitInternal(); err != nil {return nil, err}- if status == "" {- status = activitytypes.StatusSuccess- }+ status = cmp.Or(status, activitytypes.StatusSuccess)if status != activitytypes.StatusSuccess && status != activitytypes.StatusFailed && status != activitytypes.StatusCancelled {status = activitytypes.StatusSuccess}@@ -806,10 +802,7 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, actif activityID == "" {return nil, errors.New("activity id is required")}- environmentID = strings.TrimSpace(environmentID)- if environmentID == "" {- environmentID = "0"- }+ environmentID = cmp.Or(strings.TrimSpace(environmentID), "0")var model Activityif err := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", activityID, environmentID).First(&model).Error; err != nil {@@ -825,10 +818,7 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, act// Active states β cancellation can proceed.}- requestedBy = strings.TrimSpace(requestedBy)- if requestedBy == "" {- requestedBy = "a user"- }+ requestedBy = cmp.Or(strings.TrimSpace(requestedBy), "a user")writeCtx := utils.ActivityRuntimeContext(ctx, nil)if _, err := s.AppendMessage(writeCtx, activityID, AppendActivityMessageRequest{Level: activitytypes.MessageLevelWarning,@@ -876,8 +866,6 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, actreturn &dto, nil}-const cancelledMessageInternal = "Cancelled by user"-// FailStaleImageUpdateChecks marks image update checks that were left running// across a prior process lifetime as failed. It intentionally scopes cleanup to// old image-update-check activities so startup repair cannot affect other work.@@ -1120,10 +1108,7 @@ func (s *ActivityService) ListActivitiesPaginated(ctx context.Context, environmereturn nil, pagination.Response{}, err}- environmentID = strings.TrimSpace(environmentID)- if environmentID == "" {- environmentID = "0"- }+ environmentID = cmp.Or(strings.TrimSpace(environmentID), "0")var activities []Activityq := s.db.WithContext(ctx).Model(&Activity{}).Where("environment_id = ?", environmentID)@@ -1250,10 +1235,7 @@ func (s *ActivityService) DeleteHistory(ctx context.Context, environmentID strinreturn 0, nil}- environmentID = strings.TrimSpace(environmentID)- if environmentID == "" {- environmentID = "0"- }+ environmentID = cmp.Or(strings.TrimSpace(environmentID), "0")var deleted int64if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {@@ -1281,10 +1263,7 @@ func (s *ActivityService) Subscribe(environmentID string) (<-chan activitytypes.return ch, func() bool { return false }, func() {}}- environmentID = strings.TrimSpace(environmentID)- if environmentID == "" {- environmentID = "0"- }+ environmentID = cmp.Or(strings.TrimSpace(environmentID), "0")sub := newActivitySubscriberInternal(environmentID, ch)s.subscribersMu.Lock()@@ -1529,8 +1508,6 @@ func findActivityIDsBeyondHistoryLimitInternal(tx *gorm.DB, maxEntries int) ([]sreturn activityIDs, nil}-const deleteActivitiesBatchSize = 500-func deleteActivitiesByIDInternal(tx *gorm.DB, activityIDs []string) (int64, error) {if len(activityIDs) == 0 {return 0, nildiff --git a/backend/internal/activity/service_test.go b/backend/internal/activity/service_test.goindex 5027c0a3b..0874c446d 100644--- a/backend/internal/activity/service_test.go+++ b/backend/internal/activity/service_test.go@@ -1,24 +1,22 @@package activityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "go.uber.org/fx/fxtest"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/require"+ "go.uber.org/fx/fxtest"+ "gorm.io/gorm")func setupActivityServiceTestDBInternal(t *testing.T) *database.DB {@@ -137,7 +135,6 @@ func TestActivityServiceStreamFanoutInternal(t *testing.T) {require.Nil(t, messageEvent.Activity)require.Nil(t, messageEvent.Activities)require.Equal(t, messageEvent, receiveActivityEventInternal(t, otherEvents))-}func TestActivityServiceRetentionCleanupInternal(t *testing.T) {diff --git a/backend/internal/activity/visibility_test.go b/backend/internal/activity/visibility_test.goindex 30b62fd47..976fc50ae 100644--- a/backend/internal/activity/visibility_test.go+++ b/backend/internal/activity/visibility_test.go@@ -52,5 +52,4 @@ func TestJobActivityVisibilityFiltersBeforePagination(t *testing.T) {var retained Activityrequire.NoError(t, db.First(&retained, "id = ?", "private").Error)require.NoError(t, db.First(&Activity{}, "id = ?", "allowed").Error)-}diff --git a/backend/internal/apikey/handler.go b/backend/internal/apikey/handler.goindex 76cf668c4..c10898c9e 100644--- a/backend/internal/apikey/handler.go+++ b/backend/internal/apikey/handler.go@@ -5,7 +5,6 @@ import ("net/http""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"diff --git a/backend/internal/apikey/model.go b/backend/internal/apikey/model.goindex 7e03a3053..b18ae05c4 100644--- a/backend/internal/apikey/model.go+++ b/backend/internal/apikey/model.go@@ -1,10 +1,10 @@package apikeyimport (+ "time"+"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role"-- "time")const (diff --git a/backend/internal/apikey/module.go b/backend/internal/apikey/module.goindex 8a82c5b0a..554bc627a 100644--- a/backend/internal/apikey/module.go+++ b/backend/internal/apikey/module.go@@ -4,7 +4,6 @@ package apikeyimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/user"diff --git a/backend/internal/apikey/service.go b/backend/internal/apikey/service.goindex 937168a47..43e8df739 100644--- a/backend/internal/apikey/service.go+++ b/backend/internal/apikey/service.go@@ -7,17 +7,14 @@ import ("crypto/sha256""encoding/hex""log/slog"+ "maps"+ "slices""strings""sync""sync/atomic""time"- "go.getarcane.app/kit/normalization"-"emperror.dev/errors"-- "github.com/samber/hot"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role"@@ -26,6 +23,8 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2/apikey"+ "github.com/samber/hot"+ "go.getarcane.app/kit/normalization""gorm.io/gorm")@@ -34,9 +33,7 @@ const (ErrApiKeyExpired = errors.Sentinel("API key has expired")ErrApiKeyInvalid = errors.Sentinel("invalid API key")ErrApiKeyProtected = errors.Sentinel("API key is protected")-)-const (apiKeyPrefix = "arc_"apiKeyLength = 32apiKeyPrefixLen = 8@@ -45,6 +42,15 @@ const (managedByAdminBootstrap = "admin_account_default_api_key"defaultAdminUsername = "arcane"defaultAdminAPIKeyName = "Static Admin API Key"++ // ErrApiKeyPermissionEscalation is returned when a caller attempts to grant an+ // API key permissions they themselves do not hold.+ ErrApiKeyPermissionEscalation = errors.Sentinel("cannot grant a permission you do not have")++ // ErrApiKeyPersonalNoGrants is returned when a caller attempts to attach+ // permission grants to a personal key, which has none of its own β it inherits+ // the owner's role permissions at authentication time.+ ErrApiKeyPersonalNoGrants = errors.Sentinel("personal API keys inherit the owner's permissions and cannot carry grants"))var defaultAdminAPIKeyDescription = func() *string {@@ -203,10 +209,7 @@ func (s *ApiKeyService) backfillPermsForKeyInternal(ctx context.Context, tx *gor}}}- out := make([]string, 0, len(seen))- for p := range seen {- out = append(out, p)- }+ out := slices.Collect(maps.Keys(seen))return out, nil}@@ -364,15 +367,6 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerPreturn created, nil}-// ErrApiKeyPermissionEscalation is returned when a caller attempts to grant an-// API key permissions they themselves do not hold.-const ErrApiKeyPermissionEscalation = errors.Sentinel("cannot grant a permission you do not have")--// ErrApiKeyPersonalNoGrants is returned when a caller attempts to attach-// permission grants to a personal key, which has none of its own β it inherits-// the owner's role permissions at authentication time.-const ErrApiKeyPersonalNoGrants = errors.Sentinel("personal API keys inherit the owner's permissions and cannot carry grants")-// validateGrantsAgainstOwnerInternal caps grants at the key owner's role// permissions, so no holder of apikeys:create/update β sudo included β can// push a key above what its owner is allowed to do. Complements the caller-set@@ -679,7 +673,7 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, raw// the transaction commits. Invalidating pre-commit is ineffective: a concurrent// validation can still read the old committed row, snapshot the already-bumped// generation, and republish the entry so it survives the commit.-func (s *ApiKeyService) reconcileManagedAPIKeys(tx *gorm.DB, userID string, rawKey string) ([]string, error) {+func (s *ApiKeyService) reconcileManagedAPIKeys(tx *gorm.DB, userID, rawKey string) ([]string, error) {managedKeys, err := s.listManagedAPIKeys(tx, userID)if err != nil {return nil, errdiff --git a/backend/internal/apikey/service_test.go b/backend/internal/apikey/service_test.goindex 619143f9f..b5f49d4e4 100644--- a/backend/internal/apikey/service_test.go+++ b/backend/internal/apikey/service_test.go@@ -1,12 +1,6 @@package apikeyimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/session"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""fmt""runtime"@@ -15,16 +9,18 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role"+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/apikey"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm")func setupAPIKeyServiceTestDB(t *testing.T) *database.DB {diff --git a/backend/internal/apns/handler.go b/backend/internal/apns/handler.goindex c5c131afb..955d14dc8 100644--- a/backend/internal/apns/handler.go+++ b/backend/internal/apns/handler.go@@ -6,7 +6,6 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"apnstypes "github.com/getarcaneapp/arcane/types/v2/apns"diff --git a/backend/internal/apns/service.go b/backend/internal/apns/service.goindex 861a9a2bf..83f7a14a6 100644--- a/backend/internal/apns/service.go+++ b/backend/internal/apns/service.go@@ -19,12 +19,7 @@ import ("time""uuid"- "go.getarcane.app/kit/normalization"-"emperror.dev/errors"- "go.getarcane.app/sys/crypto"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -35,6 +30,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"apnstypes "github.com/getarcaneapp/arcane/types/v2/apns"+ "go.getarcane.app/kit/normalization"+ "go.getarcane.app/sys/crypto"+ "gorm.io/gorm")const (diff --git a/backend/internal/appimages/handler.go b/backend/internal/appimages/handler.goindex 5978f5c1e..ed78e8559 100644--- a/backend/internal/appimages/handler.go+++ b/backend/internal/appimages/handler.go@@ -8,6 +8,7 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2"+ kit "go.getarcane.app/kit/pkg")// AppImagesHandler provides Huma-based application image endpoints.@@ -105,10 +106,7 @@ func RegisterAppImages(api huma.API, appImagesService *ApplicationImagesService)// GetLogo returns the application logo image.func (h *AppImagesHandler) GetLogo(ctx context.Context, input *GetLogoInput) (*GetAppImageOutput, error) {- name := "logo"- if input.Full {- name = "logo-full"- }+ name := kit.Ternary(input.Full, "logo-full", "logo")if input.Animated {name += "-animated"}@@ -149,7 +147,7 @@ func (h *AppImagesHandler) getImageByFilenameInternal(filename string) (*GetAppIreturn h.getImage(name)}-func (h *AppImagesHandler) getImageWithColor(name string, colorOverride string, loop bool) (*GetAppImageOutput, error) {+func (h *AppImagesHandler) getImageWithColor(name, colorOverride string, loop bool) (*GetAppImageOutput, error) {imageData, mimeType, err := h.appImagesService.GetImageWithColor(name, colorOverride, loop)if err != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to retrieve image").Error())@@ -157,10 +155,11 @@ func (h *AppImagesHandler) getImageWithColor(name string, colorOverride string,// Always disable logo caching so theme/logo updates are reflected immediately.// Keep cache for static app images that do not change at runtime.- cacheControl := "public, max-age=900, stale-while-revalidate=86400"- if IsLogoVariant(name) || colorOverride != "" {- cacheControl = "no-cache, no-store, must-revalidate"- }+ cacheControl := kit.Ternary(+ IsLogoVariant(name) || colorOverride != "",+ "no-cache, no-store, must-revalidate",+ "public, max-age=900, stale-while-revalidate=86400",+ )return &GetAppImageOutput{ContentType: mimeType,diff --git a/backend/internal/appimages/service.go b/backend/internal/appimages/service.goindex 7212473c9..15403ddcd 100644--- a/backend/internal/appimages/service.go+++ b/backend/internal/appimages/service.go@@ -9,8 +9,8 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/settings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/image"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"+ kit "go.getarcane.app/kit/pkg")type ApplicationImagesService struct {@@ -48,7 +48,7 @@ func NewApplicationImagesService(embeddedFS embed.FS, settingsService *settings.}extWithoutDot := strings.TrimPrefix(ext, ".")- mimeType := image.GetImageMimeType(extWithoutDot)+ mimeType := kit.GetImageMimeType(extWithoutDot)if mimeType == "" {continue}@@ -60,7 +60,7 @@ func NewApplicationImagesService(embeddedFS embed.FS, settingsService *settings.return service}-func (s *ApplicationImagesService) GetImageWithColor(name string, colorOverride string, loop bool) ([]byte, string, error) {+func (s *ApplicationImagesService) GetImageWithColor(name, colorOverride string, loop bool) ([]byte, string, error) {s.mu.RLock()data, ok := s.imageData[name]mimeType := s.mimeTypes[name]diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.goindex d3dcb9d3f..d86ea0f96 100644--- a/backend/internal/auth/handler.go+++ b/backend/internal/auth/handler.go@@ -1,8 +1,6 @@package authimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/session"-"bytes""context""fmt"@@ -18,10 +16,10 @@ import ("time""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"@@ -31,6 +29,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/base"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"usertypes "github.com/getarcaneapp/arcane/types/v2/user"+ kit "go.getarcane.app/kit/pkg")type AuthHandler struct {@@ -579,10 +578,7 @@ func (h *AuthHandler) avatarMaxUploadSizeMbInternal(ctx context.Context) int {return defaultAvatarMaxUploadSizeMb}maxSizeMb := h.settingsService.GetIntSetting(ctx, "avatarMaxUploadSizeMb", defaultAvatarMaxUploadSizeMb)- if maxSizeMb <= 0 {- return defaultAvatarMaxUploadSizeMb- }- return maxSizeMb+ return kit.Ternary(maxSizeMb <= 0, defaultAvatarMaxUploadSizeMb, maxSizeMb)}// DeleteMyAvatar removes the current user's custom profile picture.diff --git a/backend/internal/auth/huma_middleware.go b/backend/internal/auth/huma_middleware.goindex 99ce386b0..706dbf6e3 100644--- a/backend/internal/auth/huma_middleware.go+++ b/backend/internal/auth/huma_middleware.go@@ -1,22 +1,20 @@package authimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-"context""errors""log/slog""net/http""strings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"-"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity")@@ -93,7 +91,7 @@ func tryBearerAuthInternal(ctx huma.Context, authService *AuthService) (*common.// through. Returns the resolved user plus the API key record so the caller// can resolve permissions according to the key's kind.func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *apikey.ApiKeyService) (*common.User, *apikey.ApiKey, bool) {- apiKey := ctx.Header(utils.HeaderApiKey)+ apiKey := ctx.Header(middleware.HeaderApiKey)if apiKey == "" {return nil, nil, false}@@ -129,18 +127,18 @@ func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*common.User, bpath := ctx.URL().Path// Check for agent bootstrap pairing- if strings.HasPrefix(path, utils.AgentPairingPrefix) &&- AgentTokenMatches(ctx.Header(utils.HeaderAgentBootstrap), cfg.AgentToken) {+ if strings.HasPrefix(path, middleware.AgentPairingPrefix) &&+ AgentTokenMatches(ctx.Header(middleware.HeaderAgentBootstrap), cfg.AgentToken) {return createAgentSudoUserInternal(), true}// Check for agent token- if AgentTokenMatches(ctx.Header(utils.HeaderAgentToken), cfg.AgentToken) {+ if AgentTokenMatches(ctx.Header(middleware.HeaderAgentToken), cfg.AgentToken) {return createAgentSudoUserInternal(), true}// Check for API key as agent token- if AgentTokenMatches(ctx.Header(utils.HeaderApiKey), cfg.AgentToken) {+ if AgentTokenMatches(ctx.Header(middleware.HeaderApiKey), cfg.AgentToken) {return createAgentSudoUserInternal(), true}@@ -170,7 +168,7 @@ func applyProxiedIconCatalogInternal(ctx huma.Context, user *common.User) {if user == nil {return}- catalog := strings.TrimSpace(ctx.Header(utils.HeaderIconCatalog))+ catalog := strings.TrimSpace(ctx.Header(middleware.HeaderIconCatalog))if catalog == "" {return}@@ -207,12 +205,12 @@ func NewHumaMiddleware(api huma.API, authService *AuthService, apiKeyService *apreturn}- if reqs.apiKeyAuth && ctx.Header(utils.HeaderApiKey) != "" {+ if reqs.apiKeyAuth && ctx.Header(middleware.HeaderApiKey) != "" {handleApiKeyAuthInternal(api, ctx, authService, apiKeyService, permResolver, envTokenResolver, reqs.bearerAuth, next)return}- if user, env, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(utils.HeaderAgentToken)); ok {+ if user, env, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(middleware.HeaderAgentToken)); ok {applyProxiedIconCatalogInternal(ctx, user)newCtx := setUserInContextInternal(ctx.Context(), user, authz.EnvironmentPermissionSet(env.ID))next(huma.WithContext(ctx, newCtx))@@ -245,11 +243,11 @@ func tryAgentAuthCtxInternal(ctx huma.Context, cfg *config.Config) (huma.ContextauthCtx := setUserInContextInternal(ctx.Context(), user, authz.SudoPermissionSet())updatePath := strings.Contains(ctx.URL().Path, "/containers/") && strings.HasSuffix(ctx.URL().Path, "/update")if ctx.Method() == http.MethodPost && updatePath {- if initiatorID := strings.TrimSpace(ctx.Header(utils.HeaderUpdateInitiatorID)); initiatorID != "" {+ if initiatorID := strings.TrimSpace(ctx.Header(middleware.HeaderUpdateInitiatorID)); initiatorID != "" {initiator := activitytypes.StartedBy{UserID: initiatorID,- Username: strings.TrimSpace(ctx.Header(utils.HeaderUpdateInitiatorName)),- DisplayName: strings.TrimSpace(ctx.Header(utils.HeaderUpdateInitiatorDisplayName)),+ Username: strings.TrimSpace(ctx.Header(middleware.HeaderUpdateInitiatorName)),+ DisplayName: strings.TrimSpace(ctx.Header(middleware.HeaderUpdateInitiatorDisplayName)),}authCtx = utils.WithUpdateInitiator(authCtx, initiator)}@@ -293,7 +291,7 @@ func handleApiKeyAuthInternal(api huma.API, ctx huma.Context, authService *AuthSnext(huma.WithContext(ctx, newCtx))return}- if user, env, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(utils.HeaderApiKey)); ok {+ if user, env, ok := tryEnvironmentAccessTokenAuthInternal(ctx, envTokenResolver, ctx.Header(middleware.HeaderApiKey)); ok {if token, _ := extractBearerTokenInternal(ctx); allowBearerFallback && token != "" {nextCtx, handled := handleBearerAuthInternal(api, ctx, authService, permResolver)if handled {diff --git a/backend/internal/auth/huma_middleware_test.go b/backend/internal/auth/huma_middleware_test.goindex 0114ca928..cb2b12326 100644--- a/backend/internal/auth/huma_middleware_test.go+++ b/backend/internal/auth/huma_middleware_test.go@@ -1,12 +1,6 @@package authimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"bytes""context""crypto/mldsa"@@ -17,13 +11,15 @@ import ("github.com/danielgtaylor/huma/v2""github.com/danielgtaylor/huma/v2/adapters/humaecho"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/session"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"authtypes "github.com/getarcaneapp/arcane/types/v2/auth""github.com/labstack/echo/v5"@@ -145,7 +141,8 @@ func TestNewHumaMiddleware_UsesBearerWhenLoopbackProxySendsEnvironmentAccessToke}, func(ctx context.Context, _ *struct {ID string `path:"id"`CID string `path:"cid"`- }) (*secureOutput, error) {+ },+ ) (*secureOutput, error) {user, ok := common.CurrentUserFromContext(ctx)require.True(t, ok)require.Equal(t, "u-loopback", user.ID)@@ -471,8 +468,8 @@ func TestNewHumaMiddleware_AgentAuthAppliesForwardedIconCatalog(t *testing.T) {})req := httptest.NewRequest(http.MethodGet, "/api/secure-agent-icon-catalog", nil)- req.Header.Set(utils.HeaderAgentToken, agentToken)- req.Header.Set(utils.HeaderIconCatalog, "dashboard-icons")+ req.Header.Set(middleware.HeaderAgentToken, agentToken)+ req.Header.Set(middleware.HeaderIconCatalog, "dashboard-icons")rec := httptest.NewRecorder()router.ServeHTTP(rec, req)diff --git a/backend/internal/auth/middleware.go b/backend/internal/auth/middleware.goindex 9fb4f7d23..e0958f5df 100644--- a/backend/internal/auth/middleware.go+++ b/backend/internal/auth/middleware.go@@ -1,12 +1,6 @@package authimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-- "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"-- "github.com/samber/mo"-"context""crypto/subtle""log/slog"@@ -14,14 +8,15 @@ import ("strings""emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/labstack/echo/v5"+ "github.com/samber/mo")type AuthOptions struct {@@ -109,28 +104,29 @@ func (m *AuthMiddleware) agentAuth(ctx context.Context, c *echo.Context, next ec}req := c.Request()- if strings.HasPrefix(req.URL.Path, utils.AgentPairingPrefix) &&- AgentTokenMatches(req.Header.Get(utils.HeaderAgentBootstrap), m.cfg.AgentToken) {+ if strings.HasPrefix(req.URL.Path, middleware.AgentPairingPrefix) &&+ AgentTokenMatches(req.Header.Get(middleware.HeaderAgentBootstrap), m.cfg.AgentToken) {slog.InfoContext(ctx, "Agent auth: bootstrap pairing accepted", "path", req.URL.Path, "method", req.Method)agentSudoInternal(c)return next(c)}- if AgentTokenMatches(req.Header.Get(utils.HeaderAgentToken), m.cfg.AgentToken) {+ if AgentTokenMatches(req.Header.Get(middleware.HeaderAgentToken), m.cfg.AgentToken) {agentSudoInternal(c)return next(c)}// Check for API key as agent token- if AgentTokenMatches(req.Header.Get(utils.HeaderApiKey), m.cfg.AgentToken) {+ if AgentTokenMatches(req.Header.Get(middleware.HeaderApiKey), m.cfg.AgentToken) {agentSudoInternal(c)return next(c)}- slog.WarnContext(ctx, "Agent auth forbidden",+ slog.WarnContext(+ ctx, "Agent auth forbidden","path", req.URL.Path,"method", req.Method,- "has_agent_token_hdr", req.Header.Get(utils.HeaderAgentToken) != "",+ "has_agent_token_hdr", req.Header.Get(middleware.HeaderAgentToken) != "","agent_token_config_set", m.cfg.AgentToken != "",)return c.JSON(http.StatusForbidden, common.APIError{@@ -150,7 +146,7 @@ func AgentTokenMatches(presented, configured string) bool {func (m *AuthMiddleware) managerAuth(ctx context.Context, c *echo.Context, next echo.HandlerFunc) error {req := c.Request()- if agentToken := req.Header.Get(utils.HeaderAgentToken); agentToken != "" {+ if agentToken := req.Header.Get(middleware.HeaderAgentToken); agentToken != "" {if env, ok := m.resolveEnvironmentAccessToken(ctx, agentToken).Get(); ok {ps := environmentScopedInternal(c, env)return m.authorizeAndContinueInternal(c, next, ps)@@ -158,7 +154,7 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c *echo.Context, next}// First, check for API key in X-API-Key header- if apiKey := req.Header.Get(utils.HeaderApiKey); apiKey != "" {+ if apiKey := req.Header.Get(middleware.HeaderApiKey); apiKey != "" {return m.apiKeyHeaderAuth(ctx, c, next, apiKey)}diff --git a/backend/internal/auth/middleware_test.go b/backend/internal/auth/middleware_test.goindex 2196e2dcc..1faf83ffa 100644--- a/backend/internal/auth/middleware_test.go+++ b/backend/internal/auth/middleware_test.go@@ -1,19 +1,16 @@package authimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"-- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""net/http""net/http/httptest""testing""time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/session"usersvc "github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"diff --git a/backend/internal/auth/module.go b/backend/internal/auth/module.goindex 978ad6097..5647d335d 100644--- a/backend/internal/auth/module.go+++ b/backend/internal/auth/module.go@@ -6,7 +6,6 @@ import ("context""github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user"authtypes "github.com/getarcaneapp/arcane/types/v2/auth"diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.goindex 39692940d..768b47236 100644--- a/backend/internal/auth/service.go+++ b/backend/internal/auth/service.go@@ -1,12 +1,8 @@package authimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""crypto/mldsa"- "crypto/sha256"- "encoding/hex""fmt""log/slog""maps"@@ -18,9 +14,9 @@ import ("emperror.dev/emperror""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/session"@@ -33,6 +29,7 @@ import ("github.com/lestrrat-go/jwx/v4/jwt""github.com/samber/hot""go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg")const (@@ -430,10 +427,7 @@ func (s *AuthService) tryMergeOidcUser(ctx context.Context, userInfo auth.OidcUsexistingUser, emailErr := s.userService.GetUserByEmail(ctx, userInfo.Email)if emailErr != nil {- if errors.Is(emailErr, common.ErrUserNotFound) {- return nil, false, nil- }- return nil, false, emailErr+ return nil, false, kit.Ternary(errors.Is(emailErr, common.ErrUserNotFound), nil, emailErr)}if existingUser == nil {return nil, false, nil@@ -672,10 +666,7 @@ func (s *AuthService) oidcGroupsClaim(ctx context.Context) string {return "groups"}v := strings.TrimSpace(settings.OidcGroupsClaim.Value)- if v == "" {- return "groups"- }- return v+ return kit.Ternary(v == "", "groups", v)}func (s *AuthService) persistOidcTokens(user *common.User, tokenResp *auth.OidcTokenResponse) {@@ -778,7 +769,7 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, met}func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*common.User, string, error) {- tokenHash := hashTokenInternal(accessToken)+ tokenHash := kit.SHA256Hex(accessToken)if user, sessionID, ok := s.cachedVerificationInternal(tokenHash); ok {return user, sessionID, nil}@@ -794,7 +785,7 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*com}func (s *AuthService) VerifyBrowserToken(ctx context.Context, browserToken string) (*common.User, string, error) {- tokenHash := "browser:" + hashTokenInternal(browserToken)+ tokenHash := "browser:" + kit.SHA256Hex(browserToken)if user, sessionID, ok := s.cachedVerificationInternal(tokenHash); ok {return user, sessionID, nil}@@ -847,10 +838,7 @@ func (s *AuthService) verifyTokenClaimsInternal(ctx context.Context, tokenHash s// even if the JWT signature is still valid (e.g. same signing key).dbUser, err := s.userService.GetUserByID(ctx, claims.UserID)if err != nil {- if errors.Is(err, common.ErrUserNotFound) {- return nil, "", common.ErrInvalidToken- }- return nil, "", err+ return nil, "", kit.Ternary[error](errors.Is(err, common.ErrUserNotFound), common.ErrInvalidToken, err)}userSession, err := s.sessionService.GetSessionByID(ctx, claims.SessionID)@@ -869,11 +857,6 @@ func (s *AuthService) verifyTokenClaimsInternal(ctx context.Context, tokenHash sreturn dbUser, userSession.ID, nil}-func hashTokenInternal(token string) string {- sum := sha256.Sum256([]byte(token))- return hex.EncodeToString(sum[:])-}-func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPassword, newPassword, currentSessionID string) error {if s.sessionService == nil {return common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))@@ -1182,8 +1165,5 @@ func ClampFederatedTokenTTLSeconds(ttlSeconds int) int {if ttlSeconds < 60 {return 60}- if ttlSeconds > 3600 {- return 3600- }- return ttlSeconds+ return kit.Ternary(ttlSeconds > 3600, 3600, ttlSeconds)}diff --git a/backend/internal/auth/service_test.go b/backend/internal/auth/service_test.goindex 0483dbe03..62debe958 100644--- a/backend/internal/auth/service_test.go+++ b/backend/internal/auth/service_test.go@@ -1,12 +1,6 @@package authimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"-- "github.com/getarcaneapp/arcane/backend/v2/internal/role"-- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-"bytes""context""crypto/mldsa"@@ -15,23 +9,25 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "go.uber.org/fx/fxtest"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"+ "github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/types/v2/auth""github.com/lestrrat-go/jwx/v4/jwa""github.com/lestrrat-go/jwx/v4/jwt"+ "github.com/libtnb/sqlite""github.com/samber/hot""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.uber.org/fx/fxtest"+ "gorm.io/gorm")func setupAuthServiceTestDB(t *testing.T) *database.DB {@@ -131,7 +127,7 @@ func signUnsignedTokenInternal(t testing.TB, claims map[string]any) string {return string(signed)}-func makeAccessToken(t *testing.T, key *mldsa.PrivateKey, subject string, id string, username string, _ []string, email, displayName string, exp time.Time, sessionIDs ...string) string {+func makeAccessToken(t *testing.T, key *mldsa.PrivateKey, subject, id, username string, _ []string, email, displayName string, exp time.Time, sessionIDs ...string) string {t.Helper()sessionID := ""if len(sessionIDs) > 0 {@@ -152,7 +148,7 @@ func makeAccessToken(t *testing.T, key *mldsa.PrivateKey, subject string, id strreturn signLegacyTokenInternal(t, key, claims)}-func makeRefreshToken(t *testing.T, key *mldsa.PrivateKey, subject string, id string, exp time.Time, userIDAndSessionID ...string) string {+func makeRefreshToken(t *testing.T, key *mldsa.PrivateKey, subject, id string, exp time.Time, userIDAndSessionID ...string) string {t.Helper()userID := idsessionID := ""@@ -227,7 +223,6 @@ func TestVerifyToken_ValidClaims(t *testing.T) {assert.False(t, verifiedUser.DisplayName == nil || *verifiedUser.DisplayName != "Alice","displayName %v", verifiedUser.DisplayName)-}func TestVerifyToken_RejectsNonMLDSAAlg(t *testing.T) {@@ -252,7 +247,6 @@ func TestVerifyToken_RejectsNonMLDSAAlg(t *testing.T) {assert.ErrorIs(t, err, common.ErrInvalidToken,"want common.ErrInvalidToken, got %v", err)-}func TestVerifyToken_Expired(t *testing.T) {@@ -277,7 +271,6 @@ func TestVerifyToken_Expired(t *testing.T) {assert.ErrorIs(t, err, common.ErrExpiredToken,"want ErrExpiredToken, got %v", err)-}func TestVerifyToken_InvalidSubject(t *testing.T) {@@ -300,7 +293,6 @@ func TestVerifyToken_InvalidSignature(t *testing.T) {assert.ErrorIs(t, err, common.ErrInvalidToken,"want common.ErrInvalidToken, got %v", err)-}func TestVerifyToken_MissingUserID(t *testing.T) {@@ -327,7 +319,6 @@ func TestGenerateUsernameFromEmail(t *testing.T) {assert.Equal(t, "user_short", u3,"short subject username %q", u3)-}func TestUniqueOidcUsernameInternal(t *testing.T) {@@ -369,7 +360,6 @@ func TestPersistOidcTokens_SetsFields(t *testing.T) {assert.False(t, user.OidcAccessTokenExpiresAt.Before(earliest) || user.OidcAccessTokenExpiresAt.After(latest),"expiresAt %v not in [%v,%v]", user.OidcAccessTokenExpiresAt, earliest, latest)-}func TestVerifyToken_VersionMismatch(t *testing.T) {@@ -726,7 +716,6 @@ func TestRefreshToken_RejectsNonHMACAlg(t *testing.T) {assert.ErrorIs(t, err, common.ErrInvalidToken,"want common.ErrInvalidToken, got %v", err)-}func TestGetOidcConfigurationStatus(t *testing.T) {@@ -789,7 +778,6 @@ func TestGetOidcConfigurationStatus(t *testing.T) {assert.False(t, !status.EnvForced || !status.EnvConfigured,"expected enabled and configured, got forced=%v configured=%v", status.EnvForced, status.EnvConfigured)-}func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_NoExistingUser_CreatesNewUser(t *testing.T) {@@ -844,7 +832,6 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_NoExistingUser_Creatrequire.True(t, isNew)require.NotEqual(t, created.ID, other.ID)require.NotEqual(t, created.Username, other.Username)-}func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_WithExistingUser_ReturnsError(t *testing.T) {diff --git a/backend/internal/auth/token.go b/backend/internal/auth/token.goindex 1c97262e3..aed41236c 100644--- a/backend/internal/auth/token.go+++ b/backend/internal/auth/token.go@@ -6,11 +6,11 @@ import ("time""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/lestrrat-go/jwx/v4/jwa""github.com/lestrrat-go/jwx/v4/jws""github.com/lestrrat-go/jwx/v4/jwt"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ kit "go.getarcane.app/kit/pkg")const (@@ -133,10 +133,8 @@ func signedTokenAlgorithmInternal(rawToken string) (string, bool) {func parseRefreshTokenInternal(ctx context.Context, rawToken string, key *mldsa.PublicKey) (*refreshTokenClaims, error) {token, err := jwt.ParseString(rawToken, append(tokenParseOptions, jwt.WithKey(jwa.MLDSA87(), key), jwt.WithContext(ctx))...)if err != nil {- if errors.Is(err, jwt.MissingRequiredClaimError{}) || errors.Is(err, jwt.ClaimValidationError{}) {- return nil, common.ErrTokenValidation- }- return nil, common.ErrInvalidToken+ claimErr := errors.Is(err, jwt.MissingRequiredClaimError{}) || errors.Is(err, jwt.ClaimValidationError{})+ return nil, kit.Ternary[error](claimErr, common.ErrTokenValidation, common.ErrInvalidToken)}subject, _ := token.Subject()diff --git a/backend/internal/backup/engine.go b/backend/internal/backup/engine.goindex 40e12b5c5..07b604ec4 100644--- a/backend/internal/backup/engine.go+++ b/backend/internal/backup/engine.go@@ -4,6 +4,7 @@package backupimport (+ "cmp""context""crypto/rand""encoding/base32"@@ -31,15 +32,20 @@ import ("github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""gorm.io/gorm")-// Admission scopes shared by the backup engine and the per-policy job-// registries so scheduled and manual runs contend on the same leases.const (+ // Admission scopes shared by the backup engine and the per-policy job+ // registries so scheduled and manual runs contend on the same leases.+VolumeAdmissionScope = "volume-backup"SystemAdmissionScope = "system-backup"++ // RecoveryKeyConfigID is the singleton row holding the instance-wide backup recovery key.+ RecoveryKeyConfigID = "system-recovery")// Repository addresses one Rustic repository. ID is the stable serialization@@ -190,10 +196,7 @@ func (e *Engine) RestoreSnapshot(ctx context.Context, dockerClient *client.Clienif options.SourcePath != "" {source = snapshotID + ":/" + strings.TrimPrefix(options.SourcePath, "/")}- destination := options.DestinationPath- if destination == "" {- destination = target.Target- }+ destination := cmp.Or(options.DestinationPath, target.Target)command = append(command, "--", source, destination)mounts := append([]mount.Mount{target}, options.ExtraMounts...)_, err := e.runInternal(ctx, dockerClient, repository, password, command, mounts...)@@ -398,17 +401,13 @@ func (e *Engine) ForgetSnapshots(ctx context.Context, dockerClient *client.Clienreturn errors.New("at least one snapshot ID is required")}requested := make([]string, 0, len(snapshotIDs))- seen := make(map[string]struct{}, len(snapshotIDs))for _, id := range snapshotIDs {if !fullSnapshotIDInternal(id) {return errors.New("a full snapshot ID is required")}- canonicalID := strings.ToLower(id)- if _, exists := seen[canonicalID]; !exists {- seen[canonicalID] = struct{}{}- requested = append(requested, canonicalID)- }+ requested = append(requested, strings.ToLower(id))}+ requested = kit.Unique(requested)if e == nil {return errors.New("backup engine is unavailable")}@@ -538,6 +537,7 @@ func (e *Engine) ensureImageInternal(ctx context.Context, dockerClient *client.C}return nil}+func arcaneNetworkModeInternal(ctx context.Context, dockerClient *client.Client) container.NetworkMode {arcane, err := libarcane.InspectCurrentArcaneContainer(ctx, dockerClient)if err != nil || arcane == nil || arcane.ID == "" {@@ -556,9 +556,6 @@ func (e *Engine) runContainerInternal(ctx context.Context, dockerClient *client.return rusticruntime.Run(ctx, dockerClient, password, command, repository.Environment, mounts, arcaneNetworkModeInternal(ctx, dockerClient))}-// RecoveryKeyConfigID is the singleton row holding the instance-wide backup recovery key.-const RecoveryKeyConfigID = "system-recovery"-var (ErrRecoveryKeyNotConfigured = errors.New("recovery key is not configured")diff --git a/backend/internal/backup/policies.go b/backend/internal/backup/policies.goindex a494e7d4c..da6a0e460 100644--- a/backend/internal/backup/policies.go+++ b/backend/internal/backup/policies.go@@ -6,7 +6,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/database"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule"diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 4873b786f..fb6de4aba 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -1,6 +1,7 @@package bootstrapimport (+ "cmp""context""io""log/slog"@@ -10,10 +11,6 @@ import ("time""emperror.dev/errors"-- "github.com/moby/moby/client"- "github.com/subosito/gotenv"-"github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"@@ -37,6 +34,8 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"httpxtypes "github.com/getarcaneapp/arcane/types/v2/httpx""github.com/labstack/echo/v5"+ "github.com/moby/moby/client"+ "github.com/subosito/gotenv""go.getarcane.app/streams/logs"libcrypto "go.getarcane.app/sys/crypto""go.uber.org/fx"@@ -272,10 +271,7 @@ func initializeStartupState(p initializeStartupStateParams) {return err}- effectiveAPIVersion := strings.TrimSpace(dockerClient.ClientVersion())- if effectiveAPIVersion == "" {- effectiveAPIVersion = strings.TrimSpace(version.APIVersion)- }+ effectiveAPIVersion := cmp.Or(strings.TrimSpace(dockerClient.ClientVersion()), strings.TrimSpace(version.APIVersion))slog.InfoContext(ctx, "Docker API versions detected", "client_api_version", dockerClient.ClientVersion(), "server_api_version", version.APIVersion, "effective_api_version", effectiveAPIVersion)return nil})diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.goindex 9cb08eda1..e3fd15207 100644--- a/backend/internal/bootstrap/edge_bootstrap.go+++ b/backend/internal/bootstrap/edge_bootstrap.go@@ -1,17 +1,15 @@package bootstrapimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""encoding/json/v2""fmt""log/slog""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -19,6 +17,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"notificationdto "github.com/getarcaneapp/arcane/types/v2/notification""github.com/labstack/echo/v5"+ kit "go.getarcane.app/kit/pkg""go.uber.org/fx")@@ -76,11 +75,11 @@ func registerEdgeTunnelRoutes(Severity: event.EventSeverity(evt.Severity),Title: evt.Title,Description: evt.Description,- ResourceType: optionalStringPtr(evt.ResourceType),- ResourceID: optionalStringPtr(evt.ResourceID),- ResourceName: optionalStringPtr(evt.ResourceName),- UserID: optionalStringPtr(evt.UserID),- Username: optionalStringPtr(evt.Username),+ ResourceType: new(evt.ResourceType),+ ResourceID: new(evt.ResourceID),+ ResourceName: new(evt.ResourceName),+ UserID: new(evt.UserID),+ Username: new(evt.Username),EnvironmentID: &envID,Metadata: metadata,}@@ -113,7 +112,7 @@ func registerEdgeTunnelRoutes(return env.Name, nil})server.SetEventCallback(eventCallback)- server.SetEnrollmentCallback(func(ctx context.Context, envID, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool) {+ server.SetEnrollmentCallback(func(ctx context.Context, envID, remoteAddr string, certIssued, caGenerated, reenrolled bool) {if eventService == nil {return}@@ -125,7 +124,7 @@ func registerEdgeTunnelRoutes(envNameCopy := envName_, _ = eventService.CreateEvent(ctx, event.CreateEventRequest{Type: event.EventTypeEnvironmentMTLSEnroll,- Severity: edgeMTLSEnrollmentSeverityInternal(reenrolled),+ Severity: kit.Ternary(reenrolled, event.EventSeverityWarning, event.EventSeverityInfo),Title: "Edge mTLS enrollment",Description: "Edge agent completed mTLS enrollment from " + remoteAddr,ResourceType: new("environment"),@@ -164,7 +163,7 @@ func registerEdgeTunnelRoutes(return server}-func createEdgeMTLSIssueEventsInternal(ctx context.Context, eventService *event.EventService, envID string, envName string, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool) {+func createEdgeMTLSIssueEventsInternal(ctx context.Context, eventService *event.EventService, envID, envName, remoteAddr string, certIssued, caGenerated, reenrolled bool) {if eventService == nil {return}@@ -180,7 +179,7 @@ func createEdgeMTLSIssueEventsInternal(ctx context.Context, eventService *event.if certIssued {_, _ = eventService.CreateEvent(ctx, event.CreateEventRequest{Type: event.EventTypeEnvironmentMTLSCertIssued,- Severity: edgeMTLSCertIssuedSeverityInternal(reenrolled),+ Severity: kit.Ternary(reenrolled, event.EventSeverityWarning, event.EventSeverityInfo),Title: "Edge mTLS certificate issued",Description: fmt.Sprintf("Arcane issued an edge mTLS client certificate for environment '%s'", envName),ResourceType: new("environment"),@@ -192,27 +191,6 @@ func createEdgeMTLSIssueEventsInternal(ctx context.Context, eventService *event.}}-func edgeMTLSEnrollmentSeverityInternal(reenrolled bool) event.EventSeverity {- if reenrolled {- return event.EventSeverityWarning- }- return event.EventSeverityInfo-}--func edgeMTLSCertIssuedSeverityInternal(reenrolled bool) event.EventSeverity {- if reenrolled {- return event.EventSeverityWarning- }- return event.EventSeverityInfo-}--func optionalStringPtr(value string) *string {- if value == "" {- return nil- }- return &value-}-// handleEdgeStatusChange records a tunnel up/down transition: it updates the// stored connection state, logs an event when the state actually changed, and// wakes any open status streams.diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex f82261fcf..b38ed1939 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -7,10 +7,7 @@ import ("net/http""slices"- "github.com/getarcaneapp/arcane/types/v2/features"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/apns"@@ -24,6 +21,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/volume""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"+ "github.com/getarcaneapp/arcane/types/v2/features"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""go.uber.org/fx")@@ -304,7 +302,7 @@ type settingsEffectsSchedulerInternal interface {type timeoutSettingsEnvironmentInternal interface {ListRemoteEnvironments(ctx context.Context) ([]environment.Environment, error)- ProxyRequest(ctx context.Context, envID string, method string, path string, body []byte) ([]byte, int, error)+ ProxyRequest(ctx context.Context, envID, method, path string, body []byte) ([]byte, int, error)}func setupSettingsSubscriptionsInternal(params settingsSubscriptionsParams) error {diff --git a/backend/internal/bootstrap/jobs_bootstrap_test.go b/backend/internal/bootstrap/jobs_bootstrap_test.goindex 0cc1b217c..669f3b116 100644--- a/backend/internal/bootstrap/jobs_bootstrap_test.go+++ b/backend/internal/bootstrap/jobs_bootstrap_test.go@@ -1,8 +1,6 @@package bootstrapimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-"context""slices""testing"@@ -10,6 +8,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler""github.com/getarcaneapp/arcane/types/v2/features"@@ -65,7 +64,7 @@ func (s *timeoutSyncEnvironmentStubInternal) ListRemoteEnvironments(context.Cont}}, nil}-func (s *timeoutSyncEnvironmentStubInternal) ProxyRequest(ctx context.Context, _ string, _ string, _ string, _ []byte) ([]byte, int, error) {+func (s *timeoutSyncEnvironmentStubInternal) ProxyRequest(ctx context.Context, _, _, _ string, _ []byte) ([]byte, int, error) {select {case <-s.started:default:diff --git a/backend/internal/bootstrap/logger_bootstrap.go b/backend/internal/bootstrap/logger_bootstrap.goindex d4dcdb760..3c6b5c1b8 100644--- a/backend/internal/bootstrap/logger_bootstrap.go+++ b/backend/internal/bootstrap/logger_bootstrap.go@@ -9,10 +9,9 @@ import ("time""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/lmittmann/tint"slogGorm "github.com/orandin/slog-gorm"-- "github.com/getarcaneapp/arcane/backend/v2/internal/config""gorm.io/gorm""gorm.io/gorm/logger")diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex b2983f2b6..3604dfa2b 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -1,10 +1,6 @@package bootstrapimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""log/slog""net"@@ -13,16 +9,13 @@ import ("strings""emperror.dev/errors"-- "github.com/labstack/echo/v5"- echomiddleware "github.com/labstack/echo/v5/middleware"- slogecho "github.com/samber/slog-echo/v2"-"github.com/getarcaneapp/arcane/backend/v2/api""github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/frontend""github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/auth"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/federated""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -32,6 +25,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx""github.com/getarcaneapp/arcane/types/v2"+ "github.com/labstack/echo/v5"+ echomiddleware "github.com/labstack/echo/v5/middleware"+ slogecho "github.com/samber/slog-echo/v2""go.uber.org/fx")@@ -128,7 +124,7 @@ func createAuthValidatorInternal(deps api.HandlerDeps) middleware.AuthValidatorreturn func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *common.User, bool) {req := c.Request()// Check for API key authentication- if apiKey := req.Header.Get("X-Api-Key"); apiKey != "" {+ if apiKey := req.Header.Get(middleware.HeaderApiKey); apiKey != "" {// User-owned API key: personal keys inherit the owner's role// permissions; scoped keys are limited to their own grants.if user, key, err := deps.ApiKey.Service().ValidateApiKeyWithID(ctx, apiKey); err == nil && user != nil {diff --git a/backend/internal/bootstrap/router_bootstrap_test.go b/backend/internal/bootstrap/router_bootstrap_test.goindex cdbdef8ab..4fac63a3d 100644--- a/backend/internal/bootstrap/router_bootstrap_test.go+++ b/backend/internal/bootstrap/router_bootstrap_test.go@@ -27,7 +27,8 @@ func TestNewEchoInternal_DecodesPathParams(t *testing.T) {}, func(_ context.Context, input *struct {ID string `path:"id"`ImageID string `path:"imageId"`- }) (*struct{}, error) {+ },+ ) (*struct{}, error) {got = input.ImageIDreturn nil, nil})diff --git a/backend/internal/bootstrap/server_bootstrap.go b/backend/internal/bootstrap/server_bootstrap.goindex ea364570c..2f12d82fb 100644--- a/backend/internal/bootstrap/server_bootstrap.go+++ b/backend/internal/bootstrap/server_bootstrap.go@@ -10,7 +10,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"diff --git a/backend/internal/build/model.go b/backend/internal/build/model.goindex f1ae411ce..52c7eefad 100644--- a/backend/internal/build/model.go+++ b/backend/internal/build/model.go@@ -1,9 +1,9 @@package buildimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database")type ImageBuildStatus stringdiff --git a/backend/internal/build/service.go b/backend/internal/build/service.goindex c75b4ae2b..e4ae34f6f 100644--- a/backend/internal/build/service.go+++ b/backend/internal/build/service.go@@ -1,8 +1,7 @@package buildimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-+ "cmp""context""fmt""io"@@ -13,14 +12,13 @@ import ("strings""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-"emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"buildgit "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil"@@ -29,8 +27,9 @@ import (buildapi "go.getarcane.app/builds/api""go.getarcane.app/builds/pkg/contextsource"buildtypes "go.getarcane.app/builds/types"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/kit/pkg/capture"- arcanekit "go.getarcane.app/kit/pkg/git"+ gitkit "go.getarcane.app/kit/pkg/git""gorm.io/gorm")@@ -184,7 +183,7 @@ func (s *BuildService) logBuildFailureEventInternal(ctx context.Context, environreturn}- resourceName := firstNonEmptyStringInternal(req.Tags...)+ resourceName := cmp.Or(kit.TrimNonEmpty(req.Tags)...)if resourceName == "" {resourceName = strings.TrimSpace(serviceName)}@@ -225,10 +224,7 @@ func sanitizeBuildContextForEventInternal(raw string) string {base, fragment, hasFragment := strings.Cut(trimmed, "#")parsed, err := url.Parse(base)if err != nil {- if strings.Contains(base, "@") {- return "[unparseable URL]"- }- return trimmed+ return kit.Ternary(strings.Contains(base, "@"), "[unparseable URL]", trimmed)}if parsed.User == nil {return trimmed@@ -250,19 +246,7 @@ func (s *BuildService) effectiveBuildProviderInternal(provider string) string {if s.settings != nil {provider = strings.ToLower(strings.TrimSpace(s.settings.GetSettingsConfig().BuildProvider.Value))}- if provider == "" {- return "local"- }- return provider-}--func firstNonEmptyStringInternal(values ...string) string {- for _, value := range values {- if trimmed := strings.TrimSpace(value); trimmed != "" {- return trimmed- }- }- return ""+ return kit.Ternary(provider == "", "local", provider)}func (s *BuildService) resolveBuildRequestInternal(@@ -291,7 +275,7 @@ func (s *BuildService) resolveBuildRequestInternal(if matchedRepository {writeBuildProgressStatusInternal(progressWriter, serviceName, "using saved git credentials for "+source.RepositoryURL)}- if arcanekit.RequiresRemoteProbe(source.RepositoryURL) {+ if gitkit.RequiresRemoteProbe(source.RepositoryURL) {writeBuildProgressStatusInternal(progressWriter, serviceName, "verifying remote git repository "+source.RepositoryURL)if err := s.probeGitContextInternal(ctx, source.RepositoryURL, authConfig); err != nil {return buildtypes.BuildRequest{}, func() error { return nil }, errors.WrapIff(err, "failed to verify remote git repository %q", source.RepositoryURL)@@ -425,9 +409,7 @@ func (s *BuildService) ListImageBuildsByEnvironmentPaginated(ctx context.Contextq = pagination.ApplyFilter(q, "status", params.Filters["status"])q = pagination.ApplyFilter(q, "provider", params.Filters["provider"])- if params.Sort == "" {- params.Sort = "createdAt"- }+ params.Sort = cmp.Or(params.Sort, "createdAt")paginationResp, err := pagination.PaginateAndSortDB(params, q, &builds)if err != nil {@@ -599,11 +581,7 @@ func mapToJSON(input map[string]string) database.JSON {out[key] = value}- if len(out) == 0 {- return nil- }-- return out+ return kit.Ternary(len(out) == 0, nil, out)}func jsonToStringMap(input database.JSON) map[string]string {@@ -612,9 +590,5 @@ func jsonToStringMap(input database.JSON) map[string]string {out[key] = fmt.Sprint(value)}- if len(out) == 0 {- return nil- }-- return out+ return kit.Ternary(len(out) == 0, nil, out)}diff --git a/backend/internal/build/service_test.go b/backend/internal/build/service_test.goindex dc7e4914e..3cb5c8788 100644--- a/backend/internal/build/service_test.go+++ b/backend/internal/build/service_test.go@@ -1,8 +1,6 @@package buildimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"bytes""context""encoding/json/v2"@@ -14,6 +12,7 @@ import ("strings""testing"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"@@ -239,7 +238,7 @@ func TestBuildService_ResolveBuildRequest_UsesSavedGitCredentials(t *testing.T)require.FailNow(t, "git remote probe should not run for ssh URLs")return nil},- gitCloneFn: func(_ context.Context, _ string, _ string, auth buildgit.AuthConfig) (string, error) {+ gitCloneFn: func(_ context.Context, _, _ string, auth buildgit.AuthConfig) (string, error) {assert.Equal(t, "ssh", auth.AuthType)assert.Equal(t, "ssh-private-key", auth.SSHKey)assert.Equal(t, "strict", auth.SSHHostKeyVerification)@@ -274,7 +273,7 @@ func TestBuildService_BuildImage_PreservesRemoteSourceInHistory(t *testing.T) {captured = req},},- gitCloneFn: func(_ context.Context, _ string, _ string, _ buildgit.AuthConfig) (string, error) {+ gitCloneFn: func(_ context.Context, _, _ string, _ buildgit.AuthConfig) (string, error) {return repoPath, nil},gitCleanupFn: func(string) error { return nil },diff --git a/backend/internal/build/workspace_service.go b/backend/internal/build/workspace_service.goindex 4bf0a30d9..6c7818378 100644--- a/backend/internal/build/workspace_service.go+++ b/backend/internal/build/workspace_service.go@@ -1,8 +1,10 @@package buildimport (+ "cmp""context""io"+ "log/slog""net/http""os""path"@@ -10,14 +12,11 @@ import ("strings""emperror.dev/errors"-- "log/slog"-"github.com/getarcaneapp/arcane/backend/v2/internal/settings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"acfsutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/acfs"workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg")const defaultBuildsDirectory = "/builds"@@ -38,7 +37,7 @@ func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath strinreturn nil, err}- cleaned, err := utils.SanitizeBrowsePath(dirPath)+ cleaned, err := kit.SanitizeBrowsePath(dirPath)if err != nil {return nil, errors.WrapIf(err, "invalid path")}@@ -63,7 +62,7 @@ func (s *BuildWorkspaceService) GetFileContent(ctx context.Context, filePath strreturn nil, "", err}- cleaned, err := utils.SanitizeBrowsePath(filePath)+ cleaned, err := kit.SanitizeBrowsePath(filePath)if err != nil {return nil, "", errors.WrapIf(err, "invalid path")}@@ -94,7 +93,7 @@ func (s *BuildWorkspaceService) DownloadFile(ctx context.Context, filePath strinreturn nil, 0, err}- cleaned, err := utils.SanitizeBrowsePath(filePath)+ cleaned, err := kit.SanitizeBrowsePath(filePath)if err != nil {return nil, 0, errors.WrapIf(err, "invalid path")}@@ -119,7 +118,7 @@ func (s *BuildWorkspaceService) UploadFile(ctx context.Context, destPath string,return err}- cleaned, err := utils.SanitizeBrowsePath(destPath)+ cleaned, err := kit.SanitizeBrowsePath(destPath)if err != nil {return errors.WrapIf(err, "invalid path")}@@ -143,7 +142,7 @@ func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath strreturn err}- cleaned, err := utils.SanitizeBrowsePath(dirPath)+ cleaned, err := kit.SanitizeBrowsePath(dirPath)if err != nil {return errors.WrapIf(err, "invalid path")}@@ -166,7 +165,7 @@ func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string)return err}- cleaned, err := utils.SanitizeBrowsePath(filePath)+ cleaned, err := kit.SanitizeBrowsePath(filePath)if err != nil {return errors.WrapIf(err, "invalid path")}@@ -187,10 +186,7 @@ func (s *BuildWorkspaceService) resolveRoot() (string, error) {return "", errors.New("settings service not available")}- root := strings.TrimSpace(s.settings.GetSettingsConfig().BuildsDirectory.Value)- if root == "" {- root = defaultBuildsDirectory- }+ root := cmp.Or(strings.TrimSpace(s.settings.GetSettingsConfig().BuildsDirectory.Value), defaultBuildsDirectory)if !filepath.IsAbs(root) {return "", errors.New("builds directory must be an absolute path")diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.goindex 065000ba5..bc5aca5e9 100644--- a/backend/internal/common/errors.go+++ b/backend/internal/common/errors.go@@ -16,11 +16,11 @@ const (ErrConflict = errors.Sentinel("kind: conflict")ErrTimeout = errors.Sentinel("kind: timeout")ErrUnavailable = errors.Sentinel("kind: service unavailable")-)-// ConfigurationErrorCodeEnvFileUnreadable is the ConfigurationError code reported-// alongside ErrProjectEnvUnreadable.-const ConfigurationErrorCodeEnvFileUnreadable = "env_file_unreadable"+ // ConfigurationErrorCodeEnvFileUnreadable is the ConfigurationError code reported+ // alongside ErrProjectEnvUnreadable.+ ConfigurationErrorCodeEnvFileUnreadable = "env_file_unreadable"+)type classified struct {kind errordiff --git a/backend/internal/common/user.go b/backend/internal/common/user.goindex dcd031da9..e1d621941 100644--- a/backend/internal/common/user.go+++ b/backend/internal/common/user.go@@ -1,11 +1,10 @@package commonimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/types/v2/user")diff --git a/backend/internal/config/config.go b/backend/internal/config/config.goindex 211e3af68..678a0b05b 100644--- a/backend/internal/config/config.go+++ b/backend/internal/config/config.go@@ -1,6 +1,7 @@package configimport (+ "cmp""fmt""log/slog""net"@@ -13,6 +14,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+ kit "go.getarcane.app/kit/pkg")type AppEnvironment string@@ -224,7 +226,7 @@ func loadFromEnv(cfg *Config) {envValue, _, fromFile = utils.LookupEnvOrFile(envTag)}if !fromFile {- envValue = utils.TrimQuotes(envValue)+ envValue = kit.TrimQuotes(envValue)if envValue == "" {envValue = fieldType.Tag.Get("default")}@@ -409,10 +411,7 @@ func (a AppEnvironment) IsTestEnvironment() bool {// It uses LISTEN as the host (if set) and PORT for the port.func (c *Config) ListenAddr() string {host := strings.TrimSpace(c.Listen)- port := c.Port- if port == "" {- port = "3552"- }+ port := cmp.Or(c.Port, "3552")if host == "" {return ":" + port}@@ -466,10 +465,7 @@ func (c *Config) MaskSensitive() map[string]any {field := v.Field(i)fieldType := t.Field(i)- envTag := fieldType.Tag.Get("env")- if envTag == "" {- envTag = fieldType.Name- }+ envTag := cmp.Or(fieldType.Tag.Get("env"), fieldType.Name)// Fields with "file" option are considered sensitiveoptionsTag := fieldType.Tag.Get("options")@@ -478,11 +474,7 @@ func (c *Config) MaskSensitive() map[string]any {if isSensitive {// Mask sensitive valuesstrVal := fmt.Sprintf("%v", field.Interface())- if len(strVal) > 0 {- result[envTag] = "****"- } else {- result[envTag] = "(empty)"- }+ result[envTag] = kit.Ternary(len(strVal) > 0, "****", "(empty)")} else {result[envTag] = field.Interface()}diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.goindex f874a8c09..a9250f0db 100644--- a/backend/internal/config/config_test.go+++ b/backend/internal/config/config_test.go@@ -7,9 +7,8 @@ import ("testing""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"-"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")diff --git a/backend/internal/config/schema/schema.go b/backend/internal/config/schema/schema.goindex 22a25718f..e3810d5f1 100644--- a/backend/internal/config/schema/schema.go+++ b/backend/internal/config/schema/schema.go@@ -2,6 +2,7 @@ package schemaimport ("bytes"+ "cmp""encoding/json/jsontext""encoding/json/v2""go/ast"@@ -17,9 +18,9 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ kit "go.getarcane.app/kit/pkg")const (@@ -251,16 +252,13 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOpticontinue}- options := splitTagListInternal(structTag.Get("options"))+ options := kit.TrimNonEmpty(strings.Split(structTag.Get("options"), ","))typeName, err := exprStringInternal(field.Type)if err != nil {return nil, errors.WrapIff(err, "render type for %s.%s", structName, field.Names[0].Name)}- description := strings.TrimSpace(strings.Join(strings.Fields(field.Doc.Text()), " "))- if description == "" {- description = strings.TrimSpace(strings.Join(strings.Fields(field.Comment.Text()), " "))- }+ description := cmp.Or(strings.Join(strings.Fields(field.Doc.Text()), " "), strings.Join(strings.Fields(field.Comment.Text()), " "))for _, name := range field.Names {entries = append(entries, ConfigEntry{@@ -295,7 +293,7 @@ func collectSettingEnvOverridesInternal() ([]SettingOverrideEntry, error) {continue}- tagParts := splitTagListInternal(keyTag)+ tagParts := kit.TrimNonEmpty(strings.Split(keyTag, ","))if len(tagParts) == 0 {continue}@@ -320,18 +318,15 @@ func collectSettingEnvOverridesInternal() ([]SettingOverrideEntry, error) {rule := overrideDocRules[key]requires := rule.requiresif !hasEnvOverride {- requires = joinRequirementsInternal(- "AGENT_MODE=true or UI_CONFIGURATION_DISABLED=true to manage this setting via env.",- requires,- )+ requires = strings.Join(kit.TrimNonEmpty([]string{"AGENT_MODE=true or UI_CONFIGURATION_DISABLED=true to manage this setting via env.", requires}), " ")}entries = append(entries, SettingOverrideEntry{- Env: strings.ToUpper(utils.CamelCaseToSnakeCase(key)),+ Env: strings.ToUpper(kit.SnakeCase(key)),SettingKey: key,Description: meta["description"],DefaultValue: defaultValue,- Type: defaultStringInternal(meta["type"], "text"),+ Type: kit.Ternary(strings.TrimSpace(meta["type"]) == "", "text", meta["type"]),Sensitive: isSensitive,Deprecated: rule.deprecated || slices.Contains(attrs, "deprecated"),Category: meta["category"],@@ -387,44 +382,6 @@ func exprStringInternal(expr ast.Expr) (string, error) {return buf.String(), nil}-func splitTagListInternal(value string) []string {- if value == "" {- return nil- }-- parts := strings.Split(value, ",")- result := make([]string, 0, len(parts))- for _, part := range parts {- trimmed := strings.TrimSpace(part)- if trimmed == "" {- continue- }- result = append(result, trimmed)- }-- return result-}--func joinRequirementsInternal(parts ...string) string {- filtered := make([]string, 0, len(parts))- for _, part := range parts {- part = strings.TrimSpace(part)- if part == "" {- continue- }- filtered = append(filtered, part)- }-- return strings.Join(filtered, " ")-}--func defaultStringInternal(value, fallback string) string {- if strings.TrimSpace(value) == "" {- return fallback- }- return value-}-func resolveSourceRootInternal(sourceRoot string) (string, error) {candidates := make([]string, 0, 2)if strings.TrimSpace(sourceRoot) != "" {diff --git a/backend/internal/config/schema/schema_test.go b/backend/internal/config/schema/schema_test.goindex 43fe6f242..ce4b1091a 100644--- a/backend/internal/config/schema/schema_test.go+++ b/backend/internal/config/schema/schema_test.go@@ -1,16 +1,16 @@package schemaimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"reflect""slices""sort""strings""testing"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")func TestGenerate_EnvConfigIncludesTaggedFields(t *testing.T) {@@ -180,7 +180,7 @@ func countDocumentedSettingOverrides() int {continue}- tagParts := splitTagListInternal(keyTag)+ tagParts := kit.TrimNonEmpty(strings.Split(keyTag, ","))if len(tagParts) == 0 {continue}diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.goindex d4fd0840d..a2238fd2a 100644--- a/backend/internal/container/handler.go+++ b/backend/internal/container/handler.go@@ -1,10 +1,6 @@package containerimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""fmt""io"@@ -13,12 +9,12 @@ import ("net/netip""strings"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"emperror.dev/errors""github.com/containerd/errdefs""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -28,11 +24,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/base"containertypes "github.com/getarcaneapp/arcane/types/v2/container"dockercontainer "github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/network""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")type ContainerHandler struct {@@ -400,22 +398,6 @@ func parsePortSpec(spec string) (network.Port, error) {return network.ParsePort(spec + "/tcp")}-func resolveCreateCommand(body containertypes.Create) []string {- if len(body.Command) > 0 {- return body.Command- }-- return body.Cmd-}--func resolveCreateEnv(body containertypes.Create) []string {- if len(body.Environment) > 0 {- return body.Environment- }-- return body.Env-}-func buildCreateLabels(body containertypes.Create) map[string]string {labels := map[string]string{"com.arcane.created": "true",@@ -428,11 +410,11 @@ func buildCreateLabels(body containertypes.Create) map[string]string {func buildContainerConfig(body containertypes.Create) *dockercontainer.Config {return &dockercontainer.Config{Image: body.Image,- Cmd: resolveCreateCommand(body),+ Cmd: kit.Ternary(len(body.Command) > 0, body.Command, body.Cmd),Entrypoint: body.Entrypoint,WorkingDir: body.WorkingDir,User: body.User,- Env: resolveCreateEnv(body),+ Env: kit.Ternary(len(body.Environment) > 0, body.Environment, body.Env),ExposedPorts: network.PortSet{},Labels: buildCreateLabels(body),Healthcheck: healthConfigFromCreateInternal(body.Healthcheck),@@ -1020,10 +1002,7 @@ func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpdareturn nil, huma.Error500InternalServerError("failed to update auto-update setting")}- msg := "Auto-update enabled"- if excluded {- msg = "Auto-update disabled"- }+ msg := kit.Ternary(excluded, "Auto-update disabled", "Auto-update enabled")return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{diff --git a/backend/internal/container/logs.go b/backend/internal/container/logs.goindex 06ca98069..25131f9c4 100644--- a/backend/internal/container/logs.go+++ b/backend/internal/container/logs.go@@ -5,11 +5,10 @@ import ("io""emperror.dev/errors"+ dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/moby/moby/api/pkg/stdcopy""github.com/moby/moby/client"-- dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"+ "go.getarcane.app/docker/compat")type demuxedLogsInternal struct {@@ -29,7 +28,7 @@ func (s *ContainerService) openLogsInternal(ctx context.Context, containerID strreturn nil, client.ContainerInspectResult{}, errors.WrapIf(err, "failed to connect to Docker")}- containerInspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ containerInspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {return nil, client.ContainerInspectResult{}, errors.WrapIf(err, "failed to inspect container for logs")}diff --git a/backend/internal/container/logs_test.go b/backend/internal/container/logs_test.goindex a07da5c7b..934a21b50 100644--- a/backend/internal/container/logs_test.go+++ b/backend/internal/container/logs_test.go@@ -11,10 +11,10 @@ import ("strings""testing"- "github.com/stretchr/testify/require"-"github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")func newLogsTestServiceInternal(t *testing.T, tty bool, logsBody []byte, gotQuery *url.Values) *ContainerService {@@ -22,10 +22,7 @@ func newLogsTestServiceInternal(t *testing.T, tty bool, logsBody []byte, gotQuerserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch dockerTestPathInternal(r.URL.Path) {case "/containers/container-1/json":- ttyJSON := "false"- if tty {- ttyJSON = "true"- }+ ttyJSON := kit.Ternary(tty, "true", "false")_, _ = io.WriteString(w, `{"Id":"0123456789abcdef0123456789abcdef","Config":{"Tty":`+ttyJSON+`}}`)case "/containers/container-1/logs":*gotQuery = r.URL.Query()diff --git a/backend/internal/container/module.go b/backend/internal/container/module.goindex 637997ef3..0202dd01c 100644--- a/backend/internal/container/module.go+++ b/backend/internal/container/module.go@@ -4,7 +4,6 @@ package containerimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"diff --git a/backend/internal/container/resource_stats.go b/backend/internal/container/resource_stats.goindex e3ad5d43b..52d1d5175 100644--- a/backend/internal/container/resource_stats.go+++ b/backend/internal/container/resource_stats.go@@ -10,16 +10,16 @@ import ("time""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ containertypes "github.com/getarcaneapp/arcane/types/v2/container""github.com/moby/moby/api/types/container""github.com/moby/moby/client""github.com/samber/hot"+ kit "go.getarcane.app/kit/pkg"containerstats "go.getarcane.app/streams/stats""golang.org/x/sync/errgroup"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"- "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- containertypes "github.com/getarcaneapp/arcane/types/v2/container")const (@@ -208,12 +208,11 @@ func (s *ContainerService) collectResourceSampleInternal(ctx context.Context, co// breaking ties by name, then ID. Valid zero values sort as zero, not as// unavailable.func containerResourceSampleSortInternal(sort string, descending bool) pagination.SortOption[containertypes.Summary] {- var value func(*containertypes.ResourceSample) float64- if sort == containertypes.SortCPUUsage {- value = func(sample *containertypes.ResourceSample) float64 { return sample.CPUPercent }- } else {- value = func(sample *containertypes.ResourceSample) float64 { return float64(sample.MemoryUsageBytes) }- }+ value := kit.Ternary(+ sort == containertypes.SortCPUUsage,+ func(sample *containertypes.ResourceSample) float64 { return sample.CPUPercent },+ func(sample *containertypes.ResourceSample) float64 { return float64(sample.MemoryUsageBytes) },+ )tieBreak := func(a, b containertypes.Summary) int {if c := compareContainerNamesForSortInternal(a, b); c != 0 {@@ -241,9 +240,6 @@ func containerResourceSampleSortInternal(sort string, descending bool) paginatioif descending {less = !less}- if less {- return -1- }- return 1+ return kit.Ternary(less, -1, 1)}}diff --git a/backend/internal/container/resource_stats_test.go b/backend/internal/container/resource_stats_test.goindex 73cf0afc3..c35a27667 100644--- a/backend/internal/container/resource_stats_test.go+++ b/backend/internal/container/resource_stats_test.go@@ -18,6 +18,7 @@ import (containertypes "github.com/getarcaneapp/arcane/types/v2/container""github.com/moby/moby/api/types/container""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")type resourceStatsServerInternal struct {@@ -121,10 +122,7 @@ func (f *resourceStatsServerInternal) handler() http.Handler {slow := f.slowIDs[id]f.mu.Unlock()- wait := delay- if slow {- wait = time.Second- }+ wait := kit.Ternary(slow, time.Second, delay)if wait > 0 {select {case <-time.After(wait):diff --git a/backend/internal/container/service.go b/backend/internal/container/service.goindex 959ad75dc..a49fe3cbf 100644--- a/backend/internal/container/service.go+++ b/backend/internal/container/service.go@@ -1,10 +1,7 @@package containerimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-+ "cmp""context""encoding/json/jsontext""encoding/json/v2"@@ -18,12 +15,8 @@ import ("time""emperror.dev/errors"-- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/api/types/mount"- "github.com/moby/moby/api/types/network"- "github.com/moby/moby/client"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image"@@ -34,12 +27,17 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/iconcatalog"containertypes "github.com/getarcaneapp/arcane/types/v2/container""github.com/getarcaneapp/arcane/types/v2/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/v2/image"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/api/types/mount"+ "github.com/moby/moby/api/types/network"+ "github.com/moby/moby/client""github.com/samber/hot"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg"containerstats "go.getarcane.app/streams/stats""go.getarcane.app/sys/cgroup""go.getarcane.app/updater"@@ -97,7 +95,7 @@ func buildCleanNetworkingConfigInternal(containerInspect container.InspectResponreturn nil}- endpointsConfig := libarcane.SanitizeContainerCreateEndpointSettingsForDockerAPI(containerInspect.NetworkSettings.Networks, apiVersion)+ endpointsConfig := compat.SanitizeContainerCreateEndpointSettingsForDockerAPI(containerInspect.NetworkSettings.Networks, apiVersion)for networkName, endpoint := range endpointsConfig {if endpoint == nil {continue@@ -152,7 +150,8 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerpullOptions, authErr := s.imageService.PullOptionsWithAuth(ctx, imageName, credentials)if authErr != nil {- slog.WarnContext(ctx, "failed to get registry authentication for container recreate pull; proceeding without auth",+ slog.WarnContext(+ ctx, "failed to get registry authentication for container recreate pull; proceeding without auth","image", imageName,"error", authErr.Error(),)@@ -162,7 +161,8 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerdefer s.eventService.BeginDockerResourceSuppressionWindow("image", "", imageName)()reader, pullErr := dockerClient.ImagePull(pullCtx, imageName, pullOptions)if pullErr != nil && image.ShouldRetryAnonymousPull(pullOptions, pullErr) {- slog.WarnContext(ctx, "container recreate image pull failed with registry auth; retrying anonymously",+ slog.WarnContext(+ ctx, "container recreate image pull failed with registry auth; retrying anonymously","image", imageName,"error", pullErr.Error(),)@@ -285,7 +285,7 @@ func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(c}defer s.eventService.BeginDockerResourceSuppressionWindow("container", "", containerName)()- createResp, err := libarcane.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{+ createResp, err := compat.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{Config: &originalConfig,HostConfig: containerInfo.HostConfig,NetworkingConfig: buildCleanNetworkingConfigInternal(containerInfo, apiVersion),@@ -308,7 +308,8 @@ func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(creturn errors.WrapIf(err, "failed to restart original auto-remove container")}- slog.InfoContext(ctx, "restored auto-remove container after failed recreate",+ slog.InfoContext(+ ctx, "restored auto-remove container after failed recreate","oldContainerId", containerID,"restoredContainerId", createResp.ID,"containerName", containerName,@@ -472,10 +473,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID strirepository := strings.TrimSpace(req.Repository)tag := strings.TrimSpace(req.Tag)- reference := repository- if repository != "" && tag != "" {- reference = repository + ":" + tag- }+ reference := kit.Ternary(repository != "" && tag != "", repository+":"+tag, repository)result, err := dockerClient.ContainerCommit(ctx, containerID, client.ContainerCommitOptions{Reference: reference,@@ -537,7 +535,8 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont// errors (should surface so a transient failure doesn't silently recreate// the container from stale cached config).if strings.Contains(err.Error(), "not found") {- slog.WarnContext(ctx, "RedeployContainer: compose project not registered, falling back to standalone redeploy",+ slog.WarnContext(+ ctx, "RedeployContainer: compose project not registered, falling back to standalone redeploy","containerId", containerID,"project", projectName,"service", serviceName,@@ -547,7 +546,8 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Contreturn "", true, errors.WrapIff(err, "failed to look up compose project %s", projectName)}if proj == nil {- slog.WarnContext(ctx, "RedeployContainer: compose project not registered, falling back to standalone redeploy",+ slog.WarnContext(+ ctx, "RedeployContainer: compose project not registered, falling back to standalone redeploy","containerId", containerID,"project", projectName,"service", serviceName,@@ -555,7 +555,8 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Contreturn "", false, nil}- slog.InfoContext(ctx, "RedeployContainer: detected compose container, using project-based redeploy",+ slog.InfoContext(+ ctx, "RedeployContainer: detected compose container, using project-based redeploy","containerId", containerID,"project", projectName,"service", serviceName,@@ -608,7 +609,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID streturn "", errors.WrapIf(err, "failed to connect to Docker")}- containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "redeploy",@@ -629,7 +630,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID stcontainerName := strings.TrimPrefix(containerInfo.Name, "/")imageName := containerInfo.Config.Image- apiVersion := libarcane.DetectDockerAPIVersion(ctx, dockerClient)+ apiVersion := compat.DetectDockerAPIVersion(ctx, dockerClient)currentContainerID, currentContainerErr := cgroup.CurrentContainerID()if labels.ShouldDisableArcaneServerRedeploy(containerInfo.Config.Labels, containerInfo.ID, currentContainerID, currentContainerErr) {@@ -692,7 +693,7 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker}defer s.eventService.BeginDockerResourceSuppressionWindow("container", "", newName)()- createResp, err := libarcane.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{+ createResp, err := compat.ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, client.ContainerCreateOptions{Config: newConfig,HostConfig: newHostConfig,NetworkingConfig: networkingConfig,@@ -740,7 +741,8 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker}}- slog.InfoContext(ctx, "container recreated successfully",+ slog.InfoContext(+ ctx, "container recreated successfully","action", action,"oldContainerId", containerID,"newContainerId", createResp.ID,@@ -755,7 +757,8 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, dockerRemoveVolumes: false,RemoveLinks: false,}); err != nil {- slog.WarnContext(ctx, "failed to remove old container after successful recreate",+ slog.WarnContext(+ ctx, "failed to remove old container after successful recreate","containerId", containerID,"backupName", backupName,"error", err,@@ -1014,7 +1017,7 @@ func buildEditNetworkingConfigInternal(containerInspect container.InspectResponsvar existing map[string]*network.EndpointSettingsif containerInspect.NetworkSettings != nil {- existing = libarcane.SanitizeContainerCreateEndpointSettingsForDockerAPI(containerInspect.NetworkSettings.Networks, apiVersion)+ existing = compat.SanitizeContainerCreateEndpointSettingsForDockerAPI(containerInspect.NetworkSettings.Networks, apiVersion)}endpoints := make(map[string]*network.EndpointSettings, len(req.EndpointsConfig))@@ -1037,7 +1040,6 @@ func buildEditNetworkingConfigInternal(containerInspect container.InspectResponsif len(endpoints) == 0 {return nil, nil}-return &network.NetworkingConfig{EndpointsConfig: endpoints}, nil}@@ -1049,7 +1051,7 @@ func (s *ContainerService) GetContainerEditConfig(ctx context.Context, containerreturn containertypes.EditConfig{}, errors.WrapIf(err, "failed to connect to Docker")}- containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {return containertypes.EditConfig{}, errors.WrapIf(err, "failed to inspect container")}@@ -1080,7 +1082,7 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID stringreturn "", errors.WrapIf(err, "failed to connect to Docker")}- containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "edit",@@ -1117,12 +1119,12 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID string}}if newName != containerName {- if _, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, newName, client.ContainerInspectOptions{}); inspectErr == nil {+ if _, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, newName, client.ContainerInspectOptions{}); inspectErr == nil {return "", errors.WrapIff(common.ErrContainerNameTaken, "container name %s", newName)}}- apiVersion := libarcane.DetectDockerAPIVersion(ctx, dockerClient)+ apiVersion := compat.DetectDockerAPIVersion(ctx, dockerClient)newConfig := *containerInfo.Configvar newHostConfig container.HostConfig@@ -1161,7 +1163,7 @@ func (s *ContainerService) GetContainerByReference(ctx context.Context, ref strireturn nil, errors.WrapIf(err, "failed to connect to Docker")}- containerInspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, ref, client.ContainerInspectOptions{})+ containerInspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, ref, client.ContainerInspectOptions{})if err != nil {return nil, errors.WrapIf(err, "container not found")}@@ -1240,7 +1242,7 @@ func (s *ContainerService) GetContainerNameByID(ctx context.Context, id string)return s.GetContainerNameByReference(ctx, id)}-func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force bool, removeVolumes bool, user common.User) error {+func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force, removeVolumes bool, user common.User) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})@@ -1250,7 +1252,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri// Get container mounts before deletion if we need to remove volumesvar volumesToRemove []stringif removeVolumes {- containerJSON, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ containerJSON, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if inspectErr == nil {for _, mount := range containerJSON.Container.Mounts {// Only collect named volumes (not bind mounts or tmpfs)@@ -1343,7 +1345,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe}defer s.eventService.BeginDockerResourceSuppressionWindow("container", "", containerName)()- resp, err := libarcane.ContainerCreateWithCompatibility(ctx, dockerClient, client.ContainerCreateOptions{+ resp, err := compat.ContainerCreateWithCompatibility(ctx, dockerClient, client.ContainerCreateOptions{Config: config,HostConfig: hostConfig,NetworkingConfig: networkingConfig,@@ -1370,7 +1372,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containereturn nil, errors.WrapIf(err, "failed to start container")}- containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, resp.ID, client.ContainerInspectOptions{})+ containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, resp.ID, client.ContainerInspectOptions{})if err != nil {s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "inspect"})return nil, errors.WrapIf(err, "failed to inspect created container")@@ -1591,11 +1593,7 @@ func getContainerProjectNameInternal(container containertypes.Summary) string {}projectName := dockerutils.ComposeProjectLabel(container.Labels)- if projectName == "" {- return containerNoProjectGroup- }-- return projectName+ return kit.Ternary(projectName == "", containerNoProjectGroup, projectName)}// FilterExcludedContainers removes internal and hidden containers unless their corresponding inclusion flags are enabled.@@ -1606,8 +1604,8 @@ func FilterExcludedContainers(containers []container.Summary, includeInternal, ifiltered := make([]container.Summary, 0, len(containers))for _, dc := range containers {- internal, _ := utils.ParseBool(dc.Labels[libarcane.InternalResourceLabel])- hidden, _ := utils.ParseBool(dc.Labels[libarcane.HiddenResourceLabel])+ internal, _ := kit.ParseBool(dc.Labels[libarcane.InternalResourceLabel])+ hidden, _ := kit.ParseBool(dc.Labels[libarcane.HiddenResourceLabel])if (!includeInternal && internal) || (!includeHidden && hidden) {continue}@@ -1642,15 +1640,12 @@ func (s *ContainerService) BuildSummaries(ctx context.Context, containers []contresolved, policyErr := tagpolicy.Resolve(dc.Image, policy)summary.UpdateStrategy = resolved.Strategyif policyErr != nil {- summary.UpdateStrategy = policy.Strategy- if summary.UpdateStrategy == "" {- summary.UpdateStrategy = "auto"- }+ summary.UpdateStrategy = cmp.Or(policy.Strategy, "auto")}summary.UpdateInfo = updateInfoMap[dc.ID]summary.RedeployDisabled = labels.ShouldDisableArcaneServerRedeploy(summary.Labels, summary.ID, currentContainerID, currentContainerErr)summary.AutoUpdateEnabled = !labels.IsUpdateDisabled(dc.Labels) && !dockerutils.ContainerNameExcluded(dc.Names, excluded)- summary.Hidden, _ = utils.ParseBool(dc.Labels[libarcane.HiddenResourceLabel])+ summary.Hidden, _ = kit.ParseBool(dc.Labels[libarcane.HiddenResourceLabel])items = append(items, summary)}return items@@ -1700,7 +1695,7 @@ func (s *ContainerService) resolveContainerIconInternal(ctx context.Context, labmeta := s.getCachedProjectIconMetadataInternal(ctx, projectName, metadataByProject)serviceName := dockerutils.ComposeServiceLabel(labels)- return iconcatalog.Resolve(project.IconCatalogForContext(ctx), iconcatalog.FirstNonEmpty(+ return iconcatalog.Resolve(project.IconCatalogForContext(ctx), cmp.Or(explicitIcon,meta.ServiceIconSets[serviceName],meta.ProjectIcon,@@ -1799,10 +1794,7 @@ func (s *ContainerService) buildContainerSortBindings() []pagination.SortBindingif a.Created < b.Created {return -1}- if a.Created > b.Created {- return 1- }- return 0+ return kit.Ternary(a.Created > b.Created, 1, 0)},},{@@ -1924,7 +1916,7 @@ func (s *ContainerService) buildContainerFilterAccessors() []pagination.FilterAcKey: "standalone",Fn: func(c containertypes.Summary, filterValue string) bool {isStandalone := dockerutils.ComposeProjectLabel(c.Labels) == ""- value, valid := utils.ParseBool(filterValue)+ value, valid := kit.ParseBool(filterValue)return !valid || isStandalone == value},},diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.goindex 650697ce4..4864b32e3 100644--- a/backend/internal/container/service_test.go+++ b/backend/internal/container/service_test.go@@ -1,14 +1,7 @@package containerimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/project"-- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-+ "cmp""context""encoding/json""io"@@ -22,9 +15,13 @@ import ("time""github.com/containerd/errdefs"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"+ "github.com/getarcaneapp/arcane/backend/v2/internal/project"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"containertypes "github.com/getarcaneapp/arcane/types/v2/container"@@ -355,11 +352,9 @@ func TestContainerServiceCommitContainerOmitsReferenceWhenRepositoryEmptyInterna}, gotRequest)}-func newGroupedContainerSummary(name string, project string) containertypes.Summary {+func newGroupedContainerSummary(name, project string) containertypes.Summary {labels := map[string]string{}- if project != "" {- labels["com.docker.compose.project"] = project- }+ labels["com.docker.compose.project"] = cmp.Or(project, labels["com.docker.compose.project"])return containertypes.Summary{ID: name,@@ -631,7 +626,6 @@ func TestBuildSummariesUsesContainerTagPolicyUpdates(t *testing.T) {encoded, err := json.Marshal(items[4])require.NoError(t, err)require.Contains(t, string(encoded), `"autoUpdateEnabled":false`, "false status must stay serialized")-}func TestContainerServiceGetContainerProcessesInternal(t *testing.T) {diff --git a/backend/internal/dashboard/handler.go b/backend/internal/dashboard/handler.goindex a7c31bb2a..8d89cd7bb 100644--- a/backend/internal/dashboard/handler.go+++ b/backend/internal/dashboard/handler.go@@ -8,7 +8,6 @@ import ("time""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/environment"diff --git a/backend/internal/dashboard/module.go b/backend/internal/dashboard/module.goindex 97a48a206..3086891bd 100644--- a/backend/internal/dashboard/module.go+++ b/backend/internal/dashboard/module.go@@ -5,7 +5,6 @@ package dashboardimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/container""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker"diff --git a/backend/internal/dashboard/service.go b/backend/internal/dashboard/service.goindex c46b2f4c3..d1c3ed711 100644--- a/backend/internal/dashboard/service.go+++ b/backend/internal/dashboard/service.go@@ -1,8 +1,6 @@package dashboardimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"-"context""sort""strconv"@@ -10,11 +8,7 @@ import ("time""emperror.dev/errors"-- dockercontainer "github.com/moby/moby/api/types/container"- "golang.org/x/sync/errgroup"- "golang.org/x/sync/singleflight"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/container""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker"@@ -34,8 +28,12 @@ import (imagetypes "github.com/getarcaneapp/arcane/types/v2/image"versiontypes "github.com/getarcaneapp/arcane/types/v2/version"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ dockercontainer "github.com/moby/moby/api/types/container"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""go.getarcane.app/updater/labels"+ "golang.org/x/sync/errgroup"+ "golang.org/x/sync/singleflight")const (@@ -73,13 +71,6 @@ type dashboardSnapshotCacheEntryInternal struct {builtAt time.Time}-func dashboardCacheIndexInternal(flag bool) int {- if flag {- return 1- }- return 0-}-type DashboardActionItemsOptions struct {DebugAllGood bool}@@ -125,7 +116,10 @@ func (s *DashboardService) GetSnapshot(ctx context.Context, options DashboardActcatalog = iconcatalog.Normalize(project.IconCatalogForContext(ctx))}- slot := &s.snapshotCache[dashboardCacheIndexInternal(includeTables)][dashboardCacheIndexInternal(options.DebugAllGood)][dashboardCacheIndexInternal(catalog == iconcatalog.CatalogDashboardIcons)]+ tables := kit.Ternary(includeTables, 1, 0)+ debug := kit.Ternary(options.DebugAllGood, 1, 0)+ icons := kit.Ternary(catalog == iconcatalog.CatalogDashboardIcons, 1, 0)+ slot := &s.snapshotCache[tables][debug][icons]if entry := slot.Load(); entry != nil && time.Since(entry.builtAt) < dashboardSnapshotCacheTTL {return entry.snapshot, nil}@@ -447,6 +441,7 @@ func (s *DashboardService) getPendingProjectUpdatesCountInternal(ctx context.Conreturn count, nil}+func (s *DashboardService) getActionableVulnerabilitiesCountInternal(ctx context.Context) (int, error) {if s.vulnerabilityService == nil {return 0, nil@@ -473,7 +468,7 @@ func (s *DashboardService) getExpiringAPIKeysCountInternal(ctx context.Context)return int(count), nil}-func buildDashboardPaginationResponseInternal(totalItems int, limit int) base.PaginationResponse {+func buildDashboardPaginationResponseInternal(totalItems, limit int) base.PaginationResponse {if limit <= 0 {limit = dashboardSnapshotPreloadLimit}diff --git a/backend/internal/dashboard/service_test.go b/backend/internal/dashboard/service_test.goindex 8f4058cb5..45d1de22c 100644--- a/backend/internal/dashboard/service_test.go+++ b/backend/internal/dashboard/service_test.go@@ -1,14 +1,6 @@package dashboardimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-- "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"-- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""encoding/json""net/http"@@ -20,11 +12,15 @@ import ("time""github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/container""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/image"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/volume"diff --git a/backend/internal/database/database.go b/backend/internal/database/database.goindex 54821ceba..68259ca0f 100644--- a/backend/internal/database/database.go+++ b/backend/internal/database/database.go@@ -14,19 +14,16 @@ import ("strings""time"- sqliteutil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/sqlite"-"emperror.dev/errors"-+ sqliteutil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/sqlite"+ "github.com/getarcaneapp/arcane/backend/v2/resources""github.com/libtnb/sqlite""github.com/pressly/goose/v3""github.com/pressly/goose/v3/lock"+ kit "go.getarcane.app/kit/pkg""gorm.io/driver/postgres""gorm.io/gorm""gorm.io/gorm/logger"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- "github.com/getarcaneapp/arcane/backend/v2/resources")type DB struct {@@ -42,17 +39,15 @@ const (dbProviderPostgres = "postgres"gooseVersionTable = "goose_db_version"legacyVersionTable = "schema_migrations"-)-// Prepared-statement cache bounds. GORM's PrepareStmt cache is a global LRU keyed-// by SQL text. When PrepareStmtMaxSize/PrepareStmtTTL are left at zero, GORM falls-// back to math.MaxInt entries with a 24h TTL, i.e. effectively unbounded. Because-// this codebase emits highly variable SQL (dynamic filter/sort/pagination and-// GORM's IN (?,?,...) slice expansion, whose placeholder count changes the query-// text), the cache β and the modernc.org/sqlite compiled statements it retains on-// the Go heap β grows steadily under normal use. Bounding size and TTL keeps hot-// queries prepared while evicting the long tail (evicted statements are closed).-const (+ // Prepared-statement cache bounds. GORM's PrepareStmt cache is a global LRU keyed+ // by SQL text. When PrepareStmtMaxSize/PrepareStmtTTL are left at zero, GORM falls+ // back to math.MaxInt entries with a 24h TTL, i.e. effectively unbounded. Because+ // this codebase emits highly variable SQL (dynamic filter/sort/pagination and+ // GORM's IN (?,?,...) slice expansion, whose placeholder count changes the query+ // text), the cache β and the modernc.org/sqlite compiled statements it retains on+ // the Go heap β grows steadily under normal use. Bounding size and TTL keeps hot+ // queries prepared while evicting the long tail (evicted statements are closed).preparedStmtMaxSize = 256preparedStmtTTL = 15 * time.Minute)@@ -423,7 +418,8 @@ func gooseVersionTableHasAppliedMigrationsInternal(ctx context.Context, db *sql.}var version int64- if err := db.QueryRowContext(ctx, fmt.Sprintf("SELECT COALESCE(MAX(version_id), 0) FROM %s WHERE is_applied = %s", gooseVersionTable, appliedLiteralInternal(dbProvider))).Scan(&version); err != nil {+ applied := kit.Ternary(dbProvider == dbProviderPostgres, "true", "1")+ if err := db.QueryRowContext(ctx, fmt.Sprintf("SELECT COALESCE(MAX(version_id), 0) FROM %s WHERE is_applied = %s", gooseVersionTable, applied)).Scan(&version); err != nil {return false, errors.WrapIff(err, "failed to read Goose migration state for %s", dbProvider)}return version > 0, nil@@ -513,13 +509,6 @@ func sqlWithProviderPlaceholderInternal(dbProvider, queryFormat string, arg any)}}-func appliedLiteralInternal(dbProvider string) string {- if dbProvider == dbProviderPostgres {- return "true"- }- return "1"-}-func getHighestEmbeddedMigrationVersionInternal(dbProvider string) (int64, error) {versions, err := getEmbeddedMigrationVersionsInternal(dbProvider)if err != nil {@@ -582,7 +571,7 @@ func missingEmbeddedDowngradeMigrationsInternal(ctx context.Context, db *sql.DB,}queryFormat := "SELECT DISTINCT version_id FROM " + gooseVersionTable +- " WHERE is_applied = " + appliedLiteralInternal(dbProvider) ++ " WHERE is_applied = " + kit.Ternary(dbProvider == dbProviderPostgres, "true", "1") +" AND version_id > %s ORDER BY version_id"query, args, err := sqlWithProviderPlaceholderInternal(dbProvider, queryFormat, requiredVersion)if err != nil {@@ -689,7 +678,7 @@ func ensureSQLiteDirectoryInternal(connString string) error {if !strings.HasPrefix(connString, "file:") {return nil}- pathPart, err := utils.SQLitePathFromDSN(connString)+ pathPart, err := kit.SQLitePathFromDSN(connString)if err != nil {return errors.WrapIf(err, "failed to parse SQLite DSN")}diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.goindex 6cbe749cf..d5873cf3a 100644--- a/backend/internal/database/database_test.go+++ b/backend/internal/database/database_test.go@@ -14,7 +14,6 @@ import ("time"sqliteutil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/sqlite"-"github.com/stretchr/testify/assert""github.com/stretchr/testify/require")diff --git a/backend/internal/di/di.go b/backend/internal/di/di.goindex 4d3a6af6f..61f653328 100644--- a/backend/internal/di/di.go+++ b/backend/internal/di/di.go@@ -3,7 +3,6 @@ package diimport ("emperror.dev/emperror"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"diff --git a/backend/internal/di/di_test.go b/backend/internal/di/di_test.goindex 0ca0e721f..d04de42c9 100644--- a/backend/internal/di/di_test.go+++ b/backend/internal/di/di_test.go@@ -3,11 +3,6 @@ package diimport ("context""encoding/json/v2"- "github.com/getarcaneapp/arcane/backend/v2/internal/actors"- "github.com/libtnb/sqlite"- "github.com/moby/moby/api/types/events"- "go.uber.org/fx/fxtest"- "gorm.io/gorm""net/http""net/http/httptest""strings"@@ -16,9 +11,17 @@ import ("time""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"+ "github.com/getarcaneapp/arcane/backend/v2/internal/appimages""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/backup"+ "github.com/getarcaneapp/arcane/backend/v2/internal/build"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/dashboard"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event"@@ -29,40 +32,36 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/job""github.com/getarcaneapp/arcane/backend/v2/internal/kv"+ "github.com/getarcaneapp/arcane/backend/v2/internal/network""github.com/getarcaneapp/arcane/backend/v2/internal/notification"+ "github.com/getarcaneapp/arcane/backend/v2/internal/oidc"+ "github.com/getarcaneapp/arcane/backend/v2/internal/port""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/role"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"+ "github.com/getarcaneapp/arcane/backend/v2/internal/search""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/swarm"- "github.com/getarcaneapp/arcane/backend/v2/internal/template"- "github.com/getarcaneapp/arcane/backend/v2/internal/user"- "github.com/getarcaneapp/arcane/backend/v2/internal/variable"- "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"-- "github.com/getarcaneapp/arcane/backend/v2/internal/appimages"- "github.com/getarcaneapp/arcane/backend/v2/internal/build"- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/container"- "github.com/getarcaneapp/arcane/backend/v2/internal/dashboard"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/diagnostics"- "github.com/getarcaneapp/arcane/backend/v2/internal/network"- "github.com/getarcaneapp/arcane/backend/v2/internal/oidc"- "github.com/getarcaneapp/arcane/backend/v2/internal/port"- "github.com/getarcaneapp/arcane/backend/v2/internal/search""github.com/getarcaneapp/arcane/backend/v2/internal/system""github.com/getarcaneapp/arcane/backend/v2/internal/systembackup"+ "github.com/getarcaneapp/arcane/backend/v2/internal/template""github.com/getarcaneapp/arcane/backend/v2/internal/updater"+ "github.com/getarcaneapp/arcane/backend/v2/internal/user"+ "github.com/getarcaneapp/arcane/backend/v2/internal/variable""github.com/getarcaneapp/arcane/backend/v2/internal/version""github.com/getarcaneapp/arcane/backend/v2/internal/volume"+ "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability""github.com/getarcaneapp/arcane/backend/v2/internal/webhook""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/oidcjwk"+ "github.com/libtnb/sqlite"+ "github.com/moby/moby/api/types/events""github.com/stretchr/testify/require""go.uber.org/fx"+ "go.uber.org/fx/fxtest"+ "gorm.io/gorm")type graphParams struct {diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.goindex ec36e16d5..a799724ae 100644--- a/backend/internal/di/providers.go+++ b/backend/internal/di/providers.go@@ -7,11 +7,17 @@ import ("net/http""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/build"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/dashboard"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event"@@ -31,21 +37,14 @@ import (s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/swarm"- "github.com/getarcaneapp/arcane/backend/v2/internal/template"- "github.com/getarcaneapp/arcane/backend/v2/internal/user"- "github.com/getarcaneapp/arcane/backend/v2/internal/version"- "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"-- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/actors"- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/container"- "github.com/getarcaneapp/arcane/backend/v2/internal/dashboard"- "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/system"+ "github.com/getarcaneapp/arcane/backend/v2/internal/template""github.com/getarcaneapp/arcane/backend/v2/internal/updater""github.com/getarcaneapp/arcane/backend/v2/internal/upload"+ "github.com/getarcaneapp/arcane/backend/v2/internal/user"+ "github.com/getarcaneapp/arcane/backend/v2/internal/version""github.com/getarcaneapp/arcane/backend/v2/internal/volume"+ "github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability""github.com/getarcaneapp/arcane/backend/v2/internal/webhook""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"diff --git a/backend/internal/diagnostics/service.go b/backend/internal/diagnostics/service.goindex 3eb44e506..f17cecd35 100644--- a/backend/internal/diagnostics/service.go+++ b/backend/internal/diagnostics/service.go@@ -12,12 +12,14 @@ import ("github.com/getarcaneapp/arcane/types/v2/system")-// recentGCPauseSamples is the number of recent GC pause durations reported.-const recentGCPauseSamples = 16+const (+ // recentGCPauseSamples is the number of recent GC pause durations reported.+ recentGCPauseSamples = 16-// goroutineLeakProfileName is the runtime/pprof profile that reports goroutines-// blocked on concurrency primitives that cannot be unblocked.-const goroutineLeakProfileName = "goroutineleak"+ // goroutineLeakProfileName is the runtime/pprof profile that reports goroutines+ // blocked on concurrency primitives that cannot be unblocked.+ goroutineLeakProfileName = "goroutineleak"+)// DiagnosticsService gathers Go runtime, memory, and garbage-collector// statistics for the diagnostics endpoints. It holds no external dependencies;diff --git a/backend/internal/docker/service.go b/backend/internal/docker/service.goindex 4230ec414..d4f112e8a 100644--- a/backend/internal/docker/service.go+++ b/backend/internal/docker/service.go@@ -9,13 +9,11 @@ import ("time""emperror.dev/errors"-"github.com/cenkalti/backoff/v5""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings"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"@@ -27,12 +25,20 @@ import ("github.com/moby/moby/api/types/network""github.com/moby/moby/api/types/volume""github.com/moby/moby/client"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/streams/bus""golang.org/x/sync/errgroup""golang.org/x/sync/singleflight")-const dockerClientNegotiationTimeout = 5 * time.Second+const (+ dockerClientNegotiationTimeout = 5 * time.Second++ // dockerEventStreamHealthyAfter is how long an event stream must survive before+ // the reconnect backoff is considered recovered and reset.+ dockerEventStreamHealthyAfter = 30 * time.Second+)type DockerClientService struct {*client.Client@@ -114,7 +120,7 @@ func detectDockerAPIVersionInternal(ctx context.Context, host string) (string, ereturn apiVersion, nil}-func newDockerClientWithAPIVersionInternal(host string, apiVersion string) (*client.Client, error) {+func newDockerClientWithAPIVersionInternal(host, apiVersion string) (*client.Client, error) {configuredClient, err := client.New(client.WithHost(host),client.WithAPIVersion(apiVersion),@@ -235,10 +241,6 @@ 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@@ -290,10 +292,7 @@ func (s *DockerClientService) consumeEventsInternal(ctx context.Context, message}s.EventBus().Publish(msg)case err, ok := <-errs:- if !ok {- return nil- }- return err+ return kit.Ternary(!ok, nil, err)}}}@@ -392,7 +391,7 @@ func (s *DockerClientService) listNetworksInternal(ctx context.Context) ([]netwoapiCtx, cancel := context.WithTimeout(ctx, s.apiTimeoutInternal())defer cancel()- networkList, err := libarcane.NetworkListWithCompatibility(apiCtx, dockerClient, client.NetworkListOptions{})+ networkList, err := compat.NetworkListWithCompatibility(apiCtx, dockerClient, client.NetworkListOptions{})if err != nil {return nil, errors.WrapIf(err, "failed to list Docker networks")}diff --git a/backend/internal/environment/edge_mtls_handler.go b/backend/internal/environment/edge_mtls_handler.goindex 8aa712215..df7de89d2 100644--- a/backend/internal/environment/edge_mtls_handler.go+++ b/backend/internal/environment/edge_mtls_handler.go@@ -9,7 +9,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"typesenvironment "github.com/getarcaneapp/arcane/types/v2/environment"@@ -82,7 +81,7 @@ func readGeneratedEdgeMTLSCertificateInfoInternal(cfg *config.Config, envID strireturn info, nil}-func edgeMTLSCertificateDaysRemainingInternal(now time.Time, expiresAt time.Time) int {+func edgeMTLSCertificateDaysRemainingInternal(now, expiresAt time.Time) int {remaining := expiresAt.Sub(now)if remaining <= 0 {return 0diff --git a/backend/internal/environment/environment.go b/backend/internal/environment/environment.goindex 646e1eff6..450a5d435 100644--- a/backend/internal/environment/environment.go+++ b/backend/internal/environment/environment.go@@ -1,9 +1,6 @@package environmentimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"- "go.getarcane.app/kit/normalization"-"context""fmt""log/slog"@@ -13,12 +10,12 @@ import ("uuid""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"@@ -28,6 +25,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/containerregistry"+ "go.getarcane.app/kit/normalization""go.getarcane.app/sys/crypto""gorm.io/gorm")@@ -62,10 +60,15 @@ type EnvironmentService struct {syncGate utils.SyncGate}-// SyncDeliveryExpiry bounds how long an accepted config push is trusted. An-// agent rebuilt with a fresh data volume while its status stayed online gets-// everything again within this window without operator action.-const SyncDeliveryExpiry = time.Hour+const (+ // SyncDeliveryExpiry bounds how long an accepted config push is trusted. An+ // agent rebuilt with a fresh data volume while its status stayed online gets+ // everything again within this window without operator action.+ SyncDeliveryExpiry = time.Hour++ ErrEnvironmentAccessTokenRequired = errors.Sentinel("environment access token required")+ ErrInvalidEnvironmentAccessToken = errors.Sentinel("invalid environment access token")+)// VariableSyncer pushes the effective global-variable set to one environment.// Implemented by variable.VariableService.@@ -83,11 +86,6 @@ func (s *EnvironmentService) ForgetSyncState(environmentID string) {}}-const (- ErrEnvironmentAccessTokenRequired = errors.Sentinel("environment access token required")- ErrInvalidEnvironmentAccessToken = errors.Sentinel("invalid environment access token")-)-func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *docker.DockerClientService, eventService *event.EventService, settingsService *settings.SettingsService, apiKeyService *apikey.ApiKeyService) *EnvironmentService {if httpClient == nil {httpClient = http.DefaultClient@@ -424,7 +422,7 @@ func (s *EnvironmentService) createEnvironmentEvent(ctx context.Context, envID,})}-func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, envID string, newApiKeyID string, apiKey string, userID, username string, envName string) error {+func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, envID, newApiKeyID, apiKey, userID, username, envName string) error {// Trim once at the boundary so the value persisted, the value cached,// and the value returned by callers (which already TrimSpace before// returning) all stay byte-identical. Any divergence here would surfacediff --git a/backend/internal/environment/environment_caches.go b/backend/internal/environment/environment_caches.goindex 31faf7289..bddb9a7ad 100644--- a/backend/internal/environment/environment_caches.go+++ b/backend/internal/environment/environment_caches.go@@ -69,7 +69,7 @@ func (c *edgeTokenCacheInternal) environmentID(token string) mo.Option[string] {return mo.None[string]()}-func (c *edgeTokenCacheInternal) put(envID string, token string) {+func (c *edgeTokenCacheInternal) put(envID, token string) {if c == nil || c.byToken == nil || envID == "" || token == "" {return}@@ -103,7 +103,7 @@ func (c *edgeTokenCacheInternal) invalidate(envID string) {// sync replaces an environment's cached token, dropping the entry entirely when// the new token is blank.-func (c *edgeTokenCacheInternal) sync(envID string, token string) {+func (c *edgeTokenCacheInternal) sync(envID, token string) {if c == nil || envID == "" {return}diff --git a/backend/internal/environment/environment_health.go b/backend/internal/environment/environment_health.goindex d68089cd4..1d2c19d36 100644--- a/backend/internal/environment/environment_health.go+++ b/backend/internal/environment/environment_health.go@@ -7,7 +7,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"@@ -15,6 +14,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/environment"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg")const (@@ -38,10 +38,7 @@ func (s *EnvironmentService) registerHealthJobInternal(ctx context.Context, envIs.jobs.Register(ctx, envID,func(ctx context.Context) string {sched := s.settingsService.GetStringSetting(ctx, "environmentHealthInterval", defaultEnvironmentHealthInterval)- if sched == "" {- return defaultEnvironmentHealthInterval- }- return sched+ return kit.Ternary(sched == "", defaultEnvironmentHealthInterval, sched)},func(ctx context.Context) (schedulertypes.Outcome, error) { return s.runHealthCheckInternal(ctx, envID) },func(context.Context, schedulertypes.Run) (schedulertypes.Outcome, error) {diff --git a/backend/internal/environment/environment_listing.go b/backend/internal/environment/environment_listing.goindex 7bea5b108..c7d4155ef 100644--- a/backend/internal/environment/environment_listing.go+++ b/backend/internal/environment/environment_listing.go@@ -5,12 +5,11 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper""github.com/getarcaneapp/arcane/types/v2/environment"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping")func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams, accessibleEnvIDs []string) ([]environment.Environment, pagination.Response, error) {@@ -47,7 +46,7 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, parareturn nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate environments")}- out, mapErr := mapper.MapSlice[Environment, environment.Environment](envs)+ out, mapErr := mapping.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")}@@ -81,7 +80,7 @@ func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternalreturn nil, pagination.Response{}, errors.WrapIf(err, "failed to list environments")}- items, mapErr := mapper.MapSlice[Environment, environment.Environment](envs)+ items, mapErr := mapping.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")}@@ -125,10 +124,7 @@ func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternalif a.Enabled == b.Enabled {return 0}- if a.Enabled {- return 1- }- return -1+ return kit.Ternary(a.Enabled, 1, -1)},},{@@ -148,7 +144,7 @@ func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternal{Key: "enabled",Fn: func(item environment.Environment, filterValue string) bool {- value, valid := utils.ParseBool(filterValue)+ value, valid := kit.ParseBool(filterValue)return !valid || item.Enabled == value},},@@ -201,7 +197,7 @@ func (s *EnvironmentService) ListVisibleEnvironments(ctx context.Context) ([]envreturn nil, errors.WrapIf(err, "failed to list visible environments")}- out, mapErr := mapper.MapSlice[Environment, environment.Environment](envs)+ out, mapErr := mapping.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {return nil, errors.WrapIf(mapErr, "failed to map environments")}diff --git a/backend/internal/environment/environment_proxy.go b/backend/internal/environment/environment_proxy.goindex 6d068bbb6..2906359b1 100644--- a/backend/internal/environment/environment_proxy.go+++ b/backend/internal/environment/environment_proxy.go@@ -1,9 +1,6 @@package environmentimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"- s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"-"context""encoding/json/v2""fmt"@@ -14,10 +11,11 @@ import ("strings""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-"emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry"+ s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"@@ -206,7 +204,7 @@ func (s *EnvironmentService) buildRemoteRequestInternal(}, nil}-func (s *EnvironmentService) ExecuteRemoteRequest(ctx context.Context, envID string, method string, path string, body []byte) (*remenv.Response, error) {+func (s *EnvironmentService) ExecuteRemoteRequest(ctx context.Context, envID, method, path string, body []byte) (*remenv.Response, error) {target, err := s.resolveRemoteEnvironmentTargetInternal(ctx, envID)if err != nil {return nil, err@@ -226,7 +224,7 @@ func (s *EnvironmentService) executeRemoteRequestForTargetInternal(// environment group the same way they do locally.var headers map[string]stringif batchID := utils.ActivityBatchIDFromContext(ctx); batchID != "" {- headers = map[string]string{utils.HeaderActivityBatchID: batchID}+ headers = map[string]string{middleware.HeaderActivityBatchID: batchID}}request, err := s.buildRemoteRequestInternal(target, method, path, body, headers)if err != nil {@@ -241,7 +239,7 @@ func (s *EnvironmentService) executeRemoteRequestForTargetInternal(return resp, nil}-func (s *EnvironmentService) ProxyJSONRequest(ctx context.Context, envID string, method string, path string, body []byte, out any) error {+func (s *EnvironmentService) ProxyJSONRequest(ctx context.Context, envID, method, path string, body []byte, out any) error {proxyCtx, cancel := s.getProxyRequestContextInternal(ctx)defer cancel()@@ -255,7 +253,7 @@ func (s *EnvironmentService) ProxyJSONRequest(ctx context.Context, envID string,// ProxyJSONRequestForEnvironment sends a JSON request using an already-loaded// environment row, avoiding an extra environment lookup on hot stream paths.-func (s *EnvironmentService) ProxyJSONRequestForEnvironment(ctx context.Context, environment Environment, method string, path string, body []byte, out any) error {+func (s *EnvironmentService) ProxyJSONRequestForEnvironment(ctx context.Context, environment Environment, method, path string, body []byte, out any) error {proxyCtx, cancel := s.getProxyRequestContextInternal(ctx)defer cancel()@@ -466,7 +464,7 @@ func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context,// manager to one remote environment. toSyncItem maps a row to its wire form and// reports whether to keep it. Mapping errors abort before sending the snapshot.// wrap builds the request envelope the target endpoint expects.-func (s *EnvironmentService) fanOutSyncToEnvironment[Model any, Item any, Request any](+func (s *EnvironmentService) fanOutSyncToEnvironment[Model, Item, Request any](ctx context.Context,environmentID string,kind string,@@ -538,7 +536,7 @@ func (s *EnvironmentService) fanOutSyncToEnvironment[Model any, Item any, Reques}// ProxyRequest sends a request to a remote environment's API.-func (s *EnvironmentService) ProxyRequest(ctx context.Context, envID string, method string, path string, body []byte) ([]byte, int, error) {+func (s *EnvironmentService) ProxyRequest(ctx context.Context, envID, method, path string, body []byte) ([]byte, int, error) {proxyCtx, cancel := s.getProxyRequestContextInternal(ctx)defer cancel()diff --git a/backend/internal/environment/environment_snippets.go b/backend/internal/environment/environment_snippets.goindex 6cd41aefc..264a1520c 100644--- a/backend/internal/environment/environment_snippets.go+++ b/backend/internal/environment/environment_snippets.go@@ -89,7 +89,7 @@ func (s *EnvironmentService) GenerateDeploymentSnippets(ctx context.Context, env// GenerateEdgeDeploymentSnippets generates Docker deployment snippets for an edge agent.// Edge agents connect outbound to the manager and don't require exposed ports.-func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context, envID string, managerURL string, apiKey string, edgeCfg *edge.Config) (*DeploymentSnippets, error) {+func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context, envID, managerURL, apiKey string, edgeCfg *edge.Config) (*DeploymentSnippets, error) {managerURL = strings.TrimRight(managerURL, "/")dockerRun := strings.Join([]string{@@ -154,7 +154,7 @@ func (s *EnvironmentService) GenerateEdgeDeploymentSnippets(ctx context.Context,return snippets, nil}-func (s *EnvironmentService) logGeneratedMTLSEventsInternal(ctx context.Context, envID string, envName string, assets *edge.GeneratedMTLSAssets) {+func (s *EnvironmentService) logGeneratedMTLSEventsInternal(ctx context.Context, envID, envName string, assets *edge.GeneratedMTLSAssets) {if s == nil || s.eventService == nil || assets == nil {return}@@ -187,7 +187,7 @@ func (s *EnvironmentService) logGeneratedMTLSEventsInternal(ctx context.Context,}}-func buildMTLSDeploymentSnippetInternal(managerURL string, apiKey string, generatedAssets *edge.GeneratedMTLSAssets) *DeploymentSnippetMTLS {+func buildMTLSDeploymentSnippetInternal(managerURL, apiKey string, generatedAssets *edge.GeneratedMTLSAssets) *DeploymentSnippetMTLS {if generatedAssets == nil {return nil}diff --git a/backend/internal/environment/environment_swarm_nodes.go b/backend/internal/environment/environment_swarm_nodes.goindex 66fad79e9..e5db1a770 100644--- a/backend/internal/environment/environment_swarm_nodes.go+++ b/backend/internal/environment/environment_swarm_nodes.go@@ -7,7 +7,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/apikey""gorm.io/gorm")diff --git a/backend/internal/environment/handler.go b/backend/internal/environment/handler.goindex db9f6c363..0a0a3bb20 100644--- a/backend/internal/environment/handler.go+++ b/backend/internal/environment/handler.go@@ -1,20 +1,18 @@package environmentimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"archive/zip""bytes"+ "cmp""context""encoding/json/v2""fmt""log/slog"+ "maps""net/http""os""path/filepath"- "sort"+ "slices""strconv""strings""time"@@ -22,7 +20,9 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -32,17 +32,18 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/environment""github.com/getarcaneapp/arcane/types/v2/version""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""go.getarcane.app/streams/agg")-const localDockerEnvironmentID = "0"-const (+ localDockerEnvironmentID = "0"+// Only covers poll-mode TTL expiry; tunnel and health-check changes arrive// on the service's runtime-change signal instead.environmentStreamPollInterval = 5 * time.Second@@ -383,11 +384,7 @@ func accessibleEnvironmentIDsInternal(ps *authz.PermissionSet) []string {if ps == nil {return []string{}}- ids := make([]string, 0, len(ps.PerEnv))- for envID := range ps.PerEnv {- ids = append(ids, envID)- }- sort.Strings(ids)+ ids := slices.Sorted(maps.Keys(ps.PerEnv))return ids}@@ -415,45 +412,6 @@ func visibleEnvironmentsForInternal(envs []environment.Environment, ps *authz.Pereturn filtered}-// 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.NewFingerprint().Slice(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)- }).Sum()-}-func (h *EnvironmentHandler) RunStreamProducer(ctx context.Context, ps *authz.PermissionSet, events chan<- environment.StreamEvent) {var lastFingerprint uint64var haveFingerprint bool@@ -461,7 +419,7 @@ func (h *EnvironmentHandler) RunStreamProducer(ctx context.Context, ps *authz.Peh.streamHub.Subscribe(ctx, environmentStreamHubKeyInternal, h.runEnvironmentStreamListerInternal, func(all []environment.Environment) bool {envs := visibleEnvironmentsForInternal(all, ps)- fingerprint := fingerprintEnvironmentsInternal(envs)+ fingerprint := kit.Fingerprint(envs)// Re-send unchanged state on a floor so relative timestamps in the UI// ("last seen 2 minutes ago") keep advancing.if haveFingerprint && fingerprint == lastFingerprint && time.Since(lastSentAt) < environmentStreamRefreshFloor {@@ -582,7 +540,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con}created = updated- out, mapErr := mapper.MapOne[*Environment, environment.Environment](created)+ out, mapErr := mapping.MapOne[*Environment, environment.Environment](created)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -614,7 +572,7 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Contexth.triggerEnvironmentResourceSyncInternal(ctx, created.ID, created.Name, "environment creation")}- out, mapErr := mapper.MapOne[*Environment, environment.Environment](created)+ out, mapErr := mapping.MapOne[*Environment, environment.Environment](created)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -637,7 +595,7 @@ func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvirreturn nil, huma.Error404NotFound("Environment not found")}- out, mapErr := mapper.MapOne[*Environment, environment.Environment](env)+ out, mapErr := mapping.MapOne[*Environment, environment.Environment](env)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -680,7 +638,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updath.triggerPostUpdateTasksInternal(ctx, input.ID, updated, &input.Body)- out, mapErr := mapper.MapOne[*Environment, environment.Environment](updated)+ out, mapErr := mapping.MapOne[*Environment, environment.Environment](updated)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -736,7 +694,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat}// Re-map with updated environment data- out, mapErr = mapper.MapOne[*Environment, environment.Environment](updated)+ out, mapErr = mapping.MapOne[*Environment, environment.Environment](updated)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -848,7 +806,7 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpushouldRotate := input.Body != nil && input.Body.Rotate != nil && *input.Body.Rotateif h.cfg.AgentToken == "" || shouldRotate {- h.cfg.AgentToken = utils.GenerateRandomString(48)+ h.cfg.AgentToken = kit.RandomString(48)}if err := h.settingsService.SetStringSetting(ctx, "agentToken", h.cfg.AgentToken); err != nil {@@ -927,7 +885,7 @@ func (h *EnvironmentHandler) handleEnvironmentPairingInternal(ctx context.Contexfunc (h *EnvironmentHandler) triggerPostUpdateTasksInternal(ctx context.Context, environmentID string, updated *Environment, req *environment.Update) {if updated.Enabled {detachedCtx := context.WithoutCancel(ctx)- go func(syncCtx context.Context, envID string, envName string) {+ go func(syncCtx context.Context, envID, envName string) {status, err := h.environmentService.TestConnection(syncCtx, envID, nil)if err != nil {slog.WarnContext(syncCtx, "Failed to test connection after environment update",@@ -941,11 +899,11 @@ func (h *EnvironmentHandler) triggerPostUpdateTasksInternal(ctx context.Context,}}-func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.Context, environmentID string, environmentName string, reason string) {+func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.Context, environmentID, environmentName, reason string) {h.environmentService.ForgetSyncState(environmentID)detachedCtx := context.WithoutCancel(ctx)- go func(syncCtx context.Context, envID string, envName string, syncReason string) {+ go func(syncCtx context.Context, envID, envName, syncReason string) {syncCtx, cancel := context.WithTimeout(syncCtx, edge.DefaultProxyTimeout)defer cancel()if err := h.environmentService.SyncRegistriesToEnvironment(syncCtx, envID); err != nil {@@ -957,7 +915,7 @@ func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.}}(detachedCtx, environmentID, environmentName, reason)- go func(syncCtx context.Context, envID string, envName string, syncReason string) {+ go func(syncCtx context.Context, envID, envName, syncReason string) {syncCtx, cancel := context.WithTimeout(syncCtx, edge.DefaultProxyTimeout)defer cancel()if err := h.environmentService.SyncS3DestinationsToEnvironment(syncCtx, envID); err != nil {@@ -969,7 +927,7 @@ func (h *EnvironmentHandler) triggerEnvironmentResourceSyncInternal(ctx context.}}(detachedCtx, environmentID, environmentName, reason)- go func(syncCtx context.Context, envID string, envName string, syncReason string) {+ go func(syncCtx context.Context, envID, envName, syncReason string) {syncCtx, cancel := context.WithTimeout(syncCtx, edge.DefaultProxyTimeout)defer cancel()if err := h.environmentService.SyncRepositoriesToEnvironment(syncCtx, envID); err != nil {@@ -1360,7 +1318,7 @@ func (h *EnvironmentHandler) loadEnvironmentMTLSFilesInternal(ctx context.Contexreturn env, snippets.MTLS.Files, nil}-func (h *EnvironmentHandler) loadEnvironmentMTLSFileInternal(ctx context.Context, environmentID string, fileName string) (*Environment, DeploymentSnippetFile, error) {+func (h *EnvironmentHandler) loadEnvironmentMTLSFileInternal(ctx context.Context, environmentID, fileName string) (*Environment, DeploymentSnippetFile, error) {env, files, err := h.loadEnvironmentMTLSFilesInternal(ctx, environmentID)if err != nil {return nil, DeploymentSnippetFile{}, err@@ -1385,10 +1343,7 @@ func isSensitiveMTLSAssetNameInternal(fileName string) bool {}func environmentMTLSDownloadBaseNameInternal(env *Environment) string {- baseName := strings.TrimSpace(env.Name)- if baseName == "" {- baseName = "environment"- }+ baseName := cmp.Or(strings.TrimSpace(env.Name), "environment")baseName = strings.Map(func(r rune) rune {switch {@@ -1403,10 +1358,7 @@ func environmentMTLSDownloadBaseNameInternal(env *Environment) string {}}, baseName)- baseName = strings.Trim(baseName, "-")- if baseName == "" {- baseName = "environment"- }+ baseName = cmp.Or(strings.Trim(baseName, "-"), "environment")return baseName + "-" + env.ID}@@ -1428,10 +1380,7 @@ func environmentMTLSAssetFileModeInternal(file DeploymentSnippetFile) os.FileModif parsed, err := strconv.ParseUint(strings.TrimSpace(file.Permissions), 8, 32); err == nil && parsed != 0 {return os.FileMode(parsed)}- if isSensitiveMTLSAssetNameInternal(file.Name) {- return 0o600- }- return 0o644+ return kit.Ternary[os.FileMode](isSensitiveMTLSAssetNameInternal(file.Name), 0o600, 0o644)}// logMTLSAuditEventInternal records an audit event for administrator-triggereddiff --git a/backend/internal/environment/model.go b/backend/internal/environment/model.goindex 46ea11808..9a5c2b330 100644--- a/backend/internal/environment/model.go+++ b/backend/internal/environment/model.go@@ -1,9 +1,9 @@package environmentimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database")type Environment struct {diff --git a/backend/internal/environment/module.go b/backend/internal/environment/module.goindex dcfb4e640..5fe80e62b 100644--- a/backend/internal/environment/module.go+++ b/backend/internal/environment/module.go@@ -4,7 +4,6 @@ package environmentimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/event"diff --git a/backend/internal/environment/service_test.go b/backend/internal/environment/service_test.goindex f65722c2d..75debfc79 100644--- a/backend/internal/environment/service_test.go+++ b/backend/internal/environment/service_test.go@@ -1,10 +1,7 @@package environmentimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"-+ "cmp""context""encoding/json""fmt"@@ -17,18 +14,16 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-"github.com/coder/websocket""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo""github.com/getarcaneapp/arcane/backend/v2/internal/registry"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -38,9 +33,12 @@ import ("github.com/getarcaneapp/arcane/types/v2/environment""github.com/getarcaneapp/arcane/types/v2/gitops"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ "github.com/libtnb/sqlite""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require""go.getarcane.app/sys/crypto""go.uber.org/fx/fxtest"+ "gorm.io/gorm")func TestEnvironmentService_OverlappingHealthCheckIsSkippedInternal(t *testing.T) {@@ -174,7 +172,7 @@ func createTestEnvironmentServiceUser(t *testing.T, ctx context.Context, userSerreturn created}-func createTestEnvironment(t *testing.T, db *database.DB, id string, apiURL string, accessToken *string) {+func createTestEnvironment(t *testing.T, db *database.DB, id, apiURL string, accessToken *string) {t.Helper()createNamedTestEnvironmentInternal(t, db, id, "env-"+id, apiURL, accessToken)}@@ -1076,7 +1074,6 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRerequire.Len(t, environments, 1,"environment count = %d, want 1", len(environments))-}// TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_TokenResolvesEndToEnd@@ -1225,9 +1222,7 @@ func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByAccessibleEnvIDs(newParams := func(typeFilter string) pagination.QueryParams {filters := map[string]string{}- if typeFilter != "" {- filters["type"] = typeFilter- }+ filters["type"] = cmp.Or(typeFilter, filters["type"])return pagination.QueryParams{Start: 0, Limit: 20,Filters: filters,diff --git a/backend/internal/environment/vocabulary.go b/backend/internal/environment/vocabulary.goindex 5063d982d..0554dcca7 100644--- a/backend/internal/environment/vocabulary.go+++ b/backend/internal/environment/vocabulary.go@@ -1,11 +1,16 @@package environment-import "strings"+import (+ "strings"-// LocalEnvironmentID is the reserved ID of the environment Arcane manages directly.-const LocalEnvironmentID = "0"+ kit "go.getarcane.app/kit/pkg"+)-const localEnvironmentFallbackNameInternal = "Local"+// LocalEnvironmentID is the reserved ID of the environment Arcane manages directly.+const (+ LocalEnvironmentID = "0"+ localEnvironmentFallbackNameInternal = "Local"+)// DisplayName returns the stored environment name or its readable fallback.func DisplayName(environmentID, storedName string) string {@@ -13,8 +18,5 @@ func DisplayName(environmentID, storedName string) string {return name}id := strings.TrimSpace(environmentID)- if id == "" || id == LocalEnvironmentID {- return localEnvironmentFallbackNameInternal- }- return id+ return kit.Ternary(id == "" || id == LocalEnvironmentID, localEnvironmentFallbackNameInternal, id)}diff --git a/backend/internal/event/docker_correlation.go b/backend/internal/event/docker_correlation.goindex ffe2bf6f7..307a53254 100644--- a/backend/internal/event/docker_correlation.go+++ b/backend/internal/event/docker_correlation.go@@ -1,9 +1,12 @@package eventimport (+ "slices""strings""sync""time"++ kit "go.getarcane.app/kit/pkg")const (@@ -184,10 +187,10 @@ func (exp dockerExpectationInternal) matchesInternal(resourceType, actorID, actoif exp.resourceType != resourceType {return false}- if exp.resourceID != "" && (exp.resourceID == actorID || exp.resourceID == actorName || dockerIDMatchesInternal(resourceType, exp.resourceID, actorID)) {- return true- }- return exp.resourceName != "" && (exp.resourceName == actorName || exp.resourceName == actorID)+ actors := kit.TrimNonEmpty([]string{actorID, actorName})+ return slices.Contains(actors, exp.resourceID) ||+ slices.Contains(actors, exp.resourceName) ||+ dockerIDMatchesInternal(resourceType, exp.resourceID, actorID)}func dockerIDMatchesInternal(resourceType, expected, actual string) bool {diff --git a/backend/internal/event/docker_correlation_test.go b/backend/internal/event/docker_correlation_test.goindex a79f71728..f674c34ef 100644--- a/backend/internal/event/docker_correlation_test.go+++ b/backend/internal/event/docker_correlation_test.go@@ -1,11 +1,13 @@package eventimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/stretchr/testify/require""strings""testing""time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")func TestDockerExpectationIdentityAndExpiry(t *testing.T) {@@ -44,10 +46,7 @@ func TestDockerExpectationIdentityAndExpiry(t *testing.T) {func TestDockerSuppressionWindowsOverlapAndGrace(t *testing.T) {t.Parallel()for _, compose := range []bool{false, true} {- name := "resource"- if compose {- name = "compose"- }+ name := kit.Ternary(compose, "compose", "resource")t.Run(name, func(t *testing.T) {svc := NewEventService(nil, nil, nil)now := time.Now()diff --git a/backend/internal/event/docker_events.go b/backend/internal/event/docker_events.goindex 166c0b7eb..0ba892d34 100644--- a/backend/internal/event/docker_events.go+++ b/backend/internal/event/docker_events.go@@ -1,6 +1,7 @@package eventimport (+ "cmp""context""encoding/json/v2""fmt"@@ -11,6 +12,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/google/uuid""github.com/moby/moby/api/types/events"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/streams/bus")@@ -141,21 +143,13 @@ func mapDaemonEventInternal(msg events.Message) (CreateEventRequest, bool) {if eventType == "" || (msg.Actor.ID == "" && msg.Action != events.ActionPrune) {return CreateEventRequest{}, false}- severity := EventSeverityInfo- if eventType == EventTypeContainerDie && msg.Actor.Attributes["exitCode"] != "0" || eventType == EventTypeContainerUnhealthy {- severity = EventSeverityWarning- }+ abnormalExit := eventType == EventTypeContainerDie && msg.Actor.Attributes["exitCode"] != "0"+ severity := kit.Ternary(abnormalExit || eventType == EventTypeContainerUnhealthy, EventSeverityWarning, EventSeverityInfo)if eventType == EventTypeContainerOOM {severity = EventSeverityError}- name := msg.Actor.Attributes["name"]- if name == "" {- name = msg.Actor.ID- }- if name == "" {- name = "prune"- }+ name := cmp.Or(msg.Actor.Attributes["name"], msg.Actor.ID, "prune")metadata := database.JSON{"source": "docker", "action": string(msg.Action), "scope": msg.Scope}for _, key := range []string{"name", "image", "exitCode", "signal"} {if value, ok := msg.Actor.Attributes[key]; ok {diff --git a/backend/internal/event/docker_events_test.go b/backend/internal/event/docker_events_test.goindex 7982cad0a..7b235e64f 100644--- a/backend/internal/event/docker_events_test.go+++ b/backend/internal/event/docker_events_test.go@@ -11,6 +11,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/moby/moby/api/types/events""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/streams/bus""gorm.io/gorm")@@ -60,10 +61,7 @@ func TestMapDaemonEventInternal(t *testing.T) {require.Nil(t, req.UserID)require.Nil(t, req.Username)require.Equal(t, database.JSON{"source": "docker", "action": string(tc.action), "scope": "local", "name": "web", "image": "alpine", "exitCode": "0", "signal": "15", "composeProject": "demo", "composeService": "web"}, req.Metadata)- severity := EventSeverityInfo- if tc.action == events.ActionOOM {- severity = EventSeverityError- }+ severity := kit.Ternary(tc.action == events.ActionOOM, EventSeverityError, EventSeverityInfo)if tc.action == events.ActionHealthStatusUnhealthy {severity = EventSeverityWarning}@@ -122,10 +120,7 @@ func TestDaemonEventsPersistEveryOccurrenceImmediately(t *testing.T) {func TestDaemonSuppressionAndFailureAllowLaterObservations(t *testing.T) {for _, failure := range []bool{false, true} {- name := "suppression"- if failure {- name = "persistence failure"- }+ name := kit.Ternary(failure, "persistence failure", "suppression")t.Run(name, func(t *testing.T) {db := setupEventServiceTestDB(t)svc := NewEventService(db, nil, nil)@@ -152,10 +147,7 @@ func TestDaemonSuppressionAndFailureAllowLaterObservations(t *testing.T) {func TestDockerEventSubscriptionsReadyAndStop(t *testing.T) {for _, closeBus := range []bool{false, true} {- name := "cancellation"- if closeBus {- name = "closed bus"- }+ name := kit.Ternary(closeBus, "closed bus", "cancellation")t.Run(name, func(t *testing.T) {synctest.Test(t, func(t *testing.T) {db := setupEventServiceTestDB(t)@@ -181,10 +173,7 @@ func TestDockerEventSubscriptionsReadyAndStop(t *testing.T) {publishBurst := func(offset int64) {for occurrence := range occurrences {for _, kind := range []events.Type{events.ContainerEventType, events.ImageEventType, events.VolumeEventType, events.NetworkEventType} {- action := events.ActionCreate- if kind == events.ImageEventType {- action = events.ActionPull- }+ action := kit.Ternary(kind == events.ImageEventType, events.ActionPull, events.ActionCreate)eventBus.Publish(events.Message{Type: kind, Action: action, TimeNano: offset + int64(occurrence+1), Actor: events.Actor{ID: "resource"}})}}diff --git a/backend/internal/event/handler.go b/backend/internal/event/handler.goindex eee2f7d39..3378a5e0d 100644--- a/backend/internal/event/handler.go+++ b/backend/internal/event/handler.go@@ -10,7 +10,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"eventtypes "github.com/getarcaneapp/arcane/types/v2/event"@@ -75,7 +74,7 @@ func RegisterAgentEventIngestion(g *echo.Group, eventService *EventService, resoData: base.MessageResponse{Message: "agent event ingestion is not configured"},})}- environmentID, err := resolveEnvironment(c.Request().Context(), c.Request().Header.Get(utils.HeaderAgentToken))+ environmentID, err := resolveEnvironment(c.Request().Context(), c.Request().Header.Get(middleware.HeaderAgentToken))if err != nil || environmentID == "" || environmentID == "0" {return c.JSON(http.StatusUnauthorized, base.ApiResponse[base.MessageResponse]{Success: false,diff --git a/backend/internal/event/model.go b/backend/internal/event/model.goindex b46f937ba..37d5f5b6d 100644--- a/backend/internal/event/model.go+++ b/backend/internal/event/model.go@@ -1,9 +1,9 @@package eventimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database")type (diff --git a/backend/internal/event/service.go b/backend/internal/event/service.goindex 8e4c24132..1f710cdde 100644--- a/backend/internal/event/service.go+++ b/backend/internal/event/service.go@@ -2,6 +2,7 @@ package eventimport ("bytes"+ "cmp""context""encoding/json/v2""fmt"@@ -12,20 +13,18 @@ import ("strings""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"eventtypes "github.com/getarcaneapp/arcane/types/v2/event""github.com/samber/mo""github.com/samber/mo/option"+ "go.getarcane.app/kit/pkg/mapping""golang.org/x/text/cases""golang.org/x/text/language""gorm.io/gorm"@@ -72,10 +71,7 @@ type CreateEventRequest struct {}func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest) (*Event, error) {- severity := req.Severity- if severity == "" {- severity = EventSeverityInfo- }+ severity := cmp.Or(req.Severity, EventSeverityInfo)userID, username := normalizeEventActor(req.UserID, req.Username)eventRecord := &Event{@@ -236,7 +232,7 @@ func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModelreturn errors.WrapIf(err, "failed to create manager event request")}req.Header.Set("Content-Type", "application/json")- req.Header.Set(utils.HeaderAgentToken, s.cfg.AgentToken)+ req.Header.Set(middleware.HeaderAgentToken, s.cfg.AgentToken)resp, err := s.httpClient.Do(req)if err != nil {@@ -283,10 +279,10 @@ func normalizeEventActor(userID, username *string) (*string, *string) {normalizedUsername := normalizeOptionalStringPtr(username)if normalizedUsername == nil && normalizedUserID != nil {- normalizedUsername = copyOptionalStringPtr(normalizedUserID)+ normalizedUsername = new(*normalizedUserID)}if normalizedUserID == nil && normalizedUsername != nil {- normalizedUserID = copyOptionalStringPtr(normalizedUsername)+ normalizedUserID = new(*normalizedUsername)}if normalizedUserID == nil && normalizedUsername == nil {normalizedUserID = new("system")@@ -307,13 +303,6 @@ func normalizeOptionalStringPtr(value *string) *string {return &trimmed}-func copyOptionalStringPtr(value *string) *string {- if value == nil {- return nil- }- return new(*value)-}-func (s *EventService) ListEventsPaginated(ctx context.Context, params pagination.QueryParams) ([]eventtypes.Event, pagination.Response, error) {var events []Eventq := s.db.WithContext(ctx).Model(&Event{})@@ -337,7 +326,7 @@ func (s *EventService) ListEventsPaginated(ctx context.Context, params paginatioreturn nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")}- eventDtos, mapErr := mapper.MapSlice[Event, eventtypes.Event](events)+ eventDtos, mapErr := mapping.MapSlice[Event, eventtypes.Event](events)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")}@@ -367,7 +356,7 @@ func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, envireturn nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")}- eventDtos, mapErr := mapper.MapSlice[Event, eventtypes.Event](events)+ eventDtos, mapErr := mapping.MapSlice[Event, eventtypes.Event](events)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")}diff --git a/backend/internal/event/service_test.go b/backend/internal/event/service_test.goindex 2341fee6f..8a40dd2fb 100644--- a/backend/internal/event/service_test.go+++ b/backend/internal/event/service_test.go@@ -11,8 +11,8 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/libtnb/sqlite""github.com/moby/moby/api/types/events""github.com/stretchr/testify/assert"@@ -192,7 +192,7 @@ func TestEventService_CreateEvent_ForwardsToManagerAPIInAgentMode(t *testing.T)if !assert.Equal(t, "/api/events", r.URL.Path) {return}- if !assert.Equal(t, "test-agent-token", r.Header.Get(utils.HeaderAgentToken)) {+ if !assert.Equal(t, "test-agent-token", r.Header.Get(middleware.HeaderAgentToken)) {return}@@ -422,5 +422,4 @@ func TestDaemonEventForwardingPreservesMetadata(t *testing.T) {}require.Never(t, func() bool { return len(requests) != 0 }, 50*time.Millisecond, time.Millisecond)requireDaemonCountInternal(t, db, 1)-}diff --git a/backend/internal/federated/credential.go b/backend/internal/federated/credential.goindex 2500531f5..53d47b793 100644--- a/backend/internal/federated/credential.go+++ b/backend/internal/federated/credential.go@@ -1,19 +1,19 @@package federatedimport (+ "cmp""context""net/url""strings"- "go.getarcane.app/kit/normalization"-"emperror.dev/errors"- "github.com/samber/mo"-"github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated"+ "github.com/samber/mo"+ "go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg")func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederatedCredential) (federatedtypes.CreateFederatedCredential, error) {@@ -23,14 +23,16 @@ func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederatreq.IssuerURL = strings.TrimRight(strings.TrimSpace(req.IssuerURL), "/")req.SubjectClaim = strings.TrimSpace(req.SubjectClaim)req.SubjectMatch = strings.TrimSpace(req.SubjectMatch)- req.MatchType = normalizeMatchTypeInternal(req.MatchType)- req.Audiences = utils.UniqueNonEmptyStrings(req.Audiences)+ req.MatchType = kit.Ternary(+ strings.EqualFold(strings.TrimSpace(req.MatchType), federatedtypes.MatchTypeGlob),+ federatedtypes.MatchTypeGlob,+ federatedtypes.MatchTypeExact,+ )+ req.Audiences = kit.Unique(kit.TrimNonEmpty(req.Audiences))req.EnvironmentID = mo.EmptyableToOption(strings.TrimSpace(mo.PointerToOption(req.EnvironmentID).OrEmpty())).ToPointer()req.TokenTTLSeconds = auth.ClampFederatedTokenTTLSeconds(req.TokenTTLSeconds)- if req.SubjectClaim == "" {- req.SubjectClaim = defaultFederatedSubjectClaim- }+ req.SubjectClaim = cmp.Or(req.SubjectClaim, defaultFederatedSubjectClaim)if req.SubjectMatch == "" || req.RoleID == "" || len(req.Audiences) == 0 {return req, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}@@ -62,17 +64,14 @@ func applyFederatedCredentialUpdateInternal(existing FederatedCredential, req feexisting.IssuerURL = issuerURL}if req.Audiences != nil {- audiences := utils.UniqueNonEmptyStrings(req.Audiences)+ audiences := kit.Unique(kit.TrimNonEmpty(req.Audiences))if len(audiences) == 0 {return existing, false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}existing.Audiences = audiences}if req.SubjectClaim != nil {- subjectClaim := strings.TrimSpace(*req.SubjectClaim)- if subjectClaim == "" {- subjectClaim = defaultFederatedSubjectClaim- }+ subjectClaim := cmp.Or(strings.TrimSpace(*req.SubjectClaim), defaultFederatedSubjectClaim)existing.SubjectClaim = subjectClaim}if req.SubjectMatch != nil {@@ -83,7 +82,11 @@ func applyFederatedCredentialUpdateInternal(existing FederatedCredential, req feexisting.SubjectMatch = subjectMatch}if req.MatchType != nil {- existing.MatchType = normalizeMatchTypeInternal(*req.MatchType)+ existing.MatchType = kit.Ternary(+ strings.EqualFold(strings.TrimSpace(*req.MatchType), federatedtypes.MatchTypeGlob),+ federatedtypes.MatchTypeGlob,+ federatedtypes.MatchTypeExact,+ )}if err := validateSubjectMatchInternal(existing.MatchType, existing.SubjectMatch); err != nil {return existing, false, err@@ -112,13 +115,6 @@ func applyFederatedCredentialUpdateInternal(existing FederatedCredential, req fereturn existing, roleChanged, nil}-func normalizeMatchTypeInternal(matchType string) string {- if strings.EqualFold(strings.TrimSpace(matchType), federatedtypes.MatchTypeGlob) {- return federatedtypes.MatchTypeGlob- }- return federatedtypes.MatchTypeExact-}-func validateIssuerURLInternal(rawURL string) error {parsed, err := url.Parse(rawURL)if err != nil || parsed == nil || parsed.Host == "" || parsed.Scheme != "https" {@@ -128,7 +124,7 @@ func validateIssuerURLInternal(rawURL string) error {}func validateSubjectMatchInternal(matchType, subjectMatch string) error {- if strings.TrimSpace(subjectMatch) == "" || normalizeMatchTypeInternal(matchType) == federatedtypes.MatchTypeGlob && strings.TrimSpace(subjectMatch) == "*" {+ if strings.TrimSpace(subjectMatch) == "" || strings.EqualFold(strings.TrimSpace(matchType), federatedtypes.MatchTypeGlob) && strings.TrimSpace(subjectMatch) == "*" {return common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}return nildiff --git a/backend/internal/federated/exchange.go b/backend/internal/federated/exchange.goindex 6e3b99ec5..3a9bc702b 100644--- a/backend/internal/federated/exchange.go+++ b/backend/internal/federated/exchange.go@@ -1,9 +1,8 @@package federatedimport (+ "cmp""context"- "crypto/sha256"- "encoding/hex""log/slog""regexp""strings"@@ -11,15 +10,14 @@ import ("emperror.dev/errors""github.com/coreos/go-oidc/v3/oidc"- "github.com/samber/mo"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/jwtclaims""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/oidcjwk"federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated"+ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req federatedtypes.TokenExchangeRequest) (*federatedtypes.FederatedTokenResponse, error) {@@ -28,9 +26,9 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fedesubject := ""var audiences []stringif claims != nil {- issuer = utils.ToString(jwtclaims.GetByPath(claims, "iss").OrEmpty())- subject = utils.ToString(jwtclaims.GetByPath(claims, "sub").OrEmpty())- audiences = utils.UniqueNonEmptyStrings(jwtclaims.StringSliceFromValue(jwtclaims.GetByPath(claims, "aud").OrEmpty()))+ issuer = kit.ToString(jwtclaims.GetByPath(claims, "iss").OrEmpty())+ subject = kit.ToString(jwtclaims.GetByPath(claims, "sub").OrEmpty())+ audiences = kit.Unique(kit.TrimNonEmpty(kit.Collect(jwtclaims.GetByPath(claims, "aud").OrEmpty(), func(item any) string { return kit.As(item, "") })))}logResult := "failure"@@ -88,7 +86,7 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req federeturn nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.WrapIf(err, "invalid federated token grant"))}if subject == "" {- subject = utils.ToString(jwtclaims.GetByPath(verifiedClaims, defaultFederatedSubjectClaim).OrEmpty())+ subject = kit.ToString(jwtclaims.GetByPath(verifiedClaims, defaultFederatedSubjectClaim).OrEmpty())}if len(audiences) == 0 {audiences = append([]string{}, verifiedToken.Audience...)@@ -175,15 +173,14 @@ func (s *FederatedCredentialService) recordTokenReplayGuardInternal(ctx context.return errors.WrapIf(err, "failed to prune federated token replay records")}- tokenID := strings.TrimSpace(utils.ToString(jwtclaims.GetByPath(claims, "jti").OrEmpty()))+ tokenID := strings.TrimSpace(kit.ToString(jwtclaims.GetByPath(claims, "jti").OrEmpty()))tokenKind := "jti"if tokenID == "" {tokenID = rawTokentokenKind = "token"}- sum := sha256.Sum256([]byte(issuer + "\x00" + tokenKind + "\x00" + tokenID))replay := FederatedTokenReplay{- TokenHash: hex.EncodeToString(sum[:]),+ TokenHash: kit.SHA256Hex(issuer + "\x00" + tokenKind + "\x00" + tokenID),IssuerURL: issuer,ExpiresAt: expiresAt,}@@ -272,15 +269,12 @@ func credentialMatchesTokenInternal(credential *FederatedCredential, tokenAudienreturn false}- subjectClaim := strings.TrimSpace(credential.SubjectClaim)- if subjectClaim == "" {- subjectClaim = defaultFederatedSubjectClaim- }- subject := utils.ToString(jwtclaims.GetByPath(claims, subjectClaim).OrEmpty())+ subjectClaim := cmp.Or(strings.TrimSpace(credential.SubjectClaim), defaultFederatedSubjectClaim)+ subject := kit.ToString(jwtclaims.GetByPath(claims, subjectClaim).OrEmpty())if subject == "" {return false}- if normalizeMatchTypeInternal(credential.MatchType) != federatedtypes.MatchTypeGlob {+ if !strings.EqualFold(strings.TrimSpace(credential.MatchType), federatedtypes.MatchTypeGlob) {return subject == credential.SubjectMatch}diff --git a/backend/internal/federated/model.go b/backend/internal/federated/model.goindex 71e678bab..65dd53c1f 100644--- a/backend/internal/federated/model.go+++ b/backend/internal/federated/model.go@@ -1,14 +1,12 @@package federatedimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/role"+ "time""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-"github.com/getarcaneapp/arcane/backend/v2/internal/database"-- "time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"+ "github.com/getarcaneapp/arcane/backend/v2/internal/role")const (diff --git a/backend/internal/federated/playwright.go b/backend/internal/federated/playwright.goindex b9c79440b..5f742f4be 100644--- a/backend/internal/federated/playwright.go+++ b/backend/internal/federated/playwright.go@@ -3,21 +3,20 @@package federatedimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/role"-"context""strings""uuid""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/role""gorm.io/gorm")// CreatePlaywrightCredential creates the service identity, credential, and role// assignment required by the federated-auth end-to-end flow in one transaction.-func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.Context, issuerURL string, audiences []string, subject string, roleID string, tokenTTLSeconds int) (string, error) {+func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.Context, issuerURL string, audiences []string, subject, roleID string, tokenTTLSeconds int) (string, error) {if s == nil || s.db == nil {return "", errors.New("federated credential service is not available")}diff --git a/backend/internal/federated/service.go b/backend/internal/federated/service.goindex de0f4da49..a7103f948 100644--- a/backend/internal/federated/service.go+++ b/backend/internal/federated/service.go@@ -10,10 +10,6 @@ import ("emperror.dev/errors""github.com/coreos/go-oidc/v3/oidc"- "github.com/samber/mo"- "golang.org/x/sync/singleflight"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -28,6 +24,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/oidcjwk"federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated"httpxtypes "github.com/getarcaneapp/arcane/types/v2/httpx"+ "github.com/samber/mo"+ "golang.org/x/sync/singleflight"+ "gorm.io/gorm")const (diff --git a/backend/internal/federated/service_test.go b/backend/internal/federated/service_test.goindex a60617008..1275b8100 100644--- a/backend/internal/federated/service_test.go+++ b/backend/internal/federated/service_test.go@@ -13,14 +13,6 @@ import ("time""emperror.dev/errors"- "github.com/lestrrat-go/jwx/v4/jwa"- "github.com/lestrrat-go/jwx/v4/jws"- "github.com/lestrrat-go/jwx/v4/jwt"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "go.uber.org/fx/fxtest"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -34,7 +26,14 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/oidcjwk"federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated"+ "github.com/lestrrat-go/jwx/v4/jwa"+ "github.com/lestrrat-go/jwx/v4/jws"+ "github.com/lestrrat-go/jwx/v4/jwt"+ "github.com/libtnb/sqlite""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.uber.org/fx/fxtest"+ "gorm.io/gorm")type federatedTestIssuerInternal struct {diff --git a/backend/internal/gitops/backup.go b/backend/internal/gitops/backup.goindex 08e4e405e..2c4d031eb 100644--- a/backend/internal/gitops/backup.go+++ b/backend/internal/gitops/backup.go@@ -2,8 +2,6 @@ package gitopsimport ("context"- "crypto/sha256"- "encoding/hex""encoding/json/v2""fmt""io/fs"@@ -23,10 +21,10 @@ import (projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project"git "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/gitops"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm""gorm.io/gorm/clause")@@ -38,6 +36,18 @@ const (backupStatusRunning = "running"backupStatusConflict = "conflict"backupCommitFileLines = 20++ backupSnapshotMaxRetry = 3+ legacyBackupManifestFileNameInternal = ".arcane-backup.json"+ backupPreviewClean = "clean"+ backupPreviewChanges = "changes"+ backupPreviewConflict = "conflict"+ backupPreviewOccupied = "destination_occupied"+ backupChangeAdded = "added"+ backupChangeModified = "modified"+ backupChangeRemoved = "removed"++ defaultBackupHistoryLimit = 20)// backupRuntimeInternal holds the in-memory coordination for backup syncs@@ -136,7 +146,7 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, txreturn nil, common.Classify(common.ErrConflict, errors.New("project already has a Git backup; disconnect it first"))}- directory, err := utils.NormalizeRelativePath(req.BackupDirectory)+ directory, err := kit.NormalizeRelativePath(req.BackupDirectory)if err == nil && slices.Contains(strings.Split(directory, "/"), ".git") {err = errors.New("backup directory must not contain a .git segment")}@@ -392,8 +402,10 @@ func backupFailureReasonInternal(err error) string {return gitops.BackupFailureSnapshot}message := strings.ToLower(err.Error())- if strings.Contains(message, "authentication") || strings.Contains(message, "authorization") || strings.Contains(message, "ssh") || strings.Contains(message, "credential") {- return gitops.BackupFailureAuth+ for _, marker := range []string{"authentication", "authorization", "ssh", "credential"} {+ if strings.Contains(message, marker) {+ return gitops.BackupFailureAuth+ }}return gitops.BackupFailureRepository}@@ -439,10 +451,7 @@ func (s *GitOpsSyncService) failBackupInternal(ctx context.Context, sync *projecerrMsg := failure.Error()result.Message = messageresult.Error = new(errMsg)- status := "failed"- if needsAttention {- status = backupStatusConflict- }+ status := kit.Ternary(needsAttention, backupStatusConflict, "failed")updates := map[string]any{"last_sync_at": time.Now(),"last_sync_status": status,@@ -583,18 +592,6 @@ func (s *GitOpsSyncService) ReconcileInterruptedBackupsOnStartup(ctx context.Conreturn nil}-const (- backupSnapshotMaxRetry = 3- legacyBackupManifestFileNameInternal = ".arcane-backup.json"- backupPreviewClean = "clean"- backupPreviewChanges = "changes"- backupPreviewConflict = "conflict"- backupPreviewOccupied = "destination_occupied"- backupChangeAdded = "added"- backupChangeModified = "modified"- backupChangeRemoved = "removed"-)-// backupSnapshotInternal is the set of project files a backup run commits.type backupSnapshotInternal struct {files []git.CommitFile@@ -609,16 +606,10 @@ type backupAnalysisInternal struct {remove []string}-func hashBackupContentInternal(content []byte) string {- sum := sha256.Sum256(content)- return hex.EncodeToString(sum[:])-}-func normalizeBackupPathsInternal(raw []string) ([]string, error) {- seen := make(map[string]struct{}, len(raw))normalized := make([]string, 0, len(raw))for _, entry := range raw {- cleaned, err := utils.NormalizeRelativePath(entry)+ cleaned, err := kit.NormalizeRelativePath(entry)if err != nil {return nil, errors.WrapIff(err, "invalid backup path %q", entry)}@@ -626,12 +617,9 @@ func normalizeBackupPathsInternal(raw []string) ([]string, error) {if base == projects.GitSourceEnvFileName || base == projects.GlobalEnvFileName || slices.Contains(strings.Split(cleaned, "/"), ".git") {return nil, errors.Errorf("backup path %q is reserved", entry)}- if _, ok := seen[cleaned]; ok {- continue- }- seen[cleaned] = struct{}{}normalized = append(normalized, cleaned)}+ normalized = kit.Unique(normalized)sort.Strings(normalized)return normalized, nil}@@ -697,7 +685,7 @@ func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, syn}snapshot := &backupSnapshotInternal{files: files, hashes: make(map[string]string, len(files))}for _, file := range files {- snapshot.hashes[file.Path] = hashBackupContentInternal(file.Content)+ snapshot.hashes[file.Path] = kit.SHA256Hex(file.Content)}stable := true@@ -706,7 +694,7 @@ func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, synif err != nil {return nil, errors.WrapIff(git.ErrSelectionUnreadable, "cannot re-read %s: %v", file.Path, err)}- if hashBackupContentInternal(content) != snapshot.hashes[file.Path] {+ if kit.SHA256Hex(content) != snapshot.hashes[file.Path] {stable = falsebreak}@@ -740,7 +728,7 @@ func analyzeBackupInternal(ctx context.Context, repoPath, directory string, snap}return analysis, errors.WrapIff(readErr, "failed to read remote backup file %s", file)}- remote[file] = hashBackupContentInternal(content)+ remote[file] = kit.SHA256Hex(content)}}}@@ -806,8 +794,6 @@ func parseBackupSnapshotInternal(raw *string) map[string]string {return hashes}-const defaultBackupHistoryLimit = 20-func (s *GitOpsSyncService) getBackupSyncInternal(ctx context.Context, environmentID, id string) (*projectpkg.GitOpsSync, error) {syncRecord, err := s.GetSyncByID(ctx, environmentID, id)if err != nil {diff --git a/backend/internal/gitops/backup_test.go b/backend/internal/gitops/backup_test.goindex be12bbe6d..f347cb958 100644--- a/backend/internal/gitops/backup_test.go+++ b/backend/internal/gitops/backup_test.go@@ -1,6 +1,7 @@package gitopsimport (+ "cmp""context""os""path/filepath"@@ -24,6 +25,7 @@ import ("github.com/go-git/go-git/v5/plumbing/transport/server""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")var installBackupTestTransportOnceInternal sync.Once@@ -166,24 +168,14 @@ func writeBackupProjectFileInternal(t *testing.T, root, relative, content stringfunc (e *backupTestEnvInternal) createBackupInternal(t *testing.T, req gitops.CreateSyncRequest) *projectpkg.GitOpsSync {t.Helper()- if req.Name == "" {- req.Name = "demo-backup"- }- if req.RepositoryID == "" {- req.RepositoryID = "repo-backup"- }- if req.Branch == "" {- req.Branch = "main"- }- if req.Mode == "" {- req.Mode = gitops.SyncModeBackup- }+ req.Name = cmp.Or(req.Name, "demo-backup")+ req.RepositoryID = cmp.Or(req.RepositoryID, "repo-backup")+ req.Branch = cmp.Or(req.Branch, "main")+ req.Mode = cmp.Or(req.Mode, gitops.SyncModeBackup)if req.ProjectID == "" {req.ProjectID = e.project.ID}- if req.BackupDirectory == "" {- req.BackupDirectory = "backups/demo"- }+ req.BackupDirectory = cmp.Or(req.BackupDirectory, "backups/demo")syncRecord, err := e.service.CreateSync(t.Context(), "0", req, common.SystemUser)require.NoError(t, err)return syncRecord@@ -260,7 +252,7 @@ func TestGitOpsBackup_FirstRunPushesSelectedFiles(t *testing.T) {snapshot := parseBackupSnapshotInternal(stored.LastBackupSnapshot)assert.Len(t, snapshot, 2)- assert.Equal(t, hashBackupContentInternal(composeBytes), snapshot["compose.yaml"])+ assert.Equal(t, kit.SHA256Hex(composeBytes), snapshot["compose.yaml"])}func TestGitOpsBackup_UnchangedContentMakesNoNewCommit(t *testing.T) {@@ -501,15 +493,11 @@ func TestGitOpsBackup_CreateValidation(t *testing.T) {}request := test.requestrequest.Mode = gitops.SyncModeBackup- if request.Name == "" {- request.Name = "demo-backup"- }+ request.Name = cmp.Or(request.Name, "demo-backup")request.RepositoryID = "repo-backup"request.Branch = "main"request.ProjectID = env.project.ID- if request.BackupDirectory == "" {- request.BackupDirectory = "backups/demo"- }+ request.BackupDirectory = cmp.Or(request.BackupDirectory, "backups/demo")_, err := env.service.CreateSync(t.Context(), "0", request, common.SystemUser)require.Error(t, err)diff --git a/backend/internal/gitops/gitops_sync.go b/backend/internal/gitops/gitops_sync.goindex f81f4efa2..1603d9dc9 100644--- a/backend/internal/gitops/gitops_sync.go+++ b/backend/internal/gitops/gitops_sync.go@@ -1,6 +1,7 @@package gitopsimport (+ "cmp""context""encoding/json/v2""fmt"@@ -11,11 +12,10 @@ import ("path""path/filepath""slices"+ "strconv""strings""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"-"emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -28,13 +28,15 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/entityjobs"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper""github.com/getarcaneapp/arcane/types/v2/gitops"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""gorm.io/gorm")@@ -53,14 +55,16 @@ type GitOpsSyncService struct {backups *backupRuntimeInternal}-const defaultGitSyncTimeout = 5 * time.Minute-const (+ defaultGitSyncTimeout = 5 * time.Minute+defaultMaxSyncFiles = 500defaultMaxSyncTotalSizeMB = 50defaultMaxSyncBinarySizeMB = 10defaultMaxSyncTotalSize = defaultMaxSyncTotalSizeMB * 1024 * 1024defaultMaxSyncBinarySize = defaultMaxSyncBinarySizeMB * 1024 * 1024++ gitOpsSyncAdmissionScopeInternal = "gitops-sync")// preparedSyncSource captures the repository data needed by the sync execution@@ -311,10 +315,7 @@ func normalizeLifecycleNetworkModeInternal(p *string) string {return "none"}trimmed := strings.TrimSpace(*p)- if trimmed == "" {- return "none"- }- return trimmed+ return kit.Ternary(trimmed == "", "none", trimmed)}func nullableTrimmedStringInternal(p *string) *string {@@ -333,17 +334,11 @@ func nullableUpdateStringValueInternal(p *string) any {return nil}trimmed := strings.TrimSpace(*p)- if trimmed == "" {- return nil- }- return trimmed+ return kit.Ternary[any](trimmed == "", nil, trimmed)}func normalizeSyncLimitSetting(value, defaultValue int) int {- if value < 0 {- return defaultValue- }- return value+ return kit.Ternary(value < 0, defaultValue, value)}func megabytesToBytes(value int) int64 {@@ -367,8 +362,6 @@ func NewGitOpsSyncService(db *database.DB, repoService *gitrepo.GitRepositorySer}}-const gitOpsSyncAdmissionScopeInternal = "gitops-sync"-// SetScheduler injects the job scheduler and the app lifecycle context. It must be// called during bootstrap (after the service graph is built) before any per-sync// jobs are registered. The lifecycle context is used for background sync kicks so@@ -489,9 +482,9 @@ func (s *GitOpsSyncService) getEnvironmentSyncLimits(ctx context.Context) (int,}cfg := s.settingsService.GetSettingsOrDefaults(ctx)- maxFiles := normalizeSyncLimitSetting(utils.IntOrDefault(cfg.GitSyncMaxFiles.Value, defaultMaxSyncFiles), defaultMaxSyncFiles)- maxTotalSizeMB := normalizeSyncLimitSetting(utils.IntOrDefault(cfg.GitSyncMaxTotalSizeMb.Value, defaultMaxSyncTotalSizeMB), defaultMaxSyncTotalSizeMB)- maxBinarySizeMB := normalizeSyncLimitSetting(utils.IntOrDefault(cfg.GitSyncMaxBinarySizeMb.Value, defaultMaxSyncBinarySizeMB), defaultMaxSyncBinarySizeMB)+ maxFiles := normalizeSyncLimitSetting(kit.ParseOrDefault(cfg.GitSyncMaxFiles.Value, defaultMaxSyncFiles, strconv.Atoi), defaultMaxSyncFiles)+ maxTotalSizeMB := normalizeSyncLimitSetting(kit.ParseOrDefault(cfg.GitSyncMaxTotalSizeMb.Value, defaultMaxSyncTotalSizeMB, strconv.Atoi), defaultMaxSyncTotalSizeMB)+ maxBinarySizeMB := normalizeSyncLimitSetting(kit.ParseOrDefault(cfg.GitSyncMaxBinarySizeMb.Value, defaultMaxSyncBinarySizeMB, strconv.Atoi), defaultMaxSyncBinarySizeMB)return maxFiles, megabytesToBytes(maxTotalSizeMB), megabytesToBytes(maxBinarySizeMB)}@@ -552,7 +545,7 @@ func (s *GitOpsSyncService) GetSyncsPaginated(ctx context.Context, environmentIDreturn nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(err, "failed to paginate gitops syncs")}- out, mapErr := mapper.MapSlice[projectpkg.GitOpsSync, gitops.GitOpsSync](syncs)+ out, mapErr := mapping.MapSlice[projectpkg.GitOpsSync, gitops.GitOpsSync](syncs)if mapErr != nil {return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(mapErr, "failed to map syncs")}@@ -648,10 +641,7 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID stringslog.InfoContext(ctx, "Found repository for GitOps sync", "repositoryID", req.RepositoryID, "repositoryName", repo.Name)// Store the project name - use sync name if project name not provided- projectName := req.ProjectName- if projectName == "" {- projectName = req.Name- }+ projectName := cmp.Or(req.ProjectName, req.Name)defaultMaxFiles, defaultMaxTotalSize, defaultMaxBinarySize := s.getEnvironmentSyncLimits(ctx)@@ -1275,7 +1265,7 @@ func (s *GitOpsSyncService) performSingleFileSyncInternal(ctx context.Context, s// credentials the same way a direct stack deploy does. Resolution happens per image at deploy// time and yields nothing unless a configured container registry matches that image's host, so// stacks built only from public images are unaffected.-func buildSwarmStackDeployRequestInternal(sync *projectpkg.GitOpsSync, source *preparedSyncSource, overrideContent string, envContent string, swarmFiles []swarmtypes.SyncFile) swarmtypes.StackDeployRequest {+func buildSwarmStackDeployRequestInternal(sync *projectpkg.GitOpsSync, source *preparedSyncSource, overrideContent, envContent string, swarmFiles []swarmtypes.SyncFile) swarmtypes.StackDeployRequest {return swarmtypes.StackDeployRequest{Name: sync.ProjectName,ComposeContent: source.composeContent,@@ -1432,11 +1422,7 @@ func (s *GitOpsSyncService) updateSyncStatus(ctx context.Context, id, status, er"last_sync_status": status,}- if errorMsg != "" {- updates["last_sync_error"] = errorMsg- } else {- updates["last_sync_error"] = nil- }+ updates["last_sync_error"] = kit.Ternary[any](errorMsg != "", errorMsg, nil)if commitHash != "" {updates["last_sync_commit"] = commitHash@@ -1591,7 +1577,7 @@ func (s *GitOpsSyncService) ReconcileDirectorySyncProjectsOnStartup(ctx context.return nil}-func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id string, path string) (*gitops.BrowseResponse, error) {+func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id, path string) (*gitops.BrowseResponse, error) {browseCtx, cancel := context.WithTimeout(ctx, defaultGitSyncTimeout)defer cancel()@@ -1742,7 +1728,7 @@ func (s *GitOpsSyncService) recordBrokenProjectBindingInternal(ctx context.Contes.disableAutoSyncForBrokenBindingInternal(ctx, sync)}-func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {+func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id, composeContent string, envContent, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {// Use the non-suffixing create: a GitOps sync must never mint a "-N" duplicate.// A name collision means a project directory already exists for this name, so the// binding is broken β fail loudly and disable auto-sync instead of duplicating.@@ -1791,7 +1777,7 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, syreturn project, nil}-func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {+func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id, composeContent string, envContent, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {var project *projectpkg.Projectif sync.ProjectID != nil && *sync.ProjectID != "" {@@ -1819,7 +1805,7 @@ func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, syncreturn project, nil}-func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, project *projectpkg.Project, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) error {+func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, project *projectpkg.Project, composeContent string, envContent, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) error {_, changed, err := s.projectService.ApplyGitSyncProjectFiles(ctx, project.ID, composeContent, envContent, overrideContent, overrideFileName, actor)if err != nil {return s.failSync(ctx, id, result, sync, actor, "Failed to update project files", err.Error())@@ -2070,10 +2056,7 @@ func linkProjectIntoStageInternal(livePath, stagePath string, scopePaths []strinlink = func(rel string) error {entries, err := os.ReadDir(filepath.Join(livePath, filepath.FromSlash(rel)))if err != nil {- if rel == "" && errors.Is(err, fs.ErrNotExist) {- return nil- }- return err+ return kit.Ternary(rel == "" && errors.Is(err, fs.ErrNotExist), nil, err)}for _, entry := range entries {entryRel := path.Join(rel, entry.Name())@@ -2595,11 +2578,7 @@ func (s *GitOpsSyncService) updateSyncStatusWithFiles(ctx context.Context, id, s"synced_files": marshalSyncedFiles(syncedFiles),}- if errorMsg != "" {- updates["last_sync_error"] = errorMsg- } else {- updates["last_sync_error"] = nil- }+ updates["last_sync_error"] = kit.Ternary[any](errorMsg != "", errorMsg, nil)if commitHash != "" {updates["last_sync_commit"] = commitHashdiff --git a/backend/internal/gitops/handler.go b/backend/internal/gitops/handler.goindex c7960b4af..a100bec5b 100644--- a/backend/internal/gitops/handler.go+++ b/backend/internal/gitops/handler.go@@ -1,15 +1,14 @@package gitopsimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/project"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-+ "cmp""context""emperror.dev/errors""github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"@@ -184,9 +183,7 @@ func (h *GitOpsSyncHandler) requireBackupSyncPermissionInternal(ctx context.Contfunc (h *GitOpsSyncHandler) ListSyncs(ctx context.Context, input *ListGitOpsSyncsInput) (*ListGitOpsSyncsOutput, error) {params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)for key, value := range map[string]string{"mode": input.Mode, "projectId": input.ProjectID, "repositoryId": input.RepositoryID, "autoSync": input.AutoSync} {- if value != "" {- params.Filters[key] = value- }+ params.Filters[key] = cmp.Or(value, params.Filters[key])}syncs, paginationResp, counts, err := h.syncService.GetSyncsPaginated(ctx, input.EnvironmentID, params)diff --git a/backend/internal/gitops/service_test.go b/backend/internal/gitops/service_test.goindex a2d5b45f1..b10713f45 100644--- a/backend/internal/gitops/service_test.go+++ b/backend/internal/gitops/service_test.go@@ -1,10 +1,6 @@package gitopsimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"-- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"-"context""encoding/json""os"@@ -18,8 +14,10 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings"git "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil"diff --git a/backend/internal/gitops/service_unix_test.go b/backend/internal/gitops/service_unix_test.goindex e0f547eaa..a46df0858 100644--- a/backend/internal/gitops/service_unix_test.go+++ b/backend/internal/gitops/service_unix_test.go@@ -3,15 +3,14 @@package gitopsimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project"-"context""encoding/json""os""path/filepath""testing"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"diff --git a/backend/internal/gitrepo/handler.go b/backend/internal/gitrepo/handler.goindex cd221773d..a9e9aac2d 100644--- a/backend/internal/gitrepo/handler.go+++ b/backend/internal/gitrepo/handler.go@@ -1,12 +1,11 @@package gitrepoimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""emperror.dev/errors""github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"diff --git a/backend/internal/gitrepo/module.go b/backend/internal/gitrepo/module.goindex dcc1012f6..1a94f72ec 100644--- a/backend/internal/gitrepo/module.go+++ b/backend/internal/gitrepo/module.go@@ -3,7 +3,6 @@ package gitrepoimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings"diff --git a/backend/internal/gitrepo/service.go b/backend/internal/gitrepo/service.goindex 47e54d432..9bd940eca 100644--- a/backend/internal/gitrepo/service.go+++ b/backend/internal/gitrepo/service.go@@ -1,15 +1,13 @@package gitrepoimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- "go.getarcane.app/kit/normalization"-+ "cmp""context""fmt""strings""emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -21,6 +19,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/gitops""github.com/samber/mo""go.getarcane.app/builds/pkg/contextsource"+ "go.getarcane.app/kit/normalization""go.getarcane.app/sys/crypto""gorm.io/gorm")@@ -137,9 +136,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req gitops.}// Default to accept_new if not specified- if repository.SSHHostKeyVerification == "" {- repository.SSHHostKeyVerification = "accept_new"- }+ repository.SSHHostKeyVerification = cmp.Or(repository.SSHHostKeyVerification, "accept_new")if req.Enabled != nil {repository.Enabled = *req.Enabled@@ -334,7 +331,7 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,return nil}-func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, branch string, actor common.User) error {+func (s *GitRepositoryService) TestConnection(ctx context.Context, id, branch string, actor common.User) error {settings := s.settingsService.GetSettingsConfig()ctx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))defer cancel()@@ -412,12 +409,8 @@ func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *Gi// repository, with the signing key unlocked when one is stored.func (s *GitRepositoryService) GetCommitIdentity(ctx context.Context, repository *GitRepository) (git.CommitIdentity, error) {identity := git.CommitIdentity{Name: repository.CommitAuthorName, Email: repository.CommitAuthorEmail}- if identity.Name == "" {- identity.Name = defaultCommitAuthorName- }- if identity.Email == "" {- identity.Email = defaultCommitAuthorEmail- }+ identity.Name = cmp.Or(identity.Name, defaultCommitAuthorName)+ identity.Email = cmp.Or(identity.Email, defaultCommitAuthorEmail)if repository.SigningKey == "" {return identity, nil}@@ -432,10 +425,7 @@ func (s *GitRepositoryService) GetCommitIdentity(ctx context.Context, repository}}identity.SignKey, err = git.ParseSigningKey(armored, passphrase)- if err != nil {- return identity, err- }- return identity, nil+ return identity, err}// encryptSigningKeyInternal validates that armored unlocks with passphrase and@@ -689,10 +679,7 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item git}}- sshHostKeyVerification := item.SSHHostKeyVerification- if sshHostKeyVerification == "" {- sshHostKeyVerification = "accept_new"- }+ sshHostKeyVerification := cmp.Or(item.SSHHostKeyVerification, "accept_new")repo := GitRepository{Name: item.Name,diff --git a/backend/internal/gitrepo/service_test.go b/backend/internal/gitrepo/service_test.goindex 27587ec93..0608132b4 100644--- a/backend/internal/gitrepo/service_test.go+++ b/backend/internal/gitrepo/service_test.go@@ -3,18 +3,11 @@ package gitrepoimport ("context""fmt"- "github.com/getarcaneapp/arcane/types/v2/gitops""strings""testing""time""emperror.dev/errors"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"- "go.uber.org/fx/fxtest"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -22,8 +15,14 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"+ "github.com/getarcaneapp/arcane/types/v2/gitops"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "go.getarcane.app/kit/pkg/mapping""go.getarcane.app/sys/crypto"+ "go.uber.org/fx/fxtest"+ "gorm.io/gorm")func setupGitRepositoryServiceTestInternal(t *testing.T) (*GitRepositoryService, *database.DB) {@@ -87,7 +86,7 @@ func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepositoryUsername: "admin",})require.NoError(t, err)- mapped, err := mapper.MapOne[*GitRepository, gitops.GitRepository](repo)+ mapped, err := mapping.MapOne[*GitRepository, gitops.GitRepository](repo)require.NoError(t, err)assert.Equal(t, req.Token != "", mapped.HasToken)assert.Equal(t, req.SSHKey != "", mapped.HasSshKey)@@ -191,7 +190,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResuppldecryptedToken, decryptErr := crypto.Decrypt(updated.Token)require.NoError(t, decryptErr)assert.Equal(t, "ghp_new_token", decryptedToken)- mapped, err := mapper.MapOne[*GitRepository, gitops.GitRepository](updated)+ mapped, err := mapping.MapOne[*GitRepository, gitops.GitRepository](updated)require.NoError(t, err)assert.True(t, mapped.HasToken)assert.False(t, mapped.HasSshKey)@@ -215,7 +214,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsClearedassert.Equal(t, "https://github.com/acme/public.git", updated.URL)assert.Empty(t, updated.Token)- mapped, err := mapper.MapOne[*GitRepository, gitops.GitRepository](updated)+ mapped, err := mapping.MapOne[*GitRepository, gitops.GitRepository](updated)require.NoError(t, err)assert.False(t, mapped.HasToken)assert.False(t, mapped.HasSshKey)diff --git a/backend/internal/image/attestations_test.go b/backend/internal/image/attestations_test.goindex 799d7412d..27cd64fcf 100644--- a/backend/internal/image/attestations_test.go+++ b/backend/internal/image/attestations_test.go@@ -35,7 +35,6 @@ func TestReadAttestationLayerBytesInternalDecompressesGzip(t *testing.T) {require.True(t, bytes.Equal(got, statement),"expected decompressed statement %q, got %q", statement, got)-}func TestReadAttestationLayerBytesInternalPassesThroughRawJSON(t *testing.T) {@@ -49,7 +48,6 @@ func TestReadAttestationLayerBytesInternalPassesThroughRawJSON(t *testing.T) {require.True(t, bytes.Equal(got, statement),"expected raw statement unchanged %q, got %q", statement, got)-}func TestReadAttestationLayerBytesInternalDecompressesZstd(t *testing.T) {@@ -75,5 +73,4 @@ func TestReadAttestationLayerBytesInternalDecompressesZstd(t *testing.T) {require.True(t, bytes.Equal(got, statement),"expected decompressed statement %q, got %q", statement, got)-}diff --git a/backend/internal/image/handler.go b/backend/internal/image/handler.goindex 37404cbd7..fe31b9b0c 100644--- a/backend/internal/image/handler.go+++ b/backend/internal/image/handler.go@@ -1,21 +1,19 @@package imageimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-+ "cmp""context""fmt""io""net/http""strings"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"emperror.dev/errors""github.com/containerd/platforms""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/build"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -26,11 +24,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/image""github.com/getarcaneapp/arcane/types/v2/system"uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"buildtypes "go.getarcane.app/builds/types"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -325,9 +325,7 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (params.Filters["updates"] = input.Updates}- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)images, paginationResp, err := h.imageService.ListImagesPaginated(ctx, params)if err != nil {@@ -498,10 +496,7 @@ func validateImageNameInternal(raw string) (string, error) {func imageExportFileNameInternal(imageName string) string {name := strings.NewReplacer("/", "_", ":", "_", "@", "_").Replace(imageName)- name = strings.Trim(name, "._-")- if name == "" {- name = "image"- }+ name = cmp.Or(strings.Trim(name, "._-"), "image")return name + ".tar"}@@ -724,7 +719,7 @@ func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput)}func resolvePruneImageModeInternal(input *PruneImagesInput) string {- mode := resolveLegacyPruneImageModeInternal(input.Dangling)+ mode := kit.Ternary(input.Dangling, "dangling", "all")if input.Body == nil {return mode}@@ -734,16 +729,13 @@ func resolvePruneImageModeInternal(input *PruneImagesInput) string {}if input.Body.Dangling != nil {- return resolveLegacyPruneImageModeInternal(*input.Body.Dangling)+ return kit.Ternary(*input.Body.Dangling, "dangling", "all")}if vals, ok := input.Body.Filters["dangling"]; ok {for _, value := range vals {- if dangling, valid := utils.ParseBool(value); valid {- if dangling {- return "dangling"- }- return "all"+ if dangling, valid := kit.ParseBool(value); valid {+ return kit.Ternary(dangling, "dangling", "all")}}}@@ -767,14 +759,6 @@ func resolvePruneImageUntilInternal(input *PruneImagesInput) string {return ""}-func resolveLegacyPruneImageModeInternal(dangling bool) string {- if dangling {- return "dangling"- }-- return "all"-}-// GetImageUsageCounts returns counts of images by usage status.func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageUsageCountsInput) (*handlerutil.Out[image.UsageCounts], error) {_, counts, err := h.dockerService.GetAllImages(ctx)diff --git a/backend/internal/image/image.go b/backend/internal/image/image.goindex a9e54df6d..006975d3c 100644--- a/backend/internal/image/image.go+++ b/backend/internal/image/image.go@@ -1,25 +1,23 @@package imageimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"cmp""context""io""log/slog"- "sort"+ "maps"+ "slices""strings""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-"emperror.dev/errors"-ref "github.com/distribution/reference"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"@@ -35,6 +33,7 @@ import ("github.com/moby/moby/client""github.com/samber/hot""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/updater""go.getarcane.app/updater/pkg/utils/tagpolicy""golang.org/x/sync/errgroup"@@ -305,10 +304,7 @@ func (s *ImageService) TagImage(ctx context.Context, source string, req imagetypreturn errors.New("repository is required")}- target := repository- if tag != "" {- target = repository + ":" + tag- }+ target := kit.Ternary(tag != "", repository+":"+tag, repository)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {@@ -937,10 +933,7 @@ func convertLabels(labels map[string]string) map[string]any {if labels == nil {return nil}- result := make(map[string]any, len(labels))- for k, v := range labels {- result[k] = v- }+ result, _ := kit.AsStringMap(labels)return result}@@ -972,15 +965,9 @@ func (s *ImageService) loadProjectIDByNameCachedInternal(ctx context.Context) ma})if err != nil {slog.WarnContext(ctx, "failed to load project ID map", "error", err)- if staleFound {- return stale- }- return map[string]string{}+ return kit.Ternary(staleFound, stale, map[string]string{})}- if !found {- return map[string]string{}- }- return byName+ return kit.Ternary(!found, map[string]string{}, byName)}// BuildProjectIDMap returns a map of compose project name β project ID for any@@ -1036,19 +1023,14 @@ func BuildVolumeUsageMap(containers []container.Summary, projectIDByName map[strType: "project",Name: projectName,}- if projectID != "" {- usedBy.ID = projectID- }+ usedBy.ID = cmp.Or(projectID, usedBy.ID)usageMap[c.ImageID] = append(usageMap[c.ImageID], usedBy)projectSeen[c.ImageID][projectName] = true}continue}- containerName := dockerutils.ContainerNameFromNames(c.Names)- if containerName == "" {- containerName = c.ID- }+ containerName := cmp.Or(dockerutils.ContainerNameFromNames(c.Names), c.ID)if containerSeen[c.ImageID] == nil {containerSeen[c.ImageID] = make(map[string]bool)@@ -1166,11 +1148,7 @@ func collectPinnedReferencesByImageIDInternal(containers []container.Summary) maresult := make(map[string][]string, len(seen))for imageID, refsMap := range seen {- refs := make([]string, 0, len(refsMap))- for r := range refsMap {- refs = append(refs, r)- }- sort.Strings(refs)+ refs := slices.Sorted(maps.Keys(refsMap))result[imageID] = refs}@@ -1263,10 +1241,7 @@ func (s *ImageService) getImagePaginationConfig() pagination.Config[imagetypes.Sif a.Size < b.Size {return -1}- if a.Size > b.Size {- return 1- }- return 0+ return kit.Ternary(a.Size > b.Size, 1, 0)},},{@@ -1275,10 +1250,7 @@ func (s *ImageService) getImagePaginationConfig() pagination.Config[imagetypes.Sif a.Created < b.Created {return -1}- if a.Created > b.Created {- return 1- }- return 0+ return kit.Ternary(a.Created > b.Created, 1, 0)},},{@@ -1287,10 +1259,7 @@ func (s *ImageService) getImagePaginationConfig() pagination.Config[imagetypes.Sif a.InUse == b.InUse {return 0}- if a.InUse {- return -1- }- return 1+ return kit.Ternary(a.InUse, -1, 1)},},{@@ -1309,13 +1278,7 @@ func (s *ImageService) getImagePaginationConfig() pagination.Config[imagetypes.S{Key: "inUse",Fn: func(i imagetypes.Summary, filterValue string) bool {- if filterValue == "true" {- return i.InUse- }- if filterValue == "false" {- return !i.InUse- }- return true+ return kit.Ternary(filterValue == "true", i.InUse, filterValue != "false" || !i.InUse)},},{@@ -1331,7 +1294,7 @@ func (s *ImageService) getImagePaginationConfig() pagination.Config[imagetypes.Scase "unknown":return i.UpdateInfo == nildefault:- value, valid := utils.ParseBool(filterValue)+ value, valid := kit.ParseBool(filterValue)hasUpdate := i.UpdateInfo != nil && i.UpdateInfo.HasUpdatereturn !valid || hasUpdate == value}diff --git a/backend/internal/image/image_attestations.go b/backend/internal/image/image_attestations.goindex e90c45d9b..39c799ebd 100644--- a/backend/internal/image/image_attestations.go+++ b/backend/internal/image/image_attestations.go@@ -2,6 +2,7 @@ package imageimport ("bytes"+ "cmp""compress/gzip""context""encoding/json/v2"@@ -11,7 +12,6 @@ import ("strings""emperror.dev/errors"-"github.com/containerd/platforms"utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"imagetypes "github.com/getarcaneapp/arcane/types/v2/image"@@ -443,10 +443,8 @@ func firstSubjectInternal(subjects []imageAttestationSubjectInternal) imageAttes}func isInlineAttestationDescriptorInternal(descriptor v1.Descriptor) bool {- if descriptor.Annotations[attestationTypes.DockerAnnotationReferenceType] == attestationTypes.DockerAnnotationReferenceTypeDefault {- return true- }- return descriptor.ArtifactType == dockerAttestationManifestArtifactTypeInternal+ return descriptor.Annotations[attestationTypes.DockerAnnotationReferenceType] == attestationTypes.DockerAnnotationReferenceTypeDefault ||+ descriptor.ArtifactType == dockerAttestationManifestArtifactTypeInternal}func readAttestationImageInternal(ctx context.Context, attestationImage v1.Image, artifactDescriptor v1.Descriptor, platform string, query ImageAttestationQuery) ([]imagetypes.Attestation, error) {@@ -500,17 +498,12 @@ func readAttestationLayerInternal(ctx context.Context, attestationImage v1.Imageif err != nil {return imagetypes.Attestation{}, false, errors.WrapIff(err, "parse attestation statement %s", layerDescriptor.Digest.String())}- if statement.PredicateType == "" {- statement.PredicateType = annotationPredicate- }+ statement.PredicateType = cmp.Or(statement.PredicateType, annotationPredicate)if query.PredicateType != "" && statement.PredicateType != query.PredicateType {return imagetypes.Attestation{}, false, nil}- size := layerDescriptor.Size- if size == 0 {- size = int64(len(rawStatement))- }+ size := cmp.Or(layerDescriptor.Size, int64(len(rawStatement)))attestation := imagetypes.Attestation{Digest: layerDescriptor.Digest.String(),diff --git a/backend/internal/image/module.go b/backend/internal/image/module.goindex abc081dca..75a656a46 100644--- a/backend/internal/image/module.go+++ b/backend/internal/image/module.go@@ -3,7 +3,6 @@ package imageimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/build""github.com/getarcaneapp/arcane/backend/v2/internal/docker"diff --git a/backend/internal/image/service_test.go b/backend/internal/image/service_test.goindex 454236c6e..58bbba9dd 100644--- a/backend/internal/image/service_test.go+++ b/backend/internal/image/service_test.go@@ -1,13 +1,6 @@package imageimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""encoding/json""errors"@@ -20,28 +13,30 @@ import ("testing""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-- "github.com/libtnb/sqlite"- dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/kv"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref""github.com/getarcaneapp/arcane/types/v2/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/v2/image"+ "github.com/libtnb/sqlite"+ dockerauthconfig "github.com/moby/moby/api/pkg/authconfig""github.com/moby/moby/api/types/container"dockercontainer "github.com/moby/moby/api/types/container"dockertypesimage "github.com/moby/moby/api/types/image"dockerregistry "github.com/moby/moby/api/types/registry""github.com/moby/moby/client""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require""go.getarcane.app/sys/crypto"+ "gorm.io/gorm")var imageDockerAPIVersionPrefixInternal = regexp.MustCompile(`^/v[0-9]+\.[0-9]+`)@@ -591,7 +586,7 @@ func newTestDockerClientInternal(t *testing.T, server *httptest.Server) *client.}// newImagePullServerWithObserverInternal is NewImagePullServer with a pull callback.-func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[string]dockertypesimage.InspectResponse, onPull func(fullRef string, authHeader string)) *httptest.Server {+func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[string]dockertypesimage.InspectResponse, onPull func(fullRef, authHeader string)) *httptest.Server {t.Helper()server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/backend/internal/imagepatch/handler.go b/backend/internal/imagepatch/handler.goindex 5682a5b7c..887dc7774 100644--- a/backend/internal/imagepatch/handler.go+++ b/backend/internal/imagepatch/handler.go@@ -4,8 +4,6 @@ import ("context""net/http"- "github.com/getarcaneapp/arcane/types/v2/features"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -13,6 +11,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"+ "github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/imagepatch")diff --git a/backend/internal/imagepatch/imagepatch.go b/backend/internal/imagepatch/imagepatch.goindex 98a51c70c..1976a49e7 100644--- a/backend/internal/imagepatch/imagepatch.go+++ b/backend/internal/imagepatch/imagepatch.go@@ -1,6 +1,7 @@package imagepatchimport (+ "cmp""context""encoding/json/jsontext""encoding/json/v2"@@ -11,23 +12,9 @@ import ("strings""time"- "github.com/getarcaneapp/arcane/types/v2/features"-"emperror.dev/errors""github.com/containerd/platforms""github.com/distribution/reference"- "github.com/google/go-containerregistry/pkg/authn"- "github.com/google/go-containerregistry/pkg/name"- "github.com/google/go-containerregistry/pkg/v1/remote"- "github.com/moby/buildkit/util/progress/progressui"- "github.com/moby/moby/client"- ispec "github.com/opencontainers/image-spec/specs-go/v1"- copacommon "github.com/project-copacetic/copacetic/pkg/common"- copapatch "github.com/project-copacetic/copacetic/pkg/patch"- copatypes "github.com/project-copacetic/copacetic/pkg/types"- "github.com/samber/mo"- "go.getarcane.app/acfs"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -41,7 +28,19 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/logging"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+ "github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/imagepatch"+ "github.com/google/go-containerregistry/pkg/authn"+ "github.com/google/go-containerregistry/pkg/name"+ "github.com/google/go-containerregistry/pkg/v1/remote"+ "github.com/moby/buildkit/util/progress/progressui"+ "github.com/moby/moby/client"+ ispec "github.com/opencontainers/image-spec/specs-go/v1"+ copacommon "github.com/project-copacetic/copacetic/pkg/common"+ copapatch "github.com/project-copacetic/copacetic/pkg/patch"+ copatypes "github.com/project-copacetic/copacetic/pkg/types"+ "github.com/samber/mo"+ "go.getarcane.app/acfs")// ImagePatchService patches image OS packages in place using the Copacetic@@ -140,9 +139,7 @@ func (s *ImagePatchService) PatchImage(ctx context.Context, envID, imageID strinif suffix == "" {suffix = strings.TrimSpace(s.settingsService.GetSettingsConfig().ImagePatchSuffix.Value)}- if suffix == "" {- suffix = "patched"- }+ suffix = cmp.Or(suffix, "patched")patchedRef, err := resolvePatchedRef(imageRef, opts.PatchedTag, suffix)if err != nil {return nil, err@@ -488,9 +485,7 @@ func (s *ImagePatchService) ListPatches(ctx context.Context, envID string, param}q = pagination.ApplyFilter(q, "status", params.Filters["status"])- if params.Sort == "" {- params.Sort = "createdAt"- }+ params.Sort = cmp.Or(params.Sort, "createdAt")paginationResp, err := pagination.PaginateAndSortDB(params, q, &records)if err != nil {@@ -560,9 +555,7 @@ func (s *ImagePatchService) ListPatchTargets(ctx context.Context, envID string,}q = pagination.ApplyLikeSearch(q, params.Search, "image_name LIKE ?")- if params.Sort == "" {- params.Sort = "scanTime"- }+ params.Sort = cmp.Or(params.Sort, "scanTime")var scans []vulnerability.VulnerabilityScanRecordpaginationResp, err := pagination.PaginateAndSortDB(params, q, &scans)if err != nil {diff --git a/backend/internal/imagepatch/imagepatch_feature_test.go b/backend/internal/imagepatch/imagepatch_feature_test.goindex eefdfcbfa..3c18bce94 100644--- a/backend/internal/imagepatch/imagepatch_feature_test.go+++ b/backend/internal/imagepatch/imagepatch_feature_test.go@@ -2,7 +2,6 @@ package imagepatchimport ("context"- "github.com/moby/moby/client""net/http""net/http/httptest""sync/atomic"@@ -20,6 +19,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/imagepatch""github.com/libtnb/sqlite"+ "github.com/moby/moby/client""github.com/stretchr/testify/require""go.uber.org/fx/fxtest""gorm.io/gorm"diff --git a/backend/internal/imagepatch/imagepatch_test.go b/backend/internal/imagepatch/imagepatch_test.goindex defeb1307..81a7e0c39 100644--- a/backend/internal/imagepatch/imagepatch_test.go+++ b/backend/internal/imagepatch/imagepatch_test.go@@ -6,15 +6,14 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm")func TestResolvePatchedRef(t *testing.T) {diff --git a/backend/internal/imagepatch/module.go b/backend/internal/imagepatch/module.goindex 39964f6b2..6b1f58d17 100644--- a/backend/internal/imagepatch/module.go+++ b/backend/internal/imagepatch/module.go@@ -3,7 +3,6 @@ package imagepatchimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil")diff --git a/backend/internal/imageupdate/handler.go b/backend/internal/imageupdate/handler.goindex d07cac9fe..4354b1cfb 100644--- a/backend/internal/imageupdate/handler.go+++ b/backend/internal/imageupdate/handler.go@@ -14,6 +14,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/base"imagetypes "github.com/getarcaneapp/arcane/types/v2/image""github.com/getarcaneapp/arcane/types/v2/imageupdate"+ kit "go.getarcane.app/kit/pkg")type ImageUpdateHandler struct {@@ -202,7 +203,7 @@ func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAll}func (h *ImageUpdateHandler) GetUpdateInfoByRefs(ctx context.Context, input *GetUpdateInfoByRefsInput) (*handlerutil.Out[map[string]*imagetypes.UpdateInfo], error) {- imageRefs := utils.UniqueNonEmptyStrings(strings.Split(input.ImageRefs, ","))+ imageRefs := kit.Unique(kit.TrimNonEmpty(strings.Split(input.ImageRefs, ",")))if len(imageRefs) == 0 {return &handlerutil.Out[map[string]*imagetypes.UpdateInfo]{Body: base.ApiResponse[map[string]*imagetypes.UpdateInfo]{diff --git a/backend/internal/imageupdate/image_update.go b/backend/internal/imageupdate/image_update.goindex a57a1043e..358cd8a69 100644--- a/backend/internal/imageupdate/image_update.go+++ b/backend/internal/imageupdate/image_update.go@@ -1,33 +1,27 @@package imageupdateimport (- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"cmp""context""fmt""log/slog""maps"+ "slices""strings""sync""time"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-"emperror.dev/emperror""emperror.dev/errors"-cerrdefs "github.com/containerd/errdefs"ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/notification"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ratelimit"@@ -36,12 +30,15 @@ import (projectspkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/getarcaneapp/arcane/types/v2/imageupdate""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/image""github.com/moby/moby/client""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""go.getarcane.app/updater/digest""go.getarcane.app/updater/refs"@@ -171,10 +168,7 @@ func (s *ImageUpdateService) startImageUpdateActivityInternal(ctx context.Contexif s.activityService == nil {return ""}- resourceType := "image"- if count > 1 {- resourceType = "images"- }+ resourceType := kit.Ternary(count > 1, "images", "image")activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{EnvironmentID: "0",Type: activitytypes.TypeImageUpdateCheck,@@ -198,9 +192,7 @@ func (s *ImageUpdateService) appendImageUpdateActivityMessageInternal(ctx contexif s.activityService == nil || activityID == "" || strings.TrimSpace(message) == "" {return}- if level == "" {- level = activitytypes.MessageLevelInfo- }+ level = cmp.Or(level, activitytypes.MessageLevelInfo)if _, err := s.activityService.AppendMessage(ctx, activityID, activity.AppendActivityMessageRequest{Level: level,Message: message,@@ -226,9 +218,7 @@ func (s *ImageUpdateService) completeImageUpdateActivityInternal(ctx context.Conmessage = "Image update check cancelled"}}- if message == "" {- message = "Image update check completed"- }+ message = cmp.Or(message, "Image update check completed")step := "Image update check complete"if _, err := s.activityService.CompleteActivity(utils.ActivityRuntimeContext(ctx, nil), activityID, status, message, errMessage, step); err != nil {// A lost terminal write strands the activity in running forever, so it@@ -355,10 +345,7 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef stri_ = s.SendBatchUpdateNotifications(ctx)}- finalMessage := "Image update check completed"- if digestResult.HasUpdate {- finalMessage = "Image update available"- }+ finalMessage := kit.Ternary(digestResult.HasUpdate, "Image update available", "Image update check completed")s.completeImageUpdateActivityInternal(ctx, activityID, true, finalMessage)return digestResult, nil}@@ -885,9 +872,7 @@ func (s *ImageUpdateService) inspectLocalImageSnapshotInternal(ctx context.ConteallDigests = append(allDigests, digestValue)// Use first digest as primary if not yet set- if primaryDigest == "" {- primaryDigest = digestValue- }+ primaryDigest = cmp.Or(primaryDigest, digestValue)}}@@ -1062,10 +1047,7 @@ func extractRepoAndTagFromImage(dockerImage image.InspectResponse) (repo, tag st}func buildImageUpdateRecord(imageID, repo, tag string, result *imageupdate.Response) *ImageUpdateRecord {- currentVersion := result.CurrentVersion- if currentVersion == "" {- currentVersion = tag- }+ currentVersion := cmp.Or(result.CurrentVersion, tag)return &ImageUpdateRecord{ID: imageID,@@ -1092,10 +1074,7 @@ func repositoryCandidatesSliceInternal(candidates map[string]struct{}) []stringreturn nil}- repositories := make([]string, 0, len(candidates))- for repository := range candidates {- repositories = append(repositories, repository)- }+ repositories := slices.Collect(maps.Keys(candidates))return repositories}diff --git a/backend/internal/imageupdate/model.go b/backend/internal/imageupdate/model.goindex dbeac59e9..652d42950 100644--- a/backend/internal/imageupdate/model.go+++ b/backend/internal/imageupdate/model.go@@ -1,11 +1,11 @@package imageupdateimport (+ "time"+"github.com/getarcaneapp/arcane/backend/v2/internal/database"imagetypes "github.com/getarcaneapp/arcane/types/v2/image""github.com/samber/mo"-- "time")type ImageUpdateRecord struct {diff --git a/backend/internal/imageupdate/module.go b/backend/internal/imageupdate/module.goindex da66bb6f9..e87d18f1b 100644--- a/backend/internal/imageupdate/module.go+++ b/backend/internal/imageupdate/module.go@@ -5,7 +5,6 @@ import ("context""github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"imagetypes "github.com/getarcaneapp/arcane/types/v2/image")diff --git a/backend/internal/imageupdate/service_test.go b/backend/internal/imageupdate/service_test.goindex b9e11c8d3..f0bfa4d8b 100644--- a/backend/internal/imageupdate/service_test.go+++ b/backend/internal/imageupdate/service_test.go@@ -1,11 +1,6 @@package imageupdateimport (- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"-- "github.com/getarcaneapp/arcane/backend/v2/internal/kv"-"context""encoding/json""errors"@@ -18,19 +13,20 @@ import ("testing""time"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/kv""github.com/getarcaneapp/arcane/backend/v2/internal/notification"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/getarcaneapp/arcane/types/v2/imageupdate""github.com/libtnb/sqlite"@@ -44,6 +40,7 @@ import ("github.com/samber/mo""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""go.getarcane.app/updater/labels""go.uber.org/fx/fxtest"@@ -1496,11 +1493,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {digestChanged := mo.PointerToOption(existingRecord.LatestDigest).OrEmpty() != mo.PointerToOption(updateRecord.LatestDigest).OrEmpty()versionChanged := mo.PointerToOption(existingRecord.LatestVersion).OrEmpty() != mo.PointerToOption(updateRecord.LatestVersion).OrEmpty()- if stateChanged || (updateRecord.HasUpdate && (digestChanged || versionChanged)) {- updateRecord.NotificationSent = false- } else {- updateRecord.NotificationSent = existingRecord.NotificationSent- }+ updateRecord.NotificationSent = !stateChanged && !(updateRecord.HasUpdate && (digestChanged || versionChanged)) && existingRecord.NotificationSent// Save the updated recorderr = db.Save(updateRecord).Error@@ -2522,10 +2515,7 @@ func TestContainerTagChecksPersistIndependentPoliciesInternal(t *testing.T) {case strings.Contains(r.URL.Path, "/images/"):require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{ID: imageID, RepoTags: []string{imageRef}, RepoDigests: []string{registryURL.Host + "/team/app@" + imageID}}))case strings.Contains(r.URL.Path, "/containers/"):- id := "one"- if strings.Contains(r.URL.Path, "/two/") {- id = "two"- }+ id := kit.Ternary(strings.Contains(r.URL.Path, "/two/"), "two", "one")require.NoError(t, json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{ID: id, Image: imageID, Config: &dockertypescontainer.Config{Image: imageRef, Labels: values[id]}}))default:t.Errorf("unexpected Docker request %s", r.URL.Path)@@ -2587,7 +2577,6 @@ func TestContainerTagChecksPersistIndependentPoliciesInternal(t *testing.T) {require.False(t, retained.HasUpdate, "a changed policy cannot inherit the previous candidate")require.Equal(t, imageref.UpdatePolicyKey(imageRef, current.Labels), retained.PolicyKey)require.Equal(t, limited.Error, *retained.LastError)-}// TestContainerTagChecksSeparateMonitoringFromInstallationInternal covers@@ -2626,10 +2615,7 @@ func TestContainerTagChecksSeparateMonitoringFromInstallationInternal(t *testing{ID: "unmonitored", Names: []string{"/unmonitored"}, Image: imageRef, ImageID: imageID, Labels: values["unmonitored"]},}))case strings.Contains(r.URL.Path, "/containers/"):- id := "install-excluded"- if strings.Contains(r.URL.Path, "/unmonitored/") {- id = "unmonitored"- }+ id := kit.Ternary(strings.Contains(r.URL.Path, "/unmonitored/"), "unmonitored", "install-excluded")inspected = append(inspected, id)require.NoError(t, json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{ID: id, Name: "/" + id, Image: imageID, Config: &dockertypescontainer.Config{Image: imageRef, Labels: values[id]}}))default:@@ -2776,10 +2762,7 @@ func TestContainerTagChecksPersistResultsFinishedBeforeScanDeadlineInternal(t *timageRefs := map[string]string{"fast": registryURL.Host + "/team/fast:1.0.0", "slow": registryURL.Host + "/team/slow:1.0.0"}imageIDs := map[string]string{"fast": digest.FromString("fast").String(), "slow": digest.FromString("slow").String()}nameFor := func(path string) string {- if strings.Contains(path, "slow") {- return "slow"- }- return "fast"+ return kit.Ternary(strings.Contains(path, "slow"), "slow", "fast")}dockerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")diff --git a/backend/internal/imageupdate/tag_updates.go b/backend/internal/imageupdate/tag_updates.goindex fe0c99a34..f2e603cf9 100644--- a/backend/internal/imageupdate/tag_updates.go+++ b/backend/internal/imageupdate/tag_updates.go@@ -20,22 +20,22 @@ import ("github.com/moby/moby/api/types/container""github.com/moby/moby/client""go.getarcane.app/updater"-"go.getarcane.app/updater/pkg/utils/tagpolicy""go.getarcane.app/updater/refs""golang.org/x/sync/errgroup""golang.org/x/sync/singleflight"-"gorm.io/gorm")-// tagCheckWorkers bounds concurrent container policy evaluations per scan; the-// registry limiter still caps concurrent requests per registry host.-const tagCheckWorkers = 10+const (+ // tagCheckWorkers bounds concurrent container policy evaluations per scan; the+ // registry limiter still caps concurrent requests per registry host.+ tagCheckWorkers = 10-// staleDigestRecordDeleteChunk bounds the IN list used to clear container-// records whose policy switched to digest tracking.-const staleDigestRecordDeleteChunk = 500+ // staleDigestRecordDeleteChunk bounds the IN list used to clear container+ // records whose policy switched to digest tracking.+ staleDigestRecordDeleteChunk = 500+)// tagRegistryInternal adapts the registry service for one container tag scan.// Successful tag listings are shared per repository and digest lookups per@@ -325,7 +325,7 @@ func (s *ImageUpdateService) saveContainerTagResultInternal(ctx context.Context,// taken before the first container result is attached so it stays untouched.// A container candidate promotes the image result to its version update when// the image itself has none.-func attachContainerUpdatesInternal(results map[string]*imageupdatetypes.Response, containerUpdates map[string]*imageupdatetypes.Response) {+func attachContainerUpdatesInternal(results, containerUpdates map[string]*imageupdatetypes.Response) {containerIDsByRef := make(map[string][]string, len(containerUpdates))for id, update := range containerUpdates {normalized := refs.NormalizeImageUpdateRef(update.ImageRef)diff --git a/backend/internal/job/execution.go b/backend/internal/job/execution.goindex e108aa84d..51f028c6a 100644--- a/backend/internal/job/execution.go+++ b/backend/internal/job/execution.go@@ -1,14 +1,13 @@package jobimport (+ "cmp""context""log/slog""net""strings""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/queue"-"emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"@@ -16,19 +15,19 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/queue""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/meta"st "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")// Submit validates job eligibility and persists acceptance before execution.// Managers may accept requests for offline environments. Reusing a run ID// deduplicates admission within the same job and environment.func (s *JobService) Submit(ctx context.Context, request st.Request) (st.Run, error) {- if request.EnvironmentID == "" {- request.EnvironmentID = "0"- }+ request.EnvironmentID = cmp.Or(request.EnvironmentID, "0")if request.EnvironmentID != "0" {if s.cfg.AgentMode {return st.Run{}, errors.New("agents cannot queue work for another environment")@@ -136,10 +135,7 @@ func (s *JobService) executeRunInternal(ctx context.Context, run st.Run) (st.Outerr := s.scheduler.RunBusWatcherNow(ctx, run.JobID)return classifyOutcomeInternal(run.JobID, st.Outcome{}, err)}- unavailableStatus := st.Canceled- if run.JobID == "auto-update" && run.AttemptCount > 1 {- unavailableStatus = st.NeedsAttention- }+ unavailableStatus := kit.Ternary(run.JobID == "auto-update" && run.AttemptCount > 1, st.NeedsAttention, st.Canceled)job, ok := s.scheduler.GetJob(run.JobID)if !ok {return st.Outcome{Status: unavailableStatus, Message: "Job or target no longer exists"}, nil@@ -157,9 +153,7 @@ func classifyOutcomeInternal(jobID string, outcome st.Outcome, err error) (st.Oureturn resultErr.Outcome, err}if err == nil {- if outcome.Status == "" {- outcome.Status = st.Succeeded- }+ outcome.Status = cmp.Or(outcome.Status, st.Succeeded)return outcome, nil}if outcome.Status == st.Waiting || outcome.Status == st.Retrying {diff --git a/backend/internal/job/module.go b/backend/internal/job/module.goindex e3021e4be..36fd4c8fc 100644--- a/backend/internal/job/module.go+++ b/backend/internal/job/module.go@@ -4,7 +4,6 @@ package jobimport ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment"diff --git a/backend/internal/job/remote.go b/backend/internal/job/remote.goindex 2e55f657b..090a23bf0 100644--- a/backend/internal/job/remote.go+++ b/backend/internal/job/remote.go@@ -2,8 +2,6 @@ package jobimport ("context"- "crypto/sha256"- "encoding/hex""encoding/json/v2""net/http""net/url"@@ -16,11 +14,14 @@ import ("github.com/getarcaneapp/arcane/types/v2/jobschedule""github.com/getarcaneapp/arcane/types/v2/meta"st "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")func remoteFailureInternal(err error) (st.Outcome, error) {var status *remenv.StatusError- if errors.As(err, &status) && status.StatusCode >= 400 && status.StatusCode < 500 && status.StatusCode != http.StatusRequestTimeout && status.StatusCode != http.StatusTooManyRequests {+ rejected := errors.As(err, &status) && status.StatusCode >= 400 && status.StatusCode < 500 &&+ status.StatusCode != http.StatusRequestTimeout && status.StatusCode != http.StatusTooManyRequests+ if rejected {return st.Outcome{Status: st.NeedsAttention, Message: "Remote agent rejected the request; check configuration and permissions"}, err}return st.Outcome{Status: st.Waiting, Message: "Waiting for environment"}, err@@ -124,8 +125,7 @@ func (s *JobService) ListRemoteJobs(ctx context.Context, environmentID string) (if _, err := s.environment.GetEnvironmentByID(ctx, environmentID); err != nil {return nil, err}- digest := sha256.Sum256([]byte(environmentID))- key := "jobs-catalog/" + hex.EncodeToString(digest[:])+ key := "jobs-catalog/" + kit.SHA256Hex(environmentID)var catalog jobschedule.JobListResponseremoteErr := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, "/api/environments/0/jobs", nil, &catalog)if remoteErr == nil {diff --git a/backend/internal/job/run_routes.go b/backend/internal/job/run_routes.goindex 2c58ad8c4..316ed0c44 100644--- a/backend/internal/job/run_routes.go+++ b/backend/internal/job/run_routes.go@@ -5,12 +5,11 @@ import ("net/http""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/queue"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/queue""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/jobschedule"st "github.com/getarcaneapp/arcane/types/v2/scheduler"diff --git a/backend/internal/job/service.go b/backend/internal/job/service.goindex 0cae5a3f4..c3703b5ac 100644--- a/backend/internal/job/service.go+++ b/backend/internal/job/service.go@@ -1,6 +1,7 @@package jobimport (+ "cmp""context""log/slog""sort"@@ -300,9 +301,7 @@ func (s *JobService) ListJobs(ctx context.Context) (*jobschedule.JobListResponseif s.scheduler != nil && jobMeta.SettingsKey != "" && jobMeta.ID != "environment-health" {if runtimeState, ok := s.scheduler.GetJobRuntimeState(jobMeta.ID); ok {- if runtimeState.Schedule != "" {- schedule = runtimeState.Schedule- }+ schedule = cmp.Or(runtimeState.Schedule, schedule)nextRun = runtimeState.NextRun}}diff --git a/backend/internal/job/service_test.go b/backend/internal/job/service_test.goindex 4939b48bf..e62a27139 100644--- a/backend/internal/job/service_test.go+++ b/backend/internal/job/service_test.go@@ -2,10 +2,10 @@ package jobimport ("context"- "emperror.dev/errors""testing""time"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"diff --git a/backend/internal/kv/service.go b/backend/internal/kv/service.goindex 0b49d3c7e..b72747934 100644--- a/backend/internal/kv/service.go+++ b/backend/internal/kv/service.go@@ -7,7 +7,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""gorm.io/gorm""gorm.io/gorm/clause"diff --git a/backend/internal/kv/service_test.go b/backend/internal/kv/service_test.goindex b7158c4bf..50df2b300 100644--- a/backend/internal/kv/service_test.go+++ b/backend/internal/kv/service_test.go@@ -1,12 +1,11 @@package kvimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"context""testing""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/libtnb/sqlite""github.com/stretchr/testify/require""gorm.io/gorm"diff --git a/backend/internal/middleware/activity_batch.go b/backend/internal/middleware/activity_batch.goindex dee67ca2c..03b318446 100644--- a/backend/internal/middleware/activity_batch.go+++ b/backend/internal/middleware/activity_batch.go@@ -4,7 +4,6 @@ import ("strings""github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/pkg/utils")@@ -14,7 +13,7 @@ import (// ignored by utils.WithActivityBatchID.func NewActivityBatchID() func(ctx huma.Context, next func(huma.Context)) {return func(ctx huma.Context, next func(huma.Context)) {- if batchID := strings.TrimSpace(ctx.Header(utils.HeaderActivityBatchID)); batchID != "" {+ if batchID := strings.TrimSpace(ctx.Header(HeaderActivityBatchID)); batchID != "" {ctx = huma.WithContext(ctx, utils.WithActivityBatchID(ctx.Context(), batchID))}next(ctx)diff --git a/backend/internal/middleware/context.go b/backend/internal/middleware/context.goindex 30d3131e2..eb19f433b 100644--- a/backend/internal/middleware/context.go+++ b/backend/internal/middleware/context.go@@ -6,10 +6,25 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/authz")-// ContextKey is a type for context keys used by Huma handlers.-type ContextKey string-const (+ // Auth header names and path prefixes shared between the Echo middleware+ // (WebSocket/diagnostics) and the Huma auth bridge (REST). Keep these in one+ // place so a change to a header name applies to every route type at once.++ HeaderAgentBootstrap = "X-Arcane-Agent-Bootstrap"+ HeaderAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential+ HeaderApiKey = "X-Api-Key" // #nosec G101: header name, not a credential+ HeaderActivityBatchID = "X-Arcane-Batch-Id"+ HeaderUpdateInitiatorID = "X-Arcane-Update-Initiator-Id"+ HeaderUpdateInitiatorName = "X-Arcane-Update-Initiator-Name"+ HeaderUpdateInitiatorDisplayName = "X-Arcane-Update-Initiator-Display-Name"+ // HeaderIconCatalog carries the requesting user's icon catalog preference to+ // remote environments. Agents authenticate proxied calls as a synthetic user+ // with no preferences, so without it every remote environment would resolve+ // container/project icons against the default catalog.+ HeaderIconCatalog = "X-Arcane-Icon-Catalog"+ AgentPairingPrefix = "/api/environments/0/agent/pair"+ContextKeyApiKeyID ContextKey = "apiKeyID"// ContextKeyUserID is the context key for the authenticated user's ID.ContextKeyUserID ContextKey = "userID"@@ -26,6 +41,9 @@ const (ContextKeyAuthMethod ContextKey = "authMethod")+// ContextKey is a type for context keys used by Huma handlers.+type ContextKey string+// GetUserIDFromContext retrieves the user ID from the context.func GetUserIDFromContext(ctx context.Context) (string, bool) {userID, ok := ctx.Value(ContextKeyUserID).(string)diff --git a/backend/internal/middleware/cors_middleware.go b/backend/internal/middleware/cors_middleware.goindex 863057e79..2343eb5f7 100644--- a/backend/internal/middleware/cors_middleware.go+++ b/backend/internal/middleware/cors_middleware.go@@ -8,6 +8,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/labstack/echo/v5"echomiddleware "github.com/labstack/echo/v5/middleware"+ kit "go.getarcane.app/kit/pkg")type CORSMiddleware struct {@@ -44,7 +45,7 @@ func (m *CORSMiddleware) Add() echo.MiddlewareFunc {"Cache-Control","Origin","Referer",- "X-Arcane-Agent-Token",+ HeaderAgentToken,"X-API-Key",},ExposeHeaders: []string{@@ -60,7 +61,7 @@ func (m *CORSMiddleware) Add() echo.MiddlewareFunc {func deriveAllowedOriginsInternal(cfg *config.Config, custom []string) []string {if len(custom) > 0 {- return dedupeInternal(custom)+ return kit.Unique(custom)}var origins []string@@ -85,7 +86,7 @@ func deriveAllowedOriginsInternal(cfg *config.Config, custom []string) []string)}- origins = dedupeInternal(origins)+ origins = kit.Unique(origins)if len(origins) == 0 {if cfg != nil && cfg.Environment == "production" {@@ -97,16 +98,3 @@ func deriveAllowedOriginsInternal(cfg *config.Config, custom []string) []stringreturn origins}--func dedupeInternal(in []string) []string {- seen := make(map[string]struct{}, len(in))- out := make([]string, 0, len(in))- for _, v := range in {- if _, ok := seen[v]; ok {- continue- }- seen[v] = struct{}{}- out = append(out, v)- }- return out-}diff --git a/backend/internal/middleware/csrf_middleware.go b/backend/internal/middleware/csrf_middleware.goindex 28f09edbd..eee8b739a 100644--- a/backend/internal/middleware/csrf_middleware.go+++ b/backend/internal/middleware/csrf_middleware.go@@ -1,14 +1,12 @@package middlewareimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"log/slog""net/http""strings"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/labstack/echo/v5")@@ -87,6 +85,6 @@ func (m *CSRFMiddleware) Add() echo.MiddlewareFunc {// susceptible to CSRF and should bypass the cross-origin check.func hasHeaderCredentialInternal(req *http.Request) bool {return strings.HasPrefix(req.Header.Get("Authorization"), "Bearer ") ||- req.Header.Get(utils.HeaderApiKey) != "" ||- req.Header.Get(utils.HeaderAgentToken) != ""+ req.Header.Get(HeaderApiKey) != "" ||+ req.Header.Get(HeaderAgentToken) != ""}diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex f2b68d6d1..081a8b359 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -1,8 +1,6 @@package middlewareimport (- "github.com/samber/mo"-"bytes""context""encoding/json/v2"@@ -22,12 +20,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"wsutil "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"containertypes "github.com/getarcaneapp/arcane/types/v2/container""github.com/getarcaneapp/arcane/types/v2/gitops"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/labstack/echo/v5"+ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")const (@@ -157,7 +156,7 @@ func (m *EnvironmentMiddleware) Handle(c *echo.Context, next echo.HandlerFunc) eif !enabled {return c.JSON(http.StatusBadRequest, map[string]any{"success": false,- "data": map[string]any{"error": (errors.New("Environment is disabled")).Error()},+ "data": map[string]any{"error": errors.New("Environment is disabled").Error()},})}@@ -204,18 +203,18 @@ func (m *EnvironmentMiddleware) Handle(c *echo.Context, next echo.HandlerFunc) e// SECURITY: the header is always cleared first, so a browser-supplied value// never rides through; only the server-resolved preference is forwarded.func (m *EnvironmentMiddleware) setIconCatalogHeaderInternal(c *echo.Context, user *common.User) {- c.Request().Header.Del(utils.HeaderIconCatalog)+ c.Request().Header.Del(HeaderIconCatalog)if user == nil || user.Preferences.IconCatalog == nil || *user.Preferences.IconCatalog == "" {return}- c.Request().Header.Set(utils.HeaderIconCatalog, *user.Preferences.IconCatalog)+ c.Request().Header.Set(HeaderIconCatalog, *user.Preferences.IconCatalog)}func (m *EnvironmentMiddleware) setUpdateInitiatorHeadersInternal(c *echo.Context, user *common.User) {headers := c.Request().Header- headers.Del(utils.HeaderUpdateInitiatorID)- headers.Del(utils.HeaderUpdateInitiatorName)- headers.Del(utils.HeaderUpdateInitiatorDisplayName)+ headers.Del(HeaderUpdateInitiatorID)+ headers.Del(HeaderUpdateInitiatorName)+ headers.Del(HeaderUpdateInitiatorDisplayName)updatePath := strings.Contains(c.Request().URL.Path, "/containers/") && strings.HasSuffix(c.Request().URL.Path, "/update")if c.Request().Method != http.MethodPost || !updatePath {return@@ -223,10 +222,10 @@ func (m *EnvironmentMiddleware) setUpdateInitiatorHeadersInternal(c *echo.Contexif user == nil || user.ID == "" {return}- headers.Set(utils.HeaderUpdateInitiatorID, user.ID)- headers.Set(utils.HeaderUpdateInitiatorName, user.Username)+ headers.Set(HeaderUpdateInitiatorID, user.ID)+ headers.Set(HeaderUpdateInitiatorName, user.Username)if user.DisplayName != nil {- headers.Set(utils.HeaderUpdateInitiatorDisplayName, *user.DisplayName)+ headers.Set(HeaderUpdateInitiatorDisplayName, *user.DisplayName)}}@@ -273,10 +272,7 @@ func (m *EnvironmentMiddleware) proxyPermissionDenied(c *echo.Context, ps *authzreturn false}- scopeEnvID := ""- if authz.IsEnvScoped(perm) {- scopeEnvID = envID- }+ scopeEnvID := kit.Ternary(authz.IsEnvScoped(perm), envID, "")if !ps.Allows(perm, scopeEnvID) {slog.DebugContext(c.Request().Context(), "Denying proxied request: permission denied","method", method, "path", suffix, "permission", perm, "environment_id", envID)diff --git a/backend/internal/middleware/environment_middleware_authz_test.go b/backend/internal/middleware/environment_middleware_authz_test.goindex 7b5b8e737..ae50c7516 100644--- a/backend/internal/middleware/environment_middleware_authz_test.go+++ b/backend/internal/middleware/environment_middleware_authz_test.go@@ -9,10 +9,9 @@ import ("net/http/httptest""testing"- "github.com/labstack/echo/v5"-"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ "github.com/labstack/echo/v5""github.com/stretchr/testify/require")@@ -45,7 +44,6 @@ func TestProxyPermissionDeniedBlocksWriteForReadOnlyUser(t *testing.T) {require.True(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),"expected restart to be denied for a read-only user")-}func TestProxyPermissionDeniedAllowsWriteForPermittedUser(t *testing.T) {@@ -57,7 +55,6 @@ func TestProxyPermissionDeniedAllowsWriteForPermittedUser(t *testing.T) {require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),"expected restart to be allowed for a user with containers:restart")-}func TestProxyPermissionDeniedAllowsRead(t *testing.T) {@@ -69,7 +66,6 @@ func TestProxyPermissionDeniedAllowsRead(t *testing.T) {require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),"expected list to be allowed for a user with containers:list")-}func TestProxyPermissionDeniedDeniesPermissionFromDifferentEnv(t *testing.T) {@@ -82,7 +78,6 @@ func TestProxyPermissionDeniedDeniesPermissionFromDifferentEnv(t *testing.T) {require.True(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),"expected denial: permission is scoped to a different environment")-}func TestProxyPermissionDeniedSudoBypasses(t *testing.T) {@@ -91,7 +86,6 @@ func TestProxyPermissionDeniedSudoBypasses(t *testing.T) {require.False(t, m.proxyPermissionDenied(c, authz.SudoPermissionSet(), proxyTestEnvID),"expected sudo permission set to bypass the permission check")-}func TestProxyPermissionDeniedDefaultDeniesUnmappedRoute(t *testing.T) {@@ -103,7 +97,6 @@ func TestProxyPermissionDeniedDefaultDeniesUnmappedRoute(t *testing.T) {require.True(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),"expected an unmapped proxied route to be denied by default")-}func TestProxyPermissionDeniedAllowsPublicRoute(t *testing.T) {@@ -114,7 +107,6 @@ func TestProxyPermissionDeniedAllowsPublicRoute(t *testing.T) {require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),"expected an explicitly public route to be allowed for any authenticated caller")-}func volumeWorkspaceMatcher() *authz.PermissionMatcher {@@ -237,7 +229,6 @@ func TestProxyPermissionDeniedWSTerminalRequiresExec(t *testing.T) {require.False(t, m.proxyPermissionDenied(c, ps, proxyTestEnvID),"expected WS terminal to be allowed with containers:exec")-}func TestProxyPermissionDeniedResourceSortRequiresRead(t *testing.T) {diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.goindex fec7486cb..3f5b8ba9a 100644--- a/backend/internal/middleware/environment_middleware_test.go+++ b/backend/internal/middleware/environment_middleware_test.go@@ -1,16 +1,14 @@package middlewareimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""net/http""net/http/httptest""testing"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""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""github.com/labstack/echo/v5""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -351,9 +349,9 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing.var forwardedInitiator stringvar forwardedName stringbackend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- forwarded = r.Header.Get(utils.HeaderIconCatalog)- forwardedInitiator = r.Header.Get(utils.HeaderUpdateInitiatorID)- forwardedName = r.Header.Get(utils.HeaderUpdateInitiatorName)+ forwarded = r.Header.Get(HeaderIconCatalog)+ forwardedInitiator = r.Header.Get(HeaderUpdateInitiatorID)+ forwardedName = r.Header.Get(HeaderUpdateInitiatorName)w.WriteHeader(http.StatusOK)}))defer backend.Close()@@ -384,10 +382,10 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing.})req := httptest.NewRequest(http.MethodPost, "/api/environments/env-remote/containers/container-1/update", nil)- req.Header.Set(utils.HeaderUpdateInitiatorID, "spoofed")- req.Header.Set(utils.HeaderUpdateInitiatorName, "spoofed")+ req.Header.Set(HeaderUpdateInitiatorID, "spoofed")+ req.Header.Set(HeaderUpdateInitiatorName, "spoofed")if tt.clientSupplied != "" {- req.Header.Set(utils.HeaderIconCatalog, tt.clientSupplied)+ req.Header.Set(HeaderIconCatalog, tt.clientSupplied)}recorder := httptest.NewRecorder()router.ServeHTTP(recorder, req)diff --git a/backend/internal/middleware/rate_limit_middleware.go b/backend/internal/middleware/rate_limit_middleware.goindex 3d83e4ac2..92e4ed4ae 100644--- a/backend/internal/middleware/rate_limit_middleware.go+++ b/backend/internal/middleware/rate_limit_middleware.go@@ -1,8 +1,7 @@package middlewareimport (- "crypto/sha256"- "encoding/hex"+ "cmp""net""net/http""sort"@@ -11,6 +10,7 @@ import ("time""github.com/labstack/echo/v5"+ kit "go.getarcane.app/kit/pkg""golang.org/x/time/rate")@@ -109,7 +109,7 @@ func (l *ipRateLimiter) evictOldestEntriesInternal(count int, protectedKey strin// PerIPRateLimit returns an Echo middleware that limits requests per client IP// to the given rate and burst. It responds with 429 when the limit is exceeded.-func PerIPRateLimit(perMinute int, burst int) echo.MiddlewareFunc {+func PerIPRateLimit(perMinute, burst int) echo.MiddlewareFunc {if perMinute <= 0 {perMinute = 10}@@ -132,7 +132,7 @@ func PerIPRateLimit(perMinute int, burst int) echo.MiddlewareFunc {// PerAgentTokenRateLimit returns an Echo middleware that limits requests per// edge agent token to the given rate and burst.-func PerAgentTokenRateLimit(perMinute int, burst int) echo.MiddlewareFunc {+func PerAgentTokenRateLimit(perMinute, burst int) echo.MiddlewareFunc {if perMinute <= 0 {perMinute = 10}@@ -144,14 +144,11 @@ func PerAgentTokenRateLimit(perMinute int, burst int) echo.MiddlewareFunc {return func(next echo.HandlerFunc) echo.HandlerFunc {return func(c *echo.Context) error {req := c.Request()- key := strings.TrimSpace(req.Header.Get("X-Arcane-Agent-Token"))- if key == "" {- key = strings.TrimSpace(req.Header.Get("X-Api-Key"))- }+ key := cmp.Or(strings.TrimSpace(req.Header.Get(HeaderAgentToken)), strings.TrimSpace(req.Header.Get(HeaderApiKey)))if key == "" {return next(c)}- if !limiter.allow(agentTokenRateLimitKeyInternal(key)) {+ if !limiter.allow(kit.SHA256Hex(key)) {c.Response().Header().Set("Retry-After", "60")return c.JSON(http.StatusTooManyRequests, map[string]any{"error": "rate limit exceeded"})}@@ -160,11 +157,6 @@ func PerAgentTokenRateLimit(perMinute int, burst int) echo.MiddlewareFunc {}}-func agentTokenRateLimitKeyInternal(token string) string {- sum := sha256.Sum256([]byte(token))- return hex.EncodeToString(sum[:])-}-// PerTokenRateLimitForPaths gives known tokens independent budgets and limits others per IP.// isKnown must be an in-memory lookup with bounded input, without request-driven cache fills.// A nil lookup falls back to the shared IP limiter.@@ -196,7 +188,7 @@ func PerTokenRateLimitForPaths(token := c.Param("token")if token != "" && isKnown != nil && isKnown(token) {- if !tokenLimiter.allow(agentTokenRateLimitKeyInternal(token)) {+ if !tokenLimiter.allow(kit.SHA256Hex(token)) {c.Response().Header().Set("Retry-After", "60")return c.JSON(http.StatusTooManyRequests, map[string]any{"error": "rate limit exceeded"})}@@ -217,7 +209,7 @@ func PerTokenRateLimitForPaths(// Each path gets its own independent token bucket, so traffic on one path// does not deplete the budget for another (e.g. a login burst will not// block a concurrent token refresh).-func PerIPRateLimitForPaths(paths []string, perMinute int, burst int) echo.MiddlewareFunc {+func PerIPRateLimitForPaths(paths []string, perMinute, burst int) echo.MiddlewareFunc {limiters := make(map[string]echo.MiddlewareFunc, len(paths))for _, p := range paths {limiters[p] = PerIPRateLimit(perMinute, burst)diff --git a/backend/internal/middleware/role.go b/backend/internal/middleware/role.goindex 9d580a116..d1fc7d325 100644--- a/backend/internal/middleware/role.go+++ b/backend/internal/middleware/role.go@@ -1,16 +1,14 @@package middlewareimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""log/slog""net/http""github.com/danielgtaylor/huma/v2"- "github.com/labstack/echo/v5"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"+ "github.com/labstack/echo/v5")// RegisterWithPermission registers a Huma operation that requires perm. Itdiff --git a/backend/internal/middleware/role_test.go b/backend/internal/middleware/role_test.goindex 9be799dc4..ae85aea33 100644--- a/backend/internal/middleware/role_test.go+++ b/backend/internal/middleware/role_test.go@@ -8,10 +8,9 @@ import ("github.com/danielgtaylor/huma/v2""github.com/danielgtaylor/huma/v2/adapters/humaecho"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/labstack/echo/v5""github.com/stretchr/testify/require"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/authz")func TestRequirePermission_RejectsCallerMissingPermission(t *testing.T) {@@ -33,7 +32,8 @@ func TestRequirePermission_RejectsCallerMissingPermission(t *testing.T) {}, func(_ context.Context, _ *struct {ID string `path:"id"`CID string `path:"cid"`- }) (*struct{}, error) {+ },+ ) (*struct{}, error) {require.FailNow(t, "handler must not run when permission is missing")return nil, nil})@@ -70,7 +70,8 @@ func TestRequirePermission_AllowsCallerWithPermissionOnEnv(t *testing.T) {}, func(_ context.Context, _ *struct {ID string `path:"id"`CID string `path:"cid"`- }) (*out, error) {+ },+ ) (*out, error) {handlerRan = truereturn &out{Body: struct {Success bool `json:"success"`@@ -104,7 +105,8 @@ func TestRequirePermission_EnvScopedDoesNotLeakAcrossEnvs(t *testing.T) {}, func(_ context.Context, _ *struct {ID string `path:"id"`CID string `path:"cid"`- }) (*struct{}, error) {+ },+ ) (*struct{}, error) {require.FailNow(t, "handler must not run when permission is scoped to a different env")return nil, nil})@@ -133,7 +135,8 @@ func TestRequirePermissionEnvironmentGrantCannotManageGlobalNotificationsInternaMiddlewares: RequirePermission(api, authz.PermNotificationsManage),}, func(_ context.Context, _ *struct {ID string `path:"id"`- }) (*struct{}, error) {+ },+ ) (*struct{}, error) {require.FailNow(t, "handler must not run for an environment-scoped grant on global notification settings")return nil, nil})@@ -161,7 +164,8 @@ func TestRequirePermission_SudoCallerAllowed(t *testing.T) {Middlewares: RequirePermission(api, authz.PermUsersDelete),}, func(_ context.Context, _ *struct {UserID string `path:"userId"`- }) (*struct{}, error) {+ },+ ) (*struct{}, error) {handlerRan = truereturn &struct{}{}, nil})@@ -205,7 +209,8 @@ func TestRequireSudoRejectsHumanAdminAndAllowsAgent(t *testing.T) {Middlewares: RequireSudo(api),}, func(_ context.Context, _ *struct {ID string `path:"id"`- }) (*struct{}, error) {+ },+ ) (*struct{}, error) {handlerRan = truereturn &struct{}{}, nil})diff --git a/backend/internal/network/handler.go b/backend/internal/network/handler.goindex 6a17bc7b0..f4391df03 100644--- a/backend/internal/network/handler.go+++ b/backend/internal/network/handler.go@@ -1,32 +1,31 @@package networkimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-+ "cmp""context""net/http""sort""strings"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/netutils"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/base"networktypes "github.com/getarcaneapp/arcane/types/v2/network"dockernetwork "github.com/moby/moby/api/types/network""github.com/moby/moby/client""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping")type NetworkHandler struct {@@ -227,7 +226,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkreturn nil, err}- dockerOptions, err := mapper.MapOne[networktypes.CreateOptions, client.NetworkCreateOptions](input.Body.Options)+ dockerOptions, err := mapping.MapOne[networktypes.CreateOptions, client.NetworkCreateOptions](input.Body.Options)if err != nil {return nil, huma.Error400BadRequest(errors.WithMessage(err, "Invalid network options").Error())}@@ -260,7 +259,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkreturn nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to create network").Error())}- out, err := mapper.MapOne[dockernetwork.CreateResponse, networktypes.CreateResponse](*response)+ out, err := mapping.MapOne[dockernetwork.CreateResponse, networktypes.CreateResponse](*response)if err != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())}@@ -280,7 +279,7 @@ func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput)return nil, huma.Error404NotFound(errors.WithMessage(err, "Network not found").Error())}- out, err := mapper.MapOne[dockernetwork.Inspect, networktypes.Inspect](*networkInspect)+ out, err := mapping.MapOne[dockernetwork.Inspect, networktypes.Inspect](*networkInspect)if err != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())}@@ -316,20 +315,11 @@ func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput)a, b := out.ContainersList[i], out.ContainersList[j]if input.Sort == "ip" {- valA := a.IPv4Address- if valA == "" {- valA = a.IPv6Address- }- valB := b.IPv4Address- if valB == "" {- valB = b.IPv6Address- }-- cmp := netutils.CompareAddresses(valA, valB)- if input.Order == "desc" {- return cmp > 0- }- return cmp < 0+ valA := cmp.Or(a.IPv4Address, a.IPv6Address)+ valB := cmp.Or(b.IPv4Address, b.IPv6Address)++ cmp := kit.CompareAddresses(valA, valB)+ return kit.Ternary(input.Order == "desc", cmp > 0, cmp < 0)}// Default to Name@@ -492,7 +482,7 @@ func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksreturn nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to prune networks").Error())}- out, err := mapper.MapOne[dockernetwork.PruneReport, networktypes.PruneReport](*report)+ out, err := mapping.MapOne[dockernetwork.PruneReport, networktypes.PruneReport](*report)if err != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to map network").Error())}diff --git a/backend/internal/network/service.go b/backend/internal/network/service.goindex 21350f278..47ca81b02 100644--- a/backend/internal/network/service.go+++ b/backend/internal/network/service.go@@ -1,8 +1,7 @@package networkimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-+ "cmp""context""fmt""log/slog"@@ -12,19 +11,20 @@ import ("strings""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"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"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/netutils"networktypes "github.com/getarcaneapp/arcane/types/v2/network""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/network""github.com/moby/moby/client"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""golang.org/x/sync/errgroup")@@ -48,7 +48,7 @@ func (s *NetworkService) GetNetworkByID(ctx context.Context, id string) (*networreturn nil, errors.WrapIf(err, "failed to connect to Docker")}- networkInspect, err := libarcane.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})+ networkInspect, err := compat.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})if err != nil {return nil, errors.WrapIf(err, "network not found")}@@ -69,7 +69,7 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.containerInfoByID := buildTopologyContainerInfoInternal(containers)- networkList, err := libarcane.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})+ networkList, err := compat.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})if err != nil {return nil, errors.WrapIf(err, "failed to list Docker networks")}@@ -92,7 +92,7 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.g.Go(func() (workerErr error) {defer utils.RecoverToError(&workerErr, "network worker")- inspected, err := libarcane.NetworkInspectWithCompatibility(groupCtx, dockerClient, rawNetwork.ID, client.NetworkInspectOptions{})+ inspected, err := compat.NetworkInspectWithCompatibility(groupCtx, dockerClient, rawNetwork.ID, client.NetworkInspectOptions{})if err != nil {return errors.WrapIff(err, "failed to inspect network %s", rawNetwork.Name)}@@ -130,9 +130,7 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.if !ok {info = topologyContainerInfo{Name: endpoint.Name}}- if info.Name == "" {- info.Name = endpoint.Name- }+ info.Name = cmp.Or(info.Name, endpoint.Name)if _, exists := containerNodeIDs[containerID]; !exists {topology.Nodes = append(topology.Nodes, networktypes.TopologyNode{@@ -172,10 +170,7 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.})sort.Slice(topology.Edges, func(i, j int) bool {left, right := topology.Edges[i], topology.Edges[j]- if left.Source != right.Source {- return left.Source < right.Source- }- return left.Target < right.Target+ return kit.Ternary(left.Source != right.Source, left.Source < right.Source, left.Target < right.Target)})return topology, nil@@ -224,13 +219,8 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user commreturn errors.WrapIf(err, "failed to connect to Docker")}- networkInfo, err := libarcane.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})- var networkName string- if err == nil {- networkName = networkInfo.Network.Name- } else {- networkName = id- }+ networkInfo, err := compat.NetworkInspectWithCompatibility(ctx, dockerClient, id, client.NetworkInspectOptions{})+ networkName := kit.Ternary(err == nil, networkInfo.Network.Name, id)defer s.eventService.BeginDockerResourceSuppressionWindow("network", id, networkName)()if _, err := dockerClient.NetworkRemove(ctx, id, client.NetworkRemoveOptions{}); err != nil {@@ -366,7 +356,7 @@ func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagininUseByID, inUseByName := dockerutil.BuildNetworkUsageMaps(containers)- networkList, err := libarcane.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})+ networkList, err := compat.NetworkListWithCompatibility(ctx, dockerClient, client.NetworkListOptions{})if err != nil {return nil, pagination.Response{}, networktypes.UsageCounts{}, errors.WrapIf(err, "failed to list Docker networks")}@@ -409,7 +399,7 @@ func buildTopologyContainerInfoInternal(containers []container.Summary) map[strifunc (s *NetworkService) convertToNetworkSummaries(rawNets []network.Summary, inUseByID, inUseByName map[string]bool) ([]networktypes.Summary, error) {items := make([]networktypes.Summary, 0, len(rawNets))for _, n := range rawNets {- netDto, err := mapper.MapOne[network.Summary, networktypes.Summary](n)+ netDto, err := mapping.MapOne[network.Summary, networktypes.Summary](n)if err != nil {return nil, errors.WrapIf(err, "failed to map network")}@@ -471,7 +461,7 @@ func (s *NetworkService) buildNetworkSortBindings() []pagination.SortBinding[netFn: func(a, b networktypes.Summary) int {subnetsA, _ := ipamValuesInternal(a)subnetsB, _ := ipamValuesInternal(b)- return compareIPAMListsInternal(subnetsA, subnetsB, netutils.CompareSubnets)+ return compareIPAMListsInternal(subnetsA, subnetsB, kit.CompareSubnets)},},{@@ -479,7 +469,7 @@ func (s *NetworkService) buildNetworkSortBindings() []pagination.SortBinding[netFn: func(a, b networktypes.Summary) int {_, gatewaysA := ipamValuesInternal(a)_, gatewaysB := ipamValuesInternal(b)- return compareIPAMListsInternal(gatewaysA, gatewaysB, netutils.CompareAddresses)+ return compareIPAMListsInternal(gatewaysA, gatewaysB, kit.CompareAddresses)},},}@@ -509,10 +499,7 @@ func (s *NetworkService) compareNetworkCreated(a, b networktypes.Summary) int {if a.Created.Before(b.Created) {return -1}- if a.Created.After(b.Created) {- return 1- }- return 0+ return kit.Ternary(a.Created.After(b.Created), 1, 0)}func (s *NetworkService) compareNetworkInUse(a, b networktypes.Summary) int {@@ -523,10 +510,7 @@ func (s *NetworkService) compareNetworkInUse(a, b networktypes.Summary) int {// Use name as secondary sort key for consistent orderingreturn strings.Compare(a.Name, b.Name)}- if aInUse {- return -1- }- return 1+ return kit.Ternary(aInUse, -1, 1)}func (s *NetworkService) buildNetworkFilterAccessors() []pagination.FilterAccessor[networktypes.Summary] {@@ -534,13 +518,7 @@ func (s *NetworkService) buildNetworkFilterAccessors() []pagination.FilterAccess{Key: "inUse",Fn: func(n networktypes.Summary, filterValue string) bool {- if filterValue == "true" {- return n.InUse || n.IsDefault- }- if filterValue == "false" {- return !n.InUse && !n.IsDefault- }- return true+ return kit.Ternary(filterValue == "true", n.InUse || n.IsDefault, filterValue != "false" || (!n.InUse && !n.IsDefault))},},}diff --git a/backend/internal/notification/email_templates.go b/backend/internal/notification/email_templates.goindex 21e48d6dc..bcc388478 100644--- a/backend/internal/notification/email_templates.go+++ b/backend/internal/notification/email_templates.go@@ -4,6 +4,8 @@ import ("bytes""fmt""html/template"+ "maps"+ "slices""sort""time"@@ -95,10 +97,7 @@ func (s *NotificationService) renderTestEmailTemplateInternal(environmentName stfunc (s *NotificationService) renderBatchEmailTemplateInternal(environmentName string, updates map[string]*imageupdate.Response) (string, string, error) {// Build list of image names- imageList := make([]string, 0, len(updates))- for imageRef := range updates {- imageList = append(imageList, imageRef)- }+ imageList := slices.Collect(maps.Keys(updates))appURL := s.config.GetAppURL()logoURL := appURL + logoURLPathdiff --git a/backend/internal/notification/handler.go b/backend/internal/notification/handler.goindex fc518c8c6..25ad8b76b 100644--- a/backend/internal/notification/handler.go+++ b/backend/internal/notification/handler.go@@ -1,25 +1,22 @@package notificationimport (- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""net/http""strings""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/notification"+ kit "go.getarcane.app/kit/pkg")type NotificationHandler struct {@@ -71,10 +68,7 @@ type DispatchNotificationInput struct {func normalizeNotificationTestType(testType string) string {normalized := strings.TrimSpace(testType)- if normalized == "" {- return notificationTestTypeSimple- }- return normalized+ return kit.Ternary(normalized == "", notificationTestTypeSimple, normalized)}func isSupportedNotificationTestType(testType string) bool {diff --git a/backend/internal/notification/module.go b/backend/internal/notification/module.goindex c053c2d08..4dc1baddc 100644--- a/backend/internal/notification/module.go+++ b/backend/internal/notification/module.go@@ -3,7 +3,6 @@ package notificationimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/config")diff --git a/backend/internal/notification/notification.go b/backend/internal/notification/notification.goindex b8c88250c..908bdf130 100644--- a/backend/internal/notification/notification.go+++ b/backend/internal/notification/notification.go@@ -2,6 +2,7 @@ package notificationimport ("bytes"+ "cmp""context""encoding/json/v2""fmt"@@ -15,13 +16,13 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/apns""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"@@ -30,6 +31,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/imageupdate"notificationdto "github.com/getarcaneapp/arcane/types/v2/notification""github.com/getarcaneapp/arcane/types/v2/system"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""golang.org/x/sync/errgroup")@@ -57,8 +59,21 @@ var notificationTargetFieldByProviderInternal = map[notifications.NotificationPrnotifications.NotificationProviderMatrix: "host",}-const ErrUnauthorizedNotificationDispatch = errors.Sentinel("unauthorized notification dispatch")-const ErrUnsupportedDispatchKind = errors.Sentinel("unsupported notification dispatch kind")+const (+ ErrUnauthorizedNotificationDispatch = errors.Sentinel("unauthorized notification dispatch")+ ErrUnsupportedDispatchKind = errors.Sentinel("unsupported notification dispatch kind")++ notificationDispatchConcurrencyInternal = 4++ notificationTestTypeSimple = "simple"+ notificationTestTypeImageUpdate = "image-update"+ notificationTestTypeBatchImageUpdate = "batch-image-update"+ notificationTestTypeVulnerability = "vulnerability-found"+ notificationTestTypePruneReport = "prune-report"+ notificationTestTypeAutoHeal = "auto-heal"++ logoURLPath = "/api/app-images/logo-email"+)type NotificationService struct {db *database.DB@@ -99,10 +114,7 @@ func NewNotificationService(db *database.DB, cfg *config.Config, environmentSvc}func (s *NotificationService) resolveNotificationTargetInternal(ctx context.Context, environmentID string) (NotificationTarget, error) {- trimmedEnvironmentID := strings.TrimSpace(environmentID)- if trimmedEnvironmentID == "" {- trimmedEnvironmentID = "0"- }+ trimmedEnvironmentID := cmp.Or(strings.TrimSpace(environmentID), "0")if s.environmentSvc != nil {env, err := s.environmentSvc.GetEnvironmentByID(ctx, trimmedEnvironmentID)@@ -184,7 +196,7 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.return notificationdto.DispatchResponse{}, errors.WrapIf(err, "failed to create notification dispatch request")}req.Header.Set("Content-Type", "application/json")- req.Header.Set("X-Api-Key", s.config.AgentToken)+ req.Header.Set(middleware.HeaderApiKey, s.config.AgentToken)resp, err := s.httpClient.Do(req)if err != nil {@@ -350,10 +362,7 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, providvar setting NotificationSettingserr := s.db.WithContext(ctx).Where("provider = ?", provider).First(&setting).Error- existingConfig := database.JSON(nil)- if err == nil {- existingConfig = setting.Config- }+ existingConfig := kit.Ternary(err == nil, setting.Config, database.JSON(nil))encryptedConfig, encryptErr := encryptNotificationConfigCredentialsInternal(provider, config, existingConfig)if encryptErr != nil {@@ -403,7 +412,7 @@ func RedactNotificationConfigCredentials(provider notifications.NotificationProvreturn redacted}-func encryptNotificationConfigCredentialsInternal(provider notifications.NotificationProvider, config database.JSON, existingConfig database.JSON) (database.JSON, error) {+func encryptNotificationConfigCredentialsInternal(provider notifications.NotificationProvider, config, existingConfig database.JSON) (database.JSON, error) {encryptedConfig := cloneNotificationConfigInternal(config)preserveConfig := existingConfigif provider == notifications.NotificationProviderSignal {@@ -460,7 +469,7 @@ func encryptNotificationConfigCredentialsInternal(provider notifications.Notificreturn encryptedConfig, nil}-func signalCredentialPreservationConfigInternal(config database.JSON, existingConfig database.JSON) database.JSON {+func signalCredentialPreservationConfigInternal(config, existingConfig database.JSON) database.JSON {preserveConfig := cloneNotificationConfigInternal(existingConfig)user, _ := config["user"].(string)password, _ := config["password"].(string)@@ -476,7 +485,7 @@ func signalCredentialPreservationConfigInternal(config database.JSON, existingCoreturn preserveConfig}-func emailCredentialPreservationConfigInternal(config database.JSON, existingConfig database.JSON) database.JSON {+func emailCredentialPreservationConfigInternal(config, existingConfig database.JSON) database.JSON {preserveConfig := cloneNotificationConfigInternal(existingConfig)if authMode, _ := config["authMode"].(string); authMode == string(notifications.EmailAuthModeNone) {delete(preserveConfig, "smtpPassword")@@ -647,8 +656,6 @@ func (s *NotificationService) notifyEnabledProvidersInternal(return delivered, nil}-const notificationDispatchConcurrencyInternal = 4-func collectNotificationSendResultInternal(errors *[]string, provider notifications.NotificationProvider, sendErr error) (string, *string) {if sendErr == nil {return "success", nil@@ -659,15 +666,6 @@ func collectNotificationSendResultInternal(errors *[]string, provider notificatireturn "failed", &msg}-const (- notificationTestTypeSimple = "simple"- notificationTestTypeImageUpdate = "image-update"- notificationTestTypeBatchImageUpdate = "batch-image-update"- notificationTestTypeVulnerability = "vulnerability-found"- notificationTestTypePruneReport = "prune-report"- notificationTestTypeAutoHeal = "auto-heal"-)-var supportedNotificationTestTypes = map[string]struct{}{notificationTestTypeSimple: {},notificationTestTypeImageUpdate: {},@@ -770,10 +768,7 @@ func (s *NotificationService) batchImageUpdateNotificationContentInternal(enviroreturn "", "", errors.WrapIf(err, "failed to render email template")}updateCount := len(updates)- plural := ""- if updateCount > 1 {- plural = "s"- }+ plural := kit.Ternary(updateCount > 1, "s", "")subject := notifications.BuildEmailSubject(environmentName, fmt.Sprintf("%d Image Update%s Available", updateCount, plural))return subject, htmlBody, nil},@@ -844,10 +839,7 @@ func (s *NotificationService) batchContainerUpdateNotificationContentInternal(enreturn "", "", errors.WrapIf(err, "failed to render email template")}updateCount := len(entries)- plural := ""- if updateCount > 1 {- plural = "s"- }+ plural := kit.Ternary(updateCount > 1, "s", "")subject := notifications.BuildEmailSubject(environmentName, fmt.Sprintf("%d Container%s Updated", updateCount, plural))return subject, htmlBody, nil},@@ -1077,10 +1069,7 @@ func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(return 0, nil}- imageRefs := make([]string, 0, len(updatesWithChanges))- for ref := range updatesWithChanges {- imageRefs = append(imageRefs, ref)- }+ imageRefs := slices.Collect(maps.Keys(updatesWithChanges))metadata := database.JSON{"updateCount": len(updatesWithChanges),@@ -1289,10 +1278,7 @@ func (s *NotificationService) testNotificationContentInternal(environmentName, t},})default: // simple and image-update- imageRef := "nginx:latest"- if testType == notificationTestTypeSimple {- imageRef = "test/image:latest"- }+ imageRef := kit.Ternary(testType == notificationTestTypeSimple, "test/image:latest", "nginx:latest")return s.imageUpdateNotificationContentInternal(environmentName, imageRef, &imageupdate.Response{HasUpdate: true,UpdateType: "digest",@@ -1312,10 +1298,7 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentIif err != nil {return "", errors.Errorf("please save your %s settings before testing", provider)}- testType = strings.TrimSpace(testType)- if testType == "" {- testType = notificationTestTypeSimple- }+ testType = cmp.Or(strings.TrimSpace(testType), notificationTestTypeSimple)if _, ok := supportedNotificationTestTypes[testType]; !ok {return "", errors.Errorf("unsupported notification test type: %s", testType)}@@ -1334,10 +1317,7 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentI// Stamp the event vars so the Test button exercises a configured generic// payload template. The simple test renders image-update content, so it// reports that event type.- testEventType := notificationEventTypeForTestTypeInternal(testType)- if testEventType == "" {- testEventType = notifications.NotificationEventImageUpdate- }+ testEventType := cmp.Or(notificationEventTypeForTestTypeInternal(testType), notifications.NotificationEventImageUpdate)content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, testEventType)handled, sendErr := notifications.Deliver(ctx, provider, setting.Config, content)if !handled {@@ -1346,8 +1326,6 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentIreturn warning, sendErr}-const logoURLPath = "/api/app-images/logo-email"-func (s *NotificationService) sendTestEmailInternal(ctx context.Context, environmentName string, config database.JSON) error {_, err := notifications.Deliver(ctx, notifications.NotificationProviderEmail, config, notifications.Content{RenderEmail: func() (string, string, error) {diff --git a/backend/internal/notification/service_test.go b/backend/internal/notification/service_test.goindex 4eb8cba0a..0faf5d8c3 100644--- a/backend/internal/notification/service_test.go+++ b/backend/internal/notification/service_test.go@@ -15,10 +15,6 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -29,8 +25,11 @@ import ("github.com/getarcaneapp/arcane/types/v2/imageupdate"notificationdto "github.com/getarcaneapp/arcane/types/v2/notification""github.com/getarcaneapp/arcane/types/v2/system"+ "github.com/libtnb/sqlite""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require""go.getarcane.app/sys/crypto"+ "gorm.io/gorm")func setupNotificationTestDB(t *testing.T) *database.DB {@@ -172,7 +171,7 @@ func TestNotificationService_DispatchNotification_UnsupportedKindReturnsSentinelrequire.Error(t, err)require.ErrorIs(t, err, ErrUnsupportedDispatchKind)- var unsupportedErr = ErrUnsupportedDispatchKind+ unsupportedErr := ErrUnsupportedDispatchKindrequire.ErrorIs(t, err, unsupportedErr)require.Contains(t, err.Error(), "bogus_kind")}diff --git a/backend/internal/oidc/handler.go b/backend/internal/oidc/handler.goindex 23bb83c98..af9825639 100644--- a/backend/internal/oidc/handler.go+++ b/backend/internal/oidc/handler.go@@ -1,25 +1,22 @@package oidcimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/session"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""log/slog""net/http""strings""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/auth"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/passkey""github.com/getarcaneapp/arcane/backend/v2/internal/role"+ "github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/internal/oidc/service.go b/backend/internal/oidc/service.goindex 37d93ea4e..953b6877e 100644--- a/backend/internal/oidc/service.go+++ b/backend/internal/oidc/service.go@@ -1,6 +1,7 @@package oidcimport (+ "cmp""context""crypto/tls""encoding/base64"@@ -14,20 +15,17 @@ import ("sync""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/auth"-"emperror.dev/errors"-"github.com/coreos/go-oidc/v3/oidc"- "github.com/samber/hot"- "golang.org/x/oauth2"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/auth""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/settings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/jwtclaims""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/oidcjwk"authtypes "github.com/getarcaneapp/arcane/types/v2/auth"+ "github.com/samber/hot"+ kit "go.getarcane.app/kit/pkg"+ "golang.org/x/oauth2")type OidcService struct {@@ -205,15 +203,7 @@ func (s *OidcService) GetMobileRedirectAllowlist(ctx context.Context) []string {if s.settingsService != nil {raw = s.settingsService.GetStringSetting(ctx, "oidcMobileRedirectUris", raw)}- parts := strings.Split(raw, ",")- allowlist := make([]string, 0, len(parts))- for _, p := range parts {- trimmed := strings.TrimSpace(p)- if trimmed != "" {- allowlist = append(allowlist, trimmed)- }- }- return allowlist+ return kit.TrimNonEmpty(strings.Split(raw, ","))}// ValidateMobileRedirectURI returns nil if uri exactly matches one of the@@ -229,7 +219,7 @@ func (s *OidcService) ValidateMobileRedirectURI(ctx context.Context, uri string)return errors.Errorf("mobile redirect URI %q is not in the configured allowlist", uri)}-func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, origin string, mobileRedirectURI string) (string, string, error) {+func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo, origin, mobileRedirectURI string) (string, string, error) {oidcConfig, err := s.getEffectiveConfigInternal(ctx)if err != nil {slog.Error("GenerateAuthURL: failed to get OIDC config", "error", err)@@ -246,9 +236,9 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, or}}- state := utils.GenerateRandomString(32)- nonce := utils.GenerateRandomString(32)- codeVerifier := utils.GenerateRandomString(128)+ state := kit.RandomString(32)+ nonce := kit.RandomString(32)+ codeVerifier := kit.RandomString(128)oauth2Config, err := s.getOauth2ConfigInternal(oidcConfig, provider, origin, mobileRedirectURI)if err != nil {@@ -339,7 +329,7 @@ func (s *OidcService) discoverProviderInternal(ctx context.Context, issuer strinreturn nil, issuer, err}-func (s *OidcService) exchangeTokenInternal(ctx context.Context, cfg *settings.OidcConfig, provider *oidc.Provider, code string, verifier string, origin string, mobileRedirectURI string) (*oauth2.Token, error) {+func (s *OidcService) exchangeTokenInternal(ctx context.Context, cfg *settings.OidcConfig, provider *oidc.Provider, code, verifier, origin, mobileRedirectURI string) (*oauth2.Token, error) {oauth2Config, err := s.getOauth2ConfigInternal(cfg, provider, origin, mobileRedirectURI)if err != nil {return nil, err@@ -429,10 +419,7 @@ func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *settreturn nil, err}- tokenType := token.TokenType- if tokenType == "" {- tokenType = "Bearer"- }+ tokenType := cmp.Or(token.TokenType, "Bearer")request.Header.Set("Authorization", fmt.Sprintf("%s %s", tokenType, token.AccessToken))request.Header.Set("Accept", "application/json")@@ -602,10 +589,7 @@ func (s *OidcService) buildUserInfoInternal(ctx context.Context, provider *oidc.Extra: claims,}- tokenType := token.TokenType- if tokenType == "" {- tokenType = "Bearer"- }+ tokenType := cmp.Or(token.TokenType, "Bearer")tokenResp := &authtypes.OidcTokenResponse{AccessToken: token.AccessToken,@@ -817,7 +801,7 @@ func (s *OidcService) ExchangeDeviceToken(ctx context.Context, deviceCode stringtoken := &oauth2.Token{AccessToken: accessToken,- TokenType: utils.GetStringOrDefault(tokenResp, "token_type", "Bearer"),+ TokenType: kit.As(tokenResp["token_type"], "Bearer"),}if refreshToken, ok := tokenResp["refresh_token"].(string); ok {token.RefreshToken = refreshTokendiff --git a/backend/internal/oidc/service_test.go b/backend/internal/oidc/service_test.goindex 7e54bd08c..5e7b95cc5 100644--- a/backend/internal/oidc/service_test.go+++ b/backend/internal/oidc/service_test.go@@ -42,7 +42,6 @@ func TestValidateMobileRedirectURI(t *testing.T) {require.Equal(t, tc.wantErr, err != nil,"ValidateMobileRedirectURI(%q): wantErr=%v got err=%v", tc.uri, tc.wantErr, err)-})}}@@ -62,10 +61,8 @@ func TestGetMobileRedirectAllowlistTrimsWhitespace(t *testing.T) {"got %d entries (%v), want %d (%v)", len(got), got, len(want), want)}for i, w := range want {-require.Equal(t, w, got[i],"entry %d: got %q, want %q", i, got[i], w)-}}@@ -101,7 +98,6 @@ func TestGetMobileRedirectAllowlistUsesSettings(t *testing.T) {require.Error(t, err,"ValidateMobileRedirectURI config fallback should fail when DB setting is configured")}-}// Test fixtures shared by this package's tests.diff --git a/backend/internal/passkey/handler.go b/backend/internal/passkey/handler.goindex e2fb4ed2a..0e733c1ef 100644--- a/backend/internal/passkey/handler.go+++ b/backend/internal/passkey/handler.go@@ -1,21 +1,18 @@package passkeyimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/session"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""encoding/json/v2""net/http""strings""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/auth"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/auth"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/internal/passkey/model.go b/backend/internal/passkey/model.goindex 47db74f22..29ebfba12 100644--- a/backend/internal/passkey/model.go+++ b/backend/internal/passkey/model.go@@ -1,11 +1,10 @@package passkeyimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"-- "time")// Passkey stores the WebAuthn credential record required to validate futurediff --git a/backend/internal/passkey/service.go b/backend/internal/passkey/service.goindex 83085491a..58295c051 100644--- a/backend/internal/passkey/service.go+++ b/backend/internal/passkey/service.go@@ -1,10 +1,6 @@package passkeyimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/session"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""crypto/rand""crypto/sha256"@@ -22,13 +18,16 @@ import ("uuid""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/resources""github.com/getarcaneapp/arcane/types/v2/auth""github.com/go-webauthn/webauthn/protocol""github.com/go-webauthn/webauthn/webauthn"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm""gorm.io/gorm/clause")@@ -134,26 +133,20 @@ type AuthenticationCompletion struct {Source string}-type passkeyService struct {+// PasskeyService owns WebAuthn ceremonies, passkey persistence, MFA+// transactions, recovery codes, and step-up grants. It intentionally does not+// issue JWTs; auth.AuthService remains the single token/session issuer.+type PasskeyService struct {db *database.DBwebAuthn *webauthn.WebAuthnrpID stringinitErr error}-// PasskeyService owns WebAuthn ceremonies, passkey persistence, MFA-// transactions, recovery codes, and step-up grants. It intentionally does not-// issue JWTs; auth.AuthService remains the single token/session issuer.-type PasskeyService = passkeyService-func NewPasskeyService(db *database.DB, cfg *config.Config) *PasskeyService {- s := &passkeyService{db: db}+ s := &PasskeyService{db: db}- appURL := "http://localhost:3552"- if cfg != nil {- appURL = cfg.GetAppURL()- }- parsedURL, err := url.Parse(strings.TrimSpace(appURL))+ parsedURL, err := url.Parse(strings.TrimSpace(cfg.GetAppURL()))if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {s.initErr = errors.WrapIf(err, "invalid APP_URL for WebAuthn")if err == nil {@@ -189,11 +182,9 @@ func NewPasskeyService(db *database.DB, cfg *config.Config) *PasskeyService {return s}-func (s *passkeyService) readyInternal() error {- if s == nil || s.db == nil || s.webAuthn == nil || s.initErr != nil {- return ErrPasskeyServiceUnavailable- }- return nil+// readyInternal reports whether WebAuthn initialised; every constructor failure sets initErr.+func (s *PasskeyService) readyInternal() error {+ return kit.Ternary[error](s.initErr != nil, ErrPasskeyServiceUnavailable, nil)}type webAuthnUser struct {@@ -221,7 +212,7 @@ func (u *webAuthnUser) WebAuthnCredentials() []webauthn.Credential {return u.credentials}-func (s *passkeyService) loadWebAuthnUserInternal(ctx context.Context, userID string) (*webAuthnUser, error) {+func (s *PasskeyService) loadWebAuthnUserInternal(ctx context.Context, userID string) (*webAuthnUser, error) {if strings.TrimSpace(userID) == "" {return nil, ErrPasskeyTransaction}@@ -285,7 +276,7 @@ func credentialFromModelInternal(row Passkey) webauthn.Credential {}// LoginAvailable reports whether a registered passkey can be used on this instance.-func (s *passkeyService) LoginAvailable(ctx context.Context) (bool, error) {+func (s *PasskeyService) LoginAvailable(ctx context.Context) (bool, error) {if errors.Is(s.readyInternal(), ErrPasskeyServiceUnavailable) {return false, nil}@@ -300,7 +291,7 @@ func (s *passkeyService) LoginAvailable(ctx context.Context) (bool, error) {return available, nil}-func (s *passkeyService) BeginPasskeyLogin(ctx context.Context) (*PasskeyChallenge, error) {+func (s *PasskeyService) BeginPasskeyLogin(ctx context.Context) (*PasskeyChallenge, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -325,7 +316,7 @@ func (s *passkeyService) BeginPasskeyLogin(ctx context.Context) (*PasskeyChallen}, nil}-func (s *passkeyService) BeginMFAAuthentication(ctx context.Context, userID string, meta auth.SessionMeta, source string) (*auth.MFAChallenge, error) {+func (s *PasskeyService) BeginMFAAuthentication(ctx context.Context, userID string, meta auth.SessionMeta, source string) (*auth.MFAChallenge, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -355,7 +346,7 @@ func (s *passkeyService) BeginMFAAuthentication(ctx context.Context, userID stri// BeginMFAForTransaction starts a passkey assertion for an already-created// pending MFA transaction. This is useful to clients that separate primary// authentication from challenge retrieval.-func (s *passkeyService) BeginMFAForTransaction(ctx context.Context, transactionID string) (*auth.MFAChallenge, error) {+func (s *PasskeyService) BeginMFAForTransaction(ctx context.Context, transactionID string) (*auth.MFAChallenge, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -369,7 +360,7 @@ func (s *passkeyService) BeginMFAForTransaction(ctx context.Context, transactionreturn s.beginMFAForTransactionInternal(ctx, transaction)}-func (s *passkeyService) beginMFAForTransactionInternal(ctx context.Context, transaction *AuthTransaction) (*auth.MFAChallenge, error) {+func (s *PasskeyService) beginMFAForTransactionInternal(ctx context.Context, transaction *AuthTransaction) (*auth.MFAChallenge, error) {if transaction == nil {return nil, ErrPasskeyTransaction}@@ -408,7 +399,7 @@ func (s *passkeyService) beginMFAForTransactionInternal(ctx context.Context, tra}, nil}-func (s *passkeyService) BeginStepUp(ctx context.Context, userID, sessionID string, meta auth.SessionMeta) (*PasskeyChallenge, error) {+func (s *PasskeyService) BeginStepUp(ctx context.Context, userID, sessionID string, meta auth.SessionMeta) (*PasskeyChallenge, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -454,7 +445,7 @@ func (s *passkeyService) BeginStepUp(ctx context.Context, userID, sessionID stri}, nil}-func (s *passkeyService) BeginRegistration(ctx context.Context, userID, sessionID, stepUpToken string) (*PasskeyChallenge, error) {+func (s *PasskeyService) BeginRegistration(ctx context.Context, userID, sessionID, stepUpToken string) (*PasskeyChallenge, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -490,7 +481,7 @@ func (s *passkeyService) BeginRegistration(ctx context.Context, userID, sessionIreturn &PasskeyChallenge{CeremonyID: ceremony.ID, Options: creation.Response, ExpiresAt: ceremony.ExpiresAt}, nil}-func (s *passkeyService) FinishRegistration(ctx context.Context, userID, sessionID, ceremonyID string, payload []byte, name string) (*PasskeySummary, error) {+func (s *PasskeyService) FinishRegistration(ctx context.Context, userID, sessionID, ceremonyID string, payload []byte, name string) (*PasskeySummary, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -541,7 +532,7 @@ func (s *passkeyService) FinishRegistration(ctx context.Context, userID, sessionreturn &summary, nil}-func (s *passkeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID string, payload []byte) (*common.User, error) {+func (s *PasskeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID string, payload []byte) (*common.User, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -565,7 +556,7 @@ func (s *passkeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID striutils.NormalizePasskeyAssertionExtensions(session.Extensions, parsed)var resolved *webAuthnUser- user, credential, err := s.webAuthn.ValidatePasskeyLogin(func(_ []byte, userHandle []byte) (webauthn.User, error) {+ user, credential, err := s.webAuthn.ValidatePasskeyLogin(func(_, userHandle []byte) (webauthn.User, error) {adapter, lookupErr := s.loadWebAuthnUserInternal(ctx, string(userHandle))if lookupErr != nil {return nil, lookupErr@@ -584,7 +575,7 @@ func (s *passkeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID strireturn &resolved.model, nil}-func (s *passkeyService) FinishMobilePasskeyLogin(ctx context.Context, ceremonyID string, payload []byte, codeChallenge string) (*auth.MobilePasskeyCompletion, error) {+func (s *PasskeyService) FinishMobilePasskeyLogin(ctx context.Context, ceremonyID string, payload []byte, codeChallenge string) (*auth.MobilePasskeyCompletion, error) {codeChallenge, err := normalizeMobilePasskeyCodeChallengeInternal(codeChallenge)if err != nil {return nil, err@@ -602,7 +593,7 @@ func (s *passkeyService) FinishMobilePasskeyLogin(ctx context.Context, ceremonyIreturn &auth.MobilePasskeyCompletion{TransactionID: transaction.ID, ExpiresAt: transaction.ExpiresAt}, nil}-func (s *passkeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transactionID, codeVerifier string) (*common.User, error) {+func (s *PasskeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transactionID, codeVerifier string) (*common.User, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -627,10 +618,7 @@ func (s *passkeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transacif result.Error != nil {return errors.WrapIf(result.Error, "failed to complete mobile passkey transaction")}- if result.RowsAffected != 1 {- return ErrPasskeyTransaction- }- return nil+ return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyTransaction, nil)})if err != nil {return nil, err@@ -638,7 +626,7 @@ func (s *passkeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transacreturn s.loadUserModelInternal(ctx, transaction.UserID)}-func (s *passkeyService) FinishMFA(ctx context.Context, transactionID string, payload []byte) (*AuthenticationCompletion, error) {+func (s *PasskeyService) FinishMFA(ctx context.Context, transactionID string, payload []byte) (*AuthenticationCompletion, error) {transaction, err := s.loadPendingTransactionInternal(ctx, transactionID, authTransactionKindMFA)if err != nil {return nil, err@@ -659,7 +647,7 @@ func (s *passkeyService) FinishMFA(ctx context.Context, transactionID string, pa}, nil}-func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID, code string) (*AuthenticationCompletion, error) {+func (s *PasskeyService) FinishRecoveryCode(ctx context.Context, transactionID, code string) (*AuthenticationCompletion, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -668,7 +656,7 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,return nil, ErrPasskeyRecoveryCode}- hash := hashSecretInternal(normalized)+ hash := kit.SHA256Hex(normalized)var transaction AuthTransactionerr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ? AND kind = ? AND status = ? AND expires_at > ?", transactionID, authTransactionKindMFA, authTransactionPending, time.Now()).First(&transaction).Error; err != nil {@@ -709,10 +697,7 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,if result.Error != nil {return errors.WrapIf(result.Error, "failed to complete MFA transaction")}- if result.RowsAffected != 1 {- return ErrPasskeyTransaction- }- return nil+ return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyTransaction, nil)})if err != nil {return nil, err@@ -729,7 +714,7 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,}, nil}-func (s *passkeyService) FinishStepUp(ctx context.Context, transactionID, sessionID string, payload []byte) (*StepUpGrant, error) {+func (s *PasskeyService) FinishStepUp(ctx context.Context, transactionID, sessionID string, payload []byte) (*StepUpGrant, error) {transaction, err := s.loadPendingTransactionInternal(ctx, transactionID, authTransactionKindStepUp)if err != nil {return nil, err@@ -746,7 +731,7 @@ func (s *passkeyService) FinishStepUp(ctx context.Context, transactionID, sessioreturn s.issueStepUpGrantInternal(ctx, transaction.ID)}-func (s *passkeyService) CreatePasswordStepUpGrant(ctx context.Context, userID, sessionID string) (*StepUpGrant, error) {+func (s *PasskeyService) CreatePasswordStepUpGrant(ctx context.Context, userID, sessionID string) (*StepUpGrant, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -763,7 +748,7 @@ func (s *passkeyService) CreatePasswordStepUpGrant(ctx context.Context, userID,// VerifyStepUpToken accepts a grant repeatedly until it expires, so a single// re-authentication covers a short run of management actions instead of one.// The grant stays bound to the issuing user and session.-func (s *passkeyService) VerifyStepUpToken(ctx context.Context, userID, sessionID, token string) error {+func (s *PasskeyService) VerifyStepUpToken(ctx context.Context, userID, sessionID, token string) error {if err := s.readyInternal(); err != nil {return err}@@ -774,20 +759,17 @@ func (s *passkeyService) VerifyStepUpToken(ctx context.Context, userID, sessionIif err := s.ensureActiveSessionInternal(ctx, userID, sessionID); err != nil {return err}- hash := hashSecretInternal(token)+ hash := kit.SHA256Hex(token)var count int64if err := s.db.WithContext(ctx).Model(&AuthTransaction{}).Where("user_id = ? AND session_id = ? AND kind = ? AND status = ? AND secret_hash = ? AND expires_at > ?", userID, sessionID, authTransactionKindStepUp, authTransactionCompleted, hash, time.Now()).Count(&count).Error; err != nil {return errors.WrapIf(err, "failed to verify step-up grant")}- if count != 1 {- return ErrPasskeyStepUpRequired- }- return nil+ return kit.Ternary[error](count != 1, ErrPasskeyStepUpRequired, nil)}-func (s *passkeyService) ListPasskeys(ctx context.Context, userID string) ([]PasskeySummary, error) {+func (s *PasskeyService) ListPasskeys(ctx context.Context, userID string) ([]PasskeySummary, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -802,7 +784,7 @@ func (s *passkeyService) ListPasskeys(ctx context.Context, userID string) ([]Pasreturn result, nil}-func (s *passkeyService) GetCapabilities(ctx context.Context, userID string, oidcEnabled bool) (*PasskeyCapabilities, error) {+func (s *PasskeyService) GetCapabilities(ctx context.Context, userID string, oidcEnabled bool) (*PasskeyCapabilities, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -827,7 +809,7 @@ func (s *passkeyService) GetCapabilities(ctx context.Context, userID string, oid}, nil}-func (s *passkeyService) RenamePasskey(ctx context.Context, userID, passkeyID, name, sessionID, stepUpToken string) (*PasskeySummary, error) {+func (s *PasskeyService) RenamePasskey(ctx context.Context, userID, passkeyID, name, sessionID, stepUpToken string) (*PasskeySummary, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -856,7 +838,7 @@ func (s *passkeyService) RenamePasskey(ctx context.Context, userID, passkeyID, nreturn &summary, nil}-func (s *passkeyService) DeletePasskey(ctx context.Context, userID, passkeyID, sessionID, stepUpToken string, oidcFallbackAllowed bool) error {+func (s *PasskeyService) DeletePasskey(ctx context.Context, userID, passkeyID, sessionID, stepUpToken string, oidcFallbackAllowed bool) error {if err := s.readyInternal(); err != nil {return err}@@ -886,14 +868,11 @@ func (s *passkeyService) DeletePasskey(ctx context.Context, userID, passkeyID, sif result.Error != nil {return errors.WrapIf(result.Error, "failed to delete passkey")}- if result.RowsAffected != 1 {- return ErrPasskeyNotFound- }- return nil+ return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyNotFound, nil)})}-func (s *passkeyService) GetMFAStatus(ctx context.Context, userID string) (*MFAStatus, error) {+func (s *PasskeyService) GetMFAStatus(ctx context.Context, userID string) (*MFAStatus, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -912,7 +891,7 @@ func (s *passkeyService) GetMFAStatus(ctx context.Context, userID string) (*MFASreturn &MFAStatus{Enabled: user.PasskeyMFAEnabled, PasskeyCount: passkeyCount, RecoveryCodesRemaining: int(recoveryCodes)}, nil}-func (s *passkeyService) EnableMFA(ctx context.Context, userID, sessionID, stepUpToken string) ([]string, error) {+func (s *PasskeyService) EnableMFA(ctx context.Context, userID, sessionID, stepUpToken string) ([]string, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -955,7 +934,7 @@ func (s *passkeyService) EnableMFA(ctx context.Context, userID, sessionID, stepUreturn codes, nil}-func (s *passkeyService) DisableMFA(ctx context.Context, userID, sessionID, stepUpToken string) error {+func (s *PasskeyService) DisableMFA(ctx context.Context, userID, sessionID, stepUpToken string) error {if err := s.readyInternal(); err != nil {return err}@@ -989,7 +968,7 @@ func (s *passkeyService) DisableMFA(ctx context.Context, userID, sessionID, stepreturn err}-func (s *passkeyService) RegenerateRecoveryCodes(ctx context.Context, userID, sessionID, stepUpToken string) ([]string, error) {+func (s *PasskeyService) RegenerateRecoveryCodes(ctx context.Context, userID, sessionID, stepUpToken string) ([]string, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -1021,7 +1000,7 @@ func (s *passkeyService) RegenerateRecoveryCodes(ctx context.Context, userID, se// ResetMFAForUser is intentionally separate from self-service operations. It// is used only by the explicitly gated embedded admin recovery command.-func (s *passkeyService) ResetMFAForUser(ctx context.Context, userID string) error {+func (s *PasskeyService) ResetMFAForUser(ctx context.Context, userID string) error {if err := s.readyInternal(); err != nil {return err}@@ -1053,7 +1032,7 @@ func (s *passkeyService) ResetMFAForUser(ctx context.Context, userID string) err})}-func (s *passkeyService) createCeremonyInternal(ctx context.Context, purpose string, userID, sessionID, transactionID *string, session *webauthn.SessionData) (*PasskeyCeremony, error) {+func (s *PasskeyService) createCeremonyInternal(ctx context.Context, purpose string, userID, sessionID, transactionID *string, session *webauthn.SessionData) (*PasskeyCeremony, error) {if session == nil {return nil, ErrPasskeyCeremony}@@ -1081,7 +1060,7 @@ func (s *passkeyService) createCeremonyInternal(ctx context.Context, purpose strreturn ceremony, nil}-func (s *passkeyService) sweepCeremoniesInternal(ctx context.Context) error {+func (s *PasskeyService) sweepCeremoniesInternal(ctx context.Context) error {now := time.Now()if err := s.db.WithContext(ctx).Where("expires_at <= ? OR consumed_at IS NOT NULL", now).@@ -1091,7 +1070,7 @@ func (s *passkeyService) sweepCeremoniesInternal(ctx context.Context) error {return nil}-func (s *passkeyService) consumeCeremonyInternal(ctx context.Context, ceremonyID, purpose string) (*PasskeyCeremony, error) {+func (s *PasskeyService) consumeCeremonyInternal(ctx context.Context, ceremonyID, purpose string) (*PasskeyCeremony, error) {if strings.TrimSpace(ceremonyID) == "" {return nil, ErrPasskeyCeremony}@@ -1116,7 +1095,7 @@ func (s *passkeyService) consumeCeremonyInternal(ctx context.Context, ceremonyIDreturn &ceremony, nil}-func (s *passkeyService) loadPendingTransactionInternal(ctx context.Context, transactionID, kind string) (*AuthTransaction, error) {+func (s *PasskeyService) loadPendingTransactionInternal(ctx context.Context, transactionID, kind string) (*AuthTransaction, error) {if strings.TrimSpace(transactionID) == "" {return nil, ErrPasskeyTransaction}@@ -1130,11 +1109,11 @@ func (s *passkeyService) loadPendingTransactionInternal(ctx context.Context, trareturn &transaction, nil}-func (s *passkeyService) finishKnownUserAssertionInternal(ctx context.Context, transaction *AuthTransaction, purpose string, payload []byte) (*common.User, error) {+func (s *PasskeyService) finishKnownUserAssertionInternal(ctx context.Context, transaction *AuthTransaction, purpose string, payload []byte) (*common.User, error) {if transaction == nil || len(payload) == 0 || len(payload) > maxPasskeyPayloadBytes {return nil, ErrPasskeyResponse}- ceremony, err := s.consumeCeremonyInternal(ctx, ceremonyIDForTransactionInternal(ctx, s.db, transaction.ID, purpose), purpose)+ ceremony, err := s.consumeCeremonyInternal(ctx, s.ceremonyIDForTransactionInternal(ctx, transaction.ID, purpose), purpose)if err != nil {return nil, err}@@ -1164,15 +1143,16 @@ func (s *passkeyService) finishKnownUserAssertionInternal(ctx context.Context, treturn &adapter.model, nil}-func ceremonyIDForTransactionInternal(ctx context.Context, db *database.DB, transactionID, purpose string) string {+func (s *PasskeyService) ceremonyIDForTransactionInternal(ctx context.Context, transactionID, purpose string) string {var ceremony PasskeyCeremony- if db == nil || db.WithContext(ctx).Where("auth_transaction_id = ? AND purpose = ? AND consumed_at IS NULL", transactionID, purpose).Order("created_at DESC").First(&ceremony).Error != nil {- return ""- }- return ceremony.ID+ err := s.db.WithContext(ctx).+ Where("auth_transaction_id = ? AND purpose = ? AND consumed_at IS NULL", transactionID, purpose).+ Order("created_at DESC").+ First(&ceremony).Error+ return kit.Ternary(err != nil, "", ceremony.ID)}-func (s *passkeyService) completeTransactionInternal(ctx context.Context, transactionID string) error {+func (s *PasskeyService) completeTransactionInternal(ctx context.Context, transactionID string) error {now := time.Now()result := s.db.WithContext(ctx).Model(&AuthTransaction{}).Where("id = ? AND status = ? AND expires_at > ?", transactionID, authTransactionPending, now).@@ -1180,23 +1160,17 @@ func (s *passkeyService) completeTransactionInternal(ctx context.Context, transaif result.Error != nil {return errors.WrapIf(result.Error, "failed to complete authentication transaction")}- if result.RowsAffected != 1 {- return ErrPasskeyTransaction- }- return nil+ return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyTransaction, nil)}-func (s *passkeyService) issueStepUpGrantInternal(ctx context.Context, transactionID string) (*StepUpGrant, error) {- token, err := randomSecretInternal()- if err != nil {- return nil, errors.WrapIf(err, "failed to create step-up grant")- }+func (s *PasskeyService) issueStepUpGrantInternal(ctx context.Context, transactionID string) (*StepUpGrant, error) {+ token := kit.RandomString(43)now := time.Now()result := s.db.WithContext(ctx).Model(&AuthTransaction{}).Where("id = ? AND kind = ? AND status = ? AND expires_at > ?", transactionID, authTransactionKindStepUp, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted,- "secret_hash": hashSecretInternal(token),+ "secret_hash": kit.SHA256Hex(token),"completed_at": now,"updated_at": now,})@@ -1213,7 +1187,7 @@ func (s *passkeyService) issueStepUpGrantInternal(ctx context.Context, transactireturn &StepUpGrant{Token: token, ExpiresAt: transaction.ExpiresAt}, nil}-func (s *passkeyService) authorizeManagementInternal(ctx context.Context, userID, sessionID, stepUpToken string, allowFirstEnrollment bool) error {+func (s *PasskeyService) authorizeManagementInternal(ctx context.Context, userID, sessionID, stepUpToken string, allowFirstEnrollment bool) error {if strings.TrimSpace(sessionID) == "" {return ErrPasskeyStepUpRequired}@@ -1227,7 +1201,7 @@ func (s *passkeyService) authorizeManagementInternal(ctx context.Context, userIDreturn s.VerifyStepUpToken(ctx, userID, sessionID, stepUpToken)}-func (s *passkeyService) loadUserModelInternal(ctx context.Context, userID string) (*common.User, error) {+func (s *PasskeyService) loadUserModelInternal(ctx context.Context, userID string) (*common.User, error) {var user common.Userif err := s.db.WithContext(ctx).Where("id = ?", userID).First(&user).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {@@ -1238,7 +1212,7 @@ func (s *passkeyService) loadUserModelInternal(ctx context.Context, userID strinreturn &user, nil}-func (s *passkeyService) ensureActiveSessionInternal(ctx context.Context, userID, sessionID string) error {+func (s *PasskeyService) ensureActiveSessionInternal(ctx context.Context, userID, sessionID string) error {if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {return ErrPasskeyStepUpRequired}@@ -1254,7 +1228,7 @@ func (s *passkeyService) ensureActiveSessionInternal(ctx context.Context, userIDreturn nil}-func (s *passkeyService) countPasskeysInternal(ctx context.Context, userID string) (int, error) {+func (s *PasskeyService) countPasskeysInternal(ctx context.Context, userID string) (int, error) {var count int64if err := s.db.WithContext(ctx).Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {return 0, errors.WrapIf(err, "failed to count passkeys")@@ -1262,7 +1236,7 @@ func (s *passkeyService) countPasskeysInternal(ctx context.Context, userID strinreturn int(count), nil}-func (s *passkeyService) persistCredentialInternal(ctx context.Context, userID string, credential *webauthn.Credential, name string) (*Passkey, error) {+func (s *PasskeyService) persistCredentialInternal(ctx context.Context, userID string, credential *webauthn.Credential, name string) (*Passkey, error) {if credential == nil || len(credential.ID) == 0 || len(credential.PublicKey) == 0 {return nil, ErrPasskeyResponse}@@ -1309,7 +1283,7 @@ func (s *passkeyService) persistCredentialInternal(ctx context.Context, userID sreturn row, nil}-func (s *passkeyService) updateCredentialAfterAssertionInternal(ctx context.Context, adapter *webAuthnUser, credential *webauthn.Credential) error {+func (s *PasskeyService) updateCredentialAfterAssertionInternal(ctx context.Context, adapter *webAuthnUser, credential *webauthn.Credential) error {if adapter == nil || credential == nil || len(credential.ID) == 0 {return ErrPasskeyResponse}@@ -1331,10 +1305,7 @@ func (s *passkeyService) updateCredentialAfterAssertionInternal(ctx context.Contif result.Error != nil {return errors.WrapIf(result.Error, "failed to update passkey counter")}- if result.RowsAffected != 1 {- return ErrPasskeyResponse- }- return nil+ return kit.Ternary[error](result.RowsAffected != 1, ErrPasskeyResponse, nil)}func newAuthTransactionInternal(userID, kind, source string, meta auth.SessionMeta, sessionID *string) *AuthTransaction {@@ -1438,7 +1409,7 @@ func generateRecoveryCodeRowsInternal(userID string) ([]string, []PasskeyRecover}encoded := strings.TrimRight(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw), "=")codes[i] = groupRecoveryCodeInternal(encoded)- hash := hashSecretInternal(strings.ToUpper(strings.ReplaceAll(codes[i], "-", "")))+ hash := kit.SHA256Hex(strings.ToUpper(strings.ReplaceAll(codes[i], "-", "")))rows[i] = PasskeyRecoveryCode{ID: uuid.New().String(), UserID: userID, CodeHash: hash}}return codes, rows, nil@@ -1456,11 +1427,6 @@ func groupRecoveryCodeInternal(code string) string {return strings.Join(groups, "-")}-func hashSecretInternal(secret string) string {- sum := sha256.Sum256([]byte(secret))- return hex.EncodeToString(sum[:])-}-func normalizeMobilePasskeyCodeChallengeInternal(codeChallenge string) (string, error) {codeChallenge = strings.TrimSpace(codeChallenge)decoded, err := base64.RawURLEncoding.DecodeString(codeChallenge)@@ -1480,14 +1446,6 @@ func mobilePasskeyCodeChallengeInternal(codeVerifier string) (string, error) {return base64.RawURLEncoding.EncodeToString(sum[:]), nil}-func randomSecretInternal() (string, error) {- raw := make([]byte, 32)- if _, err := rand.Read(raw); err != nil {- return "", err- }- return base64.RawURLEncoding.EncodeToString(raw), nil-}-func optionalStringInternal(value string) *string {value = strings.TrimSpace(value)if value == "" {diff --git a/backend/internal/passkey/service_test.go b/backend/internal/passkey/service_test.goindex e2d73141f..ad5c0277d 100644--- a/backend/internal/passkey/service_test.go+++ b/backend/internal/passkey/service_test.go@@ -1,21 +1,19 @@package passkeyimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""testing""time""uuid"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/types/v2/auth"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm")func newPasskeyServiceTestDB(t *testing.T) *database.DB {diff --git a/backend/internal/port/service.go b/backend/internal/port/service.goindex ee2c195d9..a73639485 100644--- a/backend/internal/port/service.go+++ b/backend/internal/port/service.go@@ -12,6 +12,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"containertypes "github.com/getarcaneapp/arcane/types/v2/container"porttypes "github.com/getarcaneapp/arcane/types/v2/port"+ kit "go.getarcane.app/kit/pkg")type PortService struct {@@ -84,10 +85,7 @@ func (s *PortService) buildPortSortBindings() []pagination.SortBinding[porttypesKey: "containerPort",Fn: func(a, b porttypes.PortMapping) int {if a.ContainerPort != b.ContainerPort {- if a.ContainerPort < b.ContainerPort {- return -1- }- return 1+ return kit.Ternary(a.ContainerPort < b.ContainerPort, -1, 1)}return strings.Compare(a.ContainerName, b.ContainerName)},@@ -120,10 +118,7 @@ func (s *PortService) buildPortSortBindings() []pagination.SortBinding[porttypesKey: "isPublished",Fn: func(a, b porttypes.PortMapping) int {if a.IsPublished != b.IsPublished {- if a.IsPublished {- return -1- }- return 1+ return kit.Ternary(a.IsPublished, -1, 1)}return strings.Compare(a.ContainerName, b.ContainerName)},@@ -218,8 +213,5 @@ func compareOptionalStringDescInternal(a, b, fallbackA, fallbackB string) int {}func normalizeOptionalStringSortValueInternal(value string) string {- if strings.EqualFold(strings.TrimSpace(value), "invalid IP") {- return ""- }- return value+ return kit.Ternary(strings.EqualFold(strings.TrimSpace(value), "invalid IP"), "", value)}diff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.goindex a6592546e..2a50c198c 100644--- a/backend/internal/project/handler.go+++ b/backend/internal/project/handler.go@@ -23,15 +23,14 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/base"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"-volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace""github.com/samber/mo"+ "go.getarcane.app/kit/pkg/mapping""gorm.io/gorm")@@ -702,7 +701,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject}var response projecttypes.CreateReponse- if err := mapper.MapStruct(proj, &response); err != nil {+ if err := mapping.MapStruct(proj, &response); err != nil {return nil, huma.Error500InternalServerError("failed to map response")}response.Status = string(proj.Status)diff --git a/backend/internal/project/lifecycle.go b/backend/internal/project/lifecycle.goindex 9c2cad525..950188ca9 100644--- a/backend/internal/project/lifecycle.go+++ b/backend/internal/project/lifecycle.go@@ -1,9 +1,8 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"bufio"+ "cmp""context""fmt""io"@@ -15,18 +14,9 @@ import ("strings""time"- lifecycletype "github.com/getarcaneapp/arcane/types/v2/lifecycle"-"emperror.dev/errors"-cerrdefs "github.com/containerd/errdefs"- "github.com/moby/moby/api/pkg/stdcopy"- containertypes "github.com/moby/moby/api/types/container"- mounttypes "github.com/moby/moby/api/types/mount"- "github.com/moby/moby/client"- "github.com/samber/mo"- "gorm.io/gorm"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"@@ -36,12 +26,20 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ lifecycletype "github.com/getarcaneapp/arcane/types/v2/lifecycle"+ "github.com/moby/moby/api/pkg/stdcopy"+ containertypes "github.com/moby/moby/api/types/container"+ mounttypes "github.com/moby/moby/api/types/mount"+ "github.com/moby/moby/client"+ "github.com/samber/mo""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/kit/pkg/capture"+ "gorm.io/gorm")-// Lifecycle hook configuration limits and conventions.const (+ // Lifecycle hook configuration limits and conventions.// lifecycleWorkspaceMount is the in-container path the project dir is// bind-mounted to. Scripts run with this as their working dir.lifecycleWorkspaceMount = "/workspace"@@ -58,10 +56,8 @@ const (// goroutine to drain after the container exits, before force-closing.// Mirrors the value used by vulnerability scanning for the same purpose.lifecycleStreamDrainTimeout = 30 * time.Second-)-// Last-run status values written to GitOpsSync.PreDeployLastRunStatus.-const (+ // Last-run status values written to GitOpsSync.PreDeployLastRunStatus.lifecycleStatusSuccess = "success"lifecycleStatusFailed = "failed"lifecycleStatusTimeout = "timeout"@@ -219,7 +215,7 @@ func (s *LifecycleService) runScriptInContainerInternal(networkMode string,timeout time.Duration,actor common.User,-) (stdoutContent string, stderrContent string, exitCode int64, err error) {+) (stdoutContent, stderrContent string, exitCode int64, err error) {dockerClient, dErr := s.dockerService.GetClient(ctx)if dErr != nil {return "", "", 0, errors.WrapIf(dErr, "failed to connect to Docker")@@ -666,24 +662,15 @@ func buildLifecycleMountsInternal(workspace *mounttypes.Mount, extras []lifecycl// An empty stored value is treated as "none" so scripts never accidentally// run on the default bridge network.func resolveLifecycleNetworkModeInternal(mode string) containertypes.NetworkMode {- trimmed := strings.TrimSpace(mode)- if trimmed == "" {- trimmed = "none"- }+ trimmed := cmp.Or(strings.TrimSpace(mode), "none")return containertypes.NetworkMode(trimmed)}func lifecycleStatusForResultInternal(exitCode int64, runErr error) string {if runErr != nil {- if errors.Is(runErr, context.DeadlineExceeded) {- return lifecycleStatusTimeout- }- return lifecycleStatusFailed- }- if exitCode != 0 {- return lifecycleStatusFailed+ return kit.Ternary(errors.Is(runErr, context.DeadlineExceeded), lifecycleStatusTimeout, lifecycleStatusFailed)}- return lifecycleStatusSuccess+ return kit.Ternary(exitCode != 0, lifecycleStatusFailed, lifecycleStatusSuccess)}func combineLifecycleOutputInternal(stdout, stderr string) string {diff --git a/backend/internal/project/lifecycle_test.go b/backend/internal/project/lifecycle_test.goindex 22d85f3b0..893c7471f 100644--- a/backend/internal/project/lifecycle_test.go+++ b/backend/internal/project/lifecycle_test.go@@ -1,8 +1,6 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""errors""os"@@ -10,16 +8,16 @@ import ("testing""time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/libtnb/sqlite""github.com/stretchr/testify/assert""github.com/stretchr/testify/require""go.uber.org/fx/fxtest""gorm.io/gorm"-- "github.com/getarcaneapp/arcane/backend/v2/internal/actors"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/settings")func setupLifecycleTestDB(t *testing.T) *database.DB {diff --git a/backend/internal/project/module.go b/backend/internal/project/module.goindex 9546b5f98..e35d847a4 100644--- a/backend/internal/project/module.go+++ b/backend/internal/project/module.go@@ -3,7 +3,6 @@ package projectimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil")diff --git a/backend/internal/project/project.go b/backend/internal/project/project.goindex be6eb3832..8aa9be896 100644--- a/backend/internal/project/project.go+++ b/backend/internal/project/project.go@@ -6,6 +6,7 @@ import ("log/slog""os""path/filepath"+ "strconv""strings""sync""time"@@ -23,13 +24,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/containerregistry"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"dockerregistry "github.com/moby/moby/api/types/registry""github.com/moby/moby/client""github.com/samber/mo"buildtypes "go.getarcane.app/builds/types"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -757,7 +758,7 @@ func (s *ProjectService) loadComposeProjectForProjectInternal(ctx context.ContexpathMapper := s.projectPathMapperInternal(ctx)- composeProject, loadErr := projects.LoadComposeProject(ctx, composeFileFullPath, projects.NormalizeProjectName(proj.Name), projectsDirectory, utils.BoolOrDefault(cfg.AutoInjectEnv.Value, false), pathMapper, nil, nil, false, nil, services, prepare)+ composeProject, loadErr := projects.LoadComposeProject(ctx, composeFileFullPath, projects.NormalizeProjectName(proj.Name), projectsDirectory, kit.ParseOrDefault(cfg.AutoInjectEnv.Value, false, strconv.ParseBool), pathMapper, nil, nil, false, nil, services, prepare)if loadErr != nil {return nil, "", loadErr}@@ -780,7 +781,7 @@ func (s *ProjectService) getCachedComposeProjectInternal(ctx context.Context, prif err != nil {return nil, err}- return projects.LoadCachedComposeProject(ctx, s.parsedCompose, proj.ID, proj.Path, composePath, projects.NormalizeProjectName(proj.Name), getProjectsDirectoryOrDefaultInternal(ctx, cfg), utils.BoolOrDefault(cfg.AutoInjectEnv.Value, false), s.projectPathMapperInternal(ctx))+ return projects.LoadCachedComposeProject(ctx, s.parsedCompose, proj.ID, proj.Path, composePath, projects.NormalizeProjectName(proj.Name), getProjectsDirectoryOrDefaultInternal(ctx, cfg), kit.ParseOrDefault(cfg.AutoInjectEnv.Value, false, strconv.ParseBool), s.projectPathMapperInternal(ctx))}func (s *ProjectService) refreshComposeProjectNameInternal(ctx context.Context, proj *Project) {diff --git a/backend/internal/project/project_details.go b/backend/internal/project/project_details.goindex 64e76a69e..c1e43dd38 100644--- a/backend/internal/project/project_details.go+++ b/backend/internal/project/project_details.go@@ -1,34 +1,34 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"- "github.com/moby/moby/api/types/container"-"bufio"+ "cmp""context""io""log/slog""maps""path/filepath""slices"+ "strconv""strings""sync""time""emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-composetypes "github.com/compose-spec/compose-go/v2/types"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/iconcatalog""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"imagetypes "github.com/getarcaneapp/arcane/types/v2/image""github.com/getarcaneapp/arcane/types/v2/project"+ "github.com/moby/moby/api/types/container""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""go.getarcane.app/sys/cgroup""go.getarcane.app/updater""go.getarcane.app/updater/labels"@@ -52,7 +52,7 @@ type ProjectServiceInfo struct {ImageID string `json:"-"`}-func getServiceCounts(services []ProjectServiceInfo) (total int, running int) {+func getServiceCounts(services []ProjectServiceInfo) (total, running int) {total = len(services)for _, service := range services {st := strings.ToLower(strings.TrimSpace(service.Status))@@ -151,7 +151,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strinsvcConfig = &cfg}- resolvedIcon := iconcatalog.Resolve(IconCatalogForContext(ctx), iconcatalog.FirstNonEmpty(+ resolvedIcon := iconcatalog.Resolve(IconCatalogForContext(ctx), cmp.Or(projects.FindArcaneIconSet(c.Labels),meta.ServiceIconSets[c.Service],meta.ProjectIcon,@@ -176,7 +176,7 @@ func (s *ProjectService) GetProjectServices(ctx context.Context, projectID strinfor _, svc := range composeProject.Services {if !have[svc.Name] {- resolvedIcon := iconcatalog.Resolve(IconCatalogForContext(ctx), iconcatalog.FirstNonEmpty(+ resolvedIcon := iconcatalog.Resolve(IconCatalogForContext(ctx), cmp.Or(meta.ServiceIconSets[svc.Name],meta.ProjectIcon,))@@ -272,7 +272,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string}var resp project.Details- if err := mapper.MapStruct(proj, &resp); err != nil {+ if err := mapping.MapStruct(proj, &resp); err != nil {return project.Details{}, errors.WrapIf(err, "failed to map project")}@@ -304,10 +304,7 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string// configuration problem is diagnosable.composeSelection, selErr := projects.ComposeFileEnvSelection(ctx, projectsDir, proj.Path)if selErr != nil {- selLogLevel := slog.LevelWarn- if errors.Is(selErr, common.ErrProjectEnvUnreadable) {- selLogLevel = slog.LevelDebug- }+ selLogLevel := kit.Ternary(errors.Is(selErr, common.ErrProjectEnvUnreadable), slog.LevelDebug, slog.LevelWarn)slog.Log(ctx, selLogLevel, "failed to resolve COMPOSE_FILE selection for project details", "projectID", proj.ID, "path", proj.Path, "error", selErr)composeSelection = nil}@@ -451,7 +448,7 @@ func (s *ProjectService) enrichWithIncludeFiles(ctx context.Context, composeFile// Load environment variables so that include paths with ${VAR} references are expandedcfg := s.settingsService.GetSettingsOrDefaults(ctx)projectsDirectory, _ := projects.GetProjectsDirectory(ctx, strings.TrimSpace(cfg.ProjectsDirectory.Value))- envLoader := projects.NewEnvLoader(projectsDirectory, filepath.Dir(composeFile), utils.BoolOrDefault(cfg.AutoInjectEnv.Value, false))+ envLoader := projects.NewEnvLoader(projectsDirectory, filepath.Dir(composeFile), kit.ParseOrDefault(cfg.AutoInjectEnv.Value, false, strconv.ParseBool))envMap, _, _ := envLoader.LoadEnvironment(ctx)includes, parseErr := projects.ParseIncludes(composeFile, envMap, false)@@ -506,7 +503,7 @@ func excludeHiddenRuntimeServicesInternal(details []project.Details) (map[stringhiddenRefs := make(map[string]bool)visibleServices := make([]project.RuntimeService, 0, len(details[i].RuntimeServices))for _, service := range details[i].RuntimeServices {- hidden, _ := utils.ParseBool(service.ContainerLabels[libarcane.HiddenResourceLabel])+ hidden, _ := kit.ParseBool(service.ContainerLabels[libarcane.HiddenResourceLabel])if hidden {hiddenServices[service.Name] = truehiddenRefs[service.Image] = true@@ -621,7 +618,7 @@ func (s *ProjectService) resolveProjectUpdateServicesInternal(ctx context.Contex}services := make([]composetypes.ServiceConfig, 0, len(composeProject.Services))for _, service := range composeProject.Services {- hidden, _ := utils.ParseBool(service.Labels[libarcane.HiddenResourceLabel])+ hidden, _ := kit.ParseBool(service.Labels[libarcane.HiddenResourceLabel])if !includeHidden && (hidden || hiddenRuntimeServices[service.Name]) {continue}@@ -1021,8 +1018,5 @@ func calculateProjectStatus(services []ProjectServiceInfo) ProjectStatus {if runningCount > 0 {return ProjectStatusPartiallyRunning}- if stoppedCount > 0 {- return ProjectStatusStopped- }- return ProjectStatusUnknown+ return kit.Ternary(stoppedCount > 0, ProjectStatusStopped, ProjectStatusUnknown)}diff --git a/backend/internal/project/project_lifecycle.go b/backend/internal/project/project_lifecycle.goindex 880049491..9677f8206 100644--- a/backend/internal/project/project_lifecycle.go+++ b/backend/internal/project/project_lifecycle.go@@ -24,9 +24,9 @@ import ("github.com/getarcaneapp/arcane/types/v2""github.com/getarcaneapp/arcane/types/v2/containerregistry"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"-"go.getarcane.app/acfs"buildtypes "go.getarcane.app/builds/types"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""go.getarcane.app/updater/labels""gorm.io/gorm"@@ -244,10 +244,7 @@ func prepareProjectBindDirectoriesInternal(projectPath string) projects.PreparePfunc ensureProjectBindDirectoryInternal(ctx context.Context, projectPath, source string) error {logicalPath, err := acfs.LogicalPath(projectPath, source)if err != nil {- if errors.Is(err, acfs.ErrOutsideRoot) {- return nil- }- return err+ return kit.Ternary(errors.Is(err, acfs.ErrOutsideRoot), nil, err)}if logicalPath == "/" {return nil@@ -262,10 +259,7 @@ func ensureProjectBindDirectoryInternal(ctx context.Context, projectPath, source}if err := acfs.MkdirAll(ctx, projectPath, logicalPath, utils.DirPerm); err != nil {- if errors.Is(err, acfs.ErrOutsideRoot) {- return nil- }- return err+ return kit.Ternary(errors.Is(err, acfs.ErrOutsideRoot), nil, err)}slog.InfoContext(ctx, "created missing bind directory for project deployment", "projectPath", projectPath, "source", source)return nil@@ -560,7 +554,7 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContentreturn proj, nil}-func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, removeFiles bool, removeVolumes bool, user common.User) error {+func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, removeFiles, removeVolumes bool, user common.User) error {slog.DebugContext(ctx, "DestroyProject service called","projectID", projectID,"removeFiles", removeFiles,diff --git a/backend/internal/project/project_listing.go b/backend/internal/project/project_listing.goindex 0e59d937d..dc4cb12b4 100644--- a/backend/internal/project/project_listing.go+++ b/backend/internal/project/project_listing.go@@ -1,8 +1,7 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-+ "cmp""context""fmt""log/slog"@@ -15,7 +14,7 @@ import ("emperror.dev/errors"composeapi "github.com/docker/compose/v5/pkg/api"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/image"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -23,12 +22,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/iconcatalog"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"imagetypes "github.com/getarcaneapp/arcane/types/v2/image""github.com/getarcaneapp/arcane/types/v2/project""github.com/moby/moby/api/types/container""github.com/moby/moby/client""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""go.getarcane.app/sys/cgroup""go.getarcane.app/updater/labels""golang.org/x/sync/errgroup"@@ -128,7 +128,7 @@ func projectServiceInfoFromContainerInternal(ctx context.Context, c container.Su// resolveServiceIconInternal picks a service icon from its container labels,// then the compose metadata's per-service and project-level icon sets.func resolveServiceIconInternal(catalog string, containerLabels map[string]string, serviceName string, meta projects.ArcaneComposeMetadata) iconcatalog.ResolvedIconSet {- return iconcatalog.Resolve(catalog, iconcatalog.FirstNonEmpty(+ return iconcatalog.Resolve(catalog, cmp.Or(projects.FindArcaneIconSet(containerLabels),meta.ServiceIconSets[serviceName],meta.ProjectIcon,@@ -312,7 +312,7 @@ func applyProjectArchivedDBFilterInternal(query *gorm.DB, filterValue string) *gif strings.EqualFold(strings.TrimSpace(filterValue), "all") {return query}- archived, _ := utils.ParseBool(filterValue)+ archived, _ := kit.ParseBool(filterValue)return query.Where("is_archived = ?", archived)}@@ -325,20 +325,13 @@ func applyProjectTagsDBFilterInternal(query *gorm.DB, filterValue string) *gorm.}func normalizeTagFilterValuesInternal(filterValue string) []string {- seen := map[string]struct{}{}result := make([]string, 0)for value := range strings.SplitSeq(filterValue, ",") {- normalized, err := projects.NormalizeProjectTag(value)- if err != nil {- continue+ if normalized, err := projects.NormalizeProjectTag(value); err == nil {+ result = append(result, normalized)}- if _, exists := seen[normalized]; exists {- continue- }- seen[normalized] = struct{}{}- result = append(result, normalized)}- return result+ return kit.Unique(result)}func applyProjectSearchDBFilterInternal(query *gorm.DB, term string) *gorm.DB {@@ -615,10 +608,7 @@ func buildDiscoveredRuntimeServicesInternal(containers []container.Summary, iconcontinue}- serviceName := dockerutil.ComposeServiceLabel(c.Labels)- if serviceName == "" {- serviceName = c.ID- }+ serviceName := cmp.Or(dockerutil.ComposeServiceLabel(c.Labels), c.ID)key := serviceName + "\x00" + imageRefif _, exists := seenServices[key]; exists {continue@@ -645,7 +635,7 @@ func buildDiscoveredRuntimeServicesInternal(containers []container.Summary, iconreturn runtimeServices}-func resolveDiscoveredProjectStatusInternal(serviceCount int, runningCount int) string {+func resolveDiscoveredProjectStatusInternal(serviceCount, runningCount int) string {switch {case serviceCount == 0:return string(ProjectStatusUnknown)@@ -693,10 +683,7 @@ func (s *ProjectService) buildProjectDerivedPaginationConfigInternal() paginatioif a.ServiceCount < b.ServiceCount {return -1}- if a.ServiceCount > b.ServiceCount {- return 1- }- return 0+ return kit.Ternary(a.ServiceCount > b.ServiceCount, 1, 0)},},{@@ -716,10 +703,7 @@ func (s *ProjectService) buildProjectDerivedPaginationConfigInternal() paginatioif at.Before(bt) {return -1}- if at.After(bt) {- return 1- }- return 0+ return kit.Ternary(at.After(bt), 1, 0)},},},@@ -777,7 +761,7 @@ func buildProjectArchivedFilterAccessorInternal() pagination.FilterAccessor[projif strings.EqualFold(strings.TrimSpace(filterValue), "all") {return true}- archived, _ := utils.ParseBool(filterValue)+ archived, _ := kit.ParseBool(filterValue)return p.IsArchived == archived},}@@ -848,7 +832,7 @@ func (s *ProjectService) CountProjectsWithPendingUpdates(ctx context.Context, alvisibleContainers := make([]container.Summary, 0, len(allContainers))for _, c := range allContainers {- hidden, _ := utils.ParseBool(c.Labels[libarcane.HiddenResourceLabel])+ hidden, _ := kit.ParseBool(c.Labels[libarcane.HiddenResourceLabel])if !hidden {visibleContainers = append(visibleContainers, c)}@@ -987,10 +971,7 @@ func (s *ProjectService) persistInferredServiceCountsInternal(ctx context.Contexif len(counts) == 0 || s.db == nil {return}- ids := make([]string, 0, len(counts))- for id := range counts {- ids = append(ids, id)- }+ ids := slices.Collect(maps.Keys(counts))for chunk := range slices.Chunk(ids, inferredServiceCountBatchSizeInternal) {var caseExpr strings.Builderargs := make([]any, 0, 2*len(chunk))@@ -1020,7 +1001,7 @@ const inferredServiceCountBatchSizeInternal = 200// the container listing failed the row reports an unknown status.func projectListRowInternal(ctx context.Context, projectsDir string, p Project, snapshot projectContainerSnapshotInternal) project.Details {var resp project.Details- _ = mapper.MapStruct(p, &resp)+ _ = mapping.MapStruct(p, &resp)resp.CreatedAt = p.CreatedAt.Format(time.RFC3339)resp.UpdatedAt = p.UpdatedAt.Format(time.RFC3339)diff --git a/backend/internal/project/project_sync.go b/backend/internal/project/project_sync.goindex 97b364866..24efafd75 100644--- a/backend/internal/project/project_sync.go+++ b/backend/internal/project/project_sync.go@@ -1,18 +1,20 @@package projectimport (+ "cmp""context""log/slog""os""path/filepath"+ "strconv""strings""time""emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -53,10 +55,7 @@ func (s *ProjectService) refreshProjectImageRefsInternal(ctx context.Context, prreturn}imageRefsJSON := projects.MarshalImageRefsJSON(refs)- buildImageRefsJSON := projects.MarshalImageRefsJSON(buildRefs)- if buildImageRefsJSON == "" {- buildImageRefsJSON = "[]"- }+ buildImageRefsJSON := cmp.Or(projects.MarshalImageRefsJSON(buildRefs), "[]")if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", proj.ID).@@ -186,10 +185,7 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPaFirst(&existing).ErrorcomposeMetadata, serviceCountErr := s.loadComposeMetadataForSyncInternal(ctx, dirPath, dirName)- serviceCountLogLevel := slog.LevelWarn- if errors.Is(serviceCountErr, common.ErrProjectEnvUnreadable) {- serviceCountLogLevel = slog.LevelDebug- }+ serviceCountLogLevel := kit.Ternary(errors.Is(serviceCountErr, common.ErrProjectEnvUnreadable), slog.LevelDebug, slog.LevelWarn)if errors.Is(err, gorm.ErrRecordNotFound) {// Create a minimal project entry@@ -476,7 +472,7 @@ func (s *ProjectService) loadComposeMetadataForSyncInternal(ctx context.Context,pathMapper := s.projectPathMapperInternal(ctx)- autoInjectEnv := utils.BoolOrDefault(cfg.AutoInjectEnv.Value, false)+ autoInjectEnv := kit.ParseOrDefault(cfg.AutoInjectEnv.Value, false, strconv.ParseBool)// First, try loading without forcing a project name so compose-go can// resolve COMPOSE_PROJECT_NAME from the .env file. If this fails (e.g.diff --git a/backend/internal/project/project_tags.go b/backend/internal/project/project_tags.goindex dfaf437c1..11213bdcc 100644--- a/backend/internal/project/project_tags.go+++ b/backend/internal/project/project_tags.go@@ -1,17 +1,14 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/event"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""sort""strings""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"projectpkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"gitopstypes "github.com/getarcaneapp/arcane/types/v2/gitops"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"diff --git a/backend/internal/project/project_tags_test.go b/backend/internal/project/project_tags_test.goindex 88d2b2e79..d6999893d 100644--- a/backend/internal/project/project_tags_test.go+++ b/backend/internal/project/project_tags_test.go@@ -1,11 +1,10 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""testing"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/stretchr/testify/require")diff --git a/backend/internal/project/project_update.go b/backend/internal/project/project_update.goindex fcdb3ea85..00f4895f3 100644--- a/backend/internal/project/project_update.go+++ b/backend/internal/project/project_update.go@@ -1,21 +1,20 @@package projectimport (+ "bytes""context""encoding/json/v2"stderrors "errors"+ "fmt"+ "io""log/slog""os""path/filepath"+ "slices""strings""time""unicode/utf8"- "bytes"- "fmt"- "io"- "slices"-"emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -36,7 +35,7 @@ import ("gorm.io/gorm")-func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent, overrideContent *string, user common.User) (*Project, error) {+func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name, composeContent, envContent, overrideContent *string, user common.User) (*Project, error) {proj, projectsDirectory, err := s.getProjectForUpdate(ctx, projectID)if err != nil {return nil, err@@ -117,7 +116,7 @@ func ensureProjectEnvReadableInternal(ctx context.Context, projectsDirectory, pr// the compose file is authoritative over the submitted project name. For// name-only renames, it checks the compose file on disk so the lock can't be// bypassed via the API.-func resolveAuthoritativeProjectNameInternal(ctx context.Context, proj *Project, name *string, composeContent *string) *string {+func resolveAuthoritativeProjectNameInternal(ctx context.Context, proj *Project, name, composeContent *string) *string {if composeContent != nil {if yamlName := projects.ComposeContentProjectName(*composeContent); yamlName != "" {return &yamlName@@ -147,7 +146,7 @@ func (s *ProjectService) prepareProjectUpdateBackupInternal(ctx context.Context,return projects.BackupProjectDirectory(ctx, projectsDirectory, projectPath, ".project-update-backup-*", scope)}-func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context.Context, proj *Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, volumeMigration volumetypes.Migration, renameJournal *projecttypes.RenameJournal, journalActive *bool, projectStateCommitted *bool) (err error) {+func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context.Context, proj *Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, volumeMigration volumetypes.Migration, renameJournal *projecttypes.RenameJournal, journalActive, projectStateCommitted *bool) (err error) {volumeMigrationApplied := falsedefer func() {stateCommitted := projectStateCommitted != nil && *projectStateCommitted@@ -253,7 +252,7 @@ func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Co}}-func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID string, composeContent string, gitEnvContent *string, gitOverrideContent *string, gitOverrideFileName string, user common.User) (*Project, bool, error) {+func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID, composeContent string, gitEnvContent, gitOverrideContent *string, gitOverrideFileName string, user common.User) (*Project, bool, error) {proj, projectsDirectory, err := s.getProjectForUpdate(ctx, projectID)if err != nil {return nil, false, errdiff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.goindex 6549a512f..44d12d26a 100644--- a/backend/internal/project/service_test.go+++ b/backend/internal/project/service_test.go@@ -1,6 +1,7 @@package projectimport (+ "cmp""context""encoding/json""errors"@@ -18,13 +19,12 @@ import ("testing""time"- volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"-composetypes "github.com/compose-spec/compose-go/v2/types"composeapi "github.com/docker/compose/v5/pkg/api""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image"@@ -41,6 +41,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/v2/image"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/libtnb/sqlite"dockerauthconfig "github.com/moby/moby/api/pkg/authconfig""github.com/moby/moby/api/types/container"@@ -55,11 +56,9 @@ import ("go.getarcane.app/acfs"buildtypes "go.getarcane.app/builds/types""go.getarcane.app/updater/labels"+ updatertypes "go.getarcane.app/updater/types""go.uber.org/fx/fxtest""gorm.io/gorm"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- updatertypes "go.getarcane.app/updater/types")type testBuildBuilder struct {@@ -158,7 +157,7 @@ func decodeRegistryAuthInternal(t *testing.T, encoded string) dockerregistry.Autreturn *cfg}-func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[string]dockertypesimage.InspectResponse, onPull func(fullRef string, authHeader string)) *httptest.Server {+func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[string]dockertypesimage.InspectResponse, onPull func(fullRef, authHeader string)) *httptest.Server {t.Helper()server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -875,7 +874,7 @@ func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSuccRepoTags: []string{publicImageRef},RepoDigests: []string{publicRepository + "@" + publicImageDigest},},- }, func(fullRef string, authHeader string) {+ }, func(fullRef, authHeader string) {pullsByRef[fullRef]++authHeadersByRef[fullRef] = authHeader})@@ -1114,7 +1113,7 @@ func TestProjectService_UpdateProjectServicesForcesRecreateInternal(t *testing.TRepoTags: []string{imageRef},RepoDigests: []string{repository + "@" + imageDigest},},- }, func(fullRef string, _ string) {+ }, func(fullRef, _ string) {assert.Equal(t, imageRef, fullRef, "namespace dependents must not be pulled")})@@ -1163,7 +1162,7 @@ func TestProjectService_UpdateProjectServicesForcesRecreateInternal(t *testing.T}upCalled := falseforceRecreate := false- composeUpProjectServicesInternal = func(_ context.Context, selected *composetypes.Project, services []string, removeOrphans bool, force bool, _ bool, _ map[string]dockerregistry.AuthConfig, _ time.Duration) error {+ composeUpProjectServicesInternal = func(_ context.Context, selected *composetypes.Project, services []string, removeOrphans, force, _ bool, _ map[string]dockerregistry.AuthConfig, _ time.Duration) error {assert.True(t, eventService.ShouldSuppressDaemonEvent("container", "replacement", "app", selected.Name))assert.False(t, eventService.ShouldSuppressDaemonEvent("image", "pulled-image", "", ""))upCalled = true@@ -2287,7 +2286,6 @@ services:require.NoError(t, err)require.Len(t, details.IncludeFiles, 1)assert.Equal(t, "metadata.yaml", details.IncludeFiles[0].RelativePath)-}func TestProjectService_CreateProject_AllowsExternalInclude(t *testing.T) {@@ -7539,7 +7537,6 @@ func TestDiscoveredProjectTagUpdatesRemainScoped(t *testing.T) {service.enrichProjectUpdateInfoInternal(t.Context(), &detail)require.False(t, detail.UpdateInfo.HasUpdate, "runtime fallback must not apply a stale policy")}-}func TestProjectTagSummaryDoesNotMutateSharedReferenceResults(t *testing.T) {@@ -7712,7 +7709,6 @@ func TestProjectServiceManualUpdateRejectsUnsafeTagPolicies(t *testing.T) {changes, err := (&ProjectService{}).projectServiceImageChangesInternal(t.Context(), &Project{}, &composetypes.Project{Services: composetypes.Services{"app": local}})require.NoError(t, err)require.Empty(t, changes, "automatic inference must preserve local-build handling")-}func TestConfiguredProjectTagChecksMatchCurrentServicePolicy(t *testing.T) {@@ -7812,9 +7808,7 @@ func TestConfiguredProjectUsesScheduledRuntimeChecks(t *testing.T) {target := "3.2.0"require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "container::scheduled", ContainerID: "scheduled", ImageID: "shared", PolicyKey: imageref.UpdatePolicyKey("example:3.1.0", map[string]string{labels.LabelUpdateStrategy: "auto"}), Repository: "docker.io/library/example", Tag: "3.1.0", LatestVersion: &target, HasUpdate: true, UpdateType: "tag", CheckTime: time.Now()}).Error)runtimeLabels := map[string]string{"com.docker.compose.project": "scheduled-project", "com.docker.compose.service": "web", labels.LabelUpdateStrategy: "auto"}- if tt.runtimeConstraint != "" {- runtimeLabels[labels.LabelUpdateConstraint] = tt.runtimeConstraint- }+ runtimeLabels[labels.LabelUpdateConstraint] = cmp.Or(tt.runtimeConstraint, runtimeLabels[labels.LabelUpdateConstraint])runtime := []projecttypes.RuntimeService{{Name: "web", ContainerID: "scheduled", Image: "example:3.1.0", ContainerLabels: runtimeLabels}}service := &ProjectService{db: db, settingsService: settingsService, imageService: image.NewImageService(db, nil, nil, nil, nil, nil)}detail := projecttypes.Details{ID: proj.ID, Services: []composetypes.ServiceConfig{{Name: "web", Image: tt.sourceRef, Labels: sourceLabels}}, RuntimeServices: runtime}diff --git a/backend/internal/project/service_unix_test.go b/backend/internal/project/service_unix_test.goindex 6815d9a6b..7b327df6b 100644--- a/backend/internal/project/service_unix_test.go+++ b/backend/internal/project/service_unix_test.go@@ -3,14 +3,13 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""os""path/filepath""testing"composetypes "github.com/compose-spec/compose-go/v2/types"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/event"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"diff --git a/backend/internal/project/workspace.go b/backend/internal/project/workspace.goindex cd1f56c22..99f85e758 100644--- a/backend/internal/project/workspace.go+++ b/backend/internal/project/workspace.go@@ -1,10 +1,6 @@package projectimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/event"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""encoding/json/v2""io"@@ -14,16 +10,17 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"acfsutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/acfs"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace""go.getarcane.app/acfs"acfstypes "go.getarcane.app/acfs/types"+ kit "go.getarcane.app/kit/pkg")func (s *ProjectService) GetProjectWorkspace(ctx context.Context, projectID string) (*workspacetypes.Workspace, error) {@@ -190,7 +187,7 @@ func (s *ProjectService) resolveProjectWorkspacePathInternal(ctx context.Contextif err != nil {return nil, "", "", acfstypes.Entry{}, err}- rel, err := utils.NormalizeRelativePath(relativePath)+ rel, err := kit.NormalizeRelativePath(relativePath)if err != nil {return nil, "", "", acfstypes.Entry{}, common.Classify(common.ErrProjectWorkspaceForbidden, errors.WrapIf(err, "invalid project workspace path"))}@@ -278,7 +275,7 @@ func (s *ProjectService) gitOpsOwnedWorkspacePathsInternal(ctx context.Context,owned := make(map[string]struct{})add := func(p string) {- if rel, err := utils.NormalizeRelativePath(p); err == nil {+ if rel, err := kit.NormalizeRelativePath(p); err == nil {owned[rel] = struct{}{}}}@@ -303,14 +300,14 @@ func (s *ProjectService) gitOpsOwnedWorkspacePathsInternal(ctx context.Context,// path a workspace file change can create, overwrite or delete. Shared by the// backup scope and the GitOps ownership check so the two cannot diverge.func workspaceChangeTargetPathsInternal(change projecttypes.WorkspaceFileChange) []string {- rel, err := utils.NormalizeRelativePath(change.RelativePath)+ rel, err := kit.NormalizeRelativePath(change.RelativePath)if err != nil {return nil}paths := []string{rel}switch change.Operation {case projecttypes.FileOpRename:- if newName, nameErr := utils.ValidateFileName(change.NewName); nameErr == nil {+ if newName, nameErr := kit.ValidateFileName(change.NewName); nameErr == nil {paths = append(paths, filepath.ToSlash(filepath.Join(filepath.Dir(rel), newName)))}case projecttypes.FileOpMove:diff --git a/backend/internal/registry/browse.go b/backend/internal/registry/browse.goindex ebf8c52a8..025303483 100644--- a/backend/internal/registry/browse.go+++ b/backend/internal/registry/browse.go@@ -9,17 +9,16 @@ import ("sync""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/google/go-containerregistry/pkg/authn""github.com/google/go-containerregistry/pkg/name"v1 "github.com/google/go-containerregistry/pkg/v1""github.com/google/go-containerregistry/pkg/v1/remote""github.com/google/go-containerregistry/pkg/v1/remote/transport""golang.org/x/sync/errgroup"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"- "github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- "github.com/getarcaneapp/arcane/types/v2/containerregistry")const tagDetailsConcurrency = 4diff --git a/backend/internal/registry/handler.go b/backend/internal/registry/handler.goindex 107511f19..942c0c460 100644--- a/backend/internal/registry/handler.go+++ b/backend/internal/registry/handler.go@@ -1,19 +1,19 @@package registryimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""log/slog""strings""emperror.dev/errors""github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/containerregistry"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto")@@ -309,10 +309,8 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Testreturn nil, huma.Error400BadRequest(errors.WithMessage(err, "Registry test failed").Error())}- msg := "Authentication succeeded"- if strings.TrimSpace(reg.Username) == "" && strings.TrimSpace(decryptedToken) == "" {- msg = "Registry saved (no credentials to test)"- }+ noCredentials := strings.TrimSpace(reg.Username) == "" && strings.TrimSpace(decryptedToken) == ""+ msg := kit.Ternary(noCredentials, "Registry saved (no credentials to test)", "Authentication succeeded")return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{diff --git a/backend/internal/registry/model.go b/backend/internal/registry/model.goindex da99f5cae..4b0fac449 100644--- a/backend/internal/registry/model.go+++ b/backend/internal/registry/model.go@@ -1,9 +1,9 @@package registryimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database")type ContainerRegistry struct {diff --git a/backend/internal/registry/module.go b/backend/internal/registry/module.goindex 2a9540863..97a1ad783 100644--- a/backend/internal/registry/module.go+++ b/backend/internal/registry/module.go@@ -6,7 +6,6 @@ import ("context""github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/kv"diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.goindex 4b2d29e45..6b9f3035a 100644--- a/backend/internal/registry/service.go+++ b/backend/internal/registry/service.go@@ -9,16 +9,10 @@ import ("strings""time"- "go.getarcane.app/kit/normalization"-- "github.com/cenkalti/backoff/v5"- ref "github.com/distribution/reference"- "github.com/samber/hot"- "github.com/samber/mo"- "golang.org/x/sync/singleflight"-"emperror.dev/errors"+ "github.com/cenkalti/backoff/v5"cerrdefs "github.com/containerd/errdefs"+ ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/kv"@@ -33,10 +27,15 @@ import ("github.com/google/go-containerregistry/pkg/v1/remote/transport"dockerregistry "github.com/moby/moby/api/types/registry""github.com/moby/moby/client"+ "github.com/samber/hot"+ "github.com/samber/mo"+ "go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""go.getarcane.app/updater/digest""go.getarcane.app/updater/refs""go.getarcane.app/updater/registry"+ "golang.org/x/sync/singleflight""gorm.io/gorm")@@ -521,11 +520,7 @@ func (s *ContainerRegistryService) GetAllRegistryAuthConfigs(ctx context.Context}}- if len(authConfigs) == 0 {- return nil, nil- }-- return authConfigs, nil+ return kit.Ternary(len(authConfigs) == 0, nil, authConfigs), nil}// RecordImagePull increments Arcane's observed successful pull counter for an image registry.@@ -760,10 +755,7 @@ func registryProviderInternal(registryHost, registryType string) string {if registryType == RegistryTypeECR {return "ecr"}- if registryHost == "docker.io" {- return "dockerhub"- }- return "generic"+ return kit.Ternary(registryHost == "docker.io", "dockerhub", "generic")}func registryDisplayNameInternal(registryHost, registryType string) string {@@ -1299,7 +1291,7 @@ func NormalizeRegistryType(value string) (string, error) {// entries (preserving first-occurrence order) and validates what remains. It// returns a non-nil slice so that GORM always serializes to a JSON array.func normalizeRepositoryNamesInternal(raw []string) (database.StringSlice, error) {- names := utils.UniqueNonEmptyStrings(raw)+ names := kit.Unique(kit.TrimNonEmpty(raw))result := make(database.StringSlice, 0, len(names))for _, name := range names {// A repository name is only a path, so pair it with placeholder domaindiff --git a/backend/internal/registry/service_label.go b/backend/internal/registry/service_label.goindex 2b8007d0a..c85113c77 100644--- a/backend/internal/registry/service_label.go+++ b/backend/internal/registry/service_label.go@@ -7,11 +7,10 @@ import ("time""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/google/go-containerregistry/pkg/name"v1 "github.com/google/go-containerregistry/pkg/v1""github.com/google/go-containerregistry/pkg/v1/remote"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts")const (diff --git a/backend/internal/registry/service_test.go b/backend/internal/registry/service_test.goindex 9f110a13f..feb6bd551 100644--- a/backend/internal/registry/service_test.go+++ b/backend/internal/registry/service_test.go@@ -916,7 +916,8 @@ func TestContainerRegistryService_InspectImageDigest_UsesStoredCredentialsInsteaif options.EncodedRegistryAuth == "" {anonymousCalls++return client.DistributionInspectResult{}, errors.New(- "Error response from daemon: toomanyrequests: retry-after: 1.246809ms, allowed: 44000/minute")+ "Error response from daemon: toomanyrequests: retry-after: 1.246809ms, allowed: 44000/minute",+ )}return client.DistributionInspectResult{@@ -980,7 +981,8 @@ func TestContainerRegistryService_InspectImageDigest_DoesNotFallBackToAnonymousOanonymousCalls++}return client.DistributionInspectResult{}, errors.New(- "Error response from daemon: toomanyrequests: retry-after: 1.246809ms, allowed: 44000/minute")+ "Error response from daemon: toomanyrequests: retry-after: 1.246809ms, allowed: 44000/minute",+ )},}, nil}, nil)diff --git a/backend/internal/role/model.go b/backend/internal/role/model.goindex f3bbfbec7..eb05608a1 100644--- a/backend/internal/role/model.go+++ b/backend/internal/role/model.go@@ -32,10 +32,14 @@ type UserRoleAssignment struct {func (UserRoleAssignment) TableName() string { return "user_role_assignments" }-// Assignment source values stored in UserRoleAssignment.Source.const (+ // Assignment source values stored in UserRoleAssignment.Source.+RoleAssignmentSourceManual = "manual"RoleAssignmentSourceOidc = "oidc"++ OidcMappingSourceManual = "manual"+ OidcMappingSourceEnv = "env")// ApiKeyPermission is one permission grant on an API key, optionally scoped to@@ -71,8 +75,3 @@ type OidcRoleMapping struct {}func (OidcRoleMapping) TableName() string { return "oidc_role_mappings" }--const (- OidcMappingSourceManual = "manual"- OidcMappingSourceEnv = "env"-)diff --git a/backend/internal/role/service.go b/backend/internal/role/service.goindex fcbb750aa..c9fe0278b 100644--- a/backend/internal/role/service.go+++ b/backend/internal/role/service.go@@ -4,16 +4,12 @@ import ("context""encoding/json/v2""log/slog"+ "maps"+ "slices""strings""time"- "go.getarcane.app/kit/normalization"-"emperror.dev/errors"-- "gorm.io/gorm"- "gorm.io/gorm/clause"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/kv"@@ -23,12 +19,20 @@ import (roletypes "github.com/getarcaneapp/arcane/types/v2/role""github.com/samber/hot""github.com/samber/mo"+ "go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg"+ "gorm.io/gorm"+ "gorm.io/gorm/clause")-// permissionCacheTTL bounds how long a resolved PermissionSet is reused-// before re-querying the DB. The service also invalidates entries explicitly-// on mutation paths, so this TTL is a safety net.-const permissionCacheTTL = 60 * time.Second+const (+ // permissionCacheTTL bounds how long a resolved PermissionSet is reused+ // before re-querying the DB. The service also invalidates entries explicitly+ // on mutation paths, so this TTL is a safety net.+ permissionCacheTTL = 60 * time.Second++ legacyRoleBackfillCompletedKey = "migration.legacy_user_roles.v1.completed"+)// RoleService owns role definitions, user role assignments, OIDC role// mappings, and API key permissions. It resolves a caller's effective@@ -89,8 +93,6 @@ func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error {})}-const legacyRoleBackfillCompletedKey = "migration.legacy_user_roles.v1.completed"-// BackfillLegacyRoleAssignments converts pre-RBAC users.roles into global assignments once, gated by a kv marker committed with the rows.func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {migrator := s.db.WithContext(ctx).Migrator()@@ -119,10 +121,7 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {return errors.WrapIf(err, "failed to read legacy users.roles for backfill")}for _, u := range rows {- roleID := authz.BuiltInRoleViewer- if legacyRolesContainsAdminInternal(u.Roles) {- roleID = authz.BuiltInRoleAdmin- }+ roleID := kit.Ternary(legacyRolesContainsAdminInternal(u.Roles), authz.BuiltInRoleAdmin, authz.BuiltInRoleViewer)assignment := UserRoleAssignment{UserID: u.ID,RoleID: roleID,@@ -449,10 +448,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment)}if len(roleIDSet) > 0 {- roleIDs := make([]string, 0, len(roleIDSet))- for id := range roleIDSet {- roleIDs = append(roleIDs, id)- }+ roleIDs := slices.Collect(maps.Keys(roleIDSet))var found []stringif err := tx.Model(&Role{}).Where("id IN ?", roleIDs).Pluck("id", &found).Error; err != nil {return errors.WrapIf(err, "failed to verify role ids")@@ -469,10 +465,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment)}if len(envIDSet) > 0 {- envIDs := make([]string, 0, len(envIDSet))- for id := range envIDSet {- envIDs = append(envIDs, id)- }+ envIDs := slices.Collect(maps.Keys(envIDSet))var found []stringif err := tx.Table("environments").Where("id IN ?", envIDs).Pluck("id", &found).Error; err != nil {return errors.WrapIf(err, "failed to verify environment ids")@@ -762,10 +755,7 @@ func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {roleIDSet[roleID] = struct{}{}}- normalized := make([]string, 0, len(roleIDSet))- for roleID := range roleIDSet {- normalized = append(normalized, roleID)- }+ normalized := slices.Collect(maps.Keys(roleIDSet))var found []stringif err := tx.Model(&Role{}).Where("id IN ?", normalized).Pluck("id", &found).Error; err != nil {return errors.WrapIf(err, "failed to verify role ids")diff --git a/backend/internal/role/service_test.go b/backend/internal/role/service_test.goindex b07e05b9b..be513af6a 100644--- a/backend/internal/role/service_test.go+++ b/backend/internal/role/service_test.go@@ -1,10 +1,6 @@package roleimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/session"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"context""path/filepath""slices"@@ -14,6 +10,8 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/libtnb/sqlite""github.com/stretchr/testify/require"diff --git a/backend/internal/s3/handler.go b/backend/internal/s3/handler.goindex b65bebb73..dd8a1ccb7 100644--- a/backend/internal/s3/handler.go+++ b/backend/internal/s3/handler.go@@ -6,7 +6,6 @@ import ("net/http""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/internal/s3/service.go b/backend/internal/s3/service.goindex d744bb7fa..e15ff744a 100644--- a/backend/internal/s3/service.go+++ b/backend/internal/s3/service.go@@ -5,16 +5,14 @@ import ("fmt""strings"- "go.getarcane.app/kit/normalization"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"s3config "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/s3"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup""github.com/samber/mo"+ "go.getarcane.app/kit/normalization""go.getarcane.app/sys/crypto""gorm.io/gorm")diff --git a/backend/internal/s3/service_test.go b/backend/internal/s3/service_test.goindex fca44df8c..4347e20a2 100644--- a/backend/internal/s3/service_test.go+++ b/backend/internal/s3/service_test.go@@ -17,6 +17,7 @@ import (backuptypes "github.com/getarcaneapp/arcane/types/v2/backup""github.com/libtnb/sqlite""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""gorm.io/gorm")@@ -320,10 +321,7 @@ func TestS3DestinationService_TestS3DestinationRoundTrip(t *testing.T) {Name: "Metadata destination", Endpoint: metadataServer.URL, Bucket: "arcane-backups",AccessKeyID: "test-access", SecretAccessKey: "test-secret", Prefix: "production", ForcePathStyle: true,}- requestedID := snapshotID- if scenario.configOnly {- requestedID = ""- }+ requestedID := kit.Ternary(scenario.configOnly, "", snapshotID)observation, checkErr := s3config.CheckRepository(t.Context(), configuration, "repository", requestedID)if scenario.wantError {require.Error(t, checkErr)diff --git a/backend/internal/search/metadata.go b/backend/internal/search/metadata.goindex 501e1f4a2..804a4b852 100644--- a/backend/internal/search/metadata.go+++ b/backend/internal/search/metadata.go@@ -1,6 +1,7 @@package searchimport (+ "cmp""reflect""slices""sort"@@ -10,6 +11,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/category""github.com/getarcaneapp/arcane/types/v2/meta"searchtypes "github.com/getarcaneapp/arcane/types/v2/search"+ kit "go.getarcane.app/kit/pkg")// BuildCategories extracts searchable metadata in model field order.@@ -28,14 +30,8 @@ func BuildCategories[T any](profile searchtypes.Profile) []category.Category {}metaTag := utils.ParseMetaTag(field.Tag.Get("meta"))- label := metaTag["label"]- if label == "" {- label = key- }- typ := metaTag["type"]- if typ == "" {- typ = "text"- }+ label := cmp.Or(metaTag["label"], key)+ typ := cmp.Or(metaTag["type"], "text")desc := metaTag["description"]keywords := utils.ParseKeywords(metaTag["keywords"])categoryID := metaTag["category"]@@ -44,10 +40,7 @@ func BuildCategories[T any](profile searchtypes.Profile) []category.Category {categoryID = catMeta["id"]}if categoryID == "" {- categoryID = "defaults"- if profile == searchtypes.SettingsProfile {- categoryID = "jobs"- }+ categoryID = kit.Ternary(profile == searchtypes.SettingsProfile, "jobs", "defaults")}if categoryID == "internal" && profile == searchtypes.SettingsProfile {diff --git a/backend/internal/session/model.go b/backend/internal/session/model.goindex 207e5b190..6e21ea292 100644--- a/backend/internal/session/model.go+++ b/backend/internal/session/model.go@@ -1,11 +1,10 @@package sessionimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"-- "time")const (@@ -13,6 +12,11 @@ const (UserSessionSourceOidc = "oidc"UserSessionSourceFederated = "federated"UserSessionSourcePasskey = "passkey"++ // PasskeyMFAMethod and RecoveryCodeMFAMethod name the second factor a login+ // completed with, recorded on the session for auditing.+ PasskeyMFAMethod = "passkey"+ RecoveryCodeMFAMethod = "recovery_code")type UserSession struct {@@ -37,10 +41,3 @@ type UserSession struct {func (UserSession) TableName() string {return "user_sessions"}--const (- // PasskeyMFAMethod and RecoveryCodeMFAMethod name the second factor a login- // completed with, recorded on the session for auditing.- PasskeyMFAMethod = "passkey"- RecoveryCodeMFAMethod = "recovery_code"-)diff --git a/backend/internal/session/service.go b/backend/internal/session/service.goindex 1345dd93d..630c0f106 100644--- a/backend/internal/session/service.go+++ b/backend/internal/session/service.go@@ -1,21 +1,20 @@package sessionimport (+ "cmp""context"- "crypto/sha256""crypto/subtle"- "encoding/hex""strings""time""uuid""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2/auth""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -29,13 +28,10 @@ func NewSessionService(db *database.DB) *SessionService {func (s *SessionService) CreateSession(ctx context.Context, userID string, expiresAt time.Time, meta auth.SessionMeta) (*UserSession, string, error) {refreshJTI := uuid.New().String()- refreshHash := hashRefreshJTIInternal(refreshJTI)+ refreshHash := kit.SHA256Hex(refreshJTI)now := time.Now()- source := strings.TrimSpace(meta.Source)- if source == "" {- source = UserSessionSourceLocal- }+ source := cmp.Or(strings.TrimSpace(meta.Source), UserSessionSourceLocal)session := &UserSession{UserID: userID,RefreshTokenHash: refreshHash,@@ -56,7 +52,7 @@ func (s *SessionService) CreateSession(ctx context.Context, userID string, expir}func (s *SessionService) CreateFederatedSession(ctx context.Context, userID string, expiresAt time.Time, credentialID string) (*UserSession, error) {- refreshHash := hashRefreshJTIInternal(uuid.New().String())+ refreshHash := kit.SHA256Hex(uuid.New().String())now := time.Now()session := &UserSession{@@ -90,13 +86,13 @@ func (s *SessionService) GetSessionByID(ctx context.Context, sessionID string) (return &session, nil}-func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID string, refreshJTI string, meta auth.SessionMeta) (*UserSession, string, error) {+func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID, refreshJTI string, meta auth.SessionMeta) (*UserSession, string, error) {if strings.TrimSpace(sessionID) == "" || strings.TrimSpace(refreshJTI) == "" {return nil, "", common.ErrInvalidToken}newRefreshJTI := uuid.New().String()- newHash := hashRefreshJTIInternal(newRefreshJTI)+ newHash := kit.SHA256Hex(newRefreshJTI)now := time.Now()var rotated UserSession@@ -112,7 +108,7 @@ func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID strinif err := ValidateActive(&session); err != nil {return err}- if subtle.ConstantTimeCompare([]byte(session.RefreshTokenHash), []byte(hashRefreshJTIInternal(refreshJTI))) != 1 {+ if subtle.ConstantTimeCompare([]byte(session.RefreshTokenHash), []byte(kit.SHA256Hex(refreshJTI))) != 1 {return common.ErrInvalidToken}@@ -174,11 +170,6 @@ func (s *SessionService) DeleteExpiredSessions(ctx context.Context, revokedRetenreturn result.RowsAffected, nil}-func hashRefreshJTIInternal(jti string) string {- sum := sha256.Sum256([]byte(jti))- return hex.EncodeToString(sum[:])-}-// RevokeAllUserSessionsExcept revokes every active session for userID, leaving// exceptSessionID active. Pass "" to revoke all sessions.func (s *SessionService) RevokeAllUserSessionsExcept(ctx context.Context, userID, exceptSessionID string) error {@@ -211,8 +202,5 @@ func ValidateActive(userSession *UserSession) error {if userSession.RevokedAt != nil {return common.Classify(common.ErrSessionRevoked, errors.New("Session has been revoked"))}- if time.Now().After(userSession.ExpiresAt) {- return common.ErrExpiredToken- }- return nil+ return kit.Ternary[error](time.Now().After(userSession.ExpiresAt), common.ErrExpiredToken, nil)}diff --git a/backend/internal/session/service_test.go b/backend/internal/session/service_test.goindex 8464c4728..f4c8aaf48 100644--- a/backend/internal/session/service_test.go+++ b/backend/internal/session/service_test.go@@ -1,19 +1,18 @@package sessionimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/role"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"context""testing""time""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/role"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/types/v2/auth""github.com/libtnb/sqlite""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -33,7 +32,7 @@ func TestSessionService_RotateRefreshTokenRequiresCurrentHash(t *testing.T) {require.NoError(t, err)require.NotEmpty(t, newJTI)require.NotEqual(t, refreshJTI, newJTI)- require.Equal(t, hashRefreshJTIInternal(newJTI), rotated.RefreshTokenHash)+ require.Equal(t, kit.SHA256Hex(newJTI), rotated.RefreshTokenHash)_, _, err = sessionSvc.RotateRefreshToken(ctx, session.ID, refreshJTI, auth.SessionMeta{})require.ErrorIs(t, err, common.ErrInvalidToken)diff --git a/backend/internal/settings/features.go b/backend/internal/settings/features.goindex b4ff69a2d..c9bf54d54 100644--- a/backend/internal/settings/features.go+++ b/backend/internal/settings/features.go@@ -7,6 +7,7 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/types/v2/features"+ kit "go.getarcane.app/kit/pkg")// IsFeatureEnabled resolves feature availability on this environment.@@ -24,10 +25,7 @@ func (s *SettingsService) IsFeatureEnabled(ctx context.Context, id features.ID)return definition.DefaultEnabled}enabled, err := strconv.ParseBool(value)- if err != nil {- return definition.DefaultEnabled- }- return enabled+ return kit.Ternary(err != nil, definition.DefaultEnabled, enabled)}// RequireFeature rejects operations when their runtime feature is disabled.diff --git a/backend/internal/settings/handler.go b/backend/internal/settings/handler.goindex 25b2c7314..8c870122c 100644--- a/backend/internal/settings/handler.go+++ b/backend/internal/settings/handler.go@@ -1,8 +1,6 @@package settingsimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""fmt""net/http"@@ -11,8 +9,8 @@ import ("strings""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/search"@@ -20,12 +18,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace""github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/category"searchtypes "github.com/getarcaneapp/arcane/types/v2/search"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""go.yaml.in/yaml/v4")@@ -283,8 +282,8 @@ func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublisettingsList := h.settingsService.ListSettings(SettingVisibilityPublic)- var settingsDto []settingstypes.PublicSetting- if err := mapper.MapStructList(settingsList, &settingsDto); err != nil {+ settingsDto, err := mapping.MapSlice[SettingVariable, settingstypes.PublicSetting](settingsList)+ if err != nil {return nil, huma.Error500InternalServerError("Failed to map settings")}@@ -295,10 +294,7 @@ func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublifunc (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInput) (*GetSettingsOutput, error) {ps, _ := middleware.PermissionsFromContext(ctx)isAdmin := ps.IsGlobalAdmin()- visibility := SettingVisibilityNonAdmin- if isAdmin {- visibility = SettingVisibilityAll- }+ visibility := kit.Ternary(isAdmin, SettingVisibilityAll, SettingVisibilityNonAdmin)if input.EnvironmentID != "0" {settingsDto, err := h.proxyRemoteJSON.JSON[[]settingstypes.PublicSetting](ctx, input.EnvironmentID, http.MethodGet, "/api/environments/0/settings", nil)@@ -325,8 +321,8 @@ func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInpsettingsList := h.settingsService.ListSettings(visibility)- var settingsDto []settingstypes.PublicSetting- if err := mapper.MapStructList(settingsList, &settingsDto); err != nil {+ settingsDto, err := mapping.MapSlice[SettingVariable, settingstypes.PublicSetting](settingsList)+ if err != nil {return nil, huma.Error500InternalServerError("Failed to map settings")}diff --git a/backend/internal/settings/model.go b/backend/internal/settings/model.goindex 53becf70c..5b25e387f 100644--- a/backend/internal/settings/model.go+++ b/backend/internal/settings/model.go@@ -9,9 +9,14 @@ import ("time""emperror.dev/errors"+ kit "go.getarcane.app/kit/pkg")const (+ SettingVisibilityPublic SettingVisibility = 0+ SettingVisibilityNonAdmin SettingVisibility = 1+ SettingVisibilityAll SettingVisibility = 2+redactionMask = "XXXXXXXXXX")@@ -22,12 +27,6 @@ type SettingVariable struct {type SettingVisibility int-const (- SettingVisibilityPublic SettingVisibility = iota- SettingVisibilityNonAdmin- SettingVisibilityAll-)-type settingFieldMeta struct {index intkey string@@ -58,10 +57,7 @@ func (s SettingVariable) AsInt() int {// AsDurationSeconds returns the value as a time.Duration in secondsfunc (s SettingVariable) AsDurationSeconds() time.Duration {val, err := strconv.Atoi(s.Value)- if err != nil {- return 0- }- return time.Duration(val) * time.Second+ return kit.Ternary(err != nil, 0, time.Duration(val)*time.Second)}type Settings struct {@@ -277,7 +273,7 @@ func (s *Settings) ToSettingVariableSlice(visibility SettingVisibility, redactSe}value := cfgValue.Field(field.index).FieldByName("Value").String()- value = redactSettingValue(value, field.attrs, redactSensitiveValues)+ value = kit.Ternary(value == "" || !redactSensitiveValues || !strings.Contains(field.attrs, "sensitive"), value, redactionMask)settingVariable := SettingVariable{Key: field.key,@@ -302,7 +298,7 @@ func fieldVisibleForSettingVisibilityInternal(field settingFieldMeta, visibility}}-func (s *Settings) FieldByKey(key string) (defaultValue string, isPublic bool, isSensitive bool, err error) {+func (s *Settings) FieldByKey(key string) (defaultValue string, isPublic, isSensitive bool, err error) {rv := reflect.ValueOf(s).Elem()_, byKey := getSettingsFieldCacheInternal()@@ -315,7 +311,7 @@ func (s *Settings) FieldByKey(key string) (defaultValue string, isPublic bool, ireturn valueField.String(), field.isPublic, field.isSensitive, nil}-func (s *Settings) UpdateField(key string, value string, noSensitive bool) error {+func (s *Settings) UpdateField(key, value string, noSensitive bool) error {rv := reflect.ValueOf(s).Elem()_, byKey := getSettingsFieldCacheInternal()@@ -337,15 +333,6 @@ func (s *Settings) UpdateField(key string, value string, noSensitive bool) errorreturn nil}-// helper keeps redaction logic in one place; behavior unchanged-func redactSettingValue(value, attrs string, redact bool) string {- if value == "" || !redact || !strings.Contains(attrs, "sensitive") {- return value- }-- return redactionMask-}-type SettingKeyNotFoundError struct {field string}diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.goindex 0cd93393a..15213b068 100644--- a/backend/internal/settings/service.go+++ b/backend/internal/settings/service.go@@ -8,6 +8,7 @@ import ("encoding/base64""fmt""log/slog"+ "maps""os""path/filepath""reflect"@@ -18,15 +19,7 @@ import ("time""uuid"- "go.getarcane.app/kit/normalization"-"emperror.dev/errors"-- "github.com/samber/mo"- "gorm.io/gorm"-- libcrypto "go.getarcane.app/sys/crypto"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -37,6 +30,11 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"+ "github.com/samber/mo"+ "go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg"+ libcrypto "go.getarcane.app/sys/crypto"+ "gorm.io/gorm")const (@@ -376,7 +374,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *datcontinue}- envVarName := strings.ToUpper(utils.CamelCaseToSnakeCase(key))+ envVarName := strings.ToUpper(kit.SnakeCase(key))// debug: log each env name checked and whether a value existsif val, ok, _ := utils.LookupEnvOrFile(envVarName); ok {@@ -385,7 +383,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *datmask = fmt.Sprintf("%d chars", len(val))}slog.DebugContext(ctx, "loadDatabaseConfigFromEnv: env override found", "key", key, "env", envVarName, "valueMasked", mask)- rv.Field(i).FieldByName("Value").SetString(utils.TrimQuotes(val))+ rv.Field(i).FieldByName("Value").SetString(kit.TrimQuotes(val))continue}if val, ok := settingsMap[key]; ok {@@ -439,13 +437,13 @@ func resolveSettingsEnvOverridesInternal() []settingsEnvOverride {continue}- envVarName := strings.ToUpper(utils.CamelCaseToSnakeCase(key))+ envVarName := strings.ToUpper(kit.SnakeCase(key))if val, ok, _ := utils.LookupEnvOrFile(envVarName); ok && val != "" {overrides = append(overrides, settingsEnvOverride{fieldIndex: i,key: key,envVarName: envVarName,- value: utils.TrimQuotes(val),+ value: kit.TrimQuotes(val),})}}@@ -476,16 +474,13 @@ func (s *SettingsService) GetSettings(ctx context.Context) (*Settings, error) {// GetSettingsOrDefaults is a convenience for hot paths that need a snapshot but cannot// meaningfully recover from a settings load failure. It logs any error and guarantees a// non-nil *Settings (defaults: a zero-valued struct, which the SettingVariable helpers-// like utils.BoolOrDefault treat as "use the caller's default").+// like kit.ParseOrDefault treat as "use the caller's default").func (s *SettingsService) GetSettingsOrDefaults(ctx context.Context) *Settings {cfg, err := s.GetSettings(ctx)if err != nil {slog.WarnContext(ctx, "failed to load settings, falling back to defaults", "error", err)}- if cfg == nil {- return &Settings{}- }- return cfg+ return kit.Ternary(cfg == nil, &Settings{}, cfg)}func (s *SettingsService) getEffectiveSettingsConfigInternal(ctx context.Context) *Settings {@@ -810,10 +805,7 @@ func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {return actors.NoPayload{}, nil}- keys := make([]string, 0, len(allowedKeys))- for key := range allowedKeys {- keys = append(keys, key)- }+ keys := slices.Collect(maps.Keys(allowedKeys))result := s.db.WithContext(writeCtx).Where("key NOT IN ?", keys).Delete(&SettingVariable{})if result.Error != nil {@@ -873,12 +865,12 @@ func (s *SettingsService) processEnvField(ctx context.Context, tx *gorm.DB, fielreturn nil}- envVarName := strings.ToUpper(utils.CamelCaseToSnakeCase(key))+ envVarName := strings.ToUpper(kit.SnakeCase(key))envVal, ok, _ := utils.LookupEnvOrFile(envVarName)if !ok {return nil}- envVal = utils.TrimQuotes(envVal)+ envVal = kit.TrimQuotes(envVal)return s.upsertEnvSetting(ctx, tx, key, envVal)}@@ -889,11 +881,7 @@ func (s *SettingsService) shouldProcessField(key, attrs string, isEnvOnlyMode bo}// If not in env-only mode, only persist if it's explicitly marked as envOverride- if !isEnvOnlyMode && !strings.Contains(attrs, "envOverride") {- return false- }-- return true+ return isEnvOnlyMode || strings.Contains(attrs, "envOverride")}func (s *SettingsService) upsertEnvSetting(ctx context.Context, tx *gorm.DB, key, envVal string) error {@@ -1002,12 +990,10 @@ func (s *SettingsService) SetStringSetting(ctx context.Context, key, value strin// is added to the list; when false it is removed.func (s *SettingsService) SetContainerAutoUpdateExclusionInternal(ctx context.Context, containerName string, excluded bool) error {_, err := s.writes.Execute(ctx, "update container auto-update exclusion", func(writeCtx context.Context) (actors.NoPayload, error) {- ordered := utils.UniqueNonEmptyStrings(strings.Split(s.GetStringSetting(writeCtx, "autoUpdateExcludedContainers", ""), ","))+ ordered := kit.Unique(kit.TrimNonEmpty(strings.Split(s.GetStringSetting(writeCtx, "autoUpdateExcludedContainers", ""), ",")))if excluded {- if !slices.Contains(ordered, containerName) {- ordered = append(ordered, containerName)- }+ ordered = kit.Unique(append(ordered, containerName))} else {filtered := ordered[:0]for _, name := range ordered {@@ -1182,7 +1168,7 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projecfunc (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {const buildsKey = "buildsDirectory"- envVarName := strings.ToUpper(utils.CamelCaseToSnakeCase(buildsKey))+ envVarName := strings.ToUpper(kit.SnakeCase(buildsKey))if envVal, ok, _ := utils.LookupEnvOrFile(envVarName); ok && strings.TrimSpace(envVal) != "" {slog.DebugContext(ctx, "BUILDS_DIRECTORY environment variable is set, skipping normalization", "value", envVal)return nildiff --git a/backend/internal/settings/service_test.go b/backend/internal/settings/service_test.goindex 7e32d8f81..467d92446 100644--- a/backend/internal/settings/service_test.go+++ b/backend/internal/settings/service_test.go@@ -10,18 +10,17 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- libcrypto "go.getarcane.app/sys/crypto"- "go.uber.org/fx/fxtest"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/require"+ libcrypto "go.getarcane.app/sys/crypto"+ "go.uber.org/fx/fxtest"+ "gorm.io/gorm")func setupSettingsTestDB(t *testing.T) *database.DB {diff --git a/backend/internal/swarm/easy_join.go b/backend/internal/swarm/easy_join.goindex e0245dfe2..5009fdb64 100644--- a/backend/internal/swarm/easy_join.go+++ b/backend/internal/swarm/easy_join.go@@ -7,6 +7,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"+ kit "go.getarcane.app/kit/pkg")// GetJoinCandidates lists environments available to join the selected manager.@@ -51,10 +52,7 @@ func (s *SwarmService) GetJoinCandidates(ctx context.Context, environmentID striif _, bound := boundEnvironmentIDs[candidate.ID]; bound {continue}- environmentType := "direct"- if candidate.IsEdge {- environmentType = "edge"- }+ environmentType := kit.Ternary(candidate.IsEdge, "edge", "direct")candidates = append(candidates, swarmtypes.SwarmJoinCandidate{EnvironmentID: candidate.ID,EnvironmentName: candidate.Name,diff --git a/backend/internal/swarm/handler.go b/backend/internal/swarm/handler.goindex c79c4b75f..695f378b7 100644--- a/backend/internal/swarm/handler.go+++ b/backend/internal/swarm/handler.go@@ -1,8 +1,7 @@package swarmimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-+ "cmp""context""log/slog""maps"@@ -15,6 +14,7 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"@@ -1615,10 +1615,7 @@ func (h *SwarmHandler) auditSwarmMutation(ctx context.Context, environmentID, acresourceNamePtr = new(resourceName)}- env := strings.TrimSpace(environmentID)- if env == "" {- env = "0"- }+ env := cmp.Or(strings.TrimSpace(environmentID), "0")envPtr := &envmeta := database.JSON{"action": action}diff --git a/backend/internal/swarm/module.go b/backend/internal/swarm/module.goindex e6d14456b..b179a23b5 100644--- a/backend/internal/swarm/module.go+++ b/backend/internal/swarm/module.go@@ -3,7 +3,6 @@ package swarmimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event"diff --git a/backend/internal/swarm/swarm.go b/backend/internal/swarm/swarm.goindex 3a70e77bd..56a832f54 100644--- a/backend/internal/swarm/swarm.go+++ b/backend/internal/swarm/swarm.go@@ -2,29 +2,31 @@ package swarmimport ("bytes"+ "cmp""context"stdjson "encoding/json""encoding/json/v2""fmt""io/fs""log/slog"+ "maps""net/http""net/netip""path""path/filepath"+ "slices""sort""strings""sync""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-"emperror.dev/errors"cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/kv"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"@@ -41,6 +43,7 @@ import ("github.com/samber/hot""go.getarcane.app/acfs"acfstypes "go.getarcane.app/acfs/types"+ kit "go.getarcane.app/kit/pkg""golang.org/x/sync/errgroup")@@ -49,6 +52,11 @@ const (swarmNodeIdentityCacheTTL = 30 * time.SecondKVKeySwarmEnabled = "swarm.enabled"defaultSwarmListenAddr = "0.0.0.0:2377"++ defaultSwarmStackSourceRootDir = "/app/data/swarm/sources"+ swarmStackComposeFilename = "compose.yaml"+ swarmStackOverrideFilename = "compose.override.yaml"+ swarmStackEnvFilename = ".env")// SwarmService provides Docker Swarm related operations.@@ -246,11 +254,7 @@ func (s *SwarmService) resolveServiceNodeNamesInternal(ctx context.Context, dock}}- nodeNames := make([]string, 0, len(nodeSet))- for name := range nodeSet {- nodeNames = append(nodeNames, name)- }- sort.Strings(nodeNames)+ nodeNames := slices.Sorted(maps.Keys(nodeSet))return nodeNames}@@ -285,9 +289,7 @@ func (s *SwarmService) enrichServiceNetworkDetailsInternal(ConfigOnly: networkInfo.ConfigOnly,Options: networkInfo.Options,}- if networkInfo.ConfigFrom.Network != "" {- detail.ConfigFrom = networkInfo.ConfigFrom.Network- }+ detail.ConfigFrom = cmp.Or(networkInfo.ConfigFrom.Network, detail.ConfigFrom)for _, ipamCfg := range networkInfo.IPAM.Config {detail.IPAMConfigs = append(detail.IPAMConfigs, toServiceNetworkIPAMConfigInternal(ipamCfg))@@ -651,11 +653,7 @@ func (s *SwarmService) GetLocalNodeIdentity(ctx context.Context) (*SwarmNodeIdenswarmActive := swarmInfo.Swarm.LocalNodeState == swarm.LocalNodeStateActive && strings.TrimSpace(swarmInfo.Swarm.NodeID) != ""role := ""if swarmActive {- if swarmInfo.Swarm.ControlAvailable {- role = "manager"- } else {- role = "worker"- }+ role = kit.Ternary(swarmInfo.Swarm.ControlAvailable, "manager", "worker")}return &SwarmNodeIdentity{@@ -812,10 +810,7 @@ func preferredNodeAgentEnvironmentInternal(environments []environment.Environmenfunc buildNodeAgentCandidatesInternal(environments []environment.Environment) []swarmtypes.NodeAgentCandidate {candidates := make([]swarmtypes.NodeAgentCandidate, 0, len(environments))for _, environment := range environments {- environmentType := "direct"- if environment.IsEdge {- environmentType = "edge"- }+ environmentType := kit.Ternary(environment.IsEdge, "edge", "direct")candidates = append(candidates, swarmtypes.NodeAgentCandidate{EnvironmentID: environment.ID,EnvironmentName: environment.Name,@@ -942,12 +937,7 @@ func (s *SwarmService) JoinEnvironments(ctx context.Context, managerEnvironmentI// selectSwarmManagerAddressesInternal prefers explicit manager addresses and// otherwise uses the addresses advertised by the cluster's manager nodes.func selectSwarmManagerAddressesInternal(explicit []string, nodes []swarmtypes.NodeSummary) ([]string, error) {- addrs := make([]string, 0, len(explicit))- for _, addr := range explicit {- if trimmed := strings.TrimSpace(addr); trimmed != "" {- addrs = append(addrs, trimmed)- }- }+ addrs := kit.TrimNonEmpty(explicit)if len(addrs) > 0 {return addrs, nil}@@ -1146,16 +1136,11 @@ func (s *SwarmService) buildNodeAgentStatusInternal(nodeID string, env *environmLastHeartbeat: runtime.lastHeartbeat,LastPollAt: runtime.lastPollAt,- EnvironmentName: &env.Name}- environmentType := "direct"- if env.IsEdge {- environmentType = "edge"+ EnvironmentName: &env.Name,}+ environmentType := kit.Ternary(env.IsEdge, "edge", "direct")status.EnvironmentType = &environmentType- bindingKind := swarmtypes.NodeAgentBindingKindEnvironment- if env.Hidden {- bindingKind = swarmtypes.NodeAgentBindingKindDedicated- }+ bindingKind := kit.Ternary(env.Hidden, swarmtypes.NodeAgentBindingKindDedicated, swarmtypes.NodeAgentBindingKindEnvironment)status.BindingKind = &bindingKindif runtime.identity != nil {@@ -1697,10 +1682,7 @@ func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmtreturn errors.WrapIf(err, "failed to inspect swarm node")}- version := req.Version- if version == 0 {- version = nodeResult.Node.Version.Index- }+ version := cmp.Or(req.Version, nodeResult.Node.Version.Index)spec := nodeResult.Node.Specif req.Name != nil {@@ -1778,10 +1760,7 @@ func (s *SwarmService) GetStack(ctx context.Context, environmentID, stackName stif len(services) == 0 {persisted, err := s.getPersistedStackSourceSummaryInternal(ctx, environmentID, stackName)if err != nil {- if cerrdefs.IsNotFound(err) {- return nil, cerrdefs.ErrNotFound- }- return nil, err+ return nil, kit.Ternary[error](cerrdefs.IsNotFound(err), cerrdefs.ErrNotFound, err)}return &swarmtypes.StackInspect{@@ -2038,10 +2017,7 @@ func (s *SwarmService) RemoveStack(ctx context.Context, environmentID, stackName}if len(services) == 0 {if _, err := s.getPersistedStackSourceSummaryInternal(ctx, environmentID, stackName); err != nil {- if cerrdefs.IsNotFound(err) {- return cerrdefs.ErrNotFound- }- return err+ return kit.Ternary[error](cerrdefs.IsNotFound(err), cerrdefs.ErrNotFound, err)}} else {if err := s.removeStackServicesInternal(ctx, dockerClient, services); err != nil {@@ -2569,11 +2545,7 @@ func decodeSwarmSpecInternal(raw stdjson.RawMessage) (swarm.Spec, error) {func defaultSwarmListenAddrInternal(listenAddr string) string {trimmed := strings.TrimSpace(listenAddr)- if trimmed == "" {- return defaultSwarmListenAddr- }-- return trimmed+ return kit.Ternary(trimmed == "", defaultSwarmListenAddr, trimmed)}func decodeSecretSpecInternal(raw stdjson.RawMessage) (swarm.SecretSpec, error) {@@ -2694,19 +2666,9 @@ func (s *SwarmService) deleteStackSourceInternal(ctx context.Context, environmenfunc normalizeSwarmEnvironmentIDInternal(environmentID string) string {envID := strings.TrimSpace(environmentID)- if envID == "" {- return "0"- }- return envID+ return kit.Ternary(envID == "", "0", envID)}-const (- defaultSwarmStackSourceRootDir = "/app/data/swarm/sources"- swarmStackComposeFilename = "compose.yaml"- swarmStackOverrideFilename = "compose.override.yaml"- swarmStackEnvFilename = ".env"-)-func (s *SwarmService) resolveSwarmStackSourceDirInternal(ctx context.Context, environmentID, stackName string) (string, string, error) {normalizedStackName := appfs.SanitizeProjectName(strings.TrimSpace(stackName))if normalizedStackName == "" || strings.Trim(normalizedStackName, "_") == "" {@@ -2920,30 +2882,21 @@ func compareTimeInternal(a, b time.Time) int {if a.Before(b) {return -1}- if a.After(b) {- return 1- }- return 0+ return kit.Ternary(a.After(b), 1, 0)}func compareUint64Internal(a, b uint64) int {if a < b {return -1}- if a > b {- return 1- }- return 0+ return kit.Ternary(a > b, 1, 0)}func compareIntInternal(a, b int) int {if a < b {return -1}- if a > b {- return 1- }- return 0+ return kit.Ternary(a > b, 1, 0)}func sanitizeServiceSpecInternal(spec *swarm.ServiceSpec) {diff --git a/backend/internal/system/handler.go b/backend/internal/system/handler.goindex 72202d157..d8b9114b8 100644--- a/backend/internal/system/handler.go+++ b/backend/internal/system/handler.go@@ -1,17 +1,14 @@package systemimport (+ "cmp""context""log/slog""net/http""strings""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2"- dockersystem "github.com/moby/moby/api/types/system"- "github.com/moby/moby/client"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -25,8 +22,11 @@ import (containertypes "github.com/getarcaneapp/arcane/types/v2/container""github.com/getarcaneapp/arcane/types/v2/dockerinfo""github.com/getarcaneapp/arcane/types/v2/system"+ dockersystem "github.com/moby/moby/api/types/system"+ "github.com/moby/moby/client""go.getarcane.app/docker/convert"converttypes "go.getarcane.app/docker/convert/types"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup")@@ -341,17 +341,11 @@ func extractVersionDetailsFromComponents(components []dockersystem.ComponentVersfor key, value := range component.Details {switch strings.ToLower(key) {case "gitcommit":- if gitCommit == "" {- gitCommit = value- }+ gitCommit = cmp.Or(gitCommit, value)case "goversion":- if goVersion == "" {- goVersion = value- }+ goVersion = cmp.Or(goVersion, value)case "buildtime":- if buildTime == "" {- buildTime = value- }+ buildTime = cmp.Or(buildTime, value)}}}@@ -506,10 +500,11 @@ func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradreturn nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to initiate upgrade").Error())}- message := "Upgrade initiated successfully. A new container is being created and will replace this one shortly."- if upToDate {- message = "Already running the newest image. The upgrade pulls it again and leaves the container in place."- }+ message := kit.Ternary(+ upToDate,+ "Already running the newest image. The upgrade pulls it again and leaves the container in place.",+ "Upgrade initiated successfully. A new container is being created and will replace this one shortly.",+ )return &handlerutil.Out[TriggerUpgradeData]{Body: base.ApiResponse[TriggerUpgradeData]{diff --git a/backend/internal/system/memory.go b/backend/internal/system/memory.goindex eb58ab060..2e93d2635 100644--- a/backend/internal/system/memory.go+++ b/backend/internal/system/memory.go@@ -8,8 +8,8 @@ import ("time""emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/moby/moby/client"+ "go.getarcane.app/docker/compat""go.getarcane.app/sys/cgroup")@@ -59,7 +59,7 @@ func (s *SystemService) loadDockerHostMemoryInternal(ctx context.Context) (dockeif err != nil {return dockerHostMemoryInfo{}, err}- inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {return dockerHostMemoryInfo{}, err}diff --git a/backend/internal/system/model.go b/backend/internal/system/model.goindex e60c9ef64..0bcbc8835 100644--- a/backend/internal/system/model.go+++ b/backend/internal/system/model.go@@ -1,10 +1,10 @@package systemimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"database/sql/driver""time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database")// EnvironmentUpdateJobStatus is the lifecycle status of a fleet-wide "update all@@ -22,12 +22,7 @@ const (EnvironmentUpdateJobStatusCompleted EnvironmentUpdateJobStatus = "completed"// EnvironmentUpdateJobStatusFailed means the job stopped before completing.EnvironmentUpdateJobStatusFailed EnvironmentUpdateJobStatus = "failed"-)--// EnvironmentUpdateResultStatus is the per-environment outcome within a job.-type EnvironmentUpdateResultStatus string-const (// EnvironmentUpdateResultStatusPending is the initial state recorded for an// environment that is seeded into the job but not yet being processed (and for// the manager entry while its self-upgrade is in flight).@@ -50,6 +45,9 @@ const (EnvironmentUpdateResultStatusFailed EnvironmentUpdateResultStatus = "failed")+// EnvironmentUpdateResultStatus is the per-environment outcome within a job.+type EnvironmentUpdateResultStatus string+// EnvironmentUpdateResult is the outcome for a single environment within a job.// The manager appears as the first entry with EnvironmentID "0".type EnvironmentUpdateResult struct {diff --git a/backend/internal/system/module.go b/backend/internal/system/module.goindex 8e67975b1..4872c0588 100644--- a/backend/internal/system/module.go+++ b/backend/internal/system/module.go@@ -5,15 +5,14 @@ package systemimport ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/network""github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/volume""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil")diff --git a/backend/internal/system/system.go b/backend/internal/system/system.goindex 573147f4a..296b1e1d6 100644--- a/backend/internal/system/system.go+++ b/backend/internal/system/system.go@@ -1,35 +1,30 @@package systemimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-+ "cmp""context""fmt""log/slog""strings""sync"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/image"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/network""github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/container"-- "emperror.dev/errors"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/volume"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"containertypes "github.com/getarcaneapp/arcane/types/v2/container"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/getarcaneapp/arcane/types/v2/system"mobycontainer "github.com/moby/moby/api/types/container""github.com/moby/moby/client"@@ -651,9 +646,6 @@ func (s *SystemService) GetDiskUsagePath(ctx context.Context) string {return "/"}- path := cfg.DiskUsagePath.Value- if path == "" {- path = "/"- }+ path := cmp.Or(cfg.DiskUsagePath.Value, "/")return path}diff --git a/backend/internal/system/upgrade_service.go b/backend/internal/system/upgrade_service.goindex 96be4995e..017179db3 100644--- a/backend/internal/system/upgrade_service.go+++ b/backend/internal/system/upgrade_service.go@@ -15,7 +15,6 @@ import ("time""emperror.dev/errors"-cerrdefs "github.com/containerd/errdefs"ref "github.com/distribution/reference""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -37,6 +36,8 @@ import ("github.com/moby/moby/api/types/mount""github.com/moby/moby/client""github.com/opencontainers/go-digest"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""go.getarcane.app/updater""go.getarcane.app/updater/labels"@@ -97,10 +98,7 @@ func (s *SystemUpgradeService) CanUpgrade(ctx context.Context) (bool, error) {// find nothing to swap in and skip the recreate β so callers can use this to stop// waiting for a restart that is not coming.func (s *SystemUpgradeService) AlreadyOnNewestImage(ctx context.Context) bool {- if s.versionService == nil {- return false- }- return agentAlreadyOnTargetInternal(s.versionService.GetAppVersionInfo(ctx))+ return s.versionService.GetAppVersionInfo(ctx).AlreadyOnNewest()}// TriggerUpgradeViaCLI spawns the upgrade CLI command in a separate container and@@ -174,7 +172,7 @@ func (s *SystemUpgradeService) prepareUpgradeInternal(ctx context.Context, user// Determine binary path based on container type (agent vs main)binaryPath := "/app/arcane"if currentContainer.Config != nil {- binaryPath = determineUpgradeBinaryPathInternal(currentContainer.Config.Labels)+ binaryPath = kit.Ternary(labels.IsArcaneAgentContainer(currentContainer.Config.Labels), "/app/arcane-agent", "/app/arcane")}targetImage, err := s.resolveUpgradeTargetImageInternal(ctx, currentContainer, target.NewImageRef, targetVersion)@@ -361,19 +359,11 @@ func daemonHasSELinuxEnabledInternal(ctx context.Context, dockerClient *client.Creturn slices.Contains(infoResult.Info.SecurityOptions, "name=selinux")}-func determineUpgradeBinaryPathInternal(containerLabels map[string]string) string {- if labels.IsArcaneAgentContainer(containerLabels) {- return "/app/arcane-agent"- }-- return "/app/arcane"-}-// resolveUpgradeTargetImageInternal picks the image the upgrade should move to.// Explicit targets from the updater engine are authoritative. A blank target// (manual trigger, update-all) resolves against the version check so a// version-pinned install actually moves to the newest release (#3687).-func (s *SystemUpgradeService) resolveUpgradeTargetImageInternal(ctx context.Context, currentContainer container.InspectResponse, explicitImageRef string, targetVersion string) (string, error) {+func (s *SystemUpgradeService) resolveUpgradeTargetImageInternal(ctx context.Context, currentContainer container.InspectResponse, explicitImageRef, targetVersion string) (string, error) {if targetImage := strings.TrimSpace(explicitImageRef); targetImage != "" {return targetImage, nil}@@ -382,10 +372,7 @@ func (s *SystemUpgradeService) resolveUpgradeTargetImageInternal(ctx context.Conif currentContainer.Config != nil {currentImageRef = strings.TrimSpace(currentContainer.Config.Image)}- var info *versiontypes.Info- if s.versionService != nil {- info = s.versionService.GetAppVersionInfo(ctx)- }+ info := s.versionService.GetAppVersionInfo(ctx)// A manager-supplied target version outranks this instance's own version check.if targetVersion = strings.TrimSpace(targetVersion); targetVersion != "" {merged := versiontypes.Info{}@@ -452,11 +439,11 @@ func resolveSelfUpgradeTargetImageInternal(currentImageRef string, info *versionif newestVersion == "" {return "", errors.Errorf("running exact release %q but the newest release could not be resolved", tagged.Tag())}- newest := utils.EnsureVPrefix(newestVersion)+ newest := kit.EnsurePrefix(newestVersion, "v")if !semver.IsValid(newest) {return "", errors.Errorf("resolved newest version %q is not a valid semver release", newestVersion)}- if semver.Compare(newest, utils.EnsureVPrefix(tagged.Tag())) < 0 {+ if semver.Compare(newest, kit.EnsurePrefix(tagged.Tag(), "v")) < 0 {return "", errors.Errorf("newest release %q is older than the running %q; refusing to downgrade", newestVersion, tagged.Tag())}@@ -571,7 +558,7 @@ func (s *SystemUpgradeService) findArcaneContainerInternal(ctx context.Context,}// Try to inspect the container directly- inspectResult, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerId, client.ContainerInspectOptions{})+ inspectResult, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerId, client.ContainerInspectOptions{})if err == nil {return inspectResult.Container, nil}@@ -590,7 +577,7 @@ func (s *SystemUpgradeService) findArcaneContainerInternal(ctx context.Context,for _, c := range containers.Items {if strings.HasPrefix(c.ID, containerId) {- inspect, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})+ inspect, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})if inspectErr != nil {return container.InspectResponse{}, inspectErr}@@ -606,7 +593,7 @@ func (s *SystemUpgradeService) findArcaneContainerInternal(ctx context.Context,for _, c := range allContainers.Items {if strings.HasPrefix(c.ID, containerId) || c.ID == containerId {- inspect, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})+ inspect, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})if inspectErr != nil {return container.InspectResponse{}, inspectErr}@@ -630,6 +617,16 @@ func (s *SystemUpgradeService) findArcaneContainerInternal(ctx context.Context,}const (+ // The run never finished observably: nothing may be concluded from it.+ upgraderExitUnobservedInternal upgraderExitInternal = 0+ // The upgrader exited 0.+ upgraderExitSucceededInternal upgraderExitInternal = 1+ // The upgrader exited non-zero.+ upgraderExitFailedInternal upgraderExitInternal = 2+ // The upgrader is gone, but its exit code was lost with it β success and failure+ // are indistinguishable.+ upgraderExitCodeLostInternal upgraderExitInternal = 3+updateAllStaleThresholdInternal = time.HourupdateAllAgentRequestTimeoutInternal = 15 * time.SecondupdateAllConfirmPollIntervalInternal = 10 * time.Second@@ -741,10 +738,7 @@ func (s *SystemUpgradeService) ResumeUpdateAllOnStartup(ctx context.Context) {// The agents phase already ran before the restart. Finalize the manager's own// result and close the job β do not re-run the agents phase.- managerStatus := EnvironmentUpdateResultStatusFailed- if action.managerSucceeded {- managerStatus = EnvironmentUpdateResultStatusUpdated- }+ managerStatus := kit.Ternary(action.managerSucceeded, EnvironmentUpdateResultStatusUpdated, EnvironmentUpdateResultStatusFailed)s.recordManagerResultInternal(job, managerStatus, info.CurrentVersion)s.finalizeUpdateAllJobInternal(ctx, job)@@ -896,7 +890,7 @@ func (s *SystemUpgradeService) watchManagerUpgraderInternal(ctx context.Context,// image) into a green row and zero logged failures, leaving a broken upgrade with no// retry path. Anything less is a failure; the job closes either way, since no restart// is coming.- if exit == upgraderExitCodeLostInternal && (!wasAlreadyNewest || !agentAlreadyOnTargetInternal(info)) {+ if exit == upgraderExitCodeLostInternal && (!wasAlreadyNewest || !info.AlreadyOnNewest()) {s.markUpdateAllFailedInternal(ctx, job, "manager upgrade could not be confirmed: the upgrader exited without a readable status and this manager was not a confirmed no-op upgrade")return}@@ -948,18 +942,6 @@ func (s *SystemUpgradeService) closeOutUnobservedUpgradeInternal(ctx context.Con// upgraderExitInternal is how much the watcher managed to learn about an upgrader run.type upgraderExitInternal int-const (- // The run never finished observably: nothing may be concluded from it.- upgraderExitUnobservedInternal upgraderExitInternal = iota- // The upgrader exited 0.- upgraderExitSucceededInternal- // The upgrader exited non-zero.- upgraderExitFailedInternal- // The upgrader is gone, but its exit code was lost with it β success and failure- // are indistinguishable.- upgraderExitCodeLostInternal-)-// waitForUpgraderExitInternal blocks until the upgrader container stops, reporting what// could be learned about how it ended along with its exit code when one was observed.func (s *SystemUpgradeService) waitForUpgraderExitInternal(ctx context.Context, upgraderID string) (upgraderExitInternal, int64) {@@ -1065,16 +1047,14 @@ func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *en// The manager's newest release outranks the agent's own check, mirrored into info// so the recorded target, up-to-date check and confirm poll track what was sent.var triggerBody []byte- if s.versionService != nil {- if managerInfo := s.versionService.GetAppVersionInfo(ctx); managerInfo != nil {- if newest := strings.TrimSpace(managerInfo.NewestVersion); newest != "" {- body, err := json.Marshal(TriggerUpgradeBody{TargetVersion: newest})- if err != nil {- slog.WarnContext(ctx, "update-all: failed to marshal trigger body", "environmentId", envID, "error", err)- } else {- info.NewestVersion = newest- triggerBody = body- }+ if managerInfo := s.versionService.GetAppVersionInfo(ctx); managerInfo != nil {+ if newest := strings.TrimSpace(managerInfo.NewestVersion); newest != "" {+ body, err := json.Marshal(TriggerUpgradeBody{TargetVersion: newest})+ if err != nil {+ slog.WarnContext(ctx, "update-all: failed to marshal trigger body", "environmentId", envID, "error", err)+ } else {+ info.NewestVersion = newest+ triggerBody = body}}}@@ -1099,7 +1079,7 @@ func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *en// nothing to swap in: its upgrader pulls, finds the same image and skips the// recreate. Confirming that would only burn the poll window waiting for a version// change that cannot come, so record it directly.- if agentAlreadyOnTargetInternal(&info) {+ if info.AlreadyOnNewest() {result.Status = EnvironmentUpdateResultStatusUpToDateresult.ToVersion = info.CurrentVersionreturn@@ -1113,34 +1093,6 @@ func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *en}}-// agentAlreadyOnTargetInternal reports whether a version check is confident that the-// environment already runs the newest image. Only a positive answer is actionable:-// anything unresolved or contradictory reports false, which keeps the full-// trigger-and-confirm flow rather than claiming there was nothing to do.-func agentAlreadyOnTargetInternal(info *versiontypes.Info) bool {- if info == nil || info.UpdateAvailable {- return false- }-- currentDigest := strings.TrimSpace(info.CurrentDigest)- newestDigest := strings.TrimSpace(info.NewestDigest)-- // Digests are the only thing that catches a mutable tag rebuilt at the same version,- // since the semver track's UpdateAvailable ignores them entirely. Once either side- // resolves, both must resolve and agree: with only one in hand there is no way to- // rule out that the pull is about to replace the image, so a matching version tag- // must not be trusted on its own.- if currentDigest != "" || newestDigest != "" {- return currentDigest == newestDigest- }-- // No digest information at all β the resolved version tag is all there is to go on.- if info.NewestVersion != "" {- return strings.TrimPrefix(info.NewestVersion, "v") == strings.TrimPrefix(info.CurrentVersion, "v")- }- return false-}-// updateAllAgentFailureStatusInternal classifies a failed agent pre-check. An// environment we actually reached but whose request failed or timed out is a real// failure, not an offline skip: poll-mode agents connect on demand, so a slowdiff --git a/backend/internal/system/upgrade_service_test.go b/backend/internal/system/upgrade_service_test.goindex 5209a55a7..2cbe9a4af 100644--- a/backend/internal/system/upgrade_service_test.go+++ b/backend/internal/system/upgrade_service_test.go@@ -6,7 +6,6 @@ import ("testing""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"versiontypes "github.com/getarcaneapp/arcane/types/v2/version"@@ -14,7 +13,6 @@ import (mounttypes "github.com/moby/moby/api/types/mount"networktypes "github.com/moby/moby/api/types/network""github.com/stretchr/testify/require"- "go.getarcane.app/updater/labels")// TestSystemUpgradeService_UpgradeFlag tests the upgrading flag behavior@@ -51,10 +49,10 @@ func TestSystemUpgradeService_ErrorVariables(t *testing.T) {require.Error(t, errors.New("docker socket is not accessible"))// Test error messages- require.Equal(t, "arcane is not running in a Docker container", (errors.New("arcane is not running in a Docker container")).Error())- require.Equal(t, "could not find Arcane container", (common.Classify(common.ErrNotFound, errors.New("could not find Arcane container"))).Error())- require.Equal(t, "an upgrade is already in progress", (common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress"))).Error())- require.Equal(t, "docker socket is not accessible", (errors.New("docker socket is not accessible")).Error())+ require.Equal(t, "arcane is not running in a Docker container", errors.New("arcane is not running in a Docker container").Error())+ require.Equal(t, "could not find Arcane container", common.Classify(common.ErrNotFound, errors.New("could not find Arcane container")).Error())+ require.Equal(t, "an upgrade is already in progress", common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress")).Error())+ require.Equal(t, "docker socket is not accessible", errors.New("docker socket is not accessible").Error())}// TestSystemUpgradeService_UpgradingFlag_ConcurrentAccess tests upgrading flag@@ -162,39 +160,6 @@ func TestSystemUpgradeService_AtomicOperations(t *testing.T) {require.True(t, s.upgrading.Load())}-func TestDetermineUpgradeBinaryPath(t *testing.T) {- tests := []struct {- name string- labels map[string]string- want string- }{- {- name: "agent container uses agent binary",- labels: map[string]string{- labels.LabelArcaneAgent: "true",- },- want: "/app/arcane-agent",- },- {- name: "main container uses main binary",- labels: map[string]string{- labels.LabelArcane: "true",- },- want: "/app/arcane",- },- {- name: "no labels defaults to main binary",- want: "/app/arcane",- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- require.Equal(t, tt.want, determineUpgradeBinaryPathInternal(tt.labels))- })- }-}-func TestResolveSystemUpgraderRuntimeOptionsInternal_TCPDockerHost(t *testing.T) {currentContainer := &containertypes.InspectResponse{HostConfig: &containertypes.HostConfig{NetworkMode: "bridge"},diff --git a/backend/internal/system/upgrade_update_all_test.go b/backend/internal/system/upgrade_update_all_test.goindex 41ec3c786..39b2952ac 100644--- a/backend/internal/system/upgrade_update_all_test.go+++ b/backend/internal/system/upgrade_update_all_test.go@@ -5,10 +5,9 @@ import ("testing""time"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/version"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"versiontypes "github.com/getarcaneapp/arcane/types/v2/version""github.com/libtnb/sqlite""github.com/stretchr/testify/require"@@ -85,7 +84,6 @@ func TestUpdateAllResolveResumeAction(t *testing.T) {require.False(t, !tt.wantStale && got.managerSucceeded != tt.wantManagerOK,"managerSucceeded = %v, want %v", got.managerSucceeded, tt.wantManagerOK)-})}}@@ -134,7 +132,6 @@ func TestUpsertPendingResult(t *testing.T) {require.Equal(t, EnvironmentUpdateResultStatusPending, got.Status,"appended row status = %q, want pending", got.Status)-}func TestUpdateAllFailedJobMarksUpdatingResultsFailed(t *testing.T) {@@ -282,7 +279,7 @@ func TestAgentAlreadyOnTarget(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- require.Equal(t, tt.want, agentAlreadyOnTargetInternal(&tt.info))+ require.Equal(t, tt.want, tt.info.AlreadyOnNewest())})}}diff --git a/backend/internal/systembackup/background.go b/backend/internal/systembackup/background.goindex 7316fdee9..0c44cf705 100644--- a/backend/internal/systembackup/background.go+++ b/backend/internal/systembackup/background.go@@ -6,7 +6,6 @@ import ("log/slog""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -103,7 +102,7 @@ func (s *SystemBackupService) StartSystemVolumeBackups(ctx context.Context, userreturn &backuptypes.BackupRunAccepted{ActivityID: activityID, Status: "running"}, nil}-func (s *SystemBackupService) updateSystemVolumeProgressInternal(ctx context.Context, activityID string, policyID string, candidates []backuptypes.SystemVolumeBackupOption, result *backuptypes.SystemVolumeBackupRunResult) {+func (s *SystemBackupService) updateSystemVolumeProgressInternal(ctx context.Context, activityID, policyID string, candidates []backuptypes.SystemVolumeBackupOption, result *backuptypes.SystemVolumeBackupRunResult) {if activityID == "" {return}diff --git a/backend/internal/systembackup/handler.go b/backend/internal/systembackup/handler.goindex be308b9d4..c276843b0 100644--- a/backend/internal/systembackup/handler.go+++ b/backend/internal/systembackup/handler.go@@ -6,7 +6,6 @@ import ("strings""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -83,11 +82,13 @@ type GenerateSystemBackupRecoveryKeyOutput struct {type CreateSystemBackupInput struct {Body backuptypes.CreateSystemBackupRequest}-type SystemBackupOutput struct{ Body backuptypes.SystemBackupRun }-type RestoreSystemBackupInput struct {- ID string `path:"id"`- Body backuptypes.RestoreSystemBackupRequest-}+type (+ SystemBackupOutput struct{ Body backuptypes.SystemBackupRun }+ RestoreSystemBackupInput struct {+ ID string `path:"id"`+ Body backuptypes.RestoreSystemBackupRequest+ }+)// BrowseSystemBackupFilesInput selects one page of a system backup tree.type BrowseSystemBackupFilesInput struct {diff --git a/backend/internal/systembackup/model.go b/backend/internal/systembackup/model.goindex c94391276..616f9c952 100644--- a/backend/internal/systembackup/model.go+++ b/backend/internal/systembackup/model.go@@ -13,16 +13,14 @@ const (SystemBackupStatusRunning SystemBackupStatus = "running"SystemBackupStatusSucceeded SystemBackupStatus = "succeeded"SystemBackupStatusFailed SystemBackupStatus = "failed"-)--type SystemBackupTrigger string-const (SystemBackupTriggerManual SystemBackupTrigger = "manual"SystemBackupTriggerScheduled SystemBackupTrigger = "scheduled"SystemBackupTriggerSafety SystemBackupTrigger = "safety")+type SystemBackupTrigger string+type SystemBackupRun struct {database.BaseModeldiff --git a/backend/internal/systembackup/service.go b/backend/internal/systembackup/service.goindex 514601b7f..5c566fc5f 100644--- a/backend/internal/systembackup/service.go+++ b/backend/internal/systembackup/service.go@@ -16,7 +16,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/backup"@@ -46,6 +45,8 @@ import ("github.com/moby/moby/api/types/mount""github.com/moby/moby/client""go.getarcane.app/acfs"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""gorm.io/gorm")@@ -56,6 +57,13 @@ const (systemRecoveryRequestName = ".arcane-recovery-request.json"systemRecoveryHelperPath = "/app/arcane-recovery-helper"systemAdmissionID = "system"++ snapshotDataPath = "/data"+ snapshotProjectsPath = "/projects"++ recoveryDataRestoreTarget = "/restore"+ recoveryProjectsRestoreTarget = "/restore-projects"+ selectiveProjectsRestoreTarget = "/arcane-projects")var ErrSystemBackupAlreadyRunning = errors.New("an Arcane system backup is already running")@@ -149,7 +157,7 @@ func (s *SystemBackupService) recoveryEnvironmentInternal(ctx context.Context) m// databaseFileInternal resolves the SQLite database file: under /app/data in// the container, the local data directory in host development.func (s *SystemBackupService) databaseFileInternal() (string, error) {- databasePath, err := utils.SQLitePathFromDSN(s.config.DatabaseURL)+ databasePath, err := kit.SQLitePathFromDSN(s.config.DatabaseURL)if err != nil {return "", fmt.Errorf("failed to parse database URL: %w", err)}@@ -643,13 +651,6 @@ func snapshotRelativePathInternal(filePath, snapshotPath string) (string, bool)return strings.TrimPrefix(cleanedFile, prefix), true}-func protectedSystemBackupPathInternal(candidate, databasePath string) bool {- if candidate == systemRecoveryManifestName || candidate == systemRecoveryRequestName {- return true- }- return candidate == databasePath || candidate == databasePath+"-wal" || candidate == databasePath+"-shm" || candidate == databasePath+"-journal"-}-// projectEntriesFromSnapshotInternal maps a snapshot listing to entries// relative to the projects root, dropping protected Arcane data files.func projectEntriesFromSnapshotInternal(files []string, layout snapshotLayoutInternal, browsePath string, recursive bool) []backuptypes.BackupFileEntry {@@ -659,7 +660,7 @@ func projectEntriesFromSnapshotInternal(files []string, layout snapshotLayoutIntif !ok || layout.protectedInternal(projectRelative) {continue}- normalized, err := utils.NormalizeRelativePath(projectRelative)+ normalized, err := kit.NormalizeRelativePath(projectRelative)if err != nil {continue}@@ -1137,7 +1138,7 @@ func (s *SystemBackupService) RestoreBackup(ctx context.Context, id, recoveryKeyif err != nil {return errors.New("arcane system restore requires Arcane to run in Docker")}- inspectResult, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ inspectResult, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {return fmt.Errorf("inspect Arcane container: %w", err)}@@ -1460,9 +1461,11 @@ func (s *SystemBackupService) runScheduledBackupInternal(ctx context.Context, poResourceID: policy.ID, ResourceName: "Arcane", User: &common.SystemUser,Step: "Creating scheduled system backup", Message: "Creating scheduled Arcane system backup",SuccessMessage: "Scheduled Arcane system backup created successfully",- Metadata: database.JSON{"action": "scheduled_system_backup", "policyId": policy.ID, "schedule": policy.Schedule,+ Metadata: database.JSON{+ "action": "scheduled_system_backup", "policyId": policy.ID, "schedule": policy.Schedule,"retentionCount": policy.RetentionCount, "localEnabled": policy.LocalEnabled,- "s3Enabled": policy.S3Enabled, "s3DestinationId": policy.S3DestinationID},+ "s3Enabled": policy.S3Enabled, "s3DestinationId": policy.S3DestinationID,+ },}, func(activityCtx context.Context) error {var backupErr errorrun, backupErr = s.CreateBackup(activityCtx, common.SystemUser, SystemBackupTriggerScheduled,@@ -1580,10 +1583,7 @@ func (s *SystemBackupService) disableMissingS3Internal(ctx context.Context, poliif !errors.Is(err, backup.ErrRemoteRepositoryMissing) {return false, nil}- column := "enabled"- if policy.LocalEnabled {- column = "s3_enabled"- }+ column := kit.Ternary(policy.LocalEnabled, "s3_enabled", "enabled")result := s.db.WithContext(ctx).Model(&SystemBackupPolicy{}).Where("id = ? AND s3_destination_id = ? AND enabled = ? AND s3_enabled = ? AND local_enabled = ?", policy.ID, policy.S3DestinationID, true, true, policy.LocalEnabled).Update(column, false)@@ -1599,11 +1599,6 @@ func (s *SystemBackupService) disableMissingS3Internal(ctx context.Context, polireturn true, nil}-const (- snapshotDataPath = "/data"- snapshotProjectsPath = "/projects"-)-// backupSourceLayoutInternal is what one system backup snapshots and where// each source appears inside the snapshot.type backupSourceLayoutInternal struct {@@ -1628,9 +1623,9 @@ func projectsSnapshotPathInternal(dataDirectory, projectsDirectory string) (projswitch {case projectsDir == data:return snapshotDataPath, false, nil- case utils.FilePathMatches(projectsDir, data):+ case kit.FilePathMatches(projectsDir, data):return path.Join(snapshotDataPath, strings.TrimPrefix(projectsDir, data+"/")), false, nil- case utils.FilePathMatches(data, projectsDir):+ case kit.FilePathMatches(data, projectsDir):return "", false, fmt.Errorf("the projects directory %s contains Arcane's data directory %s; move it inside or outside the data directory before creating system backups", projectsDir, data)default:return snapshotProjectsPath, true, nil@@ -1725,12 +1720,6 @@ func (s *SystemBackupService) backupSourceLayoutInternal(ctx context.Context, doreturn layout, nil}-const (- recoveryDataRestoreTarget = "/restore"- recoveryProjectsRestoreTarget = "/restore-projects"- selectiveProjectsRestoreTarget = "/arcane-projects"-)-var (errProjectsOutsideDataInternal = errors.New("the backup-time projects directory is outside Arcane's system backup data")errProjectsNotInBackupInternal = errors.New("this system backup does not include the projects directory because it was created before Arcane backed up separately mounted projects; create a new system backup to restore project files")@@ -1767,7 +1756,13 @@ func (layout snapshotLayoutInternal) protectedInternal(projectRelative string) bif !inside {return false}- return protectedSystemBackupPathInternal(path.Join(relative, projectRelative), layout.databaseName)+ candidate := path.Join(relative, projectRelative)+ switch candidate {+ case systemRecoveryManifestName, systemRecoveryRequestName, layout.databaseName, layout.databaseName + "-wal", layout.databaseName + "-shm", layout.databaseName + "-journal":+ return true+ default:+ return false+ }}// projectsCoveredByDataInternal reports whether restoring the data root already@@ -1822,7 +1817,7 @@ func snapshotLayoutFromManifestInternal(manifest recoverytypes.Manifest, manifesif err != nil {return snapshotLayoutInternal{}, fmt.Errorf("invalid projects path: %w", err)}- databaseName, err := utils.NormalizeRelativePath(manifest.DatabasePath)+ databaseName, err := kit.NormalizeRelativePath(manifest.DatabasePath)if err != nil {return snapshotLayoutInternal{}, fmt.Errorf("invalid database path: %w", err)}@@ -1835,7 +1830,7 @@ func snapshotLayoutFromManifestInternal(manifest recoverytypes.Manifest, manifes// confinedSnapshotPathInternal validates a recorded snapshot path and returns// it in absolute form.func confinedSnapshotPathInternal(value string) (string, error) {- relative, err := utils.NormalizeRelativePath(strings.TrimPrefix(strings.TrimSpace(value), "/"))+ relative, err := kit.NormalizeRelativePath(strings.TrimPrefix(strings.TrimSpace(value), "/"))if err != nil {return "", err}@@ -1866,7 +1861,7 @@ func recoveryManifestDatabasePathInternal(manifest recoverytypes.Manifest) (striif databaseURL == "" {return "", errors.New("system recovery manifest does not record the database path")}- databasePath, err := utils.SQLitePathFromDSN(databaseURL)+ databasePath, err := kit.SQLitePathFromDSN(databaseURL)if err != nil {return "", fmt.Errorf("parse database URL from system recovery manifest: %w", err)}@@ -1923,7 +1918,7 @@ func projectsRelativePathFromManifestInternal(manifest recoverytypes.Manifest) (if projectsPath == dataPath {return "", nil}- if !utils.FilePathMatches(projectsPath, dataPath) {+ if !kit.FilePathMatches(projectsPath, dataPath) {return "", errProjectsOutsideDataInternal}return strings.TrimPrefix(projectsPath, dataPath+"/"), nil@@ -1943,7 +1938,7 @@ func restoreTargetInternal(mounts []containertypes.MountPoint, containerPath, ta}destination := path.Join(target, relative)candidates := slices.DeleteFunc(slices.Clone(mounts), func(m containertypes.MountPoint) bool {- return exclude != "" && utils.FilePathMatches(m.Destination, exclude)+ return exclude != "" && kit.FilePathMatches(m.Destination, exclude)})result := recoverytypes.RestoreTarget{Mounts: []mount.Mount{*enclosing}, Path: destination}result.Mounts = append(result.Mounts, dockerutil.NestedMounts(candidates, containerPath, destination)...)@@ -1986,10 +1981,7 @@ func restoreStagesInternal(mounts []containertypes.MountPoint, dataDirectory, prif separate && layout.projectsPath == layout.dataPath {return nil, fmt.Errorf("the backup keeps projects in Arcane's data directory; set the projects directory to %s before a full restore, or restore individual project files instead", dataDirectory)}- exclude := ""- if separate {- exclude = projectsDirectory- }+ exclude := kit.Ternary(separate, projectsDirectory, "")dataTarget, err := restoreTargetInternal(mounts, dataDirectory, recoveryDataRestoreTarget, exclude)if err != nil {return nil, errdiff --git a/backend/internal/systembackup/service_test.go b/backend/internal/systembackup/service_test.goindex 7c117565d..409bcf962 100644--- a/backend/internal/systembackup/service_test.go+++ b/backend/internal/systembackup/service_test.go@@ -147,7 +147,6 @@ func TestSystemBackupPoliciesRegisterIndependentJobs(t *testing.T) {require.Equal(t, !local, policy.S3Enabled)require.Equal(t, local, scheduler.HasJob(service.jobs.JobName(policy.ID)))}-}func TestSystemBackupPolicyRequiresConfiguredRecoveryKeyWhenEnabled(t *testing.T) {diff --git a/backend/internal/systembackup/system_volume.go b/backend/internal/systembackup/system_volume.goindex b84d680f7..e1cd66b90 100644--- a/backend/internal/systembackup/system_volume.go+++ b/backend/internal/systembackup/system_volume.go@@ -2,28 +2,25 @@ package systembackupimport ("context"- "crypto/sha256"- "encoding/hex""encoding/json/v2""fmt""log/slog""slices""strings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/backup""github.com/getarcaneapp/arcane/backend/v2/internal/common"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3""github.com/getarcaneapp/arcane/backend/v2/internal/volume""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/google/uuid"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -31,6 +28,8 @@ const (systemVolumeBackupConfigKey = "systemVolumeBackupConfig"systemVolumeBackupJobPrefix = "volumes:"defaultSystemVolumeSchedule = "0 0 2 * * *"++ backupHistoryUnionInternal = `SELECT id, size, created_at, status, trigger, destination, '' AS format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, 'system' AS type, 'system' AS resource_type, 'Arcane' AS resource_name FROM system_backup_runs UNION ALL SELECT id, size, created_at, status, trigger, destination, format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, CASE WHEN policy_id LIKE 'system-volume:%' THEN 'system' ELSE 'volume' END AS type, 'volume' AS resource_type, volume_name AS resource_name FROM volume_backups`)func (s *SystemBackupService) loadSystemVolumeBackupPoliciesInternal() (*backuptypes.SystemVolumeBackupPolicyCollection, error) {@@ -116,7 +115,7 @@ func (s *SystemBackupService) normalizeSystemVolumePolicyUpdateInternal(ctx contif err != nil {return backuptypes.SystemVolumeBackupPolicy{}, err}- names := utils.UniqueNonEmptyStrings(input.VolumeNames)+ names := kit.Unique(kit.TrimNonEmpty(input.VolumeNames))slices.Sort(names)if input.SelectionMode == backuptypes.SystemVolumeSelectionAll || names == nil {names = []string{}@@ -219,13 +218,11 @@ func selectSystemVolumeBackupCandidatesInternal(policy backuptypes.SystemVolumeB}func systemVolumePolicyIDInternal(policyID, volumeName string) string {- sum := sha256.Sum256([]byte(volumeName))- return backuptypes.SystemVolumePolicyPrefix + policyID + ":" + hex.EncodeToString(sum[:8])+ return backuptypes.SystemVolumePolicyPrefix + policyID + ":" + kit.SHA256Hex(volumeName)[:16]}func systemVolumeManualPolicyIDInternal(volumeName string) string {- sum := sha256.Sum256([]byte(volumeName))- return backuptypes.SystemVolumePolicyPrefix + "manual:" + hex.EncodeToString(sum[:8])+ return backuptypes.SystemVolumePolicyPrefix + "manual:" + kit.SHA256Hex(volumeName)[:16]}func customSystemVolumePolicyInternal(custom *backuptypes.SystemVolumeBackupCustomRun) backuptypes.UpdateSystemVolumeBackupPolicy {@@ -437,8 +434,6 @@ func (s *SystemBackupService) rescheduleSystemVolumeBackupInternal(ctx context.C})}-const backupHistoryUnionInternal = `SELECT id, size, created_at, status, trigger, destination, '' AS format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, 'system' AS type, 'system' AS resource_type, 'Arcane' AS resource_name FROM system_backup_runs UNION ALL SELECT id, size, created_at, status, trigger, destination, format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, CASE WHEN policy_id LIKE 'system-volume:%' THEN 'system' ELSE 'volume' END AS type, 'volume' AS resource_type, volume_name AS resource_name FROM volume_backups`-// ListBackupHistory returns a unified, server-paginated view of local backup records.func (s *SystemBackupService) ListBackupHistory(ctx context.Context, params pagination.QueryParams) ([]backuptypes.HistoryEntry, pagination.Response, error) {query := s.db.WithContext(ctx).Table("(?) AS backup_history", s.db.Raw(backupHistoryUnionInternal))@@ -464,10 +459,7 @@ func (s *SystemBackupService) ListBackupHistory(ctx context.Context, params pagi}volumeAvailable := backup.RemoteSnapshotChecker(ctx, s.s3Destinations, volumeRoot)for i := range history {- check := systemAvailable- if history[i].ResourceType == "volume" {- check = volumeAvailable- }+ check := kit.Ternary(history[i].ResourceType == "volume", volumeAvailable, systemAvailable)history[i].RemoteAvailable = check(history[i].S3DestinationID, history[i].RemoteSnapshotID)}diff --git a/backend/internal/template/handler.go b/backend/internal/template/handler.goindex fea964bc9..2dc6129c1 100644--- a/backend/internal/template/handler.go+++ b/backend/internal/template/handler.go@@ -1,6 +1,7 @@package templateimport (+ "cmp""context""encoding/json/v2"@@ -10,9 +11,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper""github.com/getarcaneapp/arcane/types/v2/base"templatetypes "github.com/getarcaneapp/arcane/types/v2/template"+ "go.getarcane.app/kit/pkg/mapping")// TemplateHandler handles template management endpoints.@@ -264,9 +265,7 @@ func RegisterTemplates(api huma.API, templateService *TemplateService) {// ListTemplates returns a paginated list of templates.func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatesInput) (*handlerutil.Page[templatetypes.Template], error) {params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)if input.Type != "" {params.Filters["type"] = input.Type}@@ -292,7 +291,7 @@ func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatereturn nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())}- out, mapErr := mapper.MapSlice[ComposeTemplate, templatetypes.Template](templates)+ out, mapErr := mapping.MapSlice[ComposeTemplate, templatetypes.Template](templates)if mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}@@ -320,7 +319,7 @@ func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInp}var out templatetypes.Template- if mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {+ if mapErr := mapping.MapStruct(tmpl, &out); mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}@@ -372,7 +371,7 @@ func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTempl}var out templatetypes.Template- if mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {+ if mapErr := mapping.MapStruct(tmpl, &out); mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}@@ -414,7 +413,7 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTempl}var out templatetypes.Template- if mapErr := mapper.MapStruct(updated, &out); mapErr != nil {+ if mapErr := mapping.MapStruct(updated, &out); mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}@@ -472,7 +471,7 @@ func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadT}var out templatetypes.Template- if mapErr := mapper.MapStruct(localTemplate, &out); mapErr != nil {+ if mapErr := mapping.MapStruct(localTemplate, &out); mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}@@ -531,7 +530,7 @@ func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegisreturn nil, huma.Error500InternalServerError("Failed to fetch registry")}- out, mapErr := mapper.MapSlice[TemplateRegistry, templatetypes.TemplateRegistry](registries)+ out, mapErr := mapping.MapSlice[TemplateRegistry, templatetypes.TemplateRegistry](registries)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to fetch registry")}@@ -567,7 +566,7 @@ func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTempl}var out templatetypes.TemplateRegistry- if mapErr := mapper.MapStruct(registry, &out); mapErr != nil {+ if mapErr := mapping.MapStruct(registry, &out); mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}diff --git a/backend/internal/template/module.go b/backend/internal/template/module.goindex 7adb13eb1..4f78117eb 100644--- a/backend/internal/template/module.go+++ b/backend/internal/template/module.go@@ -6,7 +6,6 @@ import ("net/http""github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings")diff --git a/backend/internal/template/service.go b/backend/internal/template/service.goindex d81991196..2bd47079c 100644--- a/backend/internal/template/service.go+++ b/backend/internal/template/service.go@@ -15,10 +15,7 @@ import ("time""uuid"- "go.getarcane.app/kit/normalization"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -26,12 +23,14 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper""github.com/getarcaneapp/arcane/types/v2/env"tmpl "github.com/getarcaneapp/arcane/types/v2/template""github.com/samber/hot""github.com/samber/mo""go.getarcane.app/acfs"+ "go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""golang.org/x/sync/errgroup""gorm.io/gorm")@@ -62,9 +61,9 @@ const (remoteCacheDuration = 5 * time.MinutefsSyncInterval = 1 * time.MinuteremoteIconResolveLimit = 4-)-const remoteIDPrefix = "remote"+ remoteIDPrefix = "remote"+)var errNoRemoteTemplates = errors.New("remote template registries returned no templates")@@ -134,10 +133,7 @@ func (s *TemplateService) ensureRemoteTemplatesLoaded(_ context.Context) error {if err != nil {return errors.WrapIf(err, "failed to load remote templates")}- if !found || len(templates) == 0 {- return errNoRemoteTemplates- }- return nil+ return kit.Ternary(!found || len(templates) == 0, errNoRemoteTemplates, nil)}func (s *TemplateService) refreshRemoteTemplates(ctx context.Context) error {@@ -169,7 +165,7 @@ func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params pitems := make([]tmpl.Template, 0, len(templates))for _, t := range templates {var dtoItem tmpl.Template- if err := mapper.MapStruct(&t, &dtoItem); err != nil {+ if err := mapping.MapStruct(&t, &dtoItem); err != nil {slog.WarnContext(ctx, "failed to map template to DTO", "error", err, "templateID", t.ID)continue}@@ -206,10 +202,7 @@ func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params pif a.IsRemote == b.IsRemote {return 0}- if a.IsRemote {- return 1- }- return -1+ return kit.Ternary(a.IsRemote, 1, -1)},},},@@ -217,7 +210,7 @@ func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params p{Key: "type",Fn: func(item tmpl.Template, filterValue string) bool {- value, valid := utils.ParseBool(filterValue)+ value, valid := kit.ParseBool(filterValue)return !valid || item.IsRemote == value},},@@ -1166,7 +1159,7 @@ func (s *TemplateService) GetTemplateContentWithParsedData(ctx context.Context,setTemplateIconURL(composeTemplate, projects.ResolveTemplateIconURL(ctx, composeContent, envContent))var outTemplate tmpl.Template- if mapErr := mapper.MapStruct(composeTemplate, &outTemplate); mapErr != nil {+ if mapErr := mapping.MapStruct(composeTemplate, &outTemplate); mapErr != nil {return nil, errors.WrapIf(mapErr, "failed to map template")}diff --git a/backend/internal/template/service_test.go b/backend/internal/template/service_test.goindex fb3a5d2af..3af106202 100644--- a/backend/internal/template/service_test.go+++ b/backend/internal/template/service_test.go@@ -14,12 +14,6 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/samber/mo"- "github.com/stretchr/testify/require"- "go.uber.org/fx/fxtest"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -27,6 +21,11 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"tmpl "github.com/getarcaneapp/arcane/types/v2/template"+ "github.com/libtnb/sqlite"+ "github.com/samber/mo"+ "github.com/stretchr/testify/require"+ "go.uber.org/fx/fxtest"+ "gorm.io/gorm")func setupTemplateServiceTestDB(t *testing.T) *database.DB {diff --git a/backend/internal/updater/model.go b/backend/internal/updater/model.goindex 8537e84f6..3b5ce072f 100644--- a/backend/internal/updater/model.go+++ b/backend/internal/updater/model.go@@ -1,9 +1,9 @@package updaterimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database")type AutoUpdateStatus stringdiff --git a/backend/internal/updater/module.go b/backend/internal/updater/module.goindex 73bf8d48c..cd31feada 100644--- a/backend/internal/updater/module.go+++ b/backend/internal/updater/module.go@@ -4,7 +4,6 @@ package updaterimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/database"diff --git a/backend/internal/updater/recovery.go b/backend/internal/updater/recovery.goindex 43b65336c..1b024185d 100644--- a/backend/internal/updater/recovery.go+++ b/backend/internal/updater/recovery.go@@ -1,6 +1,7 @@package updaterimport (+ "cmp""context""log/slog""strings"@@ -15,13 +16,15 @@ import ("go.getarcane.app/updater")-type updateProgressKeyInternal struct{}-type updateProgressInternal struct {- mu sync.Mutex- err error- selfTriggered bool- selfID string-}+type (+ updateProgressKeyInternal struct{}+ updateProgressInternal struct {+ mu sync.Mutex+ err error+ selfTriggered bool+ selfID string+ }+)// RecordUpdateRun persists one updater resource result into Arcane history.func (s *UpdaterService) RecordUpdateRun(ctx context.Context, result updater.ResourceResult) error {@@ -29,10 +32,7 @@ func (s *UpdaterService) RecordUpdateRun(ctx context.Context, result updater.Resif s != nil && s.deps.DB != nil {recordErr = s.recordRunInternal(ctx, resourceResultFromModuleInternal(result))}- name := strings.TrimSpace(result.ResourceName)- if name == "" {- name = result.ResourceID- }+ name := cmp.Or(strings.TrimSpace(result.ResourceName), result.ResourceID)message := name + ": " + string(result.Status)level := activitytypes.MessageLevelInfostatus := schedulertypes.NeedsAttentiondiff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.goindex aa58c3548..434b87ff9 100644--- a/backend/internal/updater/service.go+++ b/backend/internal/updater/service.go@@ -1,6 +1,7 @@package updaterimport (+ "cmp""context""fmt""io"@@ -11,13 +12,7 @@ import ("sync""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -31,16 +26,20 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"projectspkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"arcaneupdater "github.com/getarcaneapp/arcane/types/v2/updater""github.com/moby/moby/api/types/container""github.com/moby/moby/client""github.com/samber/mo"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""go.getarcane.app/updater""go.getarcane.app/updater/labels"@@ -145,10 +144,7 @@ func (s *UpdaterService) configInternal() updater.Config {// container is missing the Arcane labels. Empty when not running in Docker.func selfContainerIDInternal() string {id, err := cgroup.CurrentContainerID()- if err != nil {- return ""- }- return id+ return kit.Ternary(err != nil, "", id)}func (s *UpdaterService) engineInternal() *updater.Service {@@ -331,12 +327,7 @@ func (s *UpdaterService) applyScopedUpdatesInternal(ctx context.Context, options// resolveScopedContainerIDsInternal maps a scoped options payload to the// container IDs it covers.func (s *UpdaterService) resolveScopedContainerIDsInternal(ctx context.Context, options arcaneupdater.Options) ([]string, error) {- requested := make([]string, 0, len(options.ResourceIds))- for _, id := range options.ResourceIds {- if trimmed := strings.TrimSpace(id); trimmed != "" {- requested = append(requested, trimmed)- }- }+ requested := kit.TrimNonEmpty(options.ResourceIds)if len(requested) == 0 {return nil, nil}@@ -538,7 +529,7 @@ func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]AutoUpdat}// RestartContainersUsingOldIDs restarts containers matching old image IDs or refs.-func (s *UpdaterService) RestartContainersUsingOldIDs(ctx context.Context, oldIDToNewRef map[string]string, oldRefToNewRef map[string]string) ([]arcaneupdater.ResourceResult, error) {+func (s *UpdaterService) RestartContainersUsingOldIDs(ctx context.Context, oldIDToNewRef, oldRefToNewRef map[string]string) ([]arcaneupdater.ResourceResult, error) {results, err := s.engineInternal().RestartContainersUsingOldImages(ctx, oldIDToNewRef, oldRefToNewRef)return resourceResultsFromModuleInternal(results), err}@@ -551,7 +542,7 @@ func (s *UpdaterService) TriggerSelfUpdateViaCLI(ctx context.Context, source, coreturn s.TriggerSelfUpdate(ctx, updater.SelfUpdateTarget{ContainerID: containerID,ContainerName: containerName,- InstanceType: instanceTypeFromLabelsInternal(labelMap),+ InstanceType: kit.Ternary(labels.IsArcaneAgentContainer(labelMap), "agent", "server"),Labels: labelMap,})}@@ -585,60 +576,26 @@ func (s *UpdaterService) recordAutoUpdateEventInternal(ctx context.Context, seve}}-func instanceTypeFromLabelsInternal(labelMap map[string]string) string {- if labels.IsArcaneAgentContainer(labelMap) {- return "agent"- }- return "server"-}-func autoUpdateEventTitleInternal(phase string, metadata database.JSON) string {switch phase {case "start":return "Auto-update run started"case "image_pull", "image":- image := strings.TrimSpace(fmt.Sprint(metadata["imageNew"]))- if image == "" {- image = strings.TrimSpace(fmt.Sprint(metadata["imageOld"]))- }- if image != "" {- return "Auto-update: image pull " + image- }- return "Auto-update: image pull"+ image := cmp.Or(kit.ToString(metadata["imageNew"]), kit.ToString(metadata["imageOld"]))+ return kit.Ternary(image != "", "Auto-update: image pull "+image, "Auto-update: image pull")case "image_prune":- imageID := strings.TrimSpace(fmt.Sprint(metadata["imageId"]))- if imageID != "" {- return "Auto-update: image prune " + imageID- }- return "Auto-update: image prune"+ imageID := kit.ToString(metadata["imageId"])+ return kit.Ternary(imageID != "", "Auto-update: image prune "+imageID, "Auto-update: image prune")case "container":- name := strings.TrimSpace(fmt.Sprint(metadata["resourceName"]))- if name == "" {- name = strings.TrimSpace(fmt.Sprint(metadata["container"]))- }- if name == "" {- name = strings.TrimSpace(fmt.Sprint(metadata["containerId"]))- }- if name != "" {- return "Auto-update: container " + name- }- return "Auto-update: container"+ name := cmp.Or(kit.ToString(metadata["resourceName"]), kit.ToString(metadata["container"]), kit.ToString(metadata["containerId"]))+ return kit.Ternary(name != "", "Auto-update: container "+name, "Auto-update: container")case "project":- name := strings.TrimSpace(fmt.Sprint(metadata["projectName"]))- if name == "" {- name = strings.TrimSpace(fmt.Sprint(metadata["projectId"]))- }- if name != "" {- return "Auto-update: project " + name- }- return "Auto-update: project"+ name := cmp.Or(kit.ToString(metadata["projectName"]), kit.ToString(metadata["projectId"]))+ return kit.Ternary(name != "", "Auto-update: project "+name, "Auto-update: project")case "complete":return "Auto-update run completed"default:- if phase != "" {- return "Auto-update: " + phase- }- return "Auto-update"+ return kit.Ternary(phase != "", "Auto-update: "+phase, "Auto-update")}}@@ -727,7 +684,7 @@ func (s *UpdaterService) ExcludedContainers(ctx context.Context) ([]string, erroif s.deps.Settings == nil {return nil, nil}- return utils.UniqueNonEmptyStrings(strings.Split(s.deps.Settings.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""), ",")), nil+ return kit.Unique(kit.TrimNonEmpty(strings.Split(s.deps.Settings.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""), ","))), nil}// ProjectByComposeName resolves an Arcane project from a Docker Compose project name.@@ -756,10 +713,7 @@ func (s *UpdaterService) UpdateServices(ctx context.Context, projectID string, s// TriggerSelfUpdate runs Arcane's CLI-backed self-update hook.func (s *UpdaterService) TriggerSelfUpdate(ctx context.Context, target updater.SelfUpdateTarget) error {if s == nil || s.deps.SelfUpgrade == nil {- instanceType := strings.TrimSpace(target.InstanceType)- if instanceType == "" {- instanceType = "server"- }+ instanceType := cmp.Or(strings.TrimSpace(target.InstanceType), "server")return errors.Errorf("%s self-update requires CLI upgrade service", instanceType)}@@ -881,10 +835,7 @@ func (s *UpdaterService) RecordEvent(ctx context.Context, evt updater.Event) err)}- severity := event.EventSeverityInfo- if strings.EqualFold(evt.Severity, "error") {- severity = event.EventSeverityError- }+ severity := kit.Ternary(strings.EqualFold(evt.Severity, "error"), event.EventSeverityError, event.EventSeverityInfo)s.recordAutoUpdateEventInternal(ctx, severity, database.JSON{"phase": evt.Phase,"resourceId": evt.ResourceID,@@ -958,7 +909,7 @@ func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.name := containerIDlookupCtx, cancelLookup := context.WithTimeout(ctx, 2*time.Second)if dockerClient, dockerErr := s.DockerClient(lookupCtx); dockerErr == nil && dockerClient != nil {- if inspected, inspectErr := libarcane.ContainerInspectWithCompatibility(lookupCtx, dockerClient, containerID, client.ContainerInspectOptions{}); inspectErr == nil {+ if inspected, inspectErr := compat.ContainerInspectWithCompatibility(lookupCtx, dockerClient, containerID, client.ContainerInspectOptions{}); inspectErr == nil {if actualName := strings.TrimPrefix(strings.TrimSpace(inspected.Container.Name), "/"); actualName != "" {name = actualName}@@ -1184,6 +1135,12 @@ func resourceResultsFromModuleInternal(results []updater.ResourceResult) []arcan// type. The engine now reports a single old/new image; Arcane's API carries// maps, which only ever held the "main" entry, so that shape is rebuilt here.func resourceResultFromModuleInternal(result updater.ResourceResult) arcaneupdater.ResourceResult {+ mainImage := func(ref string) map[string]string {+ if ref == "" {+ return nil+ }+ return map[string]string{"main": ref}+ }return arcaneupdater.ResourceResult{ResourceID: result.ResourceID,ResourceName: result.ResourceName,@@ -1191,20 +1148,13 @@ func resourceResultFromModuleInternal(result updater.ResourceResult) arcaneupdatStatus: string(result.Status),UpdateAvailable: result.UpdateAvailable,UpdateApplied: result.UpdateApplied,- OldImages: mainImageMapInternal(result.OldImage),- NewImages: mainImageMapInternal(result.NewImage),+ OldImages: mainImage(result.OldImage),+ NewImages: mainImage(result.NewImage),Error: result.Error,Details: result.Details,}}-func mainImageMapInternal(imageRef string) map[string]string {- if imageRef == "" {- return nil- }- return map[string]string{"main": imageRef}-}-func statusFromModuleInternal(status updater.Status) arcaneupdater.Status {return arcaneupdater.Status{UpdatingContainers: status.UpdatingContainers,@@ -1368,7 +1318,7 @@ func (s *UpdaterService) collectUsedImagesFromContainersInternal(ctx context.Concontinue}- inspectResult, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dcli, summary.ID, client.ContainerInspectOptions{})+ inspectResult, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dcli, summary.ID, client.ContainerInspectOptions{})if inspectErr != nil {s.loggerInternal().DebugContext(ctx, "collectUsedImagesFromContainers: container inspect failed", "containerId", summary.ID, "error", inspectErr)continue@@ -1385,7 +1335,7 @@ func (s *UpdaterService) collectUsedImagesFromContainersInternal(ctx context.Conreturn nil}-func (s *UpdaterService) collectUsedImagesFromComposeContainersInternal(ctx context.Context, composeContainers []container.Summary, activeProjectNames map[string]struct{}, out map[string]struct{}) {+func (s *UpdaterService) collectUsedImagesFromComposeContainersInternal(ctx context.Context, composeContainers []container.Summary, activeProjectNames, out map[string]struct{}) {for _, summary := range composeContainers {projectName := dockerutil.ComposeProjectLabel(summary.Labels)if projectName == "" {@@ -1424,10 +1374,7 @@ func (s *UpdaterService) normalizedTagsForContainerInternal(ctx context.Context,addNormalizedImageUpdateRefInternal(ctx, seen, inspect.Config.Image, "normalizedTagsForContainer: skipping invalid config image reference", "imageId", inspect.Image)}- out := make([]string, 0, len(seen))- for tag := range seen {- out = append(out, tag)- }+ out := slices.Collect(maps.Keys(seen))return out}diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.goindex 7b97a58d2..95c48ff91 100644--- a/backend/internal/updater/service_test.go+++ b/backend/internal/updater/service_test.go@@ -1,28 +1,13 @@package updaterimport (- "fmt"-- composetypes "github.com/compose-spec/compose-go/v2/types"- projectspkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"- projecttypes "github.com/getarcaneapp/arcane/types/v2/project"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-- "github.com/getarcaneapp/arcane/backend/v2/internal/activity"- "github.com/getarcaneapp/arcane/backend/v2/internal/actors"- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"bytes""context""encoding/json""errors"+ "fmt""io"+ "maps""net/http""net/http/httptest""net/url"@@ -33,6 +18,10 @@ import ("testing""time"+ composetypes "github.com/compose-spec/compose-go/v2/types"+ "github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker"@@ -44,7 +33,15 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"+ projectspkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+ projecttypes "github.com/getarcaneapp/arcane/types/v2/project"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"arcaneupdater "github.com/getarcaneapp/arcane/types/v2/updater""github.com/libtnb/sqlite"dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"@@ -54,6 +51,7 @@ import ("github.com/moby/moby/client""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""go.getarcane.app/updater""go.getarcane.app/updater/labels"@@ -138,11 +136,7 @@ func (f *fakeProjectUpdaterInternal) UpdateServiceImages(_ context.Context, projf.imageChanges = map[string]map[string]updatertypes.ServiceImageChange{}}f.imageChanges[projectID] = changes- services := make([]string, 0, len(changes))- for service := range changes {- services = append(services, service)- }- slices.Sort(services)+ services := slices.Sorted(maps.Keys(changes))f.calls = append(f.calls, projectID+":"+strings.Join(services, ","))return f.updateErrs[projectID]}@@ -492,7 +486,7 @@ func TestUpdaterService_PullImageAdapterInternal(t *testing.T) {imageRef := "registry.example.com/team/app:latest"var gotAuth string- server := newImagePullServerWithObserverInternal(t, nil, func(fullRef string, authHeader string) {+ server := newImagePullServerWithObserverInternal(t, nil, func(fullRef, authHeader string) {if fullRef == imageRef {gotAuth = authHeader}@@ -778,10 +772,7 @@ func TestUpdaterService_RecordUpdateRunAppendsActivityMessageInternal(t *testingfunc TestUpdaterService_AcceptSingleContainerUpdateUsesQueuedActivityInternal(t *testing.T) {for _, cancelActivity := range []bool{false, true} {- name := "request disconnect"- if cancelActivity {- name = "activity cancellation while queued"- }+ name := kit.Ternary(cancelActivity, "activity cancellation while queued", "request disconnect")t.Run(name, func(t *testing.T) {db := setupProjectTestDBInternal(t)require.NoError(t, db.AutoMigrate(&activity.Activity{}, &activity.ActivityMessage{}))@@ -843,10 +834,7 @@ func TestUpdaterService_AcceptSingleContainerUpdateUsesQueuedActivityInternal(t}releaseOnce.Do(func() { close(release) })- wantStatus := activitytypes.StatusFailed- if cancelActivity {- wantStatus = activitytypes.StatusCancelled- }+ wantStatus := kit.Ternary(cancelActivity, activitytypes.StatusCancelled, activitytypes.StatusFailed)require.Eventually(t, func() bool {var saved activity.Activityreturn db.First(&saved, "id = ?", item.ID).Error == nil && saved.Status == wantStatus@@ -1282,7 +1270,7 @@ func newTestDockerClientInternal(t *testing.T, server *httptest.Server) *client.}// newImagePullServerWithObserverInternal is NewImagePullServer with a pull callback.-func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[string]dockertypesimage.InspectResponse, onPull func(fullRef string, authHeader string)) *httptest.Server {+func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[string]dockertypesimage.InspectResponse, onPull func(fullRef, authHeader string)) *httptest.Server {t.Helper()server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/backend/internal/updater/tag_updates.go b/backend/internal/updater/tag_updates.goindex 18ecc0fa5..219089618 100644--- a/backend/internal/updater/tag_updates.go+++ b/backend/internal/updater/tag_updates.go@@ -1,25 +1,25 @@package updaterimport (+ "cmp""context""strings""time"+ "emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types"cerrdefs "github.com/containerd/errdefs"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"- projecttypes "github.com/getarcaneapp/arcane/types/v2/project"- "gorm.io/gorm"-- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/types/v2/containerregistry"+ projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/moby/moby/client""go.getarcane.app/updater""go.getarcane.app/updater/pkg/utils/tagpolicy""go.getarcane.app/updater/refs"updatertypes "go.getarcane.app/updater/types"+ "gorm.io/gorm")// ListTags supplies Arcane's registry credentials to the updater's tag checker.@@ -178,9 +178,7 @@ func (s *UpdaterService) checkProjectServiceInternal(ctx context.Context, projec}record.HasUpdate = check.UpdateAvailablerecord.UpdateType = check.UpdateType- if check.CurrentVersion != "" {- record.CurrentVersion = check.CurrentVersion- }+ record.CurrentVersion = cmp.Or(check.CurrentVersion, record.CurrentVersion)if check.CurrentDigest != "" {record.CurrentDigest = new(check.CurrentDigest)}diff --git a/backend/internal/upload/handler.go b/backend/internal/upload/handler.goindex 029d45732..c45048118 100644--- a/backend/internal/upload/handler.go+++ b/backend/internal/upload/handler.go@@ -12,13 +12,12 @@ import ("github.com/danielgtaylor/huma/v2""github.com/danielgtaylor/huma/v2/adapters/humaecho"- "github.com/getarcaneapp/arcane/types/v2/base"- uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"+ "github.com/getarcaneapp/arcane/types/v2/base"+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload")// UploadHandler provides the Huma-based chunked upload-session endpoints.diff --git a/backend/internal/upload/service_test.go b/backend/internal/upload/service_test.goindex b0f828799..81af125e4 100644--- a/backend/internal/upload/service_test.go+++ b/backend/internal/upload/service_test.go@@ -9,9 +9,8 @@ import ("testing""time"- uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"-"github.com/getarcaneapp/arcane/backend/v2/internal/common"+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload")func TestSessionChunkRoundTrip(t *testing.T) {diff --git a/backend/internal/upload/upload.go b/backend/internal/upload/upload.goindex 707529bf3..f43649ad9 100644--- a/backend/internal/upload/upload.go+++ b/backend/internal/upload/upload.go@@ -4,6 +4,7 @@package uploadimport (+ "cmp""context""encoding/json/v2""fmt"@@ -16,12 +17,11 @@ import ("strings""time"- uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"- "go.getarcane.app/acfs"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"+ "go.getarcane.app/acfs")const (@@ -85,10 +85,7 @@ func (s *UploadService) CreateSession(ctx context.Context, kind string, requestreturn nil, fmt.Errorf("%w: file size exceeds maximum allowed size of %d MB", common.ErrUploadSessionInvalid, maxSizeMB)}}- chunkSize := request.ChunkSize- if chunkSize == 0 {- chunkSize = uploadtypes.DefaultChunkSize- }+ chunkSize := cmp.Or(request.ChunkSize, uploadtypes.DefaultChunkSize)if chunkSize < uploadtypes.MinChunkSize || chunkSize > uploadtypes.MaxChunkSize {return nil, fmt.Errorf("%w: chunk size must be between %d and %d bytes", common.ErrUploadSessionInvalid, uploadtypes.MinChunkSize, uploadtypes.MaxChunkSize)}diff --git a/backend/internal/user/handler.go b/backend/internal/user/handler.goindex 13d637ac1..96de4a1fd 100644--- a/backend/internal/user/handler.go+++ b/backend/internal/user/handler.go@@ -6,7 +6,6 @@ import ("time""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"diff --git a/backend/internal/user/module.go b/backend/internal/user/module.goindex fd7d45389..7f11e098f 100644--- a/backend/internal/user/module.go+++ b/backend/internal/user/module.go@@ -4,7 +4,6 @@ package userimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/settings")diff --git a/backend/internal/user/service.go b/backend/internal/user/service.goindex ca133630c..0e745a21e 100644--- a/backend/internal/user/service.go+++ b/backend/internal/user/service.go@@ -7,14 +7,11 @@ import ("encoding/base64""fmt""log/slog"+ "maps"+ "slices""strings""emperror.dev/errors"-- "golang.org/x/crypto/argon2"- "gorm.io/gorm"- "gorm.io/gorm/clause"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role"@@ -24,6 +21,10 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2/user""go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg"+ "golang.org/x/crypto/argon2"+ "gorm.io/gorm"+ "gorm.io/gorm/clause")type Argon2Params struct {@@ -268,10 +269,7 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gormif err != nil {return errors.WrapIf(err, "failed to resolve target permissions")}- if targetPerms != nil && targetPerms.IsGlobalAdmin() {- return ErrInsufficientPrivilege- }- return nil+ return kit.Ternary[error](targetPerms != nil && targetPerms.IsGlobalAdmin(), ErrInsufficientPrivilege, nil)}// UpdateUser persists the given user. actorPerms identifies the caller@@ -383,7 +381,7 @@ func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, us//// Note: The clause.Locking{Strength: "UPDATE"} statement is used to acquire a row-level lock.// This MUST be done inside a transaction to ensure the lock is held until the update is committed.-func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userID string, subject string, updateFn func(u *common.User)) (*common.User, error) {+func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userID, subject string, updateFn func(u *common.User)) (*common.User, error) {var out *common.Usererr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {var u common.User@@ -681,17 +679,11 @@ func permissionSetToMap(ps *authz.PermissionSet) map[string][]string {return out}if len(ps.Global) > 0 {- globals := make([]string, 0, len(ps.Global))- for p := range ps.Global {- globals = append(globals, p)- }+ globals := slices.Collect(maps.Keys(ps.Global))out["global"] = globals}for envID, perms := range ps.PerEnv {- list := make([]string, 0, len(perms))- for p := range perms {- list = append(list, p)- }+ list := slices.Collect(maps.Keys(perms))out[envID] = list}return out@@ -767,10 +759,7 @@ func (s *UserService) GetAvatar(ctx context.Context, userID string) ([]byte, str}var avatar UserAvatarif err := s.db.DB.WithContext(ctx).Where("user_id = ?", userID).First(&avatar).Error; err != nil {- if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, "", nil- }- return nil, "", err+ return nil, "", kit.Ternary(errors.Is(err, gorm.ErrRecordNotFound), nil, err)}return avatar.Data, avatar.MimeType, nil}diff --git a/backend/internal/user/service_test.go b/backend/internal/user/service_test.goindex 4159d7237..e192197df 100644--- a/backend/internal/user/service_test.go+++ b/backend/internal/user/service_test.go@@ -1,10 +1,6 @@package userimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/session"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"context""testing""time"@@ -12,6 +8,8 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/role"+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/user"diff --git a/backend/internal/variable/module.go b/backend/internal/variable/module.goindex 80763dd8f..c228aa13e 100644--- a/backend/internal/variable/module.go+++ b/backend/internal/variable/module.go@@ -3,7 +3,6 @@ package variableimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/environment")diff --git a/backend/internal/variable/variable.go b/backend/internal/variable/variable.goindex 6cba5fef7..b041cc39c 100644--- a/backend/internal/variable/variable.go+++ b/backend/internal/variable/variable.go@@ -8,6 +8,7 @@ import ("fmt""io/fs""log/slog"+ "maps""net/http""os""path/filepath"@@ -18,7 +19,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment"@@ -28,6 +28,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/env""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""gorm.io/gorm")@@ -299,11 +300,7 @@ func (s *VariableService) resolveEffectiveVariablesInternal(ctx context.Context,}}- keys := make([]string, 0, len(effective))- for key := range effective {- keys = append(keys, key)- }- slices.Sort(keys)+ keys := slices.Sorted(maps.Keys(effective))result := make([]env.Variable, 0, len(effective))for _, key := range keys {@@ -747,7 +744,7 @@ func (s *VariableService) normalizeScopeInternal(ctx context.Context, allEnviron// validateScopeConflictInternal enforces the duplicate-key rule: a key may// exist once per overlapping scope. The same key as both an all-environments// variable and an env-scoped variable is allowed (that is the override).-func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key string, excludeID string, allEnvironments bool, envIDs []string) error {+func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key, excludeID string, allEnvironments bool, envIDs []string) error {var others []GlobalVariablequery := tx.Preload("Environments").Where("key = ?", key)if excludeID != "" {@@ -815,10 +812,7 @@ func environmentsFromIDsInternal(envIDs []string) []environment.Environment {}func globalVariableToDTOInternal(variable GlobalVariable) env.GlobalVariable {- value := variable.Value- if variable.IsSecret {- value = ""- }+ value := kit.Ternary(variable.IsSecret, "", variable.Value)return env.GlobalVariable{ID: variable.ID,Key: variable.Key,diff --git a/backend/internal/version/service.go b/backend/internal/version/service.goindex bcd743d26..636784177 100644--- a/backend/internal/version/service.go+++ b/backend/internal/version/service.go@@ -10,13 +10,7 @@ import ("time""emperror.dev/errors"-ref "github.com/distribution/reference"- containertypes "github.com/moby/moby/api/types/container"- "github.com/moby/moby/client"- "github.com/samber/mo"- "golang.org/x/mod/semver"-"github.com/getarcaneapp/arcane/backend/v2/buildables""github.com/getarcaneapp/arcane/backend/v2/internal/apns""github.com/getarcaneapp/arcane/backend/v2/internal/config"@@ -25,11 +19,16 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/version"+ containertypes "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client""github.com/samber/hot"+ "github.com/samber/mo"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/streams/agg""go.getarcane.app/sys/cgroup"+ "golang.org/x/mod/semver")const (@@ -57,7 +56,7 @@ type VersionService struct {streamHub *agg.Hub[version.StreamEvent]}-func NewVersionService(httpClient *http.Client, disabled bool, appVersion string, revision string, containerRegistryService *registry.ContainerRegistryService, dockerService *docker.DockerClientService, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService) *VersionService {+func NewVersionService(httpClient *http.Client, disabled bool, appVersion, revision string, containerRegistryService *registry.ContainerRegistryService, dockerService *docker.DockerClientService, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService) *VersionService {if httpClient == nil {httpClient = http.DefaultClient}@@ -163,9 +162,7 @@ func (s *VersionService) normalizeVersion(ver string) string {if trimmed == "" || trimmed[0] < '0' || trimmed[0] > '9' {return ver}- if !strings.HasPrefix(ver, "v") {- ver = "v" + ver- }+ ver = kit.EnsurePrefix(ver, "v")// If not valid semver, try to make it validif !semver.IsValid(ver) {// Extract just the numeric part before any suffix@@ -187,11 +184,7 @@ func (s *VersionService) ReleaseURL(version string) string {return "https://github.com/getarcaneapp/arcane/releases/latest"}- v := strings.TrimSpace(version)- if !strings.HasPrefix(v, "v") {- v = "v" + v- }- return "https://github.com/getarcaneapp/arcane/releases/tag/" + v+ return "https://github.com/getarcaneapp/arcane/releases/tag/" + kit.EnsurePrefix(version, "v")}func (s *VersionService) GetVersionInformation(ctx context.Context, currentVersion string) (*version.Check, error) {@@ -268,21 +261,14 @@ func (s *VersionService) resolveNextVersionInternal(ctx context.Context, imageRe// isSemverVersion checks if a version string is semver-based (e.g., v1.0.0)func (s *VersionService) isSemverVersion() bool {- versionValue := strings.TrimSpace(s.version)- if !strings.HasPrefix(versionValue, "v") {- versionValue = "v" + versionValue- }- return semver.IsValid(versionValue)+ return semver.IsValid(kit.EnsurePrefix(s.version, "v"))}// getDisplayVersion formats the version for display purposes// Semver versions (including prereleases like 2.4.0-next.1) display as v<version>func (s *VersionService) getDisplayVersion() string {versionValue := strings.TrimPrefix(strings.TrimSpace(s.version), "v")- if s.isSemverVersion() {- return "v" + versionValue- }- return versionValue+ return kit.Ternary(s.isSemverVersion(), "v"+versionValue, versionValue)}// updateCheckImageRefInternal points the digest lookup at the configured registry; "auto" keeps the running reference.@@ -310,10 +296,7 @@ func (s *VersionService) updateCheckImageRefInternal(currentImageRef string) strrepoPath = "getarcaneapp/agent"}}- if host == ref.Domain(named) && repoPath == ref.Path(named) {- return currentImageRef- }- return host + "/" + repoPath+ return kit.Ternary(host == ref.Domain(named) && repoPath == ref.Path(named), currentImageRef, host+"/"+repoPath)}// GetAppVersionInfo returns application version information including display version@@ -335,7 +318,7 @@ func (s *VersionService) GetAppVersionInfo(ctx context.Context) *version.Info {GoVersion: config.GoVersion(),NodeVersion: config.NodeVersion,SvelteKitVersion: config.SvelteKitVersion,- EnabledFeatures: append(utils.UniqueNonEmptyStrings(strings.Split(strings.ToLower(buildables.EnabledFeatures), ",")), apns.FeatureName),+ EnabledFeatures: append(kit.Unique(kit.TrimNonEmpty(strings.Split(strings.ToLower(buildables.EnabledFeatures), ","))), apns.FeatureName),BuildTime: config.BuildTime,IsSemverVersion: isSemver,UpdateAvailable: false,@@ -404,7 +387,7 @@ func (s *VersionService) storedOrDigestBasedUpdateInternal(ctx context.Context,}// detectCurrentImageInfo attempts to detect the current container's image tag and digest-func (s *VersionService) detectCurrentImageInfo(ctx context.Context) (tag string, digest string, imageRef string, imageID string) {+func (s *VersionService) detectCurrentImageInfo(ctx context.Context) (tag, digest, imageRef, imageID string) {if s.dockerService == nil {slog.Debug("detectCurrentImageInfo: dockerService is nil")return "", "", "", ""@@ -423,7 +406,7 @@ func (s *VersionService) detectCurrentImageInfo(ctx context.Context) (tag string}slog.Debug("detectCurrentImageInfo: detected container", "containerId", containerId)- inspectResult, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerId, client.ContainerInspectOptions{})+ inspectResult, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerId, client.ContainerInspectOptions{})if err != nil {slog.Debug("detectCurrentImageInfo: failed to inspect container", "containerId", containerId, "error", err)return "", "", "", ""diff --git a/backend/internal/version/service_test.go b/backend/internal/version/service_test.goindex d0d236047..7d7094b19 100644--- a/backend/internal/version/service_test.go+++ b/backend/internal/version/service_test.go@@ -1,10 +1,6 @@package versionimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/project"-- "github.com/getarcaneapp/arcane/backend/v2/internal/event"-"context""encoding/json""fmt"@@ -19,7 +15,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"+ "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/google/go-containerregistry/pkg/name"ggcrregistry "github.com/google/go-containerregistry/pkg/registry"diff --git a/backend/internal/volume/backup.go b/backend/internal/volume/backup.goindex c6039ba51..ce89459e7 100644--- a/backend/internal/volume/backup.go+++ b/backend/internal/volume/backup.go@@ -2,10 +2,9 @@ package volumeimport ("archive/tar"+ "cmp""compress/gzip""context"- "crypto/sha256"- "encoding/hex""fmt""io""log/slog"@@ -15,12 +14,7 @@ import ("time""uuid"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"emperror.dev/errors"- "gorm.io/gorm"-cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/backup"@@ -33,16 +27,20 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/backupbrowser"s3utils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/s3"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/moby/moby/client""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"+ "gorm.io/gorm")type backupStorageMode string@@ -55,13 +53,29 @@ const (// backupStorageModeNamedVolumeFallback means no suitable Arcane container// mount was found, so Arcane's dedicated named backup volume is used.backupStorageModeNamedVolumeFallback backupStorageMode = "named_volume_fallback"-)-const backupMountMissingWarning = "No volume is mounted at /backups in the Arcane container. Backups will only live inside Docker unless you mount a host path."+ backupMountMissingWarning = "No volume is mounted at /backups in the Arcane container. Backups will only live inside Docker unless you mount a host path."-const (volumeBackupContainerRecoveryTimeout = 30 * time.SecondvolumeBackupContainerRecoveryInterval = 500 * time.Millisecond++ volumeRusticRepositoryPath = "/repository/volumes"+ localVolumeRepositoryID = "volumes:local"+ legacyVolumePasswordSaltInternal = "arcane-volume-backups:"++ restoreBackupFilesScriptInternal = `set -e+archive="$1"+shift+archive_mode=$(stat -c '%A' -- "$archive" 2>/dev/null) || { echo ARCANE_NOT_FOUND >&2; exit 44; }+case "$archive_mode" in -*) ;; *) echo ARCANE_NOT_FOUND >&2; exit 44 ;; esac+for member do+ if ! tar -tzf "$archive" -- "$member" >/dev/null 2>&1; then echo ARCANE_NOT_FOUND >&2; exit 44; fi+done+tar -xzf "$archive" -C /volume -- "$@"`++ defaultVolumeBackupSchedule = "0 0 2 * * *"++ systemRecoverySnapshotLabel = "arcane-system-recovery")type backupStorageMountInternal struct {@@ -121,10 +135,7 @@ func (s *VolumeService) resolveUsableBackupStorageMountInternal(ctx context.Cont}func backupMountWarningForStorageInternal(storage backupStorageMountInternal) string {- if storage.mode == backupStorageModeArcaneMount {- return ""- }- return backupMountMissingWarning+ return kit.Ternary(storage.mode == backupStorageModeArcaneMount, "", backupMountMissingWarning)}func backupMountWarningFromArcaneMountsInternal(mounts []container.MountPoint) string {@@ -351,11 +362,7 @@ func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName strsortCol = "created_at"}- if params.Order == pagination.SortDesc {- sortOrder = "DESC"- } else {- sortOrder = "ASC"- }+ sortOrder = kit.Ternary(params.Order == pagination.SortDesc, "DESC", "ASC")}query = query.Order(fmt.Sprintf("%s %s", sortCol, sortOrder))@@ -390,7 +397,11 @@ func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName str}remoteAvailable := backup.RemoteSnapshotChecker(ctx, s.s3Destinations, root)for i := range backups {- backups[i].Type = volumeBackupManagementTypeInternal(backups[i].PolicyID)+ backups[i].Type = kit.Ternary(+ strings.HasPrefix(backups[i].PolicyID, backuptypes.SystemVolumePolicyPrefix),+ backuptypes.ManagementTypeSystem,+ backuptypes.ManagementTypeVolume,+ )backups[i].RemoteAvailable = remoteAvailable(backups[i].S3DestinationID, backups[i].RemoteSnapshotID)}@@ -417,13 +428,6 @@ func applyBackupManagementFilterInternal(query *gorm.DB, typeFilter string) *gorreturn query.Where("policy_id NOT LIKE ? OR policy_id IS NULL", backuptypes.SystemVolumePolicyPrefix+"%")}-func volumeBackupManagementTypeInternal(policyID string) backuptypes.ManagementType {- if strings.HasPrefix(policyID, backuptypes.SystemVolumePolicyPrefix) {- return backuptypes.ManagementTypeSystem- }- return backuptypes.ManagementTypeVolume-}-func (s *VolumeService) ListBackups(ctx context.Context, volumeName string) ([]VolumeBackup, error) {slog.DebugContext(ctx, "volume service: list backups", "volume", volumeName)var backups []VolumeBackup@@ -468,24 +472,14 @@ func (s *VolumeService) backupArchiveFilenameInternal(backupID string) (string,return sanitizedBackupID + ".tar.gz", nil}-const (- volumeRusticRepositoryPath = "/repository/volumes"- localVolumeRepositoryID = "volumes:local"-)--func (s *VolumeService) legacyVolumePasswordInternal() string {- sum := sha256.Sum256([]byte("arcane-volume-backups:" + s.encryptionKey))- return hex.EncodeToString(sum[:])-}-// volumeBackupPasswordInternal returns the recovery key once one is stored, re-keying the given repositories off the legacy derivation first.func (s *VolumeService) volumeBackupPasswordInternal(ctx context.Context, dockerClient *client.Client, repositories ...backup.Repository) (string, error) {if s.recoveryKeys == nil {- return s.legacyVolumePasswordInternal(), nil+ return kit.SHA256Hex(legacyVolumePasswordSaltInternal + s.encryptionKey), nil}key, err := s.recoveryKeys.Get(ctx)if errors.Is(err, backup.ErrRecoveryKeyNotConfigured) {- return s.legacyVolumePasswordInternal(), nil+ return kit.SHA256Hex(legacyVolumePasswordSaltInternal + s.encryptionKey), nil}if err != nil {return "", err@@ -516,7 +510,7 @@ func (s *VolumeService) rekeyRepositoryInternal(ctx context.Context, dockerClien}repository = writable}- if err := s.engine.ChangeRepositoryPassword(ctx, dockerClient, repository, s.legacyVolumePasswordInternal(), recoveryKey); err != nil {+ if err := s.engine.ChangeRepositoryPassword(ctx, dockerClient, repository, kit.SHA256Hex(legacyVolumePasswordSaltInternal+s.encryptionKey), recoveryKey); err != nil {slog.DebugContext(ctx, "volume backup repository was not re-keyed", "repository", repository.ID, "error", err.Error())return}@@ -642,9 +636,7 @@ func (s *VolumeService) resolveBackupPlanInternal(ctx context.Context, volumeNam}func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, user common.User, trigger VolumeBackupTrigger, request volumetypes.CreateBackupRequest) (_ *VolumeBackup, err error) {- if trigger == "" {- trigger = VolumeBackupTriggerManual- }+ trigger = cmp.Or(trigger, VolumeBackupTriggerManual)plan, err := s.resolveBackupPlanInternal(ctx, volumeName, trigger, request, nil)if err != nil {return nil, err@@ -657,9 +649,7 @@ func (s *VolumeService) CreateSystemManagedBackup(ctx context.Context, volumeNamif !strings.HasPrefix(policyID, backuptypes.SystemVolumePolicyPrefix) {return nil, errors.New("invalid system-managed volume backup policy id")}- if trigger == "" {- trigger = VolumeBackupTriggerManual- }+ trigger = cmp.Or(trigger, VolumeBackupTriggerManual)transient := &VolumeBackupPolicy{VolumeName: volumeName, Enabled: true, Schedule: policy.Schedule, RetentionCount: policy.RetentionCount,StopContainers: policy.StopContainers, LocalEnabled: policy.LocalEnabled, S3Enabled: policy.S3Enabled,@@ -695,7 +685,12 @@ func (s *VolumeService) prepareBackupInternal(ctx context.Context, volumeName stentry := &VolumeBackup{VolumeName: volumeName, CreatedAt: time.Now(), Status: VolumeBackupStatusRunning,Trigger: trigger, Destination: plan.destination, Format: VolumeBackupFormatRustic,- S3DestinationID: plan.s3DestinationID, PolicyID: policyID, Type: volumeBackupManagementTypeInternal(policyID),+ S3DestinationID: plan.s3DestinationID, PolicyID: policyID,+ Type: kit.Ternary(+ strings.HasPrefix(policyID, backuptypes.SystemVolumePolicyPrefix),+ backuptypes.ManagementTypeSystem,+ backuptypes.ManagementTypeVolume,+ ),}entry.ID = fmt.Sprintf("%s-%d-%s", volumeName, time.Now().UnixNano(), uuid.New().String()[:8])if err := s.db.WithContext(ctx).Create(entry).Error; err != nil {@@ -1619,23 +1614,12 @@ func (s *VolumeService) listArchiveBackupPathsInternal(ctx context.Context, back}lines := strings.Split(strings.TrimSpace(stdout), "\n")files := make([]string, 0, len(lines))- seen := make(map[string]struct{})for _, line := range lines {- clean := strings.TrimSpace(line)- if clean == "" {- continue- }- clean = strings.TrimPrefix(clean, "./")- if clean == "" {- continue- }- if _, ok := seen[clean]; ok {- continue+ if clean := strings.TrimPrefix(strings.TrimSpace(line), "./"); clean != "" {+ files = append(files, clean)}- seen[clean] = struct{}{}- files = append(files, clean)}- return files, nil+ return kit.Unique(files), nil}func (s *VolumeService) restoreBackupFilesInContainerInternal(ctx context.Context, containerID, filename string, cleanedPaths []string) (string, error) {@@ -1648,16 +1632,6 @@ func (s *VolumeService) restoreBackupFilesInContainerInternal(ctx context.Contexreturn stderr, errors.WrapIf(err, "failed to restore files")}-const restoreBackupFilesScriptInternal = `set -e-archive="$1"-shift-archive_mode=$(stat -c '%A' -- "$archive" 2>/dev/null) || { echo ARCANE_NOT_FOUND >&2; exit 44; }-case "$archive_mode" in -*) ;; *) echo ARCANE_NOT_FOUND >&2; exit 44 ;; esac-for member do- if ! tar -tzf "$archive" -- "$member" >/dev/null 2>&1; then echo ARCANE_NOT_FOUND >&2; exit 44; fi-done-tar -xzf "$archive" -C /volume -- "$@"`-func (s *VolumeService) restoreArchiveBackupFilesInternal(ctx context.Context, dockerClient *client.Client, volumeName, backupID string, cleanedPaths []string) error {filename, err := s.backupArchiveFilenameInternal(backupID)if err != nil {@@ -1795,8 +1769,6 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,return nil}-const defaultVolumeBackupSchedule = "0 0 2 * * *"-func (s *VolumeService) loadVolumeBackupPoliciesInternal(ctx context.Context, volumeName string) ([]VolumeBackupPolicy, error) {var policies []VolumeBackupPolicyif err := s.db.WithContext(ctx).Where("volume_name = ?", volumeName).Order("created_at ASC").Find(&policies).Error; err != nil {@@ -2025,10 +1997,7 @@ func (s *VolumeService) disableMissingS3Internal(ctx context.Context, policy *Voif !errors.Is(err, backup.ErrRemoteRepositoryMissing) {return false, nil}- column := "enabled"- if policy.LocalEnabled {- column = "s3_enabled"- }+ column := kit.Ternary(policy.LocalEnabled, "s3_enabled", "enabled")result := s.db.WithContext(ctx).Model(&VolumeBackupPolicy{}).Where("id = ? AND s3_destination_id = ? AND enabled = ? AND s3_enabled = ? AND local_enabled = ?", policy.ID, policy.S3DestinationID, true, true, policy.LocalEnabled).Update(column, false)@@ -2044,8 +2013,6 @@ func (s *VolumeService) disableMissingS3Internal(ctx context.Context, policy *Voreturn true, nil}-const systemRecoverySnapshotLabel = "arcane-system-recovery"-type remoteRepositoryKeyInternal struct {destinationID stringinstanceID stringdiff --git a/backend/internal/volume/backup_management_test.go b/backend/internal/volume/backup_management_test.goindex 6de144a64..4572977ad 100644--- a/backend/internal/volume/backup_management_test.go+++ b/backend/internal/volume/backup_management_test.go@@ -13,6 +13,7 @@ import (volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/libtnb/sqlite""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/crypto""gorm.io/gorm")@@ -48,6 +49,7 @@ func TestListBackupsPaginatedByManagementTypeInternal(t *testing.T) {require.Equal(t, backuptypes.ManagementTypeVolume, entry.Type)}}+func TestVolumeBackupPasswordPrefersRecoveryKey(t *testing.T) {gormDB, err := gorm.Open(sqlite.Open("file:volume-backup-password?mode=memory&cache=shared"), &gorm.Config{})require.NoError(t, err)@@ -62,7 +64,7 @@ func TestVolumeBackupPasswordPrefersRecoveryKey(t *testing.T) {password, err := service.volumeBackupPasswordInternal(t.Context(), nil)require.NoError(t, err)- require.Equal(t, service.legacyVolumePasswordInternal(), password)+ require.Equal(t, kit.SHA256Hex(legacyVolumePasswordSaltInternal+service.encryptionKey), password)recoveryKey := "QWERTY-ABCDEF-234567-GHIJKL-MNOPQR-STUVWX-YZ2345-ZXCVBN"require.NoError(t, recoveryKeys.Set(t.Context(), recoveryKey))diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.goindex 077f0763a..729795a19 100644--- a/backend/internal/volume/handler.go+++ b/backend/internal/volume/handler.go@@ -1,6 +1,7 @@package volumeimport (+ "cmp""context""fmt""io"@@ -10,14 +11,13 @@ import ("strconv""strings"+ "emperror.dev/errors"+ "github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment"-- "emperror.dev/errors"- "github.com/danielgtaylor/huma/v2"- "github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -596,9 +596,7 @@ func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInputparams.Filters["inUse"] = input.InUse}- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)volumes, paginationResp, counts, err := h.volumeService.ListVolumesPaginated(ctx, params, input.IncludeInternal)if err != nil {@@ -898,9 +896,7 @@ func (h *VolumeHandler) ListBackups(ctx context.Context, input *ListBackupsInput},}- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)backups, paginationResp, err := h.volumeService.ListBackupsPaginated(ctx, input.VolumeName, params)if err != nil {diff --git a/backend/internal/volume/helper_container.go b/backend/internal/volume/helper_container.goindex 35bd2b379..0c5ecd489 100644--- a/backend/internal/volume/helper_container.go+++ b/backend/internal/volume/helper_container.go@@ -1,9 +1,8 @@package volumeimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"bytes"+ "cmp""context""encoding/json/v2""io"@@ -12,16 +11,17 @@ import ("time""emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"dockerutil "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/libarcane/volumehelper"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/moby/moby/api/types/container""github.com/moby/moby/client""github.com/samber/mo"acfstypes "go.getarcane.app/acfs/types"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg")// volumeHelper tracks a reused helper container and the last@@ -73,7 +73,7 @@ func (s *VolumeService) toolsImageInternal() string {}func isUnlabeledVolumeHelperContainerInternal(c container.Summary) bool {- if internal, _ := utils.ParseBool(c.Labels[libarcane.InternalResourceLabel]); !internal {+ if internal, _ := kit.ParseBool(c.Labels[libarcane.InternalResourceLabel]); !internal {return false}@@ -95,7 +95,7 @@ func isVolumeHelperContainerInternal(c container.Summary) bool {if isUnlabeledVolumeHelperContainerInternal(c) {return true}- if internal, _ := utils.ParseBool(c.Labels[libarcane.InternalResourceLabel]); !internal {+ if internal, _ := kit.ParseBool(c.Labels[libarcane.InternalResourceLabel]); !internal {return false}@@ -292,7 +292,7 @@ func (s *VolumeService) getReusableHelperInternal(ctx context.Context, dockerClireturn mo.None[string]()}- inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, helper.id, client.ContainerInspectOptions{})+ inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, helper.id, client.ContainerInspectOptions{})if err != nil || inspect.Container.State == nil || !inspect.Container.State.Running {s.helperMu.Lock()delete(s.helperByVolume, volumeName)@@ -454,7 +454,8 @@ func (s *VolumeService) CleanupOrphanedVolumeHelpers(ctx context.Context) (int,}if _, err := dockerClient.ContainerRemove(ctx, c.ID, volumehelper.RemoveOptions()); err != nil {- slog.WarnContext(ctx,+ slog.WarnContext(+ ctx,"volume service: failed to remove orphaned volume helper container","container_id", c.ID,"container_names", c.Names,@@ -497,10 +498,7 @@ func (s *VolumeService) execInContainerInternal(ctx context.Context, containerID}if exitCode != 0 {- execErr := strings.TrimSpace(stderr.String())- if execErr == "" {- execErr = strings.TrimSpace(stdout.String())- }+ execErr := cmp.Or(strings.TrimSpace(stderr.String()), strings.TrimSpace(stdout.String()))if execErr != "" {return stdout.String(), stderr.String(), errors.Errorf("command exited with code %d: %s", exitCode, execErr)}diff --git a/backend/internal/volume/listing.go b/backend/internal/volume/listing.goindex 9b4a753c9..7e2100bfa 100644--- a/backend/internal/volume/listing.go+++ b/backend/internal/volume/listing.go@@ -1,6 +1,7 @@package volumeimport (+ "cmp""context""log/slog""regexp"@@ -8,12 +9,10 @@ import ("time""emperror.dev/errors"-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/pagination"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/moby/moby/api/types/container"@@ -21,6 +20,7 @@ import ("github.com/moby/moby/api/types/volume""github.com/moby/moby/client""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool, []string, error) {@@ -81,7 +81,7 @@ func (s *VolumeService) GetVolumeSizes(ctx context.Context) (map[string]VolumeSireturn result, nil}-func enrichVolumesWithUsageDataInternal(volumes []volume.Volume, usageVolumes []volume.Volume) []volume.Volume {+func enrichVolumesWithUsageDataInternal(volumes, usageVolumes []volume.Volume) []volume.Volume {usageByName := make(map[string]*volume.UsageData, len(usageVolumes))for _, uv := range usageVolumes {if uv.Name == "" || uv.UsageData == nil {@@ -169,10 +169,7 @@ func (s *VolumeService) buildVolumeSortBindingsInternal() []pagination.SortBindiif a.InUse == b.InUse {return 0}- if a.InUse {- return -1- }- return 1+ return kit.Ternary(a.InUse, -1, 1)},},{@@ -196,10 +193,7 @@ func compareVolumeSizesInternal(a, b volumetypes.Volume) int {if aSize == bSize {return strings.Compare(a.Name, b.Name)}- if aSize < bSize {- return -1- }- return 1+ return kit.Ternary(aSize < bSize, -1, 1)}func (s *VolumeService) compareVolumeCreatedInternal(a, b volumetypes.Volume) int {@@ -209,10 +203,7 @@ func (s *VolumeService) compareVolumeCreatedInternal(a, b volumetypes.Volume) inif aTime.Before(bTime) {return -1}- if aTime.After(bTime) {- return 1- }- return 0+ return kit.Ternary(aTime.After(bTime), 1, 0)}return strings.Compare(a.CreatedAt, b.CreatedAt)}@@ -235,13 +226,7 @@ func buildVolumeFilterAccessorsInternal() []pagination.FilterAccessor[volumetype{Key: "inUse",Fn: func(v volumetypes.Volume, filterValue string) bool {- if filterValue == "true" {- return v.InUse- }- if filterValue == "false" {- return !v.InUse- }- return true+ return kit.Ternary(filterValue == "true", v.InUse, filterValue != "false" || !v.InUse)},},}@@ -296,7 +281,7 @@ func (s *VolumeService) isInternalVolumeInternal(v volumetypes.Volume) bool {return true}- internal, _ := utils.ParseBool(v.Labels[libarcane.InternalResourceLabel])+ internal, _ := kit.ParseBool(v.Labels[libarcane.InternalResourceLabel])return internal}@@ -315,10 +300,7 @@ func mountedVolumeNamesInternal(mounts []container.MountPoint) map[string]structif item.Type != mount.TypeVolume {continue}- name := strings.TrimSpace(item.Name)- if name == "" {- name = strings.TrimSpace(item.Source)- }+ name := cmp.Or(strings.TrimSpace(item.Name), strings.TrimSpace(item.Source))if name != "" {names[name] = struct{}{}}@@ -443,7 +425,8 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params paginatresult := config.SearchOrderAndPaginate(items, effectiveParams)counts := calculateVolumeUsageCountsInternal(items)paginationResp := pagination.BuildResponse(result.TotalCount, result.TotalAvailable, effectiveParams)- slog.DebugContext(ctx, "volume service: listed volumes",+ slog.DebugContext(+ ctx, "volume service: listed volumes","docker_host", dockerClient.DaemonHost(),"requested_sort", params.Sort,"requested_order", params.Order,diff --git a/backend/internal/volume/model.go b/backend/internal/volume/model.goindex 3121f39c0..897258a8f 100644--- a/backend/internal/volume/model.go+++ b/backend/internal/volume/model.go@@ -14,23 +14,19 @@ const (VolumeBackupStatusRunning VolumeBackupStatus = "running"VolumeBackupStatusSucceeded VolumeBackupStatus = "succeeded"VolumeBackupStatusFailed VolumeBackupStatus = "failed"-)--type VolumeBackupTrigger string-const (VolumeBackupTriggerManual VolumeBackupTrigger = "manual"VolumeBackupTriggerScheduled VolumeBackupTrigger = "scheduled"VolumeBackupTriggerSafety VolumeBackupTrigger = "safety"-)--type VolumeBackupFormat string-const (VolumeBackupFormatArchive VolumeBackupFormat = "archive"VolumeBackupFormatRustic VolumeBackupFormat = "rustic")+type VolumeBackupTrigger string++type VolumeBackupFormat string+type VolumeBackup struct {database.BaseModeldiff --git a/backend/internal/volume/module.go b/backend/internal/volume/module.goindex fbe4863e9..14336e921 100644--- a/backend/internal/volume/module.go+++ b/backend/internal/volume/module.go@@ -4,17 +4,16 @@ package volumeimport ("github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/backup"+ "github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"-- "github.com/getarcaneapp/arcane/backend/v2/internal/activity"- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/internal/volume/service.go b/backend/internal/volume/service.goindex d7f534033..7963c879a 100644--- a/backend/internal/volume/service.go+++ b/backend/internal/volume/service.go@@ -1,26 +1,23 @@package volumeimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""log/slog""strings""sync"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/backup"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image"s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"-- "emperror.dev/errors"-- "github.com/getarcaneapp/arcane/backend/v2/internal/actors"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"diff --git a/backend/internal/volume/service_test.go b/backend/internal/volume/service_test.goindex 924812316..9a2beac2e 100644--- a/backend/internal/volume/service_test.go+++ b/backend/internal/volume/service_test.go@@ -254,7 +254,6 @@ func TestIsVolumeHelperContainerInternal_UsesExplicitHelperLabel(t *testing.T) {}func TestEnrichVolumesWithUsageDataInternal(t *testing.T) {-tests := []struct {name stringvolumes []volume.Volumediff --git a/backend/internal/volume/workspace.go b/backend/internal/volume/workspace.goindex 9203327d9..df318fed0 100644--- a/backend/internal/volume/workspace.go+++ b/backend/internal/volume/workspace.go@@ -1,10 +1,6 @@package volumeimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/event"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"archive/tar""bytes""context"@@ -26,12 +22,11 @@ import ("emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"-"github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"acfsutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/acfs"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"@@ -41,6 +36,8 @@ import ("github.com/moby/moby/client""go.getarcane.app/acfs"acfstypes "go.getarcane.app/acfs/types"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg")func (s *VolumeService) GetVolumeWorkspace(ctx context.Context, volumeName string) (*workspacetypes.Workspace, error) {@@ -176,14 +173,11 @@ func decodeVolumeWorkspaceWalkInternal(source io.Reader, maxEntries int, maxFile})h := sha256.New()for _, entry := range revisionEntries {- utils.WriteFileTreeRevisionEntry(h, entry.RelativePath, classifications[entry.RelativePath], entry.Size, entry.ModTime.UnixNano(), entry.Mode, false)+ kit.WriteRecord(h, entry.RelativePath, classifications[entry.RelativePath], entry.Size, entry.ModTime.UnixNano(), entry.Mode)}slices.SortFunc(files, func(a, b workspacetypes.FileEntry) int {if a.IsDirectory != b.IsDirectory {- if a.IsDirectory {- return -1- }- return 1+ return kit.Ternary(a.IsDirectory, -1, 1)}return strings.Compare(a.RelativePath, b.RelativePath)})@@ -231,7 +225,7 @@ func (s *VolumeService) GetVolumeWorkspaceFile(ctx context.Context, volumeName,if err := s.validateVolumeHelperSupportInternal(ctx, volumeName); err != nil {return nil, classifyVolumeWorkspaceHelperSupportErrorInternal(err)}- rel, err := utils.NormalizeRelativePath(relativePath)+ rel, err := kit.NormalizeRelativePath(relativePath)if err != nil {return nil, common.Classify(common.ErrVolumeWorkspaceForbidden, errors.WrapIf(err, "invalid volume workspace path"))}@@ -299,7 +293,7 @@ func (s *VolumeService) DownloadVolumeWorkspaceFile(ctx context.Context, volumeNunlock()return nil, 0, classifyVolumeWorkspaceHelperSupportErrorInternal(err)}- rel, err := utils.NormalizeRelativePath(relativePath)+ rel, err := kit.NormalizeRelativePath(relativePath)if err != nil {unlock()return nil, 0, common.Classify(common.ErrVolumeWorkspaceForbidden, errors.WrapIf(err, "invalid volume workspace path"))@@ -340,10 +334,7 @@ func (r *volumeWorkspaceReadStreamInternal) Read(buffer []byte) (int, error) {if closeErr != nil {return 0, closeErr}- if readErr != nil && !stderrors.Is(readErr, io.EOF) {- return 0, readErr- }- return 0, io.EOF+ return 0, kit.Ternary(readErr != nil && !stderrors.Is(readErr, io.EOF), readErr, io.EOF)}if int64(len(buffer)) > r.remaining {buffer = buffer[:r.remaining]@@ -520,10 +511,7 @@ func classifyVolumeWorkspaceHelperSupportErrorInternal(err error) error {}func (s *VolumeService) validateVolumeWorkspacePathInternal(ctx context.Context, containerID, relativePath string, allowMissing bool) error {- allowMissingValue := "0"- if allowMissing {- allowMissingValue = "1"- }+ allowMissingValue := kit.Ternary(allowMissing, "1", "0")_, stderr, err := s.execInContainerInternal(ctx, containerID, "", []string{"sh", "-c", volumeWorkspaceValidatePathScriptInternal, "sh", relativePath, allowMissingValue})if err != nil {return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "validate volume workspace path")@@ -531,7 +519,8 @@ func (s *VolumeService) validateVolumeWorkspacePathInternal(ctx context.Context,return nil}-const volumeWorkspaceValidatePathScriptInternal = `set -e+const (+ volumeWorkspaceValidatePathScriptInternal = `set -erel="$1"allow_missing="$2"cur=/volume@@ -556,6 +545,40 @@ while :; doesacdone`+ volumeWorkspaceBackupCreateScriptInternal = `set -e+rel="$1"+archive="$2"+cur=/volume+current=+remaining=$rel+while :; do+ case "$remaining" in '') break ;; esac+ case "$remaining" in+ */*) segment=${remaining%%/*}; remaining=${remaining#*/} ;;+ *) segment=$remaining; remaining= ;;+ esac+ case "$current" in '') current=$segment ;; *) current="$current/$segment" ;; esac+ cur="$cur/$segment"+ if mode=$(stat -c '%A' -- "$cur" 2>/dev/null); then+ case "$mode" in l*) echo ARCANE_SYMLINK >&2; exit 42 ;; esac+ else+ printf 'absent\0%s\0' "$current"+ exit 0+ fi+ case "$remaining" in+ '') ;;+ *) case "$mode" in d*) ;; *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;; esac ;;+ esac+done+case "$rel" in+ */*) parent="/volume/${rel%/*}"; entry=${rel##*/} ;;+ *) parent=/volume; entry=$rel ;;+esac+cd "$parent"+tar -cf "$archive" "./$entry"+printf 'present\0'`+)+func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName string, manifest volumetypes.WorkspaceUpdateManifest, uploads map[int][]byte, user common.User) (*workspacetypes.Workspace, error) {totalStartedAt := time.Now()defer func() {@@ -702,7 +725,7 @@ func (s *VolumeService) resolveVolumeWorkspaceWriteIdentityInternal(ctx context.identity := volumeWorkspaceWriteIdentityInternal{}identitySource := ""for _, consumerID := range consumerIDs {- inspect, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, consumerID, client.ContainerInspectOptions{})+ inspect, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, consumerID, client.ContainerInspectOptions{})if inspectErr != nil || inspect.Container.Config == nil {// An uninspectable consumer could declare a conflicting user, so the identity is// indeterminate; defer to the volume root's owner.@@ -811,7 +834,7 @@ func (s *VolumeService) applyVolumeWorkspaceChangesInternal(for index := 0; index < len(changes); {if changes[index].Operation == volumetypes.FileOpRestoreFile {- rel, _ := utils.NormalizeRelativePath(changes[index].RelativePath)+ rel, _ := kit.NormalizeRelativePath(changes[index].RelativePath)if err := s.restoreVolumeWorkspaceFileInternal(ctx, containerID, volumeName, changes[index].BackupID, rel); err != nil {return rollbackFailureInternal(err)}@@ -882,7 +905,7 @@ func (s *VolumeService) executeVolumeWorkspaceACFSBatchInternal(}func mapVolumeWorkspaceChangeToACFSInternal(change volumetypes.WorkspaceFileChange, staged volumeWorkspaceStagedFileInternal) (acfstypes.ApplyChange, error) {- relativePath, err := utils.NormalizeRelativePath(change.RelativePath)+ relativePath, err := kit.NormalizeRelativePath(change.RelativePath)if err != nil {return acfstypes.ApplyChange{}, err}@@ -900,7 +923,7 @@ func mapVolumeWorkspaceChangeToACFSInternal(change volumetypes.WorkspaceFileChanresult.Operation = acfstypes.ApplyCreateFolderresult.Recursive = falsecase volumetypes.FileOpRename:- newName, nameErr := utils.ValidateFileName(change.NewName)+ newName, nameErr := kit.ValidateFileName(change.NewName)if nameErr != nil {return acfstypes.ApplyChange{}, nameErr}@@ -910,7 +933,7 @@ func mapVolumeWorkspaceChangeToACFSInternal(change volumetypes.WorkspaceFileChancase volumetypes.FileOpMove:parent := ""if strings.TrimSpace(change.NewParentPath) != "" {- parent, err = utils.NormalizeRelativePath(change.NewParentPath)+ parent, err = kit.NormalizeRelativePath(change.NewParentPath)if err != nil {return acfstypes.ApplyChange{}, err}@@ -927,7 +950,7 @@ func mapVolumeWorkspaceChangeToACFSInternal(change volumetypes.WorkspaceFileChan}func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileChange) error {- if _, err := utils.NormalizeRelativePath(change.RelativePath); err != nil {+ if _, err := kit.NormalizeRelativePath(change.RelativePath); err != nil {return errors.WrapIf(err, "invalid volume workspace path")}hasUpload := change.UploadIndex != nil@@ -944,7 +967,7 @@ func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileCif hasUpload {return errors.New("rename does not accept file content")}- if _, err := utils.ValidateFileName(change.NewName); err != nil {+ if _, err := kit.ValidateFileName(change.NewName); err != nil {return errors.WrapIf(err, "invalid volume workspace file name")}case volumetypes.FileOpMove:@@ -952,7 +975,7 @@ func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileCreturn errors.New("move does not accept file content")}if strings.TrimSpace(change.NewParentPath) != "" {- if _, err := utils.NormalizeRelativePath(change.NewParentPath); err != nil {+ if _, err := kit.NormalizeRelativePath(change.NewParentPath); err != nil {return errors.WrapIf(err, "invalid destination folder")}}@@ -1038,14 +1061,14 @@ func (s *VolumeService) createVolumeWorkspaceMutationContainerInternal(ctx contefunc volumeWorkspaceBackupScopeInternal(changes []volumetypes.WorkspaceFileChange) ([]string, error) {paths := make([]string, 0, len(changes)*2)for _, change := range changes {- rel, err := utils.NormalizeRelativePath(change.RelativePath)+ rel, err := kit.NormalizeRelativePath(change.RelativePath)if err != nil {return nil, err}paths = append(paths, rel)switch change.Operation {case volumetypes.FileOpRename:- newName, err := utils.ValidateFileName(change.NewName)+ newName, err := kit.ValidateFileName(change.NewName)if err != nil {return nil, err}@@ -1053,7 +1076,7 @@ func volumeWorkspaceBackupScopeInternal(changes []volumetypes.WorkspaceFileChangcase volumetypes.FileOpMove:parent := ""if strings.TrimSpace(change.NewParentPath) != "" {- parent, err = utils.NormalizeRelativePath(change.NewParentPath)+ parent, err = kit.NormalizeRelativePath(change.NewParentPath)if err != nil {return nil, err}@@ -1073,7 +1096,7 @@ func normalizeVolumeWorkspaceScopeInternal(paths []string) []string {if candidate == "." || candidate == "" {continue}- if slices.ContainsFunc(result, func(parent string) bool { return utils.FilePathMatches(candidate, parent) }) {+ if slices.ContainsFunc(result, func(parent string) bool { return kit.FilePathMatches(candidate, parent) }) {continue}result = append(result, candidate)@@ -1091,39 +1114,6 @@ type volumeWorkspaceBackupInternal struct {absentEntries []string}-const volumeWorkspaceBackupCreateScriptInternal = `set -e-rel="$1"-archive="$2"-cur=/volume-current=-remaining=$rel-while :; do- case "$remaining" in '') break ;; esac- case "$remaining" in- */*) segment=${remaining%%/*}; remaining=${remaining#*/} ;;- *) segment=$remaining; remaining= ;;- esac- case "$current" in '') current=$segment ;; *) current="$current/$segment" ;; esac- cur="$cur/$segment"- if mode=$(stat -c '%A' -- "$cur" 2>/dev/null); then- case "$mode" in l*) echo ARCANE_SYMLINK >&2; exit 42 ;; esac- else- printf 'absent\0%s\0' "$current"- exit 0- fi- case "$remaining" in- '') ;;- *) case "$mode" in d*) ;; *) echo ARCANE_NOT_DIRECTORY >&2; exit 47 ;; esac ;;- esac-done-case "$rel" in- */*) parent="/volume/${rel%/*}"; entry=${rel##*/} ;;- *) parent=/volume; entry=$rel ;;-esac-cd "$parent"-tar -cf "$archive" "./$entry"-printf 'present\0'`-func (s *VolumeService) backupVolumeWorkspaceScopeInternal(ctx context.Context, containerID string, scope []string) (*volumeWorkspaceBackupInternal, error) {if _, _, err := s.execInContainerInternal(ctx, containerID, "", []string{"mkdir", "-p", "/tmp/arcane-workspace"}); err != nil {return nil, errors.WrapIf(err, "prepare volume workspace backup directory")diff --git a/backend/internal/volume/workspace_handler.go b/backend/internal/volume/workspace_handler.goindex 7d9699a3e..97a320d96 100644--- a/backend/internal/volume/workspace_handler.go+++ b/backend/internal/volume/workspace_handler.go@@ -1,25 +1,23 @@package volumeimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""mime/multipart""net/http""path""strings"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/getarcaneapp/arcane/types/v2/base"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"diff --git a/backend/internal/volume/workspace_handler_test.go b/backend/internal/volume/workspace_handler_test.goindex 92cdf6450..7934a12aa 100644--- a/backend/internal/volume/workspace_handler_test.go+++ b/backend/internal/volume/workspace_handler_test.go@@ -1,14 +1,13 @@package volumeimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""mime/multipart""net/http""testing""github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"diff --git a/backend/internal/volume/workspace_test.go b/backend/internal/volume/workspace_test.goindex 89a14ca04..560490945 100644--- a/backend/internal/volume/workspace_test.go+++ b/backend/internal/volume/workspace_test.go@@ -32,6 +32,7 @@ import ("github.com/stretchr/testify/require""go.getarcane.app/acfs"acfstypes "go.getarcane.app/acfs/types"+ kit "go.getarcane.app/kit/pkg")func newVolumeWorkspaceTestDockerClientInternal(t *testing.T, server *httptest.Server) *client.Client {@@ -580,10 +581,11 @@ func TestUpdateVolumeWorkspaceRejectsStaleRevisionBeforeStaging(t *testing.T) {_ = json.NewEncoder(w).Encode(map[string]string{"Id": fmt.Sprintf("workspace-exec-%d", len(execCommands)-1)})case r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/exec/workspace-exec-") && strings.HasSuffix(r.URL.Path, "/start"):_, _ = io.Copy(io.Discard, r.Body)- output := "{\"version\":\"0.2.0\",\"revision\":\"test\",\"buildTime\":\"test\",\"protocol\":2}\n"- if strings.Contains(r.URL.Path, "workspace-exec-1") {- output = "{\"end\":true,\"version\":2}\n"- }+ output := kit.Ternary(+ strings.Contains(r.URL.Path, "workspace-exec-1"),+ "{\"end\":true,\"version\":2}\n",+ "{\"version\":\"0.2.0\",\"revision\":\"test\",\"buildTime\":\"test\",\"protocol\":2}\n",+ )writeDockerExecAttachResponseInternal(t, w, output)case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/exec/workspace-exec-") && strings.HasSuffix(r.URL.Path, "/json"):w.Header().Set("Content-Type", "application/json")diff --git a/backend/internal/vulnerability/handler.go b/backend/internal/vulnerability/handler.goindex d66941c19..ed62a4f1f 100644--- a/backend/internal/vulnerability/handler.go+++ b/backend/internal/vulnerability/handler.go@@ -1,14 +1,13 @@package vulnerabilityimport (+ "cmp""context""fmt""log/slog""net/http""time"- "github.com/getarcaneapp/arcane/types/v2/features"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common"@@ -18,6 +17,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"+ "github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/vulnerability")@@ -407,9 +407,7 @@ func (h *VulnerabilityHandler) GetScanSummary(ctx context.Context, input *GetSca// ListImageVulnerabilities returns a paginated list of vulnerabilities for an image.func (h *VulnerabilityHandler) ListImageVulnerabilities(ctx context.Context, input *ListImageVulnerabilitiesInput) (*handlerutil.Page[vulnerability.Vulnerability], error) {params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)if input.Severity != "" {params.Filters["severity"] = input.Severity}@@ -472,9 +470,7 @@ func (h *VulnerabilityHandler) GetEnvironmentSummary(ctx context.Context, input// ListAllVulnerabilities returns a paginated list of vulnerabilities across all images.func (input *ListAllVulnerabilitiesInput) queryParamsInternal() pagination.QueryParams {params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)if input.Severity != "" {params.Filters["severity"] = input.Severity}@@ -688,9 +684,7 @@ type ListIgnoredVulnerabilitiesInput struct {// ListIgnoredVulnerabilities returns a list of ignored vulnerabilities.func (h *VulnerabilityHandler) ListIgnoredVulnerabilities(ctx context.Context, input *ListIgnoredVulnerabilitiesInput) (*handlerutil.Page[vulnerability.IgnoredVulnerability], error) {params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)items, paginationResp, err := h.vulnerabilityService.ListIgnoredVulnerabilities(ctx, input.EnvironmentID, params)if err != nil {diff --git a/backend/internal/vulnerability/model.go b/backend/internal/vulnerability/model.goindex 4bb20b307..bacc04afb 100644--- a/backend/internal/vulnerability/model.go+++ b/backend/internal/vulnerability/model.go@@ -6,6 +6,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -186,10 +187,7 @@ func (v *VulnerabilityScanRecord) GetHighestSeverity() string {if v.LowCount > 0 {return "LOW"}- if v.UnknownCount > 0 {- return "UNKNOWN"- }- return "NONE"+ return kit.Ternary(v.UnknownCount > 0, "UNKNOWN", "NONE")}// VulnerabilityIgnore stores ignored vulnerability recordsdiff --git a/backend/internal/vulnerability/module.go b/backend/internal/vulnerability/module.goindex f1bf3cde2..e4057a81c 100644--- a/backend/internal/vulnerability/module.go+++ b/backend/internal/vulnerability/module.go@@ -3,7 +3,6 @@ package vulnerabilityimport ("github.com/danielgtaylor/huma/v2"-"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil")diff --git a/backend/internal/vulnerability/service_test.go b/backend/internal/vulnerability/service_test.goindex 3ac79c949..c43bfca5d 100644--- a/backend/internal/vulnerability/service_test.go+++ b/backend/internal/vulnerability/service_test.go@@ -1,8 +1,6 @@package vulnerabilityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"context""encoding/json""fmt"@@ -14,10 +12,10 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/kv"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/vulnerability"@@ -442,9 +440,9 @@ func TestSeverityCountColumnsForFilterInternal(t *testing.T) {want: []string{"high_count", "critical_count", "unknown_count"},},{- name: "invalid severities only",- value: "foo,bar",- want: []string{},+ name: "invalid severities only",+ value: "foo,bar",+ wantNil: true,},{name: "empty value",diff --git a/backend/internal/vulnerability/vulnerability.go b/backend/internal/vulnerability/vulnerability.goindex 23b54c540..8739ff741 100644--- a/backend/internal/vulnerability/vulnerability.go+++ b/backend/internal/vulnerability/vulnerability.go@@ -5,8 +5,6 @@ import ("sync""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/registry"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"@@ -14,6 +12,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/kv""github.com/getarcaneapp/arcane/backend/v2/internal/notification"+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"diff --git a/backend/internal/vulnerability/vulnerability_capabilities.go b/backend/internal/vulnerability/vulnerability_capabilities.goindex a9af39377..ca85c65ef 100644--- a/backend/internal/vulnerability/vulnerability_capabilities.go+++ b/backend/internal/vulnerability/vulnerability_capabilities.go@@ -2,14 +2,13 @@ package vulnerabilityimport ("context"- "crypto/sha256""encoding/json"- "fmt""log/slog""time""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg")const (@@ -25,7 +24,7 @@ type trivyCPUCapabilitiesInternal struct {}func (s *VulnerabilityService) getTrivyCPUCapabilitiesInternal(ctx context.Context, dockerClient *client.Client) (trivyCPUCapabilitiesInternal, error) {- key := fmt.Sprintf("trivy:cpu-capabilities:v1:%x", sha256.Sum256([]byte(dockerClient.DaemonHost()+"\x00"+dockerClient.ClientVersion())))+ key := "trivy:cpu-capabilities:v1:" + kit.SHA256Hex(dockerClient.DaemonHost()+"\x00"+dockerClient.ClientVersion())var cached trivyCPUCapabilitiesInternalif s.kvService != nil {raw, found, err := s.kvService.Get(ctx, key)diff --git a/backend/internal/vulnerability/vulnerability_export.go b/backend/internal/vulnerability/vulnerability_export.goindex 67989bf6b..673ad1f82 100644--- a/backend/internal/vulnerability/vulnerability_export.go+++ b/backend/internal/vulnerability/vulnerability_export.go@@ -1,6 +1,7 @@package vulnerabilityimport (+ "cmp""encoding/csv""io""iter"@@ -9,6 +10,7 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ kit "go.getarcane.app/kit/pkg")var vulnerabilityCSVHeaderInternal = []string{"CVE", "Severity", "Package", "Installed Version", "Fixed Version", "Image", "Ignored"}@@ -27,13 +29,10 @@ func WriteVulnerabilitiesCSV(w io.Writer, items iter.Seq2[vulnerability.Vulnerabif err != nil {return err}- image := item.ImageName- if image == "" {- image = item.ImageID- }+ image := cmp.Or(item.ImageName, item.ImageID)record := []string{item.VulnerabilityID, string(item.Severity), item.PkgName, item.InstalledVersion, item.FixedVersion, image, strconv.FormatBool(item.Ignored)}for j, value := range record {- record[j] = csvCellInternal(value)+ record[j] = kit.Ternary(value != "" && strings.ContainsRune("=+-@\t\r", rune(value[0])), "'"+value, value)}if err := writer.Write(record); err != nil {return errors.WrapIf(err, "failed to write csv")@@ -42,10 +41,3 @@ func WriteVulnerabilitiesCSV(w io.Writer, items iter.Seq2[vulnerability.Vulnerabwriter.Flush()return errors.WrapIf(writer.Error(), "failed to write csv")}--func csvCellInternal(value string) string {- if value != "" && strings.ContainsRune("=+-@\t\r", rune(value[0])) {- return "'" + value- }- return value-}diff --git a/backend/internal/vulnerability/vulnerability_feature_test.go b/backend/internal/vulnerability/vulnerability_feature_test.goindex dd3243a28..22270dc34 100644--- a/backend/internal/vulnerability/vulnerability_feature_test.go+++ b/backend/internal/vulnerability/vulnerability_feature_test.go@@ -8,17 +8,16 @@ import ("testing""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/docker"- "github.com/moby/moby/client"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/vulnerability""github.com/libtnb/sqlite"+ "github.com/moby/moby/client""github.com/stretchr/testify/require""go.uber.org/fx/fxtest""gorm.io/gorm"diff --git a/backend/internal/vulnerability/vulnerability_ignores.go b/backend/internal/vulnerability/vulnerability_ignores.goindex 513461268..5c3a40834 100644--- a/backend/internal/vulnerability/vulnerability_ignores.go+++ b/backend/internal/vulnerability/vulnerability_ignores.go@@ -1,18 +1,18 @@package vulnerabilityimport (+ "cmp""context""log/slog""slices""strings""emperror.dev/errors"-- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ kit "go.getarcane.app/kit/pkg"+ "gorm.io/gorm")func vulnerabilityIgnoreKeyInternal(imageID, vulnerabilityID, pkgName, installedVersion string) string {@@ -99,7 +99,7 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID st}// UnignoreVulnerability removes an ignore record together with any duplicates of its identity, so a finding never stays ignored after a restore.-func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envID string, ignoreID string) error {+func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envID, ignoreID string) error {if s.db == nil {return errors.New("database not available")}@@ -241,10 +241,7 @@ func applyIgnoredVulnerabilitiesSort(query *gorm.DB, sort string) *gorm.DB {}func applyIgnoredVulnerabilitiesSortPart(query *gorm.DB, part string, desc bool) *gorm.DB {- direction := "ASC"- if desc {- direction = "DESC"- }+ direction := kit.Ternary(desc, "DESC", "ASC")switch part {case "createdAt":@@ -285,9 +282,7 @@ func buildIgnoredVulnerabilitiesResponse(total int64, params pagination.QueryPar// ListIgnoredVulnerabilities returns a list of ignored vulnerabilities for an environmentfunc (s *VulnerabilityService) ListIgnoredVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) ([]vulnerability.IgnoredVulnerability, pagination.Response, error) {- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)if s.db == nil {return []vulnerability.IgnoredVulnerability{}, pagination.BuildResponse(0, 0, params), nil@@ -316,7 +311,7 @@ func (s *VulnerabilityService) ListIgnoredVulnerabilities(ctx context.Context, e}// GetIgnoreRecordsForImage retrieves all ignore records for a specific image-func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envID string, imageID string) ([]VulnerabilityIgnore, error) {+func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envID, imageID string) ([]VulnerabilityIgnore, error) {if s.db == nil {return nil, nil}diff --git a/backend/internal/vulnerability/vulnerability_ignores_test.go b/backend/internal/vulnerability/vulnerability_ignores_test.goindex 3f394dad3..2b2711166 100644--- a/backend/internal/vulnerability/vulnerability_ignores_test.go+++ b/backend/internal/vulnerability/vulnerability_ignores_test.go@@ -11,6 +11,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/vulnerability""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")// seedBulkIgnoreFixtureInternal stores nginx with 45 findings (more than one page) and redis with three findings covering every filter dimension.@@ -18,14 +19,8 @@ func seedBulkIgnoreFixtureInternal(t *testing.T, db *database.DB, svc *Vulnerabit.Helper()nginx := make([]vulnerability.Vulnerability, 0, 45)for i := range 45 {- severity := vulnerability.SeverityLow- if i%3 == 0 {- severity = vulnerability.SeverityHigh- }- fixed := ""- if i%2 == 0 {- fixed = "2.0.0"- }+ severity := kit.Ternary(i%3 == 0, vulnerability.SeverityHigh, vulnerability.SeverityLow)+ fixed := kit.Ternary(i%2 == 0, "2.0.0", "")nginx = append(nginx, vulnerability.Vulnerability{VulnerabilityID: fmt.Sprintf("CVE-N-%03d", i), PkgName: "libnginx", InstalledVersion: "1.0.0", FixedVersion: fixed, Severity: severity, Title: "nginx finding"})}redis := []vulnerability.Vulnerability{diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.goindex 583efac6d..fdd085dab 100644--- a/backend/internal/vulnerability/vulnerability_query.go+++ b/backend/internal/vulnerability/vulnerability_query.go@@ -12,20 +12,17 @@ import ("strings""time"- "github.com/moby/moby/api/types/container"-- "github.com/getarcaneapp/arcane/types/v2/features"-"emperror.dev/errors"-- "github.com/samber/mo"- "gorm.io/gorm"- "gorm.io/gorm/clause"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"+ "github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ "github.com/moby/moby/api/types/container"+ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"+ "gorm.io/gorm"+ "gorm.io/gorm/clause")// GetScanResult retrieves the most recent scan result for an image, with risk insights for completed scans.@@ -370,7 +367,7 @@ func (s *VulnerabilityService) listAllVulnerabilitiesQueryInternal(ctx context.Cif params.Filters["fixAvailable"] == "true" {q = q.Where("vulnerability_scan_items.fixed_version <> ''")}- if imageNameParts := splitNonEmptyCSVInternal(params.Filters["imageName"]); len(imageNameParts) > 0 {+ if imageNameParts := kit.TrimNonEmpty(strings.Split(params.Filters["imageName"], ",")); len(imageNameParts) > 0 {clauses := make([]string, 0, len(imageNameParts))args := make([]any, 0, len(imageNameParts))for _, part := range imageNameParts {@@ -391,9 +388,7 @@ func (s *VulnerabilityService) listAllVulnerabilitiesQueryInternal(ctx context.C// ListAllVulnerabilities returns a paginated list of vulnerabilities across all scanned images.func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID string, params pagination.QueryParams) ([]vulnerability.VulnerabilityWithImage, pagination.Response, error) {- if params.Limit == 0 {- params.Limit = 20- }+ params.Limit = cmp.Or(params.Limit, 20)if !s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) || s.db == nil {return []vulnerability.VulnerabilityWithImage{}, pagination.BuildResponse(0, 0, params), nil@@ -495,9 +490,21 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID}, nil}-// listAllVulnerabilityRecordBatchSizeInternal bounds how many scan records-// (each carrying a vulnerability blob of up to ~2 MiB) the backfill loads at once.-const listAllVulnerabilityRecordBatchSizeInternal = 25+const (+ // listAllVulnerabilityRecordBatchSizeInternal bounds how many scan records+ // (each carrying a vulnerability blob of up to ~2 MiB) the backfill loads at once.+ listAllVulnerabilityRecordBatchSizeInternal = 25++ threatIntelSettingKey = "vulnerabilityThreatIntelEnabled"+ highEPSSThreshold = 0.1+ riskTrendDays = 90+ riskDeltaDays = 7+ riskDeltaToleranceDays = 3+ riskSnapshotRetentionDays = 400+ riskiestImageLimit = 5+ topFindingLimit = 10+ riskDateLayout = "2006-01-02"+)// ListAllVulnerabilityImageOptions returns unique image names (or image IDs when name is empty)// for vulnerability filtering, optionally constrained by severity.@@ -530,24 +537,11 @@ func (s *VulnerabilityService) ListAllVulnerabilityImageOptions(ctx context.Contreturn nil, errors.WrapIf(err, "failed to list vulnerability image options")}- seen := make(map[string]struct{}, len(records))options := make([]string, 0, len(records))for _, record := range records {- label := strings.TrimSpace(record.ImageName)- if label == "" {- label = strings.TrimSpace(record.ID)- }- if label == "" {- continue- }- if _, exists := seen[label]; exists {- continue- }-- seen[label] = struct{}{}- options = append(options, label)+ options = append(options, cmp.Or(record.ImageName, record.ID))}-+ options = kit.Unique(kit.TrimNonEmpty(options))sort.Strings(options)return options, nil}@@ -573,7 +567,7 @@ func applyListAllVulnerabilityRecordPrefiltersInternal(query *gorm.DB, filters m}if imageNameFilter, ok := filters["imageName"]; ok {- imageNameParts := splitNonEmptyCSVInternal(imageNameFilter)+ imageNameParts := kit.TrimNonEmpty(strings.Split(imageNameFilter, ","))if len(imageNameParts) == 0 {return mo.None[*gorm.DB]()}@@ -591,13 +585,12 @@ func applyListAllVulnerabilityRecordPrefiltersInternal(query *gorm.DB, filters m}func severityCountColumnsForFilterInternal(value string) []string {- parts := splitNonEmptyCSVInternal(value)+ parts := kit.TrimNonEmpty(strings.Split(value, ","))if len(parts) == 0 {return nil}columns := make([]string, 0, len(parts))- seen := make(map[string]struct{}, len(parts))for _, part := range parts {var col stringswitch {@@ -615,27 +608,10 @@ func severityCountColumnsForFilterInternal(value string) []string {continue}- if _, exists := seen[col]; exists {- continue- }-- seen[col] = struct{}{}columns = append(columns, col)}- return columns-}--func splitNonEmptyCSVInternal(value string) []string {- parts := make([]string, 0)- for part := range strings.SplitSeq(value, ",") {- part = strings.TrimSpace(part)- if part == "" {- continue- }- parts = append(parts, part)- }- return parts+ return kit.Unique(columns)}// GetScanSummariesByImageIDs retrieves scan summaries for multiple images@@ -681,18 +657,6 @@ func (s *VulnerabilityService) GetScanSummariesByImageIDs(ctx context.Context, ireturn result, nil}-const (- threatIntelSettingKey = "vulnerabilityThreatIntelEnabled"- highEPSSThreshold = 0.1- riskTrendDays = 90- riskDeltaDays = 7- riskDeltaToleranceDays = 3- riskSnapshotRetentionDays = 400- riskiestImageLimit = 5- topFindingLimit = 10- riskDateLayout = "2006-01-02"-)-type imageUsageInternal struct {running intstopped int@@ -927,10 +891,7 @@ func (a *riskAccumulatorInternal) finishInternal() {return cmp.Compare(b.finding.Risk, a.finding.Risk)}if a.finding.KnownExploited != b.finding.KnownExploited {- if b.finding.KnownExploited {- return 1- }- return -1+ return kit.Ternary(b.finding.KnownExploited, 1, -1)}return cmp.Or(cmp.Compare(b.finding.RunningImagesAffected, a.finding.RunningImagesAffected),diff --git a/backend/internal/vulnerability/vulnerability_scan.go b/backend/internal/vulnerability/vulnerability_scan.goindex e0425f658..b20b17eda 100644--- a/backend/internal/vulnerability/vulnerability_scan.go+++ b/backend/internal/vulnerability/vulnerability_scan.go@@ -1,13 +1,7 @@package vulnerabilityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/types/v2/features"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-+ "cmp""context""fmt""log/slog"@@ -16,19 +10,21 @@ import ("sync/atomic""time"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"emperror.dev/errors"-- imagetypes "github.com/moby/moby/api/types/image"- "github.com/samber/mo"- "golang.org/x/sync/errgroup"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/notification"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+ "github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ imagetypes "github.com/moby/moby/api/types/image"+ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg"+ "golang.org/x/sync/errgroup")func (s *VulnerabilityService) setScanPhaseInternal(imageID string, phase vulnerability.ScanPhase) {@@ -78,7 +74,6 @@ func (s *VulnerabilityService) resolveScanPhaseInternal(imageID string, status vif status == vulnerability.ScanStatusPending {return vulnerability.ScanPhaseCreatingContainer}-return vulnerability.ScanPhaseScanningImage}@@ -99,7 +94,7 @@ func (s *VulnerabilityService) applyScanPhaseToResultInternal(result *vulnerabil}// ScanImage scans an image for vulnerabilities using Trivy-func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imageID string, user common.User) (*vulnerability.ScanResult, error) {+func (s *VulnerabilityService) ScanImage(ctx context.Context, envID, imageID string, user common.User) (*vulnerability.ScanResult, error) {if err := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); err != nil {return nil, err}@@ -129,10 +124,7 @@ func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imagif err != nil {return nil, err}- status := vulnerability.ScanStatusPending- if releaseSlot != nil {- status = vulnerability.ScanStatusScanning- }+ status := kit.Ternary(releaseSlot != nil, vulnerability.ScanStatusScanning, vulnerability.ScanStatusPending)slog.InfoContext(scanCtx,"vulnerability scan queued",@@ -210,7 +202,7 @@ func (s *VulnerabilityService) markStaleScanIfNeeded(ctx context.Context, record}}-func (s *VulnerabilityService) scanImageInBackgroundInternal(ctx context.Context, envID string, imageID, imageName string, user common.User, activityID string, slotID int, releaseSlot func()) {+func (s *VulnerabilityService) scanImageInBackgroundInternal(ctx context.Context, envID, imageID, imageName string, user common.User, activityID string, slotID int, releaseSlot func()) {var err errorif releaseSlot == nil {slotID, releaseSlot, err = s.acquireTrivyScanSlotInternal(ctx, imageID, true)@@ -431,11 +423,7 @@ func scheduledScanImageTargetInternal(img imagetypes.Summary) (imageID, imageNam}// Skip intermediate / dangling images with no usable name.- if imageName == "<none>:<none>" || imageName == imageID {- return imageID, imageName, false- }-- return imageID, imageName, true+ return imageID, imageName, imageName != "<none>:<none>" && imageName != imageID}func (s *VulnerabilityService) runScheduledImageScanInternal(@@ -731,7 +719,7 @@ func (s *VulnerabilityService) fixedVulnerabilitiesForNotifications(}// logScanEvent logs a vulnerability scan event-func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID string, imageID, imageName string, user common.User, success bool, errMsg string) {+func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID, imageID, imageName string, user common.User, success bool, errMsg string) {metadata := database.JSON{"action": "vulnerability_scan","imageId": imageID,@@ -742,10 +730,7 @@ func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID string, imetadata["error"] = errMsg}- environmentID := envID- if environmentID == "" {- environmentID = "0"- }+ environmentID := cmp.Or(envID, "0")eventType := event.EventTypeImageScanif err := s.eventService.LogImageEvent(ctx, eventType, imageID, imageName, user.ID, user.Username, environmentID, metadata); err != nil {@@ -754,7 +739,7 @@ func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID string, i}// logScheduledScanEvent logs a vulnerability scan event using the dedicated scheduled scan event type.-func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envID string, imageID, imageName string, user common.User, success bool, errMsg string) {+func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envID, imageID, imageName string, user common.User, success bool, errMsg string) {metadata := database.JSON{"action": "scheduled_vulnerability_scan","imageId": imageID,@@ -765,10 +750,7 @@ func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envIDmetadata["error"] = errMsg}- environmentID := envID- if environmentID == "" {- environmentID = "0"- }+ environmentID := cmp.Or(envID, "0")if err := s.eventService.LogImageEvent(ctx, event.EventTypeImageVulnerabilityScan, imageID, imageName, user.ID, user.Username, environmentID, metadata); err != nil {slog.WarnContext(ctx, "failed to log scheduled vulnerability scan event", "error", err)diff --git a/backend/internal/vulnerability/vulnerability_store.go b/backend/internal/vulnerability/vulnerability_store.goindex 0914b3019..722fe652b 100644--- a/backend/internal/vulnerability/vulnerability_store.go+++ b/backend/internal/vulnerability/vulnerability_store.go@@ -1,8 +1,6 @@package vulnerabilityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""encoding/json/v2""fmt"@@ -16,16 +14,16 @@ import ("time""emperror.dev/errors"-- "go.getarcane.app/acfs"- "gorm.io/gorm"- "gorm.io/gorm/clause"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2""github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ "go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg"+ "gorm.io/gorm"+ "gorm.io/gorm/clause")// deleteScanChildRowsInternal best-effort removes the raw report and CVE item@@ -89,7 +87,20 @@ func (s *VulnerabilityService) BackfillScanItems(ctx context.Context) {}}-const scanItemInsertBatchSizeInternal = 500+const (+ scanItemInsertBatchSizeInternal = 500++ threatIntelStateKey = "vuln:threat-intel:state:v1"+ threatIntelSyncInterval = 20 * time.Hour+ threatIntelStaleAfter = 72 * time.Hour+ kevFeedMaxBytes = 32 << 20+ epssBatchMaxIDs = 100+ epssBatchMaxChars = 1900+ epssBatchDelay = 250 * time.Millisecond+ epssMaxRetryAfter = time.Minute+ epssMaxCVEsPerSync = 20000+ threatIntelUpsertBatch = 500+)func buildScanItemsInternal(imageID string, vulns []vulnerability.Vulnerability) ([]VulnerabilityScanItem, error) {items := make([]VulnerabilityScanItem, 0, len(vulns))@@ -345,11 +356,7 @@ func (s *VulnerabilityService) saveScanResultStatusFallbackInternal(ctx context.if errMsg == "" && originalErr != nil {errMsg = fmt.Sprintf("failed to persist full scan result: %v", originalErr)}- if errMsg == "" {- updates["error"] = nil- } else {- updates["error"] = errMsg- }+ updates["error"] = kit.Ternary[any](errMsg == "", nil, errMsg)if err := s.db.WithContext(ctx).Model(&VulnerabilityScanRecord{}).@@ -508,19 +515,6 @@ func (s *VulnerabilityService) ensureSummary(result *vulnerability.ScanResult) {result.Summary = vuln.SeveritySummary(result.Vulnerabilities)}-const (- threatIntelStateKey = "vuln:threat-intel:state:v1"- threatIntelSyncInterval = 20 * time.Hour- threatIntelStaleAfter = 72 * time.Hour- kevFeedMaxBytes = 32 << 20- epssBatchMaxIDs = 100- epssBatchMaxChars = 1900- epssBatchDelay = 250 * time.Millisecond- epssMaxRetryAfter = time.Minute- epssMaxCVEsPerSync = 20000- threatIntelUpsertBatch = 500-)-type threatIntelStateInternal struct {LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"`ETag string `json:"etag,omitempty"`diff --git a/backend/internal/vulnerability/vulnerability_trivy.go b/backend/internal/vulnerability/vulnerability_trivy.goindex ae2141ef7..b3b43ffef 100644--- a/backend/internal/vulnerability/vulnerability_trivy.go+++ b/backend/internal/vulnerability/vulnerability_trivy.go@@ -1,9 +1,7 @@package vulnerabilityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/types/v2/features"-+ "cmp""context""fmt""io"@@ -14,12 +12,7 @@ import ("time""emperror.dev/errors"-- containertypes "github.com/moby/moby/api/types/container"- mounttypes "github.com/moby/moby/api/types/mount"- "github.com/moby/moby/client"- "github.com/samber/mo"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -27,7 +20,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"+ "github.com/getarcaneapp/arcane/types/v2/features""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ containertypes "github.com/moby/moby/api/types/container"+ mounttypes "github.com/moby/moby/api/types/mount"+ "github.com/moby/moby/client"+ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup""gorm.io/gorm/clause")@@ -100,11 +99,7 @@ func (s *VulnerabilityService) getTrivyConcurrentScanContainersInternal() int {}limit := cfg.TrivyConcurrentScanContainers.AsInt()- if limit < 1 {- return 1- }-- return limit+ return kit.Ternary(limit < 1, 1, limit)}func (s *VulnerabilityService) getTrivyScanSlotChannelInternal(limit int) chan int {@@ -364,10 +359,7 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, con}if err != nil {if errors.Is(err, io.EOF) {- errMsg := vuln.ReadTempFileExcerpt(stderrFile)- if errMsg == "" {- errMsg = "trivy scan produced no output"- }+ errMsg := cmp.Or(vuln.ReadTempFileExcerpt(stderrFile), "trivy scan produced no output")slog.WarnContext(ctx,"trivy scan diagnostics","image", imageName,@@ -393,10 +385,7 @@ func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, con}if trivyReport == nil {- errMsg := vuln.ReadTempFileExcerpt(stderrFile)- if errMsg == "" {- errMsg = "trivy scan produced no output"- }+ errMsg := cmp.Or(vuln.ReadTempFileExcerpt(stderrFile), "trivy scan produced no output")slog.WarnContext(ctx,"trivy scan diagnostics","image", imageName,@@ -1081,7 +1070,7 @@ func (s *VulnerabilityService) waitForTrivyContainer(return statusCode, nil}-func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scannerImage string, imageName string, imageID string, slotID int) (*vulnerability.ScanResult, error) {+func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scannerImage, imageName, imageID string, slotID int) (*vulnerability.ScanResult, error) {slog.DebugContext(ctx,"running trivy scan","imageId", imageID,@@ -1196,10 +1185,7 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner}if err != nil {if errors.Is(err, io.EOF) {- errMsg := vuln.ReadTempFileExcerpt(stderrFile)- if errMsg == "" {- errMsg = "trivy scan produced no output"- }+ errMsg := cmp.Or(vuln.ReadTempFileExcerpt(stderrFile), "trivy scan produced no output")slog.WarnContext(ctx,"trivy scan diagnostics","image", imageName,@@ -1225,10 +1211,7 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner}if trivyReport == nil {- errMsg := vuln.ReadTempFileExcerpt(stderrFile)- if errMsg == "" {- errMsg = "trivy scan produced no output"- }+ errMsg := cmp.Or(vuln.ReadTempFileExcerpt(stderrFile), "trivy scan produced no output")slog.WarnContext(ctx,"trivy scan diagnostics","image", imageName,diff --git a/backend/internal/webhook/handler.go b/backend/internal/webhook/handler.goindex 72ff048da..983290dd8 100644--- a/backend/internal/webhook/handler.go+++ b/backend/internal/webhook/handler.go@@ -1,14 +1,12 @@package webhookimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""net/http""emperror.dev/errors"-"github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"diff --git a/backend/internal/webhook/model.go b/backend/internal/webhook/model.goindex 64d3305e5..33378e379 100644--- a/backend/internal/webhook/model.go+++ b/backend/internal/webhook/model.go@@ -1,9 +1,9 @@package webhookimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database")const (diff --git a/backend/internal/webhook/module.go b/backend/internal/webhook/module.goindex 62617600b..0bcc6e58c 100644--- a/backend/internal/webhook/module.go+++ b/backend/internal/webhook/module.go@@ -4,14 +4,13 @@ package webhookimport ("github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/container"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitops""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/updater"-- "github.com/getarcaneapp/arcane/backend/v2/internal/container"- "github.com/getarcaneapp/arcane/backend/v2/internal/database")// Dependencies are the collaborators the webhook domain needs.diff --git a/backend/internal/webhook/webhook.go b/backend/internal/webhook/webhook.goindex 400f42eff..8801e791f 100644--- a/backend/internal/webhook/webhook.go+++ b/backend/internal/webhook/webhook.go@@ -1,12 +1,9 @@package webhookimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- "go.getarcane.app/kit/normalization"-+ "cmp""context""crypto/rand"- "crypto/sha256""encoding/base64""encoding/hex""fmt"@@ -19,7 +16,7 @@ import ("emperror.dev/emperror""emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/container""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment"@@ -32,6 +29,8 @@ import ("github.com/getarcaneapp/arcane/types/v2/base"updatertypes "github.com/getarcaneapp/arcane/types/v2/updater"webhooktypes "github.com/getarcaneapp/arcane/types/v2/webhook"+ "go.getarcane.app/kit/normalization"+ kit "go.getarcane.app/kit/pkg"libcrypto "go.getarcane.app/sys/crypto""gorm.io/gorm")@@ -43,9 +42,7 @@ const (ErrWebhookInvalidType = errors.Sentinel("invalid webhook target type")ErrWebhookInvalidAction = errors.Sentinel("invalid webhook action type")ErrWebhookMissingTarget = errors.Sentinel("target ID is required for container, project, and gitops webhook types")-)-const (webhookTokenPrefix = "arc_wh_"webhookTokenLength = 32 // raw bytes β 64 hex charswebhookTokenPrefixLen = 8 // chars of the hex portion used as lookup prefix@@ -106,17 +103,11 @@ func generateWebhookTokenInternal() (raw, hash, prefix string, err error) {}tokenHex := hex.EncodeToString(encryptedBytes)raw = webhookTokenPrefix + tokenHex- sum := sha256.Sum256([]byte(raw))- hash = hex.EncodeToString(sum[:])+ hash = kit.SHA256Hex(raw)prefix = webhookTokenPrefix + tokenHex[:webhookTokenPrefixLen]return raw, hash, prefix, nil}-func hashWebhookTokenInternal(raw string) string {- sum := sha256.Sum256([]byte(raw))- return hex.EncodeToString(sum[:])-}-func parseWebhookPrefixInternal(raw string) (string, error) {raw = strings.TrimSpace(raw)hexPart, ok := strings.CutPrefix(raw, webhookTokenPrefix)@@ -150,7 +141,7 @@ func (s *WebhookService) IsKnownToken(raw string) bool {if s == nil || len(raw) > len(webhookTokenPrefix)+webhookTokenHexLen || !strings.HasPrefix(raw, webhookTokenPrefix) {return false}- hash := hashWebhookTokenInternal(raw)+ hash := kit.SHA256Hex(raw)s.tokenMu.RLock()defer s.tokenMu.RUnlock()_, ok := s.tokenHashes[hash]@@ -359,10 +350,7 @@ func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, wreturn ""}name, err := s.containerService.GetContainerNameByID(ctx, wh.TargetID)- if err != nil {- return ""- }- return name+ return kit.Ternary(err != nil, "", name)case WebhookTargetTypeProject:var project project.Projectif err := s.db.WithContext(ctx).@@ -497,7 +485,7 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) erreturn errors.WrapIf(err, "failed to look up webhook")}- hash := hashWebhookTokenInternal(rawToken)+ hash := kit.SHA256Hex(rawToken)var wh *Webhookfor i := range candidates {if candidates[i].TokenHash == hash {@@ -575,10 +563,7 @@ func remoteWebhookRequestInternal(wh *Webhook, actionType string) (method, pathswitch wh.TargetType {case WebhookTargetTypeContainer:- ref := strings.TrimSpace(wh.TargetRef)- if ref == "" {- ref = strings.TrimSpace(wh.TargetID)- }+ ref := cmp.Or(strings.TrimSpace(wh.TargetRef), strings.TrimSpace(wh.TargetID))if ref == "" {return "", "", false, ErrWebhookMissingTarget}@@ -718,11 +703,7 @@ func (s *WebhookService) resolveContainerWebhookTargetIDInternal(ctx context.Conreturn containerInfo.ID, nil}- if lastErr != nil {- return "", lastErr- }-- return "", ErrWebhookMissingTarget+ return "", kit.Ternary[error](lastErr != nil, lastErr, ErrWebhookMissingTarget)}func (s *WebhookService) syncWebhookContainerTargetInternal(ctx context.Context, wh *Webhook, containerID, containerName string) {@@ -814,9 +795,7 @@ func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *Webhootitle = "Webhook trigger failed: " + wh.Name}description := fmt.Sprintf("Target type: %s, action: %s", wh.TargetType, actionType)- if errMsg != "" {- description = errMsg- }+ description = cmp.Or(errMsg, description)_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{Type: event.EventTypeWebhookTrigger,Severity: severity,diff --git a/backend/internal/webhook/webhook_test.go b/backend/internal/webhook/webhook_test.goindex 433218665..1ece4171d 100644--- a/backend/internal/webhook/webhook_test.go+++ b/backend/internal/webhook/webhook_test.go@@ -1,8 +1,6 @@package webhookimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""crypto/sha256""encoding/base64"@@ -14,16 +12,17 @@ import ("sync""testing"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/types/v2""github.com/labstack/echo/v5""github.com/libtnb/sqlite""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg"libcrypto "go.getarcane.app/sys/crypto""gorm.io/gorm"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database")// setupWebhookServiceTestDB creates an isolated in-memory SQLite DB for each test.@@ -104,8 +103,8 @@ func TestWebhookTokenFormat(t *testing.T) {func TestHashWebhookTokenIsDeterministic(t *testing.T) {raw := "arc_wh_0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20"- first := hashWebhookTokenInternal(raw)- second := hashWebhookTokenInternal(raw)+ first := kit.SHA256Hex(raw)+ second := kit.SHA256Hex(raw)assert.Equal(t, first, second)}@@ -249,7 +248,7 @@ func TestCreateWebhook_TokenNotStoredInPlaintext(t *testing.T) {stored := fetchWebhook(t, db, wh.ID)assert.NotEqual(t, rawToken, stored.TokenHash, "raw token must not be stored as-is")- assert.Equal(t, hashWebhookTokenInternal(rawToken), stored.TokenHash, "stored hash must match SHA-256 of raw token")+ assert.Equal(t, kit.SHA256Hex(rawToken), stored.TokenHash, "stored hash must match SHA-256 of raw token")}func TestCreateWebhook_PrefixMatchesToken(t *testing.T) {@@ -656,7 +655,7 @@ func TestTriggerByToken_UnknownTargetType_ReturnsInvalidType(t *testing.T) {svc := newTestWebhookService(db)rawToken := "arc_wh_aabbccdd0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c"- hash := hashWebhookTokenInternal(rawToken)+ hash := kit.SHA256Hex(rawToken)hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)prefix := webhookTokenPrefix + hexPart[:webhookTokenPrefixLen]@@ -679,7 +678,7 @@ func TestTriggerByToken_UnknownTargetType_ReturnsInvalidType(t *testing.T) {// so dispatch tests can use known target types without needing real service dependencies.func insertWebhookDirect(t *testing.T, ctx context.Context, db *database.DB, rawToken, targetType, actionType, targetID, envID string) *Webhook {t.Helper()- hash := hashWebhookTokenInternal(rawToken)+ hash := kit.SHA256Hex(rawToken)hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)wh := &Webhook{Name: "test-hook",diff --git a/backend/pkg/authz/access_policy_test.go b/backend/pkg/authz/access_policy_test.goindex 68fd851f6..c3d7bb6e6 100644--- a/backend/pkg/authz/access_policy_test.go+++ b/backend/pkg/authz/access_policy_test.go@@ -10,7 +10,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/search""github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/stretchr/testify/require")diff --git a/backend/pkg/authz/permission_matcher_huma.go b/backend/pkg/authz/permission_matcher_huma.goindex 0bb263529..859ecd58a 100644--- a/backend/pkg/authz/permission_matcher_huma.go+++ b/backend/pkg/authz/permission_matcher_huma.go@@ -8,14 +8,16 @@ import ("github.com/samber/mo")-// MetaRequiredPermission is the huma.Operation.Metadata key under which the-// environment-scoped registration helper records the permission an operation-// requires. The remote environment proxy reads this metadata (via the OpenAPI-// document) to enforce the same permission locally before forwarding a request-// to an agent.-const MetaRequiredPermission = "arcane:requiredPermission"+const (+ // MetaRequiredPermission is the huma.Operation.Metadata key under which the+ // environment-scoped registration helper records the permission an operation+ // requires. The remote environment proxy reads this metadata (via the OpenAPI+ // document) to enforce the same permission locally before forwarding a request+ // to an agent.+ MetaRequiredPermission = "arcane:requiredPermission"-const envPathPrefixInternal = "/environments/{id}"+ envPathPrefixInternal = "/environments/{id}"+)// CollectFromHumaAPI walks every operation registered on humaAPI and records,// for each environment-scoped operation, the permission it requires. Thediff --git a/backend/pkg/authz/permission_matcher_test.go b/backend/pkg/authz/permission_matcher_test.goindex cc9906ae1..a67c9c93f 100644--- a/backend/pkg/authz/permission_matcher_test.go+++ b/backend/pkg/authz/permission_matcher_test.go@@ -22,7 +22,6 @@ func TestPermissionMatcherLookupExactAndWildcard(t *testing.T) {require.False(t, !ok || perm != "containers:read","expected containers:read, got %q ok=%v", perm, ok)}-}func TestPermissionMatcherStaticBeatsWildcard(t *testing.T) {@@ -43,7 +42,6 @@ func TestPermissionMatcherStaticBeatsWildcard(t *testing.T) {require.False(t, !ok || perm != "containers:read","expected wildcard route containers:read, got %q ok=%v", perm, ok)}-}func TestPermissionMatcherMethodAndLengthMismatch(t *testing.T) {@@ -67,7 +65,6 @@ func TestPermissionMatcherMethodAndLengthMismatch(t *testing.T) {require.False(t, ok,"expected no match for shorter path")}-}func TestPermissionMatcherNormalizesEchoParamsAndStripsQuery(t *testing.T) {@@ -79,7 +76,6 @@ func TestPermissionMatcherNormalizesEchoParamsAndStripsQuery(t *testing.T) {require.False(t, !ok || perm != "volumes:read","expected volumes:read with echo param + query string, got %q ok=%v", perm, ok)}-}func TestPermissionMatcherPublicRoute(t *testing.T) {@@ -93,7 +89,6 @@ func TestPermissionMatcherPublicRoute(t *testing.T) {require.Empty(t, perm,"expected empty permission for public route, got %q", perm)-}func TestPermissionMatcherUnmappedReturnsNotFound(t *testing.T) {@@ -105,5 +100,4 @@ func TestPermissionMatcherUnmappedReturnsNotFound(t *testing.T) {require.False(t, ok,"expected unmapped path to return not found")}-}diff --git a/backend/pkg/authz/permission_set.go b/backend/pkg/authz/permission_set.goindex f839c6a38..e8946d600 100644--- a/backend/pkg/authz/permission_set.go+++ b/backend/pkg/authz/permission_set.go@@ -160,8 +160,5 @@ func EnvIDFromPath(path string) string {return ""}id := before- if id == "" {- return ""- }return id}diff --git a/backend/pkg/authz/permission_set_test.go b/backend/pkg/authz/permission_set_test.goindex cbed0ed00..f2628c2f7 100644--- a/backend/pkg/authz/permission_set_test.go+++ b/backend/pkg/authz/permission_set_test.go@@ -19,7 +19,6 @@ func TestPermissionSetAllowsGlobal(t *testing.T) {require.False(t, ps.Allows(PermContainersStart, "env-1"),"unrelated perm should be denied")-}func TestPermissionSetEnvScopedDoesNotLeak(t *testing.T) {@@ -34,7 +33,6 @@ func TestPermissionSetEnvScopedDoesNotLeak(t *testing.T) {require.False(t, ps.Allows(PermContainersStart, ""),"env perm must not satisfy an org-level check")-}func TestPermissionSetAllowsAnyEffectiveScope(t *testing.T) {@@ -70,7 +68,6 @@ func TestPermissionSetAllowsAnyEffectiveScope(t *testing.T) {require.Equal(t, tt.want, got,"AllowsAny() = %v, want %v", got, tt.want)}-})}}@@ -88,7 +85,6 @@ func TestPermissionSetIsGlobalAdminRejectsUnknownPermissions(t *testing.T) {require.False(t, ps.IsGlobalAdmin(),"global admin should reject injected unknown permissions")-}func TestPermissionSetIsGlobalAdminRequiresExactKnownSet(t *testing.T) {@@ -101,7 +97,6 @@ func TestPermissionSetIsGlobalAdminRequiresExactKnownSet(t *testing.T) {require.False(t, ps.IsGlobalAdmin(),"global admin should require the complete known permission set")-}func TestPermissionSetIsGlobalAdmin(t *testing.T) {@@ -112,7 +107,6 @@ func TestPermissionSetIsGlobalAdmin(t *testing.T) {require.True(t, ps.IsGlobalAdmin(),"complete known permission set should be global admin")-}func TestSudoAllowsEverything(t *testing.T) {@@ -126,7 +120,6 @@ func TestSudoAllowsEverything(t *testing.T) {require.True(t, ps.IsGlobalAdmin(),"sudo should report as global admin")-}func TestEnvironmentPermissionSetScopesToOwnEnvironment(t *testing.T) {@@ -148,7 +141,6 @@ func TestEnvironmentPermissionSetScopesToOwnEnvironment(t *testing.T) {require.False(t, empty.Allows(PermContainersStart, "env-A"),"environment token with empty env id must deny env-scoped permissions")-}func TestEnvIDFromPath(t *testing.T) {@@ -166,12 +158,10 @@ func TestEnvIDFromPath(t *testing.T) {assert.Equal(t, want, got,"EnvIDFromPath(%q) = %q, want %q", input, got, want)}-}}func TestIsOrgLevelAndEnvScoped(t *testing.T) {-require.True(t, IsOrgLevel(PermUsersList),"users:list should be org-level")@@ -183,7 +173,6 @@ func TestIsOrgLevelAndEnvScoped(t *testing.T) {require.True(t, IsEnvScoped(PermContainersStart),"containers:start should be env-scoped")-}func TestIsKnownPermissionRejectsSyntheticPrefixMatches(t *testing.T) {@@ -203,22 +192,16 @@ func TestIsKnownPermissionRejectsSyntheticPrefixMatches(t *testing.T) {func TestBuiltInRolesOnlyReferenceKnownPermissions(t *testing.T) {for _, p := range BuiltInEditorPermissions() {-assert.True(t, IsKnownPermission(p),"editor references unknown perm %q", p)-}for _, p := range BuiltInDeployerPermissions() {-assert.True(t, IsKnownPermission(p),"deployer references unknown perm %q", p)-}for _, p := range BuiltInViewerPermissions() {-assert.True(t, IsKnownPermission(p),"viewer references unknown perm %q", p)-}}@@ -250,10 +233,8 @@ func TestVariablePermissionsAreSeparateGlobalGrantsWithBuiltInAccess(t *testing."No-Shell Editor": BuiltInNoShellEditorPermissions(),} {for _, permission := range variablePermissions {-require.Contains(t, permissions, permission,"%s must receive %q", name, permission)-}}@@ -266,20 +247,16 @@ func TestVariablePermissionsAreSeparateGlobalGrantsWithBuiltInAccess(t *testing."%s must receive %q", name, PermVariablesRead)for _, permission := range variablePermissions[1:] {-require.NotContains(t, permissions, permission,"%s must not receive %q", name, permission)-}}templatesOnly := NewPermissionSet()templatesOnly.AddGlobal(PermTemplatesRead, PermTemplatesCreate, PermTemplatesUpdate, PermTemplatesDelete)for _, permission := range variablePermissions {-require.False(t, templatesOnly.Allows(permission, ""),"template grants must not satisfy %q", permission)-}}@@ -345,20 +322,16 @@ func TestS3DestinationPermissionsAreSeparateGlobalGrantsWithBuiltInAccess(t *tes"%s must receive %q", name, PermS3DestinationsRead)for _, permission := range s3Permissions[2:] {-require.NotContains(t, permissions, permission,"%s must not receive %q", name, permission)-}}settingsOnly := NewPermissionSet()settingsOnly.AddGlobal(PermSettingsRead, PermSettingsWrite)for _, permission := range s3Permissions {-require.False(t, settingsOnly.Allows(permission, ""),"settings grants must not satisfy %q", permission)-}}@@ -416,7 +389,6 @@ func TestPermissionCatalogDerivesKnownPermissionsAndScopes(t *testing.T) {require.True(t, exists,"AllPermissions includes %q outside catalog", permission)}-}}@@ -428,7 +400,6 @@ func TestVolumeRenamePermissionIsEditorOnlyByDefault(t *testing.T) {}func TestNotificationsManageRequiresGlobalScope(t *testing.T) {-require.True(t, IsOrgLevel(PermNotificationsManage),"notifications:manage must be org-level for manager-global notification settings")@@ -445,5 +416,4 @@ func TestNotificationsManageRequiresGlobalScope(t *testing.T) {require.True(t, ps.Allows(PermNotificationsManage, ""),"a global notification grant must authorize the global resource")-}diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.goindex 5631d88e9..39bf3016e 100644--- a/backend/pkg/authz/permissions.go+++ b/backend/pkg/authz/permissions.go@@ -5,19 +5,19 @@// from the request path).package authz-// Built-in role IDs. Stable across migrations so other code may reference them-// safely. All six built-in roles are seeded by migration 054_add_rbac.const (+ // Built-in role IDs. Stable across migrations so other code may reference them+ // safely. All six built-in roles are seeded by migration 054_add_rbac.+BuiltInRoleAdmin = "role_admin"BuiltInRoleEditor = "role_editor"BuiltInRoleNoShellEditor = "role_no_shell_editor"BuiltInRoleDeployer = "role_deployer"BuiltInRoleMonitor = "role_monitor"BuiltInRoleViewer = "role_viewer"-)-// Org-level permissions (require a global-scope role assignment).-const (+ // Org-level permissions (require a global-scope role assignment).+PermUsersList = "users:list"PermUsersRead = "users:read"PermUsersCreate = "users:create"@@ -117,10 +117,9 @@ const (// (runtime/memory/GC stats, WebSocket metrics, pprof profiles, and the live// backend log tail). Global-scoped; seeded only into the Admin role.PermDiagnosticsRead = "diagnostics:read"-)-// Env-scoped permissions (resolved against the {id} env ID in the path).-const (+ // Env-scoped permissions (resolved against the {id} env ID in the path).+PermContainersList = "containers:list"PermContainersRead = "containers:read"PermContainersLogs = "containers:logs"diff --git a/backend/pkg/authz/volume_workspace.go b/backend/pkg/authz/volume_workspace.goindex de9144d12..47f284ebf 100644--- a/backend/pkg/authz/volume_workspace.go+++ b/backend/pkg/authz/volume_workspace.go@@ -1,35 +1,30 @@package authz-import volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+import (+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"+ kit "go.getarcane.app/kit/pkg"+)// VolumeWorkspaceRequiredPermissions returns the distinct mutation permissions// required by a Volume Workspace manifest. The boolean is false when a change// uses an unknown operation so remote proxies can fail closed.func VolumeWorkspaceRequiredPermissions(changes []volumetypes.WorkspaceFileChange) ([]string, bool) {required := make([]string, 0, 3)- seen := make(map[string]struct{}, 3)- add := func(permission string) {- if _, exists := seen[permission]; exists {- return- }- seen[permission] = struct{}{}- required = append(required, permission)- }for _, change := range changes {switch change.Operation {case volumetypes.FileOpCreateFile, volumetypes.FileOpCreateFolder, volumetypes.FileOpUpdateFile:- add(PermVolumesUpload)+ required = append(required, PermVolumesUpload)case volumetypes.FileOpRename, volumetypes.FileOpMove:- add(PermVolumesUpload)- add(PermVolumesDelete)+ required = append(required, PermVolumesUpload)+ required = append(required, PermVolumesDelete)case volumetypes.FileOpDelete:- add(PermVolumesDelete)+ required = append(required, PermVolumesDelete)case volumetypes.FileOpRestoreFile:- add(PermVolumesBackup)+ required = append(required, PermVolumesBackup)default:return nil, false}}- return required, true+ return kit.Unique(required), true}diff --git a/backend/pkg/dockerutil/compose_labels_test.go b/backend/pkg/dockerutil/compose_labels_test.goindex f8da048a7..0ae08727e 100644--- a/backend/pkg/dockerutil/compose_labels_test.go+++ b/backend/pkg/dockerutil/compose_labels_test.go@@ -35,5 +35,4 @@ func TestComposeLabels(t *testing.T) {assert.Empty(t, got,"ComposeServiceLabel(empty) = %q, want %q", got, "")}-}diff --git a/backend/pkg/dockerutil/container_names.go b/backend/pkg/dockerutil/container_names.goindex 55f99d555..f6aab1cb9 100644--- a/backend/pkg/dockerutil/container_names.go+++ b/backend/pkg/dockerutil/container_names.go@@ -3,7 +3,7 @@ package dockerimport ("strings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ kit "go.getarcane.app/kit/pkg")// ContainerNameFromNames returns Docker's first container name without the@@ -19,7 +19,7 @@ func ContainerNameFromNames(names []string) string {// ExcludedContainerNameSet parses a comma-separated exclusion setting into a// name lookup. Returns nil when the setting names no containers.func ExcludedContainerNameSet(raw string) map[string]bool {- names := utils.UniqueNonEmptyStrings(strings.Split(raw, ","))+ names := kit.Unique(kit.TrimNonEmpty(strings.Split(raw, ",")))if len(names) == 0 {return nil}diff --git a/backend/pkg/dockerutil/container_names_test.go b/backend/pkg/dockerutil/container_names_test.goindex 7c312b490..a235ec618 100644--- a/backend/pkg/dockerutil/container_names_test.go+++ b/backend/pkg/dockerutil/container_names_test.go@@ -41,7 +41,6 @@ func TestContainerNameFromNames(t *testing.T) {assert.Equal(t, tt.want, got,"ContainerNameFromNames() = %v, want %v", got, tt.want)}-})}}diff --git a/backend/pkg/dockerutil/exec.go b/backend/pkg/dockerutil/exec.goindex f340bb097..626eacfef 100644--- a/backend/pkg/dockerutil/exec.go+++ b/backend/pkg/dockerutil/exec.go@@ -9,6 +9,7 @@ import ("emperror.dev/errors""github.com/moby/moby/api/pkg/stdcopy""github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg")// IsExpectedStreamEndError reports whether err is the ordinary way a Docker@@ -44,10 +45,7 @@ func StartStdCopy(stream io.Reader, stdout, stderr io.Writer) <-chan error {// end as success.func WaitStdCopy(done <-chan error) error {err := <-done- if err == nil || IsExpectedStreamEndError(err) {- return nil- }- return err+ return kit.Ternary(err == nil || IsExpectedStreamEndError(err), nil, err)}// ExecInContainer runs an exec in containerID, demultiplexing its output intodiff --git a/backend/pkg/dockerutil/log_stream.go b/backend/pkg/dockerutil/log_stream.goindex 6595f4f89..873fd941b 100644--- a/backend/pkg/dockerutil/log_stream.go+++ b/backend/pkg/dockerutil/log_stream.go@@ -9,13 +9,13 @@ import ("sync""emperror.dev/errors"-"github.com/moby/moby/api/pkg/stdcopy"+ kit "go.getarcane.app/kit/pkg")// StreamContainerLogs streams Docker container logs, handling TTY raw streams// and non-TTY multiplexed stdout/stderr streams.-func StreamContainerLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- string, follow bool, isTTY bool) error {+func StreamContainerLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- string, follow, isTTY bool) error {if isTTY {return readLogLinesInternal(ctx, logs, logsChan, "")}@@ -161,10 +161,7 @@ func readLogLinesInternal(ctx context.Context, reader io.Reader, logsChan chan<-}if err != nil {- if errors.Is(err, io.EOF) {- return nil- }- return err+ return kit.Ternary(errors.Is(err, io.EOF), nil, err)}}}diff --git a/backend/pkg/dockerutil/mount_utils.go b/backend/pkg/dockerutil/mount_utils.goindex ae8979d98..63526cb32 100644--- a/backend/pkg/dockerutil/mount_utils.go+++ b/backend/pkg/dockerutil/mount_utils.go@@ -8,12 +8,10 @@ import ("strings""emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/moby/moby/client"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane")// MountForCurrentContainerSubpath inspects the current container, finds the@@ -56,7 +54,7 @@ func MountForCurrentContainerSubpath(ctx context.Context, dockerCli *client.Clie//// Returns nil if no mount destination is a prefix of containerPath or if// the matching mount is of an unsupported type.-func MountForSubpath(mounts []container.MountPoint, containerPath string, target string) *mount.Mount {+func MountForSubpath(mounts []container.MountPoint, containerPath, target string) *mount.Mount {if strings.TrimSpace(containerPath) == "" {return nil}@@ -112,7 +110,7 @@ func MountForSubpath(mounts []container.MountPoint, containerPath string, target// mounted whole at target, plus containerPath's path relative to that mount.// Unlike MountForSubpath the subpath need not exist yet, so restores can create// it. Returns nil when no bind or volume mount covers containerPath.-func MountForEnclosingPath(mounts []container.MountPoint, containerPath string, target string) (*mount.Mount, string) {+func MountForEnclosingPath(mounts []container.MountPoint, containerPath, target string) (*mount.Mount, string) {if strings.TrimSpace(containerPath) == "" {return nil, ""}@@ -140,7 +138,7 @@ func MountForEnclosingPath(mounts []container.MountPoint, containerPath string,// strictly below containerPath, re-targeted beneath target, so a helper// container sees the same tree the current container does. Parents precede// their children; unsupported mount types are skipped.-func NestedMounts(mounts []container.MountPoint, containerPath string, target string) []mount.Mount {+func NestedMounts(mounts []container.MountPoint, containerPath, target string) []mount.Mount {containerPath = strings.TrimRight(containerPath, "/")if containerPath == "" {return nil@@ -175,7 +173,7 @@ func pathHasPrefixInternal(containerPath, prefix string) bool {//// It currently supports bind and named volume mounts. If target is empty, destination// is used as the target.-func MountForDestination(mounts []container.MountPoint, destination string, target string) *mount.Mount {+func MountForDestination(mounts []container.MountPoint, destination, target string) *mount.Mount {if strings.TrimSpace(destination) == "" {return nil}diff --git a/backend/pkg/dockerutil/render_test.go b/backend/pkg/dockerutil/render_test.goindex 87aea8114..2dddda0b1 100644--- a/backend/pkg/dockerutil/render_test.go+++ b/backend/pkg/dockerutil/render_test.go@@ -13,7 +13,8 @@ func TestRenderJSONMessageStream(t *testing.T) {stream := strings.NewReader(`{"status":"Pulling from library/nginx","id":"stable-alpine"}` + "\n" +`{"status":"Pull complete","id":"abc123"}` + "\n" +- `{"status":"Status: Downloaded newer image for nginx:stable-alpine"}` + "\n")+ `{"status":"Status: Downloaded newer image for nginx:stable-alpine"}` + "\n",+ )var out strings.Builder{@@ -28,7 +29,6 @@ func TestRenderJSONMessageStream(t *testing.T) {require.Equal(t, want, out.String(),"expected CLI-parity output %q, got %q", want, out.String())-})t.Run("returns daemon errorDetail verbatim", func(t *testing.T) {@@ -37,7 +37,6 @@ func TestRenderJSONMessageStream(t *testing.T) {require.False(t, err == nil || !strings.Contains(err.Error(), "unauthorized"),"expected unauthorized error, got %v", err)-})}@@ -96,5 +95,4 @@ func TestLogLineWriter(t *testing.T) {require.Equal(t, want, out.String(),"expected framed lines %q, got %q", want, out.String())-}diff --git a/backend/pkg/dockerutil/volume_utils.go b/backend/pkg/dockerutil/volume_utils.goindex 4d4526632..1b0da1530 100644--- a/backend/pkg/dockerutil/volume_utils.go+++ b/backend/pkg/dockerutil/volume_utils.go@@ -7,13 +7,13 @@ import ("time""emperror.dev/errors"-"github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/moby/moby/api/types/volume""github.com/moby/moby/client""github.com/samber/hot""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")var volumeUsageCache = hot.NewHotCache[string, []volume.Volume](hot.LRU, 16).@@ -100,10 +100,7 @@ func GetVolumeUsageDataStaleWhileRevalidate(ctx context.Context, dockerClient *c)return mo.Some(fresh)}- cacheState := "miss"- if found {- cacheState = "stale"- }+ cacheState := kit.Ternary(found, "stale", "miss")slog.DebugContext(ctx, "volume usage cache lookup","docker_host", key,"cache_state", cacheState,diff --git a/backend/pkg/fswatch/watcher.go b/backend/pkg/fswatch/watcher.goindex 6efe44b86..915fc3932 100644--- a/backend/pkg/fswatch/watcher.go+++ b/backend/pkg/fswatch/watcher.go@@ -4,6 +4,7 @@package fswatchimport (+ "cmp""context""log/slog""os"@@ -14,7 +15,6 @@ import ("time""emperror.dev/errors"-"github.com/fsnotify/fsnotify""github.com/getarcaneapp/arcane/backend/v2/pkg/projects")@@ -52,9 +52,7 @@ func NewWatcher(watchPath string, opts WatcherOptions) (*Watcher, error) {return nil, err}- if opts.Debounce == 0 {- opts.Debounce = 2 * time.Second- }+ opts.Debounce = cmp.Or(opts.Debounce, 2*time.Second)if opts.MaxDepth < 0 {opts.MaxDepth = 0@@ -296,7 +294,7 @@ func (fw *Watcher) addExistingDirectories(root string) error {return fw.addExistingDirectoriesRecursiveInternal(root, root, map[string]struct{}{})}-func (fw *Watcher) addExistingDirectoriesRecursiveInternal(path string, logicalPath string, ancestors map[string]struct{}) error {+func (fw *Watcher) addExistingDirectoriesRecursiveInternal(path, logicalPath string, ancestors map[string]struct{}) error {identity, err := projects.ResolveDirectoryIdentityInternal(path)if err != nil {if path != fw.watchedPath && errors.Is(err, os.ErrPermission) {@@ -383,7 +381,7 @@ func (fw *Watcher) logicalPathForWatchEventInternal(path string) string {return filepath.Join(bestLogicalPath, rel)}-func (fw *Watcher) addWatchPathInternal(path string, logicalPath string) {+func (fw *Watcher) addWatchPathInternal(path, logicalPath string) {watchPaths := []string{path}if fw.followSymlinks {if info, err := os.Lstat(path); err == nil && info.Mode()&os.ModeSymlink != 0 {diff --git a/backend/pkg/gitutil/git.go b/backend/pkg/gitutil/git.goindex 9aa0919ad..ee80fae95 100644--- a/backend/pkg/gitutil/git.go+++ b/backend/pkg/gitutil/git.go@@ -1,6 +1,7 @@package gitimport (+ "cmp""context"stderrors "errors""io"@@ -30,15 +31,28 @@ import ("github.com/gofrs/flock""go.getarcane.app/acfs"acfstypes "go.getarcane.app/acfs/types"+ kit "go.getarcane.app/kit/pkg"gossh "golang.org/x/crypto/ssh""golang.org/x/crypto/ssh/knownhosts")-// binarySniffBytes is how much of a file is inspected to classify it as binary.-const binarySniffBytes = 512+const (+ // binarySniffBytes is how much of a file is inspected to classify it as binary.+ binarySniffBytes = 512++ // cloneScratchPrefix names the per-run clone scratch dirs created by Clone.+ cloneScratchPrefix = "gitops-"-// cloneScratchPrefix names the per-run clone scratch dirs created by Clone.-const cloneScratchPrefix = "gitops-"+ errUnsupportedURL = "repository URL must use http(s)://, ssh://, git://, or git@host:path"++ // SSH host key verification modes++ SSHHostKeyVerificationStrict = "strict" // Require host key in known_hosts+ SSHHostKeyVerificationAcceptNew = "accept_new" // Auto-add unknown host keys+ SSHHostKeyVerificationSkip = "skip" // Skip host key verification (insecure)+ defaultKnownHostsDataDir = "/app/data"+ defaultKnownHostsPath = "/app/data/.ssh/known_hosts"+)// go-git's file transport execs the git binary, which doesn't exist in the// distroless image. Unregister it so a repository URL can never reach it.@@ -62,8 +76,6 @@ type Client struct {var scpLikeURLPattern = regexp.MustCompile(`^[^@/]+@[^:/]+:`)-const errUnsupportedURL = "repository URL must use http(s)://, ssh://, git://, or git@host:path"-// normalizeURL coerces a repository URL into a form go-git resolves to a// network transport, never the file transport (which execs the git binary).// Schemeless host-style URLs (e.g. github.com/org/repo.git) get https://.@@ -100,15 +112,6 @@ func NewClient(workDir string) *Client {}}-// SSH host key verification modes-const (- SSHHostKeyVerificationStrict = "strict" // Require host key in known_hosts- SSHHostKeyVerificationAcceptNew = "accept_new" // Auto-add unknown host keys- SSHHostKeyVerificationSkip = "skip" // Skip host key verification (insecure)- defaultKnownHostsDataDir = "/app/data"- defaultKnownHostsPath = "/app/data/.ssh/known_hosts"-)-// AuthConfig holds authentication configurationtype AuthConfig struct {AuthType string@@ -135,10 +138,7 @@ func (c *Client) getAuthInternal(url string, config AuthConfig) (transport.AuthMif err != nil {return nil, errors.WrapIf(err, "failed to parse SSH repository URL")}- username := endpoint.User- if username == "" {- username = "git"- }+ username := cmp.Or(endpoint.User, "git")publicKeys, err := ssh.NewPublicKeys(username, []byte(config.SSHKey), "")if err != nil {return nil, errors.WrapIf(err, "failed to create ssh auth")@@ -448,11 +448,7 @@ func (c *Client) ProbeRemote(ctx context.Context, url string, auth AuthConfig) e}_, err := c.listRemoteReferences(ctx, url, auth)- if err != nil {- return err- }-- return nil+ return err}func (c *Client) listRemoteReferences(ctx context.Context, url string, auth AuthConfig) ([]*plumbing.Reference, error) {@@ -538,10 +534,7 @@ func (c *Client) BrowseTree(ctx context.Context, repoPath, targetPath string) ([continue}- nodeType := gitops.FileTreeNodeTypeFile- if child.IsDirectory {- nodeType = gitops.FileTreeNodeTypeDirectory- }+ nodeType := kit.Ternary(child.IsDirectory, gitops.FileTreeNodeTypeDirectory, gitops.FileTreeNodeTypeFile)nodes = append(nodes, gitops.FileTreeNode{Name: child.Name,@@ -689,7 +682,8 @@ type syncWalkLimits struct {// The composePath is the path to the compose file within the repo - the directory// containing this file will be walked.func (c *Client) WalkDirectory(ctx context.Context, repoPath, composePath string,- maxFiles int, maxTotalSize, maxBinarySize int64) (*DirectoryWalkResult, error) {+ maxFiles int, maxTotalSize, maxBinarySize int64,+) (*DirectoryWalkResult, error) {if err := ctx.Err(); err != nil {return nil, err}@@ -714,7 +708,6 @@ func (c *Client) WalkDirectory(ctx context.Context, repoPath, composePath stringerr := acfs.Walk(ctx, syncDir, "/", func(entry acfstypes.Entry) error {return c.walkSyncEntry(ctx, syncDir, entry, result, limits)})-if err != nil {return nil, err}@@ -735,10 +728,7 @@ func (c *Client) walkSyncEntry(ctx context.Context, syncDir string, entry acfstyreturn nil}if entry.IsDirectory {- if entry.Name == ".git" {- return fs.SkipDir- }- return nil+ return kit.Ternary(entry.Name == ".git", fs.SkipDir, nil)}return c.appendSyncFile(ctx, syncDir, entry, result, limits)diff --git a/backend/pkg/gitutil/git_test.go b/backend/pkg/gitutil/git_test.goindex 651c77b8f..39e448ea7 100644--- a/backend/pkg/gitutil/git_test.go+++ b/backend/pkg/gitutil/git_test.go@@ -24,10 +24,8 @@ import (// "invalid reset option: object not found" (#3168).func TestInitAllowsMultiAckCapabilities(t *testing.T) {-assert.False(t, len(transport.UnsupportedCapabilities) != 1 || transport.UnsupportedCapabilities[0] != capability.ThinPack,"expected UnsupportedCapabilities to contain only thin-pack, got %v", transport.UnsupportedCapabilities)-}func TestGetKnownHostsPath(t *testing.T) {@@ -42,7 +40,6 @@ func TestGetKnownHostsPath(t *testing.T) {assert.Equal(t, customPath, result,"expected %s, got %s", customPath, result)-})t.Run("returns Arcane data path when data directory exists", func(t *testing.T) {@@ -61,7 +58,6 @@ func TestGetKnownHostsPath(t *testing.T) {assert.Equal(t, expected, result,"expected %s, got %s", expected, result)-})t.Run("falls back to home directory when Arcane data directory is unavailable", func(t *testing.T) {@@ -76,7 +72,6 @@ func TestGetKnownHostsPath(t *testing.T) {assert.Equal(t, expected, result,"expected %s, got %s", expected, result)-})t.Run("falls back to temp dir when data directory and home are unavailable", func(t *testing.T) {@@ -90,7 +85,6 @@ func TestGetKnownHostsPath(t *testing.T) {assert.Equal(t, expected, result,"expected %s, got %s", expected, result)-})}@@ -122,7 +116,6 @@ func TestGetSSHHostKeyCallback(t *testing.T) {assert.NoError(t, err,"skip mode should not return error, got: %v", err)-})t.Run("empty mode defaults to accept_new", func(t *testing.T) {@@ -137,7 +130,6 @@ func TestGetSSHHostKeyCallback(t *testing.T) {require.NotNil(t, callback,"expected non-nil callback")-})t.Run("accept_new mode creates callback", func(t *testing.T) {@@ -152,7 +144,6 @@ func TestGetSSHHostKeyCallback(t *testing.T) {require.NotNil(t, callback,"expected non-nil callback")-})}@@ -177,7 +168,6 @@ func TestAddHostKey(t *testing.T) {assert.NotEmpty(t, content,"expected non-empty known_hosts file")-})t.Run("concurrent writes don't corrupt file", func(t *testing.T) {@@ -216,7 +206,6 @@ func TestAddHostKey(t *testing.T) {assert.NotEmpty(t, content,"expected non-empty known_hosts file after concurrent writes")-})}@@ -241,7 +230,6 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {assert.False(t, os.IsNotExist(err),"expected known_hosts directory to be created")}-})t.Run("callback adds new host keys", func(t *testing.T) {@@ -271,7 +259,6 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {assert.NotEmpty(t, content,"expected host key to be added to known_hosts")-})t.Run("callback accepts known host", func(t *testing.T) {@@ -299,7 +286,6 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {assert.NoError(t, err,"second callback returned error for known host: %v", err)-})t.Run("callback detects host key mismatch", func(t *testing.T) {@@ -341,7 +327,6 @@ func TestValidatePath(t *testing.T) {assert.NoError(t, err,"expected valid path to be allowed: %v", err)-})t.Run("rejects path traversal", func(t *testing.T) {@@ -350,7 +335,6 @@ func TestValidatePath(t *testing.T) {assert.Error(t, err,"expected path traversal to be rejected")-})t.Run("rejects absolute path escape", func(t *testing.T) {@@ -359,7 +343,6 @@ func TestValidatePath(t *testing.T) {assert.Error(t, err,"expected path escape to be rejected")-})}@@ -369,7 +352,6 @@ func TestNewClient(t *testing.T) {assert.Equal(t, "/tmp/test", client.workDir,"expected workDir /tmp/test, got %s", client.workDir)-})t.Run("creates client with empty work dir", func(t *testing.T) {@@ -377,7 +359,6 @@ func TestNewClient(t *testing.T) {assert.Empty(t, client.workDir,"expected empty workDir, got %s", client.workDir)-})}@@ -391,11 +372,10 @@ func writeFileInternal(t *testing.T, dir, name string, content []byte) {}{- err := os.WriteFile(targetPath, content, 0644)+ err := os.WriteFile(targetPath, content, 0o644)require.NoError(t, err,"failed to write file %s: %v", name, err)}-}func minimalCompose() []byte {@@ -419,7 +399,6 @@ func TestWalkDirectory_BasicWalk(t *testing.T) {assert.Len(t, result.Files, 3,"expected 3 entries in Files, got %d", len(result.Files))-}func TestWalkDirectory_PreservesExecutableBit(t *testing.T) {@@ -457,7 +436,6 @@ func TestWalkDirectory_PreservesExecutableBit(t *testing.T) {assert.False(t, ok && readme.Executable,"expected README.md to not be Executable")}-}func TestWalkDirectory_MaxFilesLimit(t *testing.T) {@@ -476,7 +454,6 @@ func TestWalkDirectory_MaxFilesLimit(t *testing.T) {assert.Contains(t, err.Error(), "file count limit exceeded","expected 'file count limit exceeded' error, got: %v", err)-}func TestWalkDirectory_MaxFilesUnlimited(t *testing.T) {@@ -495,7 +472,6 @@ func TestWalkDirectory_MaxFilesUnlimited(t *testing.T) {assert.Equal(t, 5, result.TotalFiles,"expected 5 files, got %d", result.TotalFiles)-}func TestWalkDirectory_MaxTotalSizeLimit(t *testing.T) {@@ -512,7 +488,6 @@ func TestWalkDirectory_MaxTotalSizeLimit(t *testing.T) {assert.Contains(t, err.Error(), "total size limit exceeded","expected 'total size limit exceeded' error, got: %v", err)-}func TestWalkDirectory_MaxTotalSizeUnlimited(t *testing.T) {@@ -529,7 +504,6 @@ func TestWalkDirectory_MaxTotalSizeUnlimited(t *testing.T) {assert.Equal(t, 3, result.TotalFiles,"expected 3 files, got %d", result.TotalFiles)-}func TestWalkDirectory_MaxBinarySizeSkips(t *testing.T) {@@ -547,7 +521,6 @@ func TestWalkDirectory_MaxBinarySizeSkips(t *testing.T) {assert.NotEqual(t, 0, result.SkippedBinaries,"expected at least one skipped binary file, got 0")-}func TestWalkDirectory_MaxBinarySizeUnlimited(t *testing.T) {@@ -567,7 +540,6 @@ func TestWalkDirectory_MaxBinarySizeUnlimited(t *testing.T) {assert.Equal(t, 2, result.TotalFiles,"expected 2 files (compose + binary), got %d", result.TotalFiles)-}func TestWalkDirectory_LargeTextFileNotSkippedByBinaryLimit(t *testing.T) {@@ -586,7 +558,6 @@ func TestWalkDirectory_LargeTextFileNotSkippedByBinaryLimit(t *testing.T) {assert.Equal(t, 2, result.TotalFiles,"expected 2 files (compose + text), got %d", result.TotalFiles)-}func TestWalkDirectory_ComposeInSubdirectory(t *testing.T) {@@ -808,7 +779,6 @@ func TestNormalizeURL(t *testing.T) {assert.Equal(t, tc.want, got,"expected %q, got %q", tc.want, got)-})}}diff --git a/backend/pkg/gitutil/git_write.go b/backend/pkg/gitutil/git_write.goindex 5c07d5798..cd265d66c 100644--- a/backend/pkg/gitutil/git_write.go+++ b/backend/pkg/gitutil/git_write.go@@ -22,6 +22,7 @@ import ("github.com/go-git/go-git/v5/plumbing/transport""go.getarcane.app/acfs"acfstypes "go.getarcane.app/acfs/types"+ kit "go.getarcane.app/kit/pkg")var (@@ -331,10 +332,7 @@ func stageCommitFilesInternal(ctx context.Context, checkout *WriteCheckout, workif err := acfs.MkdirAll(ctx, checkout.RepoPath, path.Dir(logical), 0o755); err != nil {return errors.WrapIff(err, "failed to create directory for %s", file.Path)}- mode := os.FileMode(0o644)- if file.Executable {- mode = 0o755- }+ mode := kit.Ternary(file.Executable, 0o755, os.FileMode(0o644))if _, err := acfs.WriteFrom(ctx, checkout.RepoPath, logical, bytes.NewReader(file.Content), int64(len(file.Content)), mode); err != nil {return errors.WrapIff(err, "failed to write %s", file.Path)}@@ -403,10 +401,7 @@ func isPushRejectedInternal(err error) bool {func (c *Client) RemoteBranchHead(ctx context.Context, url, branch string, auth AuthConfig) (string, bool, error) {refs, err := c.listRemoteReferences(ctx, url, auth)if err != nil {- if errors.Is(err, transport.ErrEmptyRemoteRepository) {- return "", false, nil- }- return "", false, err+ return "", false, kit.Ternary(errors.Is(err, transport.ErrEmptyRemoteRepository), nil, err)}refName := plumbing.NewBranchReferenceName(branch)for _, ref := range refs {@@ -509,10 +504,7 @@ func (c *Client) CommitDiff(ctx context.Context, repoPath, commitHash, directoryfunc directoryPrefixInternal(directory string) string {cleaned := strings.Trim(path.Clean(filepath.ToSlash(directory)), "/")- if cleaned == "" || cleaned == "." {- return ""- }- return cleaned + "/"+ return kit.Ternary(cleaned == "" || cleaned == ".", "", cleaned+"/")}func historyEntryInternal(commit *object.Commit, files []string) HistoryEntry {diff --git a/backend/pkg/libarcane/activity/handler.go b/backend/pkg/libarcane/activity/handler.goindex 18ccc77b7..7ca8f2fcf 100644--- a/backend/pkg/libarcane/activity/handler.go+++ b/backend/pkg/libarcane/activity/handler.go@@ -1,12 +1,6 @@package activityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""encoding/json/v2""fmt"@@ -15,18 +9,25 @@ import ("net/http""strings"- activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/samber/mo")-// ErrCanceled is the cancellation cause set on an activity's work context when a-// user requests cancellation. Completion paths read context.Cause to record a-// cancelled (rather than failed) terminal status.-const ErrCanceled = errors.Sentinel("activity cancelled by user")+const (+ // ErrCanceled is the cancellation cause set on an activity's work context when a+ // user requests cancellation. Completion paths read context.Cause to record a+ // cancelled (rather than failed) terminal status.+ ErrCanceled = errors.Sentinel("activity cancelled by user")++ // cancelledMessage is the latest-message recorded when work is cancelled.+ cancelledMessage = "Cancelled by user"+)type handlerActivityIDContextKey struct{}@@ -38,9 +39,6 @@ func IDFromContext(ctx context.Context) string {return strings.TrimSpace(activityID)}-// cancelledMessage is the latest-message recorded when work is cancelled.-const cancelledMessage = "Cancelled by user"-// CancelledByContext reports whether ctx was cancelled by a user cancellation// request (as opposed to app shutdown or a deadline). Callers that finalize an// activity from a possibly-cancelled work context use this to choose between a@@ -141,7 +139,7 @@ func StartHandlerActivity(return activity.ID, workCtx}-func CompleteHandlerActivity(ctx context.Context, activityService Service, activityID string, successMessage string, err error) {+func CompleteHandlerActivity(ctx context.Context, activityService Service, activityID, successMessage string, err error) {if activityService == nil || strings.TrimSpace(activityID) == "" {return}diff --git a/backend/pkg/libarcane/activity/requests.go b/backend/pkg/libarcane/activity/requests.goindex c476682bb..30663447f 100644--- a/backend/pkg/libarcane/activity/requests.go+++ b/backend/pkg/libarcane/activity/requests.go@@ -1,12 +1,10 @@package activityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity")diff --git a/backend/pkg/libarcane/activity/writer.go b/backend/pkg/libarcane/activity/writer.goindex abfe944b5..f923845c2 100644--- a/backend/pkg/libarcane/activity/writer.go+++ b/backend/pkg/libarcane/activity/writer.go@@ -1,8 +1,6 @@package activityimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"bytes""context""encoding/json/v2"@@ -12,10 +10,10 @@ import ("strings""sync"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"-"github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")type Writer struct {@@ -57,10 +55,7 @@ type writerQueueItem struct {func NewWriter(ctx context.Context, activityService MessageAppender, activityID string, writer io.Writer, defaultStep string) io.Writer {if activityService == nil || strings.TrimSpace(activityID) == "" {- if writer == nil {- return io.Discard- }- return writer+ return kit.Ternary(writer == nil, io.Discard, writer)}if existing, ok := writer.(*Writer); ok {return existing@@ -150,14 +145,14 @@ func (w *Writer) processLineInternal(line string) mo.Option[writerAppendMessage]if errorValue, ok := payload["error"]; ok && errorValue != nil {return mo.Some(writerAppendMessage{level: activitytypes.MessageLevelError,- message: utils.ToString(errorValue),+ message: kit.ToString(errorValue),payload: payload,step: w.defaultStep,})}if logValue, ok := payload["log"]; ok {- message := utils.ToString(logValue)+ message := kit.ToString(logValue)if strings.TrimSpace(message) == "" {return mo.None[writerAppendMessage]()}diff --git a/backend/pkg/libarcane/activity/writer_test.go b/backend/pkg/libarcane/activity/writer_test.goindex 800130eb7..e0c78e11b 100644--- a/backend/pkg/libarcane/activity/writer_test.go+++ b/backend/pkg/libarcane/activity/writer_test.go@@ -140,8 +140,10 @@ func TestWriterReturnsWrappedWriteErrorWithoutActivityInternal(t *testing.T) {require.ErrorContains(t, err, "client disconnected")}-var _ MessageAppender = (*recordingAppender)(nil)-var _ io.Writer = failingWriter{}+var (+ _ MessageAppender = (*recordingAppender)(nil)+ _ io.Writer = failingWriter{}+)// TestWriterPersistsQueuedLinesAfterCancelInternal verifies that cancelling// the work context does not abandon lines the writer already accepted:diff --git a/backend/pkg/libarcane/docker_compat.go b/backend/pkg/libarcane/docker_compat.godeleted file mode 100644index d03588038..000000000--- a/backend/pkg/libarcane/docker_compat.go+++ /dev/null@@ -1,305 +0,0 @@-package libarcane--import (- "context"- "slices"- "strconv"- "strings"-- "emperror.dev/errors"-- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/api/types/network"- "github.com/moby/moby/client"- "github.com/samber/mo"-)--const NetworkScopedMacAddressMinAPIVersion = "1.44"--// MultiEndpointContainerCreateMinAPIVersion is the first Docker API version-// that reliably accepts multiple entries in NetworkingConfig.EndpointsConfig on-// ContainerCreate.-//-// This matters because Arcane has several in-process container creation paths-// (auto-update recreate, manual create, self-upgrade recreate, embedded Compose-// library usage). Those paths all speak to the daemon through the Moby API-// client, so Arcane must handle daemon API compatibility itself.-//-// A host-side `docker compose up` command can still succeed against the same-// daemon because the installed Compose CLI/plugin may implement its own-// fallback strategy for older daemon APIs, such as creating the container on-// the primary network and then attaching the remaining networks with-// NetworkConnect. Arcane cannot assume the host CLI's fallback behavior exists-// in its own code paths, so the compatibility shim below applies that fallback-// explicitly.-const MultiEndpointContainerCreateMinAPIVersion = "1.44"--// DetectDockerAPIVersion returns the configured client API version when-// available, and falls back to the daemon-reported version only when the-// client version is not yet set.-func DetectDockerAPIVersion(ctx context.Context, dockerClient client.APIClient) string {- if dockerClient == nil {- return ""- }-- if version := strings.TrimSpace(dockerClient.ClientVersion()); version != "" {- return version- }-- serverVersion, err := dockerClient.ServerVersion(ctx, client.ServerVersionOptions{})- if err != nil {- return ""- }-- return strings.TrimSpace(serverVersion.APIVersion)-}--// IsDockerAPIVersionAtLeast performs numeric dot-segment comparison for Docker-// API versions (e.g. "1.43", "1.44.1"). Returns false when either version-// cannot be parsed.-func IsDockerAPIVersionAtLeast(current, minimum string) bool {- cur, ok := parseAPIVersionInternal(current).Get()- if !ok {- return false- }-- minV, ok := parseAPIVersionInternal(minimum).Get()- if !ok {- return false- }-- for i := range cur {- if cur[i] > minV[i] {- return true- }- if cur[i] < minV[i] {- return false- }- }-- return true-}--// SanitizeContainerCreateEndpointSettingsForDockerAPI clones endpoint settings-// for container recreate and removes per-network mac-address when daemon API-// does not support it (API < 1.44).-func SanitizeContainerCreateEndpointSettingsForDockerAPI(endpoints map[string]*network.EndpointSettings, apiVersion string) map[string]*network.EndpointSettings {- if len(endpoints) == 0 {- return nil- }-- keepPerNetworkMAC := IsDockerAPIVersionAtLeast(apiVersion, NetworkScopedMacAddressMinAPIVersion)- cloned := make(map[string]*network.EndpointSettings, len(endpoints))-- for networkName, endpoint := range endpoints {- if endpoint == nil {- cloned[networkName] = nil- continue- }-- endpointCopy := *endpoint- if !keepPerNetworkMAC {- endpointCopy.MacAddress = nil- }-- cloned[networkName] = &endpointCopy- }-- return cloned-}--// PrepareContainerCreateOptionsForDockerAPI rewrites a container create request-// for older daemon APIs that cannot accept multiple endpoint attachments in the-// initial ContainerCreate call.-//-// For API versions below MultiEndpointContainerCreateMinAPIVersion, Arcane-// keeps only the primary network in NetworkingConfig.EndpointsConfig and-// returns the remaining endpoints so the caller can attach them with-// NetworkConnect after create but before start. This mirrors the compatibility-// behavior that a newer host-side Compose CLI may apply internally, which-// explains why a shell `docker compose up` can succeed while Arcane's embedded-// or manual create paths fail unless we perform the split ourselves.-func PrepareContainerCreateOptionsForDockerAPI(options client.ContainerCreateOptions, apiVersion string) (client.ContainerCreateOptions, map[string]*network.EndpointSettings) {- if IsDockerAPIVersionAtLeast(apiVersion, MultiEndpointContainerCreateMinAPIVersion) || options.NetworkingConfig == nil || len(options.NetworkingConfig.EndpointsConfig) <= 1 {- return options, nil- }-- primaryNetwork := resolvePrimaryContainerCreateNetworkInternal(options.HostConfig, options.NetworkingConfig.EndpointsConfig)- if primaryNetwork == "" {- return options, nil- }-- adjusted := options- if options.HostConfig != nil {- adjusted.HostConfig = new(*options.HostConfig)- }- if adjusted.HostConfig == nil {- adjusted.HostConfig = &container.HostConfig{}- }- if strings.TrimSpace(string(adjusted.HostConfig.NetworkMode)) == "" {- adjusted.HostConfig.NetworkMode = container.NetworkMode(primaryNetwork)- }-- primaryEndpoint := copyEndpointSettingsInternal(options.NetworkingConfig.EndpointsConfig[primaryNetwork])- adjusted.NetworkingConfig = &network.NetworkingConfig{- EndpointsConfig: map[string]*network.EndpointSettings{- primaryNetwork: primaryEndpoint,- },- }-- extraEndpoints := make(map[string]*network.EndpointSettings, len(options.NetworkingConfig.EndpointsConfig)-1)- for networkName, endpoint := range options.NetworkingConfig.EndpointsConfig {- if networkName == primaryNetwork {- continue- }- extraEndpoints[networkName] = copyEndpointSettingsInternal(endpoint)- }- if len(extraEndpoints) == 0 {- return adjusted, nil- }-- return adjusted, extraEndpoints-}--// ConnectContainerExtraNetworksForDockerAPI attaches endpoints that were-// intentionally withheld from ContainerCreate for legacy daemon API-// compatibility.-//-// The intended call order is:-// 1. create the container on the primary network-// 2. connect each additional user-defined network-// 3. start the container-//-// Doing the attachment before start preserves the expected network topology-// while avoiding the legacy daemon limitation on multi-endpoint create.-func ConnectContainerExtraNetworksForDockerAPI(ctx context.Context, dockerClient client.APIClient, containerID string, endpoints map[string]*network.EndpointSettings) error {- if dockerClient == nil || strings.TrimSpace(containerID) == "" || len(endpoints) == 0 {- return nil- }-- networkNames := make([]string, 0, len(endpoints))- for networkName := range endpoints {- networkNames = append(networkNames, networkName)- }- slices.Sort(networkNames)-- for _, networkName := range networkNames {- _, err := dockerClient.NetworkConnect(ctx, networkName, client.NetworkConnectOptions{- Container: containerID,- EndpointConfig: copyEndpointSettingsInternal(endpoints[networkName]),- })- if err != nil {- return errors.WrapIff(err, "connect network %s", networkName)- }- }-- return nil-}--// ContainerCreateWithCompatibility applies Arcane's Docker API compatibility-// shims before calling ContainerCreate.-//-// This helper exists so every in-process Arcane create/recreate path can share-// the same daemon-compatibility behavior instead of relying on whichever-// fallback logic a separate host CLI binary might have. In practice this is the-// guardrail that keeps Arcane aligned with older daemons such as Docker 24.x-// advertising API 1.43 when a container needs multiple user-defined networks.-func ContainerCreateWithCompatibility(ctx context.Context, dockerClient client.APIClient, options client.ContainerCreateOptions) (client.ContainerCreateResult, error) {- return ContainerCreateWithCompatibilityForAPIVersion(ctx, dockerClient, options, DetectDockerAPIVersion(ctx, dockerClient))-}--// ContainerCreateWithCompatibilityForAPIVersion applies Arcane's Docker API-// compatibility shims before calling ContainerCreate when the caller has-// already resolved the daemon API version.-func ContainerCreateWithCompatibilityForAPIVersion(ctx context.Context, dockerClient client.APIClient, options client.ContainerCreateOptions, apiVersion string) (client.ContainerCreateResult, error) {- if dockerClient == nil {- return client.ContainerCreateResult{}, errors.New("docker api client is nil")- }-- adjustedOptions, extraEndpoints := PrepareContainerCreateOptionsForDockerAPI(options, apiVersion)-- result, err := dockerClient.ContainerCreate(ctx, adjustedOptions)- if err != nil {- return client.ContainerCreateResult{}, err- }-- if len(extraEndpoints) == 0 {- return result, nil- }-- if err := ConnectContainerExtraNetworksForDockerAPI(ctx, dockerClient, result.ID, extraEndpoints); err != nil {- _, _ = dockerClient.ContainerRemove(ctx, result.ID, client.ContainerRemoveOptions{Force: true})- return client.ContainerCreateResult{}, err- }-- return result, nil-}--func parseAPIVersionInternal(version string) mo.Option[[3]int] {- parsed := [3]int{}-- version = strings.TrimSpace(strings.TrimPrefix(version, "v"))- if version == "" {- return mo.None[[3]int]()- }-- parts := strings.Split(version, ".")- if len(parts) < 2 {- return mo.None[[3]int]()- }-- for i := 0; i < len(parsed) && i < len(parts); i++ {- part := strings.TrimSpace(parts[i])- if part == "" {- return mo.None[[3]int]()- }-- n, err := strconv.Atoi(part)- if err != nil {- return mo.None[[3]int]()- }- parsed[i] = n- }-- return mo.Some(parsed)-}--func resolvePrimaryContainerCreateNetworkInternal(hostConfig *container.HostConfig, endpoints map[string]*network.EndpointSettings) string {- if len(endpoints) == 0 {- return ""- }-- if hostConfig != nil {- networkMode := strings.TrimSpace(string(hostConfig.NetworkMode))- switch {- case networkMode == "":- case container.NetworkMode(networkMode).IsHost(),- container.NetworkMode(networkMode).IsNone(),- container.NetworkMode(networkMode).IsContainer():- return ""- default:- if _, ok := endpoints[networkMode]; ok {- return networkMode- }- // Named network set in NetworkMode is not represented in endpoint- // config, so avoid splitting the request and let the daemon handle- // the original create options as-is.- return ""- }- }-- networkNames := make([]string, 0, len(endpoints))- for networkName := range endpoints {- networkNames = append(networkNames, networkName)- }- slices.Sort(networkNames)- return networkNames[0]-}--func copyEndpointSettingsInternal(endpoint *network.EndpointSettings) *network.EndpointSettings {- if endpoint == nil {- return nil- }-- return endpoint.Copy()-}diff --git a/backend/pkg/libarcane/docker_compat_test.go b/backend/pkg/libarcane/docker_compat_test.godeleted file mode 100644index 9e1046197..000000000--- a/backend/pkg/libarcane/docker_compat_test.go+++ /dev/null@@ -1,304 +0,0 @@-package libarcane--import (- "context"- "errors"- "net"- "net/netip"- "testing"-- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/api/types/network"- "github.com/moby/moby/client"- "github.com/stretchr/testify/require"-)--type fakeContainerCreateCompatibilityClient struct {- client.APIClient- containerCreateResult client.ContainerCreateResult- containerCreateErr error- networkConnectErrs map[string]error- containerRemoveErr error- containerCreateCalls []client.ContainerCreateOptions- networkConnectCalls []fakeNetworkConnectCall- containerRemoveCalls []fakeContainerRemoveCall- clientVersionCalls int- serverVersionCalls int-}--type fakeNetworkConnectCall struct {- network string- options client.NetworkConnectOptions-}--type fakeContainerRemoveCall struct {- containerID string- options client.ContainerRemoveOptions-}--func (f *fakeContainerCreateCompatibilityClient) ClientVersion() string {- f.clientVersionCalls++- return ""-}--func (f *fakeContainerCreateCompatibilityClient) ServerVersion(context.Context, client.ServerVersionOptions) (client.ServerVersionResult, error) {- f.serverVersionCalls++- return client.ServerVersionResult{}, nil-}--func (f *fakeContainerCreateCompatibilityClient) ContainerCreate(_ context.Context, options client.ContainerCreateOptions) (client.ContainerCreateResult, error) {- f.containerCreateCalls = append(f.containerCreateCalls, options)- if f.containerCreateErr != nil {- return client.ContainerCreateResult{}, f.containerCreateErr- }- return f.containerCreateResult, nil-}--func (f *fakeContainerCreateCompatibilityClient) NetworkConnect(_ context.Context, networkName string, options client.NetworkConnectOptions) (client.NetworkConnectResult, error) {- f.networkConnectCalls = append(f.networkConnectCalls, fakeNetworkConnectCall{network: networkName, options: options})- if err := f.networkConnectErrs[networkName]; err != nil {- return client.NetworkConnectResult{}, err- }- return client.NetworkConnectResult{}, nil-}--func (f *fakeContainerCreateCompatibilityClient) ContainerRemove(_ context.Context, containerID string, options client.ContainerRemoveOptions) (client.ContainerRemoveResult, error) {- f.containerRemoveCalls = append(f.containerRemoveCalls, fakeContainerRemoveCall{containerID: containerID, options: options})- if f.containerRemoveErr != nil {- return client.ContainerRemoveResult{}, f.containerRemoveErr- }- return client.ContainerRemoveResult{}, nil-}--func mustHardwareAddr(t *testing.T, addr string) network.HardwareAddr {- t.Helper()- parsed, err := net.ParseMAC(addr)- require.NoError(t, err)- return network.HardwareAddr(parsed)-}--func TestIsDockerAPIVersionAtLeast(t *testing.T) {- tests := []struct {- name string- current string- minimum string- expected bool- }{- {name: "equal", current: "1.44", minimum: "1.44", expected: true},- {name: "greater minor", current: "1.45", minimum: "1.44", expected: true},- {name: "lesser minor", current: "1.43", minimum: "1.44", expected: false},- {name: "patch still greater", current: "1.44.1", minimum: "1.44", expected: true},- {name: "podman api", current: "1.41", minimum: "1.44", expected: false},- {name: "trims v prefix", current: "v1.44", minimum: "1.44", expected: true},- {name: "invalid current", current: "invalid", minimum: "1.44", expected: false},- {name: "invalid minimum", current: "1.44", minimum: "invalid", expected: false},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- require.Equal(t, tt.expected, IsDockerAPIVersionAtLeast(tt.current, tt.minimum))- })- }-}--func TestSanitizeContainerCreateEndpointSettingsForDockerAPI(t *testing.T) {- input := map[string]*network.EndpointSettings{- "bridge": {- MacAddress: mustHardwareAddr(t, "02:42:ac:11:00:02"),- IPAddress: netip.MustParseAddr("172.17.0.2"),- Aliases: []string{"svc", "svc-1"},- },- "custom": {- MacAddress: mustHardwareAddr(t, "02:42:ac:11:00:03"),- IPAddress: netip.MustParseAddr("10.0.0.10"),- Aliases: []string{"custom-svc"},- },- }-- t.Run("strips mac for api below 1.44", func(t *testing.T) {- out := SanitizeContainerCreateEndpointSettingsForDockerAPI(input, "1.43")- require.Len(t, out, 2)- require.Empty(t, out["bridge"].MacAddress.String())- require.Empty(t, out["custom"].MacAddress.String())- require.Equal(t, netip.MustParseAddr("172.17.0.2"), out["bridge"].IPAddress)- require.Equal(t, []string{"svc", "svc-1"}, out["bridge"].Aliases)-- // Ensure original map entries are untouched- require.Equal(t, "02:42:ac:11:00:02", input["bridge"].MacAddress.String())- require.Equal(t, "02:42:ac:11:00:03", input["custom"].MacAddress.String())- })-- t.Run("preserves mac for api at or above 1.44", func(t *testing.T) {- out := SanitizeContainerCreateEndpointSettingsForDockerAPI(input, "1.44")- require.Len(t, out, 2)- require.Equal(t, "02:42:ac:11:00:02", out["bridge"].MacAddress.String())- require.Equal(t, "02:42:ac:11:00:03", out["custom"].MacAddress.String())- })-- t.Run("nil or empty input", func(t *testing.T) {- require.Nil(t, SanitizeContainerCreateEndpointSettingsForDockerAPI(nil, "1.44"))- require.Nil(t, SanitizeContainerCreateEndpointSettingsForDockerAPI(map[string]*network.EndpointSettings{}, "1.44"))- })-}--func TestPrepareContainerCreateOptionsForDockerAPI(t *testing.T) {- options := client.ContainerCreateOptions{- HostConfig: &container.HostConfig{- NetworkMode: container.NetworkMode("synobridge"),- },- NetworkingConfig: &network.NetworkingConfig{- EndpointsConfig: map[string]*network.EndpointSettings{- "synobridge": {- Aliases: []string{"app"},- },- "nginx-proxy-manager_zbridge": {- Aliases: []string{"proxy"},- },- },- },- }-- t.Run("splits legacy multi-network create into primary plus extras", func(t *testing.T) {- adjusted, extras := PrepareContainerCreateOptionsForDockerAPI(options, "1.43")- require.NotNil(t, adjusted.NetworkingConfig)- require.Len(t, adjusted.NetworkingConfig.EndpointsConfig, 1)- require.Contains(t, adjusted.NetworkingConfig.EndpointsConfig, "synobridge")- require.Equal(t, []string{"app"}, adjusted.NetworkingConfig.EndpointsConfig["synobridge"].Aliases)-- require.Len(t, extras, 1)- require.Contains(t, extras, "nginx-proxy-manager_zbridge")- require.Equal(t, []string{"proxy"}, extras["nginx-proxy-manager_zbridge"].Aliases)-- adjusted.NetworkingConfig.EndpointsConfig["synobridge"].Aliases[0] = "changed"- extras["nginx-proxy-manager_zbridge"].Aliases[0] = "changed-too"-- require.Equal(t, []string{"app"}, options.NetworkingConfig.EndpointsConfig["synobridge"].Aliases)- require.Equal(t, []string{"proxy"}, options.NetworkingConfig.EndpointsConfig["nginx-proxy-manager_zbridge"].Aliases)- })-- t.Run("leaves create options unchanged on newer daemon apis", func(t *testing.T) {- adjusted, extras := PrepareContainerCreateOptionsForDockerAPI(options, "1.44")- require.Len(t, adjusted.NetworkingConfig.EndpointsConfig, 2)- require.Nil(t, extras)- })-- t.Run("uses deterministic fallback primary network when mode is unset", func(t *testing.T) {- adjusted, extras := PrepareContainerCreateOptionsForDockerAPI(client.ContainerCreateOptions{- NetworkingConfig: &network.NetworkingConfig{- EndpointsConfig: map[string]*network.EndpointSettings{- "znet": {Aliases: []string{"z"}},- "anet": {Aliases: []string{"a"}},- },- },- }, "1.43")-- require.NotNil(t, adjusted.HostConfig)- require.Equal(t, container.NetworkMode("anet"), adjusted.HostConfig.NetworkMode)- require.Len(t, adjusted.NetworkingConfig.EndpointsConfig, 1)- require.Contains(t, adjusted.NetworkingConfig.EndpointsConfig, "anet")- require.Len(t, extras, 1)- require.Contains(t, extras, "znet")- })-- t.Run("leaves create options unchanged when named network mode is missing from endpoints", func(t *testing.T) {- options := client.ContainerCreateOptions{- HostConfig: &container.HostConfig{- NetworkMode: container.NetworkMode("mynetwork"),- },- NetworkingConfig: &network.NetworkingConfig{- EndpointsConfig: map[string]*network.EndpointSettings{- "anet": {Aliases: []string{"a"}},- "znet": {Aliases: []string{"z"}},- },- },- }-- adjusted, extras := PrepareContainerCreateOptionsForDockerAPI(options, "1.43")-- require.Equal(t, options.HostConfig.NetworkMode, adjusted.HostConfig.NetworkMode)- require.Len(t, adjusted.NetworkingConfig.EndpointsConfig, 2)- require.Contains(t, adjusted.NetworkingConfig.EndpointsConfig, "anet")- require.Contains(t, adjusted.NetworkingConfig.EndpointsConfig, "znet")- require.Nil(t, extras)- })-}--func TestContainerCreateWithCompatibilityForAPIVersion(t *testing.T) {- t.Run("uses provided api version without re-detecting it", func(t *testing.T) {- fakeClient := &fakeContainerCreateCompatibilityClient{- containerCreateResult: client.ContainerCreateResult{ID: "created"},- }-- result, err := ContainerCreateWithCompatibilityForAPIVersion(t.Context(), fakeClient, client.ContainerCreateOptions{- Config: &container.Config{Image: "nginx:latest"},- }, "1.44")-- require.NoError(t, err)- require.Equal(t, "created", result.ID)- require.Zero(t, fakeClient.clientVersionCalls)- require.Zero(t, fakeClient.serverVersionCalls)- require.Len(t, fakeClient.containerCreateCalls, 1)- })-- t.Run("removes created container when a later network attach fails", func(t *testing.T) {- fakeClient := &fakeContainerCreateCompatibilityClient{- containerCreateResult: client.ContainerCreateResult{ID: "created-container"},- networkConnectErrs: map[string]error{- "cnet": errors.New("boom"),- },- }-- _, err := ContainerCreateWithCompatibilityForAPIVersion(t.Context(), fakeClient, client.ContainerCreateOptions{- Config: &container.Config{Image: "nginx:latest"},- HostConfig: &container.HostConfig{- NetworkMode: "anet",- },- NetworkingConfig: &network.NetworkingConfig{- EndpointsConfig: map[string]*network.EndpointSettings{- "anet": {Aliases: []string{"a"}},- "bnet": {Aliases: []string{"b"}},- "cnet": {Aliases: []string{"c"}},- "dnet": {Aliases: []string{"d"}},- },- },- }, "1.43")-- require.ErrorContains(t, err, "connect network cnet")- require.Len(t, fakeClient.containerCreateCalls, 1)- require.Len(t, fakeClient.networkConnectCalls, 2)- require.Equal(t, "bnet", fakeClient.networkConnectCalls[0].network)- require.Equal(t, "cnet", fakeClient.networkConnectCalls[1].network)- require.Len(t, fakeClient.containerRemoveCalls, 1)- require.Equal(t, "created-container", fakeClient.containerRemoveCalls[0].containerID)- require.True(t, fakeClient.containerRemoveCalls[0].options.Force)- })-- t.Run("propagates network attach error when rollback remove also fails", func(t *testing.T) {- connectErr := errors.New("connect-boom")- removeErr := errors.New("remove-boom")- fakeClient := &fakeContainerCreateCompatibilityClient{- containerCreateResult: client.ContainerCreateResult{ID: "created-container"},- networkConnectErrs: map[string]error{- "bnet": connectErr,- },- containerRemoveErr: removeErr,- }-- _, err := ContainerCreateWithCompatibilityForAPIVersion(t.Context(), fakeClient, client.ContainerCreateOptions{- HostConfig: &container.HostConfig{- NetworkMode: "anet",- },- NetworkingConfig: &network.NetworkingConfig{- EndpointsConfig: map[string]*network.EndpointSettings{- "anet": {},- "bnet": {},- },- },- }, "1.43")-- require.ErrorContains(t, err, "connect network bnet")- require.ErrorIs(t, err, connectErr)- require.NotErrorIs(t, err, removeErr)- require.Len(t, fakeClient.containerRemoveCalls, 1)- })-}diff --git a/backend/pkg/libarcane/edge/client.go b/backend/pkg/libarcane/edge/client.goindex 948d7518b..4cf6ff429 100644--- a/backend/pkg/libarcane/edge/client.go+++ b/backend/pkg/libarcane/edge/client.go@@ -13,16 +13,15 @@ import ("time""uuid"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"-"emperror.dev/errors"-"github.com/cenkalti/backoff/v5""github.com/coder/websocket""github.com/getarcaneapp/arcane/backend/v2/internal/actors"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")const (@@ -165,15 +164,13 @@ func StartupLogAttrs(cfg *Config) []any {if cfg == nil {return []any{"control_plane", "unknown",- "managed_session_transports", []string{},+ "managed_session_transports",+ []string{},"security_mode", NormalizeEdgeMTLSMode(""),}}- controlPlane := "managed"- if UsePollEdgeTransport(cfg) {- controlPlane = EdgeTransportPoll- }+ controlPlane := kit.Ternary(UsePollEdgeTransport(cfg), EdgeTransportPoll, "managed")managedSessionTransports := make([]string, 0, 2)if UseGRPCEdgeTransport(cfg) || (UsePollEdgeTransport(cfg) && strings.TrimSpace(httpx.ManagerGRPCAddr(cfg.ManagerApiUrl)) != "") {@@ -1035,7 +1032,7 @@ func (c *TunnelClient) closeAllStreams() {})}-func (c *TunnelClient) startLocalWebSocketReadLoop(ctx context.Context, streamCtx context.Context, streamID string, ws *websocket.Conn, stream *activeWSStream) {+func (c *TunnelClient) startLocalWebSocketReadLoop(ctx, streamCtx context.Context, streamID string, ws *websocket.Conn, stream *activeWSStream) {defer func() {c.closeWebSocketStream(streamID, stream)}()@@ -1057,7 +1054,7 @@ func (c *TunnelClient) startLocalWebSocketReadLoop(ctx context.Context, streamCt}}-func (c *TunnelClient) startLocalWebSocketWriteLoop(ctx context.Context, streamCtx context.Context, ws *websocket.Conn, stream *activeWSStream, cancel context.CancelFunc) {+func (c *TunnelClient) startLocalWebSocketWriteLoop(ctx, streamCtx context.Context, ws *websocket.Conn, stream *activeWSStream, cancel context.CancelFunc) {for {select {case <-streamCtx.Done():@@ -1097,7 +1094,7 @@ func (c *TunnelClient) sendWebSocketClose(conn TunnelConnection, streamID stringc.sendStreamCloseMessage(conn, streamID, "")}-func (c *TunnelClient) sendStreamCloseMessage(conn TunnelConnection, streamID string, message string) {+func (c *TunnelClient) sendStreamCloseMessage(conn TunnelConnection, streamID, message string) {if conn == nil {return}diff --git a/backend/pkg/libarcane/edge/client_transport_grpc.go b/backend/pkg/libarcane/edge/client_transport_grpc.goindex cddebde14..7fe568fd0 100644--- a/backend/pkg/libarcane/edge/client_transport_grpc.go+++ b/backend/pkg/libarcane/edge/client_transport_grpc.go@@ -8,10 +8,8 @@ import ("strings""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"-"emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1""google.golang.org/grpc""google.golang.org/grpc/backoff"diff --git a/backend/pkg/libarcane/edge/client_transport_poll.go b/backend/pkg/libarcane/edge/client_transport_poll.goindex da532f9e3..88d1f920e 100644--- a/backend/pkg/libarcane/edge/client_transport_poll.go+++ b/backend/pkg/libarcane/edge/client_transport_poll.go@@ -10,11 +10,9 @@ import ("strings""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"-"emperror.dev/errors"-"github.com/cenkalti/backoff/v5"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx")const defaultTunnelPollRequestTimeout = 15 * time.Seconddiff --git a/backend/pkg/libarcane/edge/client_transport_websocket.go b/backend/pkg/libarcane/edge/client_transport_websocket.goindex c12ffcef6..122b890b6 100644--- a/backend/pkg/libarcane/edge/client_transport_websocket.go+++ b/backend/pkg/libarcane/edge/client_transport_websocket.go@@ -10,7 +10,6 @@ import ("time""emperror.dev/errors"-"github.com/coder/websocket")diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.goindex d667c41f0..4806baf9b 100644--- a/backend/pkg/libarcane/edge/commands.go+++ b/backend/pkg/libarcane/edge/commands.go@@ -1,10 +1,11 @@package edgeimport (- "github.com/samber/mo"-"net/http""strings"++ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")var commandRoutes = []commandRoute{@@ -293,10 +294,7 @@ func normalizeCommandPathInternal(requestPath string) string {if requestPath == "" {return "/"}- if requestPath[0] != '/' {- return "/" + requestPath- }- return requestPath+ return kit.Ternary(requestPath[0] != '/', "/"+requestPath, requestPath)}func splitCommandPathInternal(p string) []string {@@ -361,7 +359,7 @@ func (n *commandRouteNode) insertInternal(route *commandRoute) {current.route = route}-func (i commandRouteIndexInternal) resolveInternal(method string, requestPath string, stream bool) mo.Option[*commandRoute] {+func (i commandRouteIndexInternal) resolveInternal(method, requestPath string, stream bool) mo.Option[*commandRoute] {root := i.roots[commandRouteLookupKeyInternal(method, stream)]if root == nil {return mo.None[*commandRoute]()diff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.goindex 0b2a73945..fd89f8ea5 100644--- a/backend/pkg/libarcane/edge/poll_control.go+++ b/backend/pkg/libarcane/edge/poll_control.go@@ -1,8 +1,6 @@package edgeimport (- "github.com/samber/mo"-"encoding/json/v2""io""log/slog"@@ -11,9 +9,10 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/labstack/echo/v5"+ "github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")const (@@ -77,10 +76,7 @@ func (r *TunnelDemandRegistry) Touch(envID string, ttl time.Duration) time.Time// DesiredStatus returns the desired manager-side tunnel state for an environment.func (r *TunnelDemandRegistry) DesiredStatus(envID string, hasActiveTunnel bool, now time.Time) string {if r == nil || strings.TrimSpace(envID) == "" {- if hasActiveTunnel {- return TunnelStatusActive- }- return TunnelStatusIdle+ return kit.Ternary(hasActiveTunnel, TunnelStatusActive, TunnelStatusIdle)}if now.IsZero() {now = time.Now()@@ -103,10 +99,7 @@ func (r *TunnelDemandRegistry) DesiredStatus(envID string, hasActiveTunnel bool,if !ok {return TunnelStatusIdle}- if hasActiveTunnel {- return TunnelStatusActive- }- return TunnelStatusRequired+ return kit.Ternary(hasActiveTunnel, TunnelStatusActive, TunnelStatusRequired)}var (diff --git a/backend/pkg/libarcane/edge/proxy.go b/backend/pkg/libarcane/edge/proxy.goindex 5952218c4..ea2b2eb99 100644--- a/backend/pkg/libarcane/edge/proxy.go+++ b/backend/pkg/libarcane/edge/proxy.go@@ -1,8 +1,6 @@package edgeimport (- "github.com/samber/mo"-"bytes""context""io"@@ -11,8 +9,8 @@ import ("time""emperror.dev/errors"-"github.com/labstack/echo/v5"+ "github.com/samber/mo")const (diff --git a/backend/pkg/libarcane/edge/registry_test.go b/backend/pkg/libarcane/edge/registry_test.goindex 179c51791..8e34aa971 100644--- a/backend/pkg/libarcane/edge/registry_test.go+++ b/backend/pkg/libarcane/edge/registry_test.go@@ -25,6 +25,7 @@ func (c *controlledCloseTunnelConn) Send(*TunnelMessage) error { returnfunc (c *controlledCloseTunnelConn) Receive() (*TunnelMessage, error) { return nil, nil }func (c *controlledCloseTunnelConn) IsExpectedReceiveError(error) bool { return false }func (c *controlledCloseTunnelConn) Transport() string { return EdgeTransportWebSocket }+func (c *controlledCloseTunnelConn) IsClosed() bool {select {case <-c.closed:@@ -33,6 +34,7 @@ func (c *controlledCloseTunnelConn) IsClosed() bool {return false}}+func (c *controlledCloseTunnelConn) Close() error {select {case <-c.closeStarted:diff --git a/backend/pkg/libarcane/edge/remenv.go b/backend/pkg/libarcane/edge/remenv.goindex f79836f58..d6a6167a5 100644--- a/backend/pkg/libarcane/edge/remenv.go+++ b/backend/pkg/libarcane/edge/remenv.go@@ -21,7 +21,7 @@ const (ConnectionUpgradeToken = "upgrade")-func CopyRequestHeaders(from http.Header, to http.Header, skip map[string]struct{}) {+func CopyRequestHeaders(from, to http.Header, skip map[string]struct{}) {for k, vs := range from {ck := http.CanonicalHeaderKey(k)if _, ok := skip[ck]; ok || ck == http.CanonicalHeaderKey(HeaderAuthorization) || ck == http.CanonicalHeaderKey(HeaderAPIKey) {@@ -149,7 +149,7 @@ func BuildHopByHopHeaders(respHeader http.Header) map[string]struct{} {return hop}-func CopyResponseHeaders(from http.Header, to http.Header, hop map[string]struct{}) {+func CopyResponseHeaders(from, to http.Header, hop map[string]struct{}) {for k, vs := range from {ck := http.CanonicalHeaderKey(k)if _, ok := hop[ck]; ok {diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.goindex f648a31e8..f9856fe23 100644--- a/backend/pkg/libarcane/edge/server.go+++ b/backend/pkg/libarcane/edge/server.go@@ -13,13 +13,13 @@ import ("emperror.dev/emperror""emperror.dev/errors"-wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1"certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate""github.com/labstack/echo/v5""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg""google.golang.org/grpc""google.golang.org/grpc/codes""google.golang.org/grpc/credentials"@@ -58,7 +58,7 @@ type EventCallback func(ctx context.Context, environmentID string, event *Tunnel// remoteAddr is the client socket address as seen by the manager.// reenrolled is true when an environment that had already enrolled receives// assets again after the enrollment cooldown.-type EnrollmentCallback func(ctx context.Context, environmentID, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool)+type EnrollmentCallback func(ctx context.Context, environmentID, remoteAddr string, certIssued, caGenerated, reenrolled bool)// NewTunnelServerWithRegistry creates a new tunnel server using an injected tunnel registry.func NewTunnelServerWithRegistry(registry *TunnelRegistry, resolver EnvironmentResolver, statusCallback StatusUpdateCallback) *TunnelServer {@@ -377,7 +377,7 @@ func tokenFromHeadersWithSourceInternal(req *http.Request) (string, string) {return "", ""}-func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx context.Context, tunnel *AgentTunnel) {+func (s *TunnelServer) manageConnectedTunnel(ctx, callbackCtx context.Context, tunnel *AgentTunnel) {accepted, drainPrevious, rejectReason, err := s.registry.RegisterSession(callbackCtx, tunnel, TunnelStaleTimeout)if err != nil {slog.ErrorContext(ctx, "Failed to register edge agent session",@@ -412,12 +412,7 @@ func (s *TunnelServer) manageConnectedTunnel(ctx context.Context, callbackCtx co// Echo the agent's capabilities and append the manager's own so the agent// learns what this manager supports (older agents ignore extra strings).- capabilities := append([]string(nil), tunnel.Capabilities...)- for _, capability := range []string{tunnelCapabilityProtoParity, tunnelCapabilityChunkedRequest} {- if !slices.Contains(capabilities, capability) {- capabilities = append(capabilities, capability)- }- }+ capabilities := kit.Unique(append(slices.Clone(tunnel.Capabilities), tunnelCapabilityProtoParity, tunnelCapabilityChunkedRequest))if err := tunnel.Conn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse,diff --git a/backend/pkg/libarcane/edge/server_test.go b/backend/pkg/libarcane/edge/server_test.goindex d5be359ab..dd700e231 100644--- a/backend/pkg/libarcane/edge/server_test.go+++ b/backend/pkg/libarcane/edge/server_test.go@@ -423,7 +423,7 @@ func TestTunnelServer_HandleMTLSEnroll_AllowsRepeatAfterCooldownAndMarksReenrollserver.SetConfig(cfg)reenrolled := make(chan bool, 2)- server.SetEnrollmentCallback(func(ctx context.Context, environmentID, remoteAddr string, certIssued bool, caGenerated bool, wasReenrolled bool) {+ server.SetEnrollmentCallback(func(ctx context.Context, environmentID, remoteAddr string, certIssued, caGenerated, wasReenrolled bool) {require.Equal(t, "env-repeat-old", environmentID)reenrolled <- wasReenrolled})diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.goindex ed90c6aac..ff9ced99e 100644--- a/backend/pkg/libarcane/edge/tls.go+++ b/backend/pkg/libarcane/edge/tls.go@@ -2,6 +2,7 @@ package edgeimport ("bytes"+ "cmp""context""crypto""crypto/ecdsa"@@ -27,14 +28,13 @@ import ("syscall""time"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate""go.getarcane.app/acfs""go.getarcane.app/acfs/atomic"+ kit "go.getarcane.app/kit/pkg"libcrypto "go.getarcane.app/sys/crypto""google.golang.org/grpc/credentials""google.golang.org/grpc/peer"@@ -56,6 +56,11 @@ const (maxEnrollResponseBytes = 1 << 20managerCALockTimeout = 2 * time.MinutemanagerCALockPollInterval = 100 * time.Millisecond++ // caKeyEncryptedPrefix marks files written with libcrypto envelope encryption.+ // The payload after the prefix is the base64 ciphertext returned by+ // libcrypto.Encrypt of the plain PEM-encoded CA private key.+ caKeyEncryptedPrefix = "ARCANE-ENC-V1:")var generatedAssetNameSanitizer = regexp.MustCompile(`[^a-zA-Z0-9._-]+`)@@ -168,7 +173,7 @@ func AvailableManagerMTLSCAPath(cfg *Config) (string, error) {}// GenerateManagerClientMTLSAssetsWithContext creates or loads the generated CA and per-environment client certificate bundle.-func GenerateManagerClientMTLSAssetsWithContext(ctx context.Context, cfg *Config, envID string, envName string) (*GeneratedMTLSAssets, error) {+func GenerateManagerClientMTLSAssetsWithContext(ctx context.Context, cfg *Config, envID, envName string) (*GeneratedMTLSAssets, error) {if !shouldUseGeneratedManagerCAInternal(cfg) {return nil, nil}@@ -232,10 +237,7 @@ func managerMTLSEnrollmentStateInternal(cfg *Config, envID string, now time.Time}enrolledAt, err := readMTLSEnrollmentMarkerInternal(markerPath)if err != nil {- if errors.Is(err, fs.ErrNotExist) {- return false, false, nil- }- return false, false, err+ return false, false, kit.Ternary(errors.Is(err, fs.ErrNotExist), nil, err)}if now.IsZero() {now = time.Now()@@ -392,10 +394,7 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,return errors.WrapIf(err, "failed to create edge mTLS asset dir")}for _, file := range enrollResp.Files {- perm := utils.FilePerm- if strings.TrimSpace(file.Permissions) == "0600" {- perm = 0o600- }+ perm := kit.Ternary(strings.TrimSpace(file.Permissions) == "0600", 0o600, utils.FilePerm)if err := acfs.Write(ctx, assetsDir, "/"+filepath.Base(file.Name), []byte(file.Content), acfs.WriteOptions{Mode: perm}); err != nil {return errors.WrapIff(err, "failed to write edge mTLS asset %s", file.Name)}@@ -622,10 +621,7 @@ func setAgentMTLSAssetPathsInternal(cfg *Config, assetsDir string) {}func requestSecurityModeInternal(req *http.Request) string {- if hasVerifiedEdgeMTLSRequestInternal(req) {- return "mtls"- }- return "token"+ return kit.Ternary(hasVerifiedEdgeMTLSRequestInternal(req), "mtls", "token")}func hasVerifiedEdgeMTLSRequestInternal(req *http.Request) bool {@@ -649,7 +645,7 @@ func hasVerifiedPeerCertificateInternal(state *tls.ConnectionState) bool {return len(state.PeerCertificates) > 0 && len(state.VerifiedChains) > 0}-func verifiedPeerCertificateEnvironmentIDMatchesInternal(state *tls.ConnectionState, envID string, trustDomain string) error {+func verifiedPeerCertificateEnvironmentIDMatchesInternal(state *tls.ConnectionState, envID, trustDomain string) error {if !hasVerifiedPeerCertificateInternal(state) {return nil}@@ -685,10 +681,7 @@ func edgeMTLSAppURLInternal(cfg *Config) string {func expectedEdgeMTLSURIPathInternal(envID string) string {safeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")- if safeEnvID == "" {- return ""- }- return "/edge/" + safeEnvID+ return kit.Ternary(safeEnvID == "", "", "/edge/"+safeEnvID)}func edgeMTLSAssetsDirInternal(cfg *Config) (string, error) {@@ -785,7 +778,7 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, strreturn caCertPath, caKeyPath, true, nil}-func generatedCAReadyInternal(caCertPath string, caKeyPath string) bool {+func generatedCAReadyInternal(caCertPath, caKeyPath string) bool {if !fileExistsInternal(caCertPath) || !fileExistsInternal(caKeyPath) {return false}@@ -795,7 +788,7 @@ func generatedCAReadyInternal(caCertPath string, caKeyPath string) bool {return true}-func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envID string, envName string, appURL string) (string, string, bool, error) {+func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envName, appURL string) (string, string, bool, error) {caCertPath, caKeyPath, _, err := ensureManagerCAInternal(ctx, assetsDir)if err != nil {return "", "", false, err@@ -887,7 +880,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir string, envIreturn clientCertPath, clientKeyPath, true, nil}-func buildGeneratedClientCommonNameInternal(envName string, safeEnvID string) string {+func buildGeneratedClientCommonNameInternal(envName, safeEnvID string) string {safeEnvID = strings.TrimSpace(safeEnvID)if safeEnvID == "" {return ""@@ -919,7 +912,7 @@ func buildGeneratedClientCommonNameInternal(envName string, safeEnvID string) st// Names to embed in a generated edge agent client certificate. The URI SAN// provides a stable machine-readable identity; DNS SANs improve interop with// stricter verifiers. Returns a nil URI if safeEnvID is empty.-func buildGeneratedClientSANsInternal(envName string, safeEnvID string, appURL string) (*url.URL, []string) {+func buildGeneratedClientSANsInternal(envName, safeEnvID, appURL string) (*url.URL, []string) {safeEnvID = strings.TrimSpace(safeEnvID)if safeEnvID == "" {return nil, nil@@ -963,7 +956,7 @@ func validateGeneratedCAInternal(certPath, keyPath string) error {return nil}-func validateGeneratedClientCertificateInternal(certPath, keyPath string, expectedCommonName string, expectedURISAN *url.URL) error {+func validateGeneratedClientCertificateInternal(certPath, keyPath, expectedCommonName string, expectedURISAN *url.URL) error {cert, err := readCertificateInternal(certPath)if err != nil {return err@@ -1008,7 +1001,7 @@ func certificateHasURISANInternal(cert *x509.Certificate, expected *url.URL) booreturn false}-func agentMTLSAssetsNeedEnrollmentInternal(certPath string, keyPath string, now time.Time) (bool, string) {+func agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath string, now time.Time) (bool, string) {if !fileExistsInternal(certPath) || !fileExistsInternal(keyPath) {return true, "certificate or key is missing"}@@ -1129,15 +1122,12 @@ func readPrivateKeyInternal(path string) (crypto.Signer, error) {return parsePrivateKeyPEMInternal(pemBytes, path)}-func lockEdgeMTLSPathInternal(ctx context.Context, dir string, lockName string) (func(), error) {+func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func(), error) {absDir, err := filepath.Abs(dir)if err != nil {return nil, errors.WrapIf(err, "failed to resolve edge mTLS lock dir")}- lockName = strings.TrimSpace(lockName)- if lockName == "" {- lockName = ".lock"- }+ lockName = cmp.Or(strings.TrimSpace(lockName), ".lock")lockPath := filepath.Join(absDir, lockName)@@ -1252,7 +1242,7 @@ func edgeMTLSLockPIDAliveInternal(pid int) bool {return err == nil || errors.Is(err, syscall.EPERM)}-func writePEMFileInternal(path string, blockType string, bytes []byte, perm os.FileMode) error {+func writePEMFileInternal(path, blockType string, bytes []byte, perm os.FileMode) error {pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})if pemBytes == nil {return errors.Errorf("failed to encode PEM file %s", path)@@ -1260,11 +1250,6 @@ func writePEMFileInternal(path string, blockType string, bytes []byte, perm os.Freturn atomic.WriteFile(path, pemBytes, perm)}-// caKeyEncryptedPrefix marks files written with libcrypto envelope encryption.-// The payload after the prefix is the base64 ciphertext returned by-// libcrypto.Encrypt of the plain PEM-encoded CA private key.-const caKeyEncryptedPrefix = "ARCANE-ENC-V1:"-var caKeyEncryptInternal = libcrypto.Encrypt// writeCAKeyFileInternal writes the edge CA private key to disk using envelopediff --git a/backend/pkg/libarcane/edge/tls_test.go b/backend/pkg/libarcane/edge/tls_test.goindex 7ea4aa7d8..2f77e6eb6 100644--- a/backend/pkg/libarcane/edge/tls_test.go+++ b/backend/pkg/libarcane/edge/tls_test.go@@ -23,6 +23,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils"certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg"libcrypto "go.getarcane.app/sys/crypto""google.golang.org/grpc/credentials""google.golang.org/grpc/peer"@@ -196,10 +197,7 @@ func TestEnsureAgentMTLSAssets_UsesDownloadedCAPathWhenPresent(t *testing.T) {require.NotNil(t, generated)for _, file := range generated.Files {targetPath := filepath.Join(assetsDir, filepath.Base(file.Name))- perm := utils.FilePerm- if file.Permissions == "0600" {- perm = 0o600- }+ perm := kit.Ternary(file.Permissions == "0600", 0o600, utils.FilePerm)require.NoError(t, os.WriteFile(targetPath, []byte(file.Content), perm))}@@ -436,10 +434,7 @@ func TestAgentMTLSAssetsNeedEnrollmentInternal_RenewsExpiredCertificate(t *testifor _, file := range assets.Files {targetPath := filepath.Join(assetsDir, filepath.Base(file.Name))- perm := utils.FilePerm- if file.Permissions == "0600" {- perm = 0o600- }+ perm := kit.Ternary(file.Permissions == "0600", 0o600, utils.FilePerm)require.NoError(t, os.WriteFile(targetPath, []byte(file.Content), perm))}diff --git a/backend/pkg/libarcane/edge/transport.go b/backend/pkg/libarcane/edge/transport.goindex 268f206f8..14cf9ba9c 100644--- a/backend/pkg/libarcane/edge/transport.go+++ b/backend/pkg/libarcane/edge/transport.go@@ -1,9 +1,9 @@package edgeimport (- "github.com/samber/mo"-"strings"++ "github.com/samber/mo")const (diff --git a/backend/pkg/libarcane/edge/tunnel.go b/backend/pkg/libarcane/edge/tunnel.goindex 2986e597a..ef03653ca 100644--- a/backend/pkg/libarcane/edge/tunnel.go+++ b/backend/pkg/libarcane/edge/tunnel.go@@ -8,7 +8,6 @@ import ("net""emperror.dev/errors"-"github.com/coder/websocket"wshub "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1"@@ -19,23 +18,17 @@ import (// TunnelMessageType represents the type of message sent over the tunnel.type TunnelMessageType string-const maxGRPCTunnelMessageSize = 16 * 1024 * 1024--// maxWebSocketTunnelMessageSize caps inbound websocket tunnel frames at 2x the-// gRPC limit, since JSON base64-encodes binary bodies a gRPC peer would accept.-const maxWebSocketTunnelMessageSize = 2 * maxGRPCTunnelMessageSize+const (+ maxGRPCTunnelMessageSize = 16 * 1024 * 1024-// ErrTunnelConnectionClosed is returned by Send and Receive on every transport-// once the tunnel connection is closed.-const ErrTunnelConnectionClosed = errors.Sentinel("edge tunnel connection is closed")+ // maxWebSocketTunnelMessageSize caps inbound websocket tunnel frames at 2x the+ // gRPC limit, since JSON base64-encodes binary bodies a gRPC peer would accept.+ maxWebSocketTunnelMessageSize = 2 * maxGRPCTunnelMessageSize-// tunnelReadWait bounds how long a websocket tunnel read may sit idle. Both-// peers see traffic at least every DefaultHeartbeatInterval (agent heartbeat,-// manager heartbeat_ack), so 3x tolerates transient stalls while still-// detecting a silently dead peer. Variable so tests can shorten it.-var tunnelReadWait = 3 * DefaultHeartbeatInterval+ // ErrTunnelConnectionClosed is returned by Send and Receive on every transport+ // once the tunnel connection is closed.+ ErrTunnelConnectionClosed = errors.Sentinel("edge tunnel connection is closed")-const (// MessageTypeRequest is sent from manager to agent to initiate a request.MessageTypeRequest TunnelMessageType = "request"// MessageTypeResponse is sent from agent to manager with the response.@@ -78,6 +71,12 @@ const (MessageTypeCancelRequest TunnelMessageType = "cancel_request")+// tunnelReadWait bounds how long a websocket tunnel read may sit idle. Both+// peers see traffic at least every DefaultHeartbeatInterval (agent heartbeat,+// manager heartbeat_ack), so 3x tolerates transient stalls while still+// detecting a silently dead peer. Variable so tests can shorten it.+var tunnelReadWait = 3 * DefaultHeartbeatInterval+// TunnelConnection is the transport contract shared by WebSocket and gRPC wrappers.type TunnelConnection interface {Send(msg *TunnelMessage) errordiff --git a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go b/backend/pkg/libarcane/edge/tunnel_proto_adapter.goindex e9103fca2..ba285e1da 100644--- a/backend/pkg/libarcane/edge/tunnel_proto_adapter.go+++ b/backend/pkg/libarcane/edge/tunnel_proto_adapter.go@@ -5,7 +5,6 @@ import ("math""emperror.dev/errors"-tunnelpb "github.com/getarcaneapp/arcane/backend/v2/proto/tunnel/v1")diff --git a/backend/pkg/libarcane/edge/ws_proxy.go b/backend/pkg/libarcane/edge/ws_proxy.goindex 14f3def05..6b78ee2e7 100644--- a/backend/pkg/libarcane/edge/ws_proxy.go+++ b/backend/pkg/libarcane/edge/ws_proxy.go@@ -98,7 +98,7 @@ func buildWebSocketHeaders(req *http.Request) map[string]string {return headers}-func forwardClientToAgent(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, streamID string, doneCh chan<- struct{}) {+func forwardClientToAgent(ctx, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, streamID string, doneCh chan<- struct{}) {defer close(doneCh)for {msgType, data, err := clientWS.Read(streamCtx)@@ -121,7 +121,7 @@ func forwardClientToAgent(ctx context.Context, streamCtx context.Context, client}}-func forwardAgentToClient(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, pending *PendingRequest, streamID string, clientDoneCh <-chan struct{}) {+func forwardAgentToClient(ctx, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, pending *PendingRequest, streamID string, clientDoneCh <-chan struct{}) {pingTicker := time.NewTicker(tunnelWSPingPeriod)defer pingTicker.Stop()@@ -159,7 +159,7 @@ func forwardAgentToClient(ctx context.Context, streamCtx context.Context, client}}-func handleAgentMessage(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, msg *TunnelMessage, streamID string) (bool, error) {+func handleAgentMessage(ctx, streamCtx context.Context, clientWS *websocket.Conn, msg *TunnelMessage, streamID string) (bool, error) {switch msg.Type {case MessageTypeWebSocketData, MessageTypeStreamData:return false, writeWebSocketData(streamCtx, clientWS, msg)diff --git a/backend/pkg/libarcane/engine_compat.go b/backend/pkg/libarcane/engine_compat.godeleted file mode 100644index cb9cca130..000000000--- a/backend/pkg/libarcane/engine_compat.go+++ /dev/null@@ -1,122 +0,0 @@-package libarcane--import (- "context"- "strings"-- containertypes "github.com/moby/moby/api/types/container"- systemtypes "github.com/moby/moby/api/types/system"- "github.com/moby/moby/client"-)--// EngineCompatibilityInfo describes the container engine details Arcane uses to-// decide whether recreate-time HostConfig sanitization is required.-type EngineCompatibilityInfo struct {- // Name is the normalized engine identifier, such as "docker" or "podman".- Name string- // CgroupVersion is the daemon-reported cgroup version, such as "1" or "2".- CgroupVersion string-}--// PrepareRecreateHostConfigForEngine clones hostConfig and removes recreate-// options that are known to be incompatible with the connected engine.-//-// The returned HostConfig is a shallow copy, so field reassignment is isolated-// from the caller's original value, but content-level mutation of shared slice-// or map fields is not. The boolean result reports whether the helper removed-// any incompatible fields. EngineCompatibilityInfo reports the daemon details-// used to make that decision.-func PrepareRecreateHostConfigForEngine(ctx context.Context, dockerClient *client.Client, hostConfig *containertypes.HostConfig) (*containertypes.HostConfig, bool, EngineCompatibilityInfo, error) {- if hostConfig == nil {- return nil, false, EngineCompatibilityInfo{}, nil- }-- cloned := cloneContainerHostConfigInternal(hostConfig)- if dockerClient == nil {- return cloned, false, EngineCompatibilityInfo{}, nil- }-- serverVersion, err := dockerClient.ServerVersion(ctx, client.ServerVersionOptions{})- if err != nil {- return cloned, false, EngineCompatibilityInfo{}, err- }-- infoResult, err := dockerClient.Info(ctx, client.InfoOptions{})- if err != nil {- return cloned, false, EngineCompatibilityInfo{}, err- }-- engineInfo := detectEngineCompatibilityInfoInternal(serverVersion, infoResult.Info)- sanitized := sanitizeRecreateHostConfigInternal(cloned, engineInfo)-- return cloned, sanitized, engineInfo, nil-}--func cloneContainerHostConfigInternal(hostConfig *containertypes.HostConfig) *containertypes.HostConfig {- if hostConfig == nil {- return nil- }-- return new(*hostConfig)-}--func sanitizeRecreateHostConfigInternal(hostConfig *containertypes.HostConfig, engineInfo EngineCompatibilityInfo) bool {- if hostConfig == nil {- return false- }-- if !strings.EqualFold(strings.TrimSpace(engineInfo.Name), "podman") || !isCgroupV2Internal(engineInfo.CgroupVersion) {- return false- }-- if hostConfig.MemorySwappiness == nil {- return false- }-- hostConfig.MemorySwappiness = nil- return true-}--func detectEngineCompatibilityInfoInternal(version client.ServerVersionResult, info systemtypes.Info) EngineCompatibilityInfo {- return EngineCompatibilityInfo{- Name: detectEngineNameInternal(version, info),- CgroupVersion: strings.TrimSpace(info.CgroupVersion),- }-}--func detectEngineNameInternal(version client.ServerVersionResult, info systemtypes.Info) string {- candidates := []string{version.Platform.Name}- for _, component := range version.Components {- candidates = append(candidates, component.Name)- for _, value := range component.Details {- candidates = append(candidates, value)- }- }- candidates = append(candidates, info.ServerVersion, info.OperatingSystem)-- for _, candidate := range candidates {- if name := normalizeEngineNameInternal(candidate); name != "" {- return name- }- }-- return ""-}--func normalizeEngineNameInternal(value string) string {- normalized := strings.ToLower(strings.TrimSpace(value))- switch {- case strings.Contains(normalized, "podman"):- return "podman"- case strings.Contains(normalized, "docker"):- return "docker"- default:- return ""- }-}--func isCgroupV2Internal(cgroupVersion string) bool {- normalized := strings.ToLower(strings.TrimSpace(cgroupVersion))- normalized = strings.TrimPrefix(normalized, "v")- return normalized == "2"-}diff --git a/backend/pkg/libarcane/engine_compat_test.go b/backend/pkg/libarcane/engine_compat_test.godeleted file mode 100644index bc034ef46..000000000--- a/backend/pkg/libarcane/engine_compat_test.go+++ /dev/null@@ -1,143 +0,0 @@-package libarcane--import (- "testing"-- containertypes "github.com/moby/moby/api/types/container"- systemtypes "github.com/moby/moby/api/types/system"- "github.com/moby/moby/client"- "github.com/stretchr/testify/require"-)--func TestPrepareRecreateHostConfigForEngine_NilHostConfig(t *testing.T) {- out, sanitized, engineInfo, err := PrepareRecreateHostConfigForEngine(t.Context(), nil, nil)- require.NoError(t, err)- require.Nil(t, out)- require.False(t, sanitized)- require.Empty(t, engineInfo.Name)- require.Empty(t, engineInfo.CgroupVersion)-}--func TestSanitizeRecreateHostConfigInternal(t *testing.T) {- swappiness := int64(60)-- tests := []struct {- name string- engineInfo EngineCompatibilityInfo- wantSanitized bool- wantSwappinessNil bool- }{- {- name: "podman cgroup v2 strips memory swappiness",- engineInfo: EngineCompatibilityInfo{- Name: "podman",- CgroupVersion: "2",- },- wantSanitized: true,- wantSwappinessNil: true,- },- {- name: "podman cgroup v1 preserves memory swappiness",- engineInfo: EngineCompatibilityInfo{- Name: "podman",- CgroupVersion: "1",- },- wantSanitized: false,- wantSwappinessNil: false,- },- {- name: "docker cgroup v2 preserves memory swappiness",- engineInfo: EngineCompatibilityInfo{- Name: "docker",- CgroupVersion: "2",- },- wantSanitized: false,- wantSwappinessNil: false,- },- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- input := &containertypes.HostConfig{- MemorySwappiness: &swappiness,- CPUShares: 1024,- PublishAllPorts: true,- ReadonlyRootfs: true,- NetworkMode: "bridge",- ContainerIDFile: "/tmp/id",- VolumeDriver: "local",- Annotations: map[string]string{"test": "value"},- MaskedPaths: []string{"/proc/kcore"},- ReadonlyPaths: []string{"/proc/asound"},- }-- cloned := cloneContainerHostConfigInternal(input)- require.NotNil(t, cloned)- require.NotSame(t, input, cloned)-- sanitized := sanitizeRecreateHostConfigInternal(cloned, tt.engineInfo)- require.Equal(t, tt.wantSanitized, sanitized)-- if tt.wantSwappinessNil {- require.Nil(t, cloned.MemorySwappiness)- } else {- require.NotNil(t, cloned.MemorySwappiness)- require.Equal(t, int64(60), *cloned.MemorySwappiness)- }-- require.NotNil(t, input.MemorySwappiness)- require.Equal(t, int64(60), *input.MemorySwappiness)- require.Equal(t, int64(1024), cloned.CPUShares)- require.True(t, cloned.PublishAllPorts)- require.True(t, cloned.ReadonlyRootfs)- require.Equal(t, containertypes.NetworkMode("bridge"), cloned.NetworkMode)- require.Equal(t, "/tmp/id", cloned.ContainerIDFile)- require.Equal(t, "local", cloned.VolumeDriver)- require.Equal(t, map[string]string{"test": "value"}, cloned.Annotations)- require.Equal(t, []string{"/proc/kcore"}, cloned.MaskedPaths)- require.Equal(t, []string{"/proc/asound"}, cloned.ReadonlyPaths)- })- }-}--func TestSanitizeRecreateHostConfigInternal_NilHostConfig(t *testing.T) {- sanitized := sanitizeRecreateHostConfigInternal(nil, EngineCompatibilityInfo{Name: "podman", CgroupVersion: "2"})- require.False(t, sanitized)-}--func TestDetectEngineCompatibilityInfoInternal(t *testing.T) {- t.Run("prefers platform name for podman detection", func(t *testing.T) {- version := client.ServerVersionResult{}- version.Platform.Name = "Podman Engine"- info := systemtypes.Info{CgroupVersion: "2"}-- engineInfo := detectEngineCompatibilityInfoInternal(version, info)- require.Equal(t, "podman", engineInfo.Name)- require.Equal(t, "2", engineInfo.CgroupVersion)- })-- t.Run("detects podman from component names", func(t *testing.T) {- version := client.ServerVersionResult{- Components: []systemtypes.ComponentVersion{- {Name: "Podman Engine"},- },- }- info := systemtypes.Info{CgroupVersion: "2"}-- engineInfo := detectEngineCompatibilityInfoInternal(version, info)- require.Equal(t, "podman", engineInfo.Name)- require.Equal(t, "2", engineInfo.CgroupVersion)- })-- t.Run("falls back to docker markers", func(t *testing.T) {- version := client.ServerVersionResult{}- info := systemtypes.Info{- CgroupVersion: "2",- ServerVersion: "Docker Engine - Community",- }-- engineInfo := detectEngineCompatibilityInfoInternal(version, info)- require.Equal(t, "docker", engineInfo.Name)- require.Equal(t, "2", engineInfo.CgroupVersion)- })-}diff --git a/backend/pkg/libarcane/inspect_compat.go b/backend/pkg/libarcane/inspect_compat.godeleted file mode 100644index 7a2518142..000000000--- a/backend/pkg/libarcane/inspect_compat.go+++ /dev/null@@ -1,557 +0,0 @@-package libarcane--import (- "bufio"- "context"- "encoding/json/v2"- "io"- "net/http"- "net/netip"- "net/url"- "path"- "strconv"- "strings"-- "emperror.dev/errors"-- containertypes "github.com/moby/moby/api/types/container"- networktypes "github.com/moby/moby/api/types/network"- "github.com/moby/moby/client"- "github.com/samber/mo"-)--// WrapDockerAPIClientForInspectCompatibility wraps a Docker API client so-// inspect calls can recover from daemon responses that encode address fields-// with CIDR suffixes that newer typed Moby structs reject.-func WrapDockerAPIClientForInspectCompatibility(apiClient client.APIClient) client.APIClient {- if apiClient == nil {- return nil- }- if _, ok := apiClient.(*inspectCompatibilityClient); ok {- return apiClient- }- return &inspectCompatibilityClient{APIClient: apiClient}-}--type inspectCompatibilityClient struct {- client.APIClient-}--func (c *inspectCompatibilityClient) ContainerCreate(ctx context.Context, options client.ContainerCreateOptions) (client.ContainerCreateResult, error) {- return ContainerCreateWithCompatibility(ctx, c.APIClient, options)-}--func (c *inspectCompatibilityClient) ContainerInspect(ctx context.Context, containerID string, options client.ContainerInspectOptions) (client.ContainerInspectResult, error) {- return ContainerInspectWithCompatibility(ctx, c.APIClient, containerID, options)-}--func (c *inspectCompatibilityClient) NetworkInspect(ctx context.Context, networkID string, options client.NetworkInspectOptions) (client.NetworkInspectResult, error) {- return NetworkInspectWithCompatibility(ctx, c.APIClient, networkID, options)-}--func (c *inspectCompatibilityClient) NetworkList(ctx context.Context, options client.NetworkListOptions) (client.NetworkListResult, error) {- return NetworkListWithCompatibility(ctx, c.APIClient, options)-}--// ContainerInspectWithCompatibility retries inspect decoding against raw daemon-// JSON when the primary typed decode fails on a ParseAddr-style CIDR issue.-func ContainerInspectWithCompatibility(ctx context.Context, apiClient client.APIClient, containerID string, options client.ContainerInspectOptions) (client.ContainerInspectResult, error) {- if apiClient == nil {- return client.ContainerInspectResult{}, errors.New("docker api client is nil")- }-- result, err := apiClient.ContainerInspect(ctx, containerID, options)- if err == nil || !isInspectAddressParseErrorInternal(err) {- return result, err- }-- query := url.Values{}- if options.Size {- query.Set("size", "1")- }-- raw, fetchErr := fetchDockerAPIJSONInternal(ctx, apiClient, "/containers/"+strings.TrimSpace(containerID)+"/json", query)- if fetchErr != nil {- return client.ContainerInspectResult{}, err- }-- normalized, changed, normalizeContainerInspectRawJSONInternalErr := normalizeContainerInspectRawJSONInternal(raw)- if normalizeContainerInspectRawJSONInternalErr != nil || !changed {- return client.ContainerInspectResult{}, err- }-- var repaired containertypes.InspectResponse- if unmarshalErr := json.Unmarshal(normalized, &repaired); unmarshalErr != nil {- return client.ContainerInspectResult{}, err- }-- return client.ContainerInspectResult{- Container: repaired,- Raw: normalized,- }, nil-}--// NetworkInspectWithCompatibility retries inspect decoding against raw daemon-// JSON when the primary typed decode fails on a ParseAddr-style CIDR issue.-func NetworkInspectWithCompatibility(ctx context.Context, apiClient client.APIClient, networkID string, options client.NetworkInspectOptions) (client.NetworkInspectResult, error) {- if apiClient == nil {- return client.NetworkInspectResult{}, errors.New("docker api client is nil")- }-- result, err := apiClient.NetworkInspect(ctx, networkID, options)- if err == nil || !isInspectAddressParseErrorInternal(err) {- return result, err- }-- query := url.Values{}- if options.Verbose {- query.Set("verbose", "true")- }- if scope := strings.TrimSpace(options.Scope); scope != "" {- query.Set("scope", scope)- }-- raw, fetchErr := fetchDockerAPIJSONInternal(ctx, apiClient, "/networks/"+strings.TrimSpace(networkID), query)- if fetchErr != nil {- return client.NetworkInspectResult{}, err- }-- normalized, changed, normalizeNetworkInspectRawJSONInternalErr := normalizeNetworkInspectRawJSONInternal(raw)- if normalizeNetworkInspectRawJSONInternalErr != nil || !changed {- return client.NetworkInspectResult{}, err- }-- var repaired networktypes.Inspect- if unmarshalErr := json.Unmarshal(normalized, &repaired); unmarshalErr != nil {- return client.NetworkInspectResult{}, err- }-- return client.NetworkInspectResult{- Network: repaired,- Raw: normalized,- }, nil-}--// NetworkListWithCompatibility retries list decoding against raw daemon JSON-// when the primary typed decode fails on a ParseAddr-style CIDR issue.-func NetworkListWithCompatibility(ctx context.Context, apiClient client.APIClient, options client.NetworkListOptions) (client.NetworkListResult, error) {- if apiClient == nil {- return client.NetworkListResult{}, errors.New("docker api client is nil")- }-- result, err := apiClient.NetworkList(ctx, options)- if err == nil || !isInspectAddressParseErrorInternal(err) {- return result, err- }-- query, queryErr := buildNetworkListQueryInternal(options)- if queryErr != nil {- return client.NetworkListResult{}, err- }-- raw, fetchErr := fetchDockerAPIJSONInternal(ctx, apiClient, "/networks", query)- if fetchErr != nil {- return client.NetworkListResult{}, err- }-- normalized, changed, normalizeErr := normalizeNetworkListRawJSONInternal(raw)- if normalizeErr != nil || !changed {- return client.NetworkListResult{}, err- }-- var repaired []networktypes.Summary- if unmarshalErr := json.Unmarshal(normalized, &repaired); unmarshalErr != nil {- return client.NetworkListResult{}, err- }-- return client.NetworkListResult{- Items: repaired,- }, nil-}--func fetchDockerAPIJSONInternal(ctx context.Context, apiClient client.APIClient, resourcePath string, query url.Values) ([]byte, error) {- dialer := apiClient.Dialer()- if dialer == nil {- return nil, errors.New("docker api client does not expose a dialer")- }-- reqURL := &url.URL{- Scheme: "http",- Host: client.DummyHost,- Path: buildDockerAPIPathInternal(apiClient.ClientVersion(), resourcePath),- RawQuery: query.Encode(),- }- req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL.String(), http.NoBody)- if err != nil {- return nil, err- }-- // The official Moby client uses a TLS-aware dialer here when the daemon is- // configured with client certificates, so this fallback continues to work- // for remote tcp+TLS and local socket transports without reimplementing the- // client's private request machinery.- conn, err := dialer(ctx)- if err != nil {- return nil, err- }- defer func() { _ = conn.Close() }()-- if err := req.Write(conn); err != nil {- return nil, err- }-- resp, err := http.ReadResponse(bufio.NewReader(conn), req)- if err != nil {- return nil, err- }- defer func() { _ = resp.Body.Close() }()-- body, err := io.ReadAll(resp.Body)- if err != nil {- return nil, err- }- if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return nil, errors.Errorf("docker api GET %s failed with %s: %s", resourcePath, resp.Status, strings.TrimSpace(string(body)))- }-- return body, nil-}--func buildDockerAPIPathInternal(version, resourcePath string) string {- if trimmedVersion := strings.TrimSpace(strings.TrimPrefix(version, "v")); trimmedVersion != "" {- return path.Join("/v"+trimmedVersion, resourcePath)- }- return path.Join("/", resourcePath)-}--func normalizeContainerInspectRawJSONInternal(raw []byte) ([]byte, bool, error) {- payload := map[string]any{}- if err := json.Unmarshal(raw, &payload); err != nil {- return nil, false, err- }-- changed := false-- networkSettings, ok := asMapInternal(payload["NetworkSettings"]).Get()- if ok {- changed = normalizeAddressStringFieldInternal(networkSettings, "Gateway")- changed = normalizeAddressStringFieldInternal(networkSettings, "IPv6Gateway") || changed- changed = normalizeAddressWithPrefixFieldInternal(networkSettings, "IPAddress", "IPPrefixLen") || changed- changed = normalizeAddressWithPrefixFieldInternal(networkSettings, "GlobalIPv6Address", "GlobalIPv6PrefixLen") || changed-- if networks, ok := asMapInternal(networkSettings["Networks"]).Get(); ok {- for _, endpointAny := range networks {- endpoint, ok := asMapInternal(endpointAny).Get()- if !ok {- continue- }-- changed = normalizeAddressStringFieldInternal(endpoint, "Gateway") || changed- changed = normalizeAddressStringFieldInternal(endpoint, "IPv6Gateway") || changed- changed = normalizeAddressWithPrefixFieldInternal(endpoint, "IPAddress", "IPPrefixLen") || changed- changed = normalizeAddressWithPrefixFieldInternal(endpoint, "GlobalIPv6Address", "GlobalIPv6PrefixLen") || changed-- if ipam, ok := asMapInternal(endpoint["IPAMConfig"]).Get(); ok {- changed = normalizeAddressStringFieldInternal(ipam, "IPv4Address") || changed- changed = normalizeAddressStringFieldInternal(ipam, "IPv6Address") || changed- changed = normalizeAddressStringSliceFieldInternal(ipam, "LinkLocalIPs") || changed- }- }- }- }-- if !changed {- return raw, false, nil- }-- normalized, err := json.Marshal(payload)- if err != nil {- return nil, false, err- }- return normalized, true, nil-}--func normalizeNetworkListRawJSONInternal(raw []byte) ([]byte, bool, error) {- var payload []any- if err := json.Unmarshal(raw, &payload); err != nil {- return nil, false, err- }-- changed := false- for _, item := range payload {- networkPayload, ok := asMapInternal(item).Get()- if !ok {- continue- }- changed = normalizeNetworkObjectInternal(networkPayload) || changed- }-- if !changed {- return raw, false, nil- }-- normalized, err := json.Marshal(payload)- if err != nil {- return nil, false, err- }- return normalized, true, nil-}--func normalizeNetworkInspectRawJSONInternal(raw []byte) ([]byte, bool, error) {- payload := map[string]any{}- if err := json.Unmarshal(raw, &payload); err != nil {- return nil, false, err- }-- changed := normalizeNetworkObjectInternal(payload)- if !changed {- return raw, false, nil- }-- normalized, err := json.Marshal(payload)- if err != nil {- return nil, false, err- }- return normalized, true, nil-}--func normalizeNetworkObjectInternal(payload map[string]any) bool {- changed := false- if ipam, ok := asMapInternal(payload["IPAM"]).Get(); ok {- if configs, ok := asSliceInternal(ipam["Config"]).Get(); ok {- for _, configAny := range configs {- config, ok := asMapInternal(configAny).Get()- if !ok {- continue- }-- changed = normalizeAddressStringFieldInternal(config, "Gateway") || changed- changed = normalizeAuxiliaryAddressesInternal(config, "AuxiliaryAddresses") || changed- changed = normalizeAuxiliaryAddressesInternal(config, "AuxAddress") || changed- }- }- }- if containers, ok := asMapInternal(payload["Containers"]).Get(); ok {- for _, endpointAny := range containers {- endpoint, ok := asMapInternal(endpointAny).Get()- if !ok {- continue- }-- changed = normalizePrefixStringFieldInternal(endpoint, "IPv4Address") || changed- changed = normalizePrefixStringFieldInternal(endpoint, "IPv6Address") || changed- }- }- return changed-}--func normalizeAddressStringFieldInternal(obj map[string]any, key string) bool {- raw, ok := obj[key].(string)- if !ok {- return false- }-- normalized, changed := normalizeAddressStringInternal(raw).Get()- if !changed {- return false- }-- obj[key] = normalized- return true-}--func normalizeAddressWithPrefixFieldInternal(obj map[string]any, addrKey, prefixLenKey string) bool {- raw, ok := obj[addrKey].(string)- if !ok {- return false- }-- trimmed := strings.TrimSpace(raw)- if trimmed == "" {- return false- }- if _, err := netip.ParseAddr(trimmed); err == nil {- if raw == trimmed {- return false- }- obj[addrKey] = trimmed- return true- }-- prefix, err := netip.ParsePrefix(trimmed)- if err != nil {- return false- }-- changed := false- addrValue := prefix.Addr().String()- if raw != addrValue {- obj[addrKey] = addrValue- changed = true- }-- if prefixLenMissingInternal(obj[prefixLenKey]) {- obj[prefixLenKey] = prefix.Bits()- changed = true- }-- return changed-}--func normalizeAddressStringSliceFieldInternal(obj map[string]any, key string) bool {- values, ok := asSliceInternal(obj[key]).Get()- if !ok {- return false- }-- changed := false- for i, value := range values {- raw, ok := value.(string)- if !ok {- continue- }- normalized, fieldChanged := normalizeAddressStringInternal(raw).Get()- if !fieldChanged {- continue- }- values[i] = normalized- changed = true- }-- if changed {- obj[key] = values- }- return changed-}--func normalizeAuxiliaryAddressesInternal(obj map[string]any, key string) bool {- auxMap, ok := asMapInternal(obj[key]).Get()- if !ok {- return false- }-- changed := false- for auxKey, auxValue := range auxMap {- raw, ok := auxValue.(string)- if !ok {- continue- }- normalized, fieldChanged := normalizeAddressStringInternal(raw).Get()- if !fieldChanged {- continue- }- auxMap[auxKey] = normalized- changed = true- }-- if changed {- obj[key] = auxMap- }- return changed-}--func normalizePrefixStringFieldInternal(obj map[string]any, key string) bool {- raw, ok := obj[key].(string)- if !ok {- return false- }-- trimmed := strings.TrimSpace(raw)- if trimmed == "" {- return false- }-- prefix, err := netip.ParsePrefix(trimmed)- if err != nil {- return false- }-- normalized := prefix.String()- if normalized == raw {- return false- }-- obj[key] = normalized- return true-}--func normalizeAddressStringInternal(raw string) mo.Option[string] {- trimmed := strings.TrimSpace(raw)- if trimmed == "" {- return mo.None[string]()- }- if _, err := netip.ParseAddr(trimmed); err == nil {- if trimmed != raw {- return mo.Some(trimmed)- }- return mo.None[string]()- }-- prefix, err := netip.ParsePrefix(trimmed)- if err != nil {- return mo.None[string]()- }-- normalized := prefix.Addr().String()- if normalized != raw {- return mo.Some(normalized)- }- return mo.None[string]()-}--func prefixLenMissingInternal(value any) bool {- switch v := value.(type) {- case nil:- return true- case float64:- return v == 0- case int:- return v == 0- case int32:- return v == 0- case int64:- return v == 0- case string:- trimmed := strings.TrimSpace(v)- if trimmed == "" {- return true- }- parsed, err := strconv.Atoi(trimmed)- return err != nil || parsed == 0- default:- return false- }-}--func asMapInternal(value any) mo.Option[map[string]any] {- mapped, ok := value.(map[string]any)- return mo.TupleToOption(mapped, ok)-}--func asSliceInternal(value any) mo.Option[[]any] {- slice, ok := value.([]any)- return mo.TupleToOption(slice, ok)-}--func buildNetworkListQueryInternal(options client.NetworkListOptions) (url.Values, error) {- query := url.Values{}- if len(options.Filters) == 0 {- return query, nil- }-- filtersJSON, err := json.Marshal(options.Filters)- if err != nil {- return nil, err- }- query.Set("filters", string(filtersJSON))- return query, nil-}--func isInspectAddressParseErrorInternal(err error) bool {- if err == nil {- return false- }-- msg := err.Error()- return strings.Contains(msg, "ParseAddr(") || strings.Contains(msg, "ParsePrefix(")-}diff --git a/backend/pkg/libarcane/inspect_compat_test.go b/backend/pkg/libarcane/inspect_compat_test.godeleted file mode 100644index 0bce8d1db..000000000--- a/backend/pkg/libarcane/inspect_compat_test.go+++ /dev/null@@ -1,580 +0,0 @@-package libarcane--import (- "context"- "encoding/json"- "io"- "net/http"- "net/http/httptest"- "net/netip"- "strings"- "testing"-- containertypes "github.com/moby/moby/api/types/container"- networktypes "github.com/moby/moby/api/types/network"- "github.com/moby/moby/client"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func TestNormalizeContainerInspectRawJSONInternal(t *testing.T) {- raw := []byte(`{- "Id":"abc123",- "Name":"/app",- "Config":{"Image":"test:latest"},- "HostConfig":{"NetworkMode":"bridge"},- "NetworkSettings":{- "Networks":{- "bridge":{- "IPAMConfig":{- "IPv4Address":"172.18.0.50/16",- "IPv6Address":"fdd0:0:0:c::10/64",- "LinkLocalIPs":["169.254.10.10/16","fe80::10/64"]- },- "Gateway":"172.18.0.1/16",- "IPAddress":"172.18.0.20/16",- "IPPrefixLen":0,- "IPv6Gateway":"fdd0:0:0:c::1/64",- "GlobalIPv6Address":"fdd0:0:0:c::10/64",- "GlobalIPv6PrefixLen":0- }- }- }- }`)-- normalized, changed, err := normalizeContainerInspectRawJSONInternal(raw)- require.NoError(t, err)- require.True(t, changed)-- var inspect containertypes.InspectResponse- require.NoError(t, json.Unmarshal(normalized, &inspect))-- endpoint := inspect.NetworkSettings.Networks["bridge"]- require.NotNil(t, endpoint)- require.NotNil(t, endpoint.IPAMConfig)- assert.Equal(t, netip.MustParseAddr("172.18.0.1"), endpoint.Gateway)- assert.Equal(t, netip.MustParseAddr("172.18.0.20"), endpoint.IPAddress)- assert.Equal(t, 16, endpoint.IPPrefixLen)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), endpoint.IPv6Gateway)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::10"), endpoint.GlobalIPv6Address)- assert.Equal(t, 64, endpoint.GlobalIPv6PrefixLen)- assert.Equal(t, netip.MustParseAddr("172.18.0.50"), endpoint.IPAMConfig.IPv4Address)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::10"), endpoint.IPAMConfig.IPv6Address)- assert.Equal(t, []netip.Addr{- netip.MustParseAddr("169.254.10.10"),- netip.MustParseAddr("fe80::10"),- }, endpoint.IPAMConfig.LinkLocalIPs)-}--func TestNormalizeContainerInspectRawJSONInternal_NormalizesTopLevelNetworkSettings(t *testing.T) {- raw := []byte(`{- "Id":"abc123",- "Name":"/app",- "Config":{"Image":"test:latest"},- "HostConfig":{"NetworkMode":"bridge"},- "NetworkSettings":{- "Gateway":"172.18.0.1/16",- "IPAddress":"172.18.0.20/16",- "IPPrefixLen":0,- "IPv6Gateway":"fdd0:0:0:c::1/64",- "GlobalIPv6Address":"fdd0:0:0:c::10/64",- "GlobalIPv6PrefixLen":0,- "Networks":{}- }- }`)-- normalized, changed, err := normalizeContainerInspectRawJSONInternal(raw)- require.NoError(t, err)- require.True(t, changed)-- payload := map[string]any{}- require.NoError(t, json.Unmarshal(normalized, &payload))-- networkSettings, ok := asMapInternal(payload["NetworkSettings"]).Get()- require.True(t, ok)- assert.Equal(t, "172.18.0.1", networkSettings["Gateway"])- assert.Equal(t, "172.18.0.20", networkSettings["IPAddress"])- assert.InDelta(t, float64(16), networkSettings["IPPrefixLen"], 0.000001)- assert.Equal(t, "fdd0:0:0:c::1", networkSettings["IPv6Gateway"])- assert.Equal(t, "fdd0:0:0:c::10", networkSettings["GlobalIPv6Address"])- assert.InDelta(t, float64(64), networkSettings["GlobalIPv6PrefixLen"], 0.000001)-}--func TestNormalizeNetworkInspectRawJSONInternal(t *testing.T) {- raw := []byte(`{- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "EnableIPv6":true,- "IPAM":{- "Driver":"default",- "Config":[- {- "Subnet":"fdd0:0:0:c::/64",- "Gateway":"fdd0:0:0:c::1/64",- "AuxiliaryAddresses":{- "router":"fdd0:0:0:c::2/64"- }- }- ]- },- "Containers":{}- }`)-- normalized, changed, err := normalizeNetworkInspectRawJSONInternal(raw)- require.NoError(t, err)- require.True(t, changed)-- var inspect networktypes.Inspect- require.NoError(t, json.Unmarshal(normalized, &inspect))- require.Len(t, inspect.IPAM.Config, 1)- assert.Equal(t, netip.MustParsePrefix("fdd0:0:0:c::/64"), inspect.IPAM.Config[0].Subnet)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), inspect.IPAM.Config[0].Gateway)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::2"), inspect.IPAM.Config[0].AuxAddress["router"])-}--func TestNormalizeNetworkInspectRawJSONInternal_NormalizesContainerEndpoints(t *testing.T) {- raw := []byte(`{- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{"Driver":"default","Config":[]},- "Containers":{- "abc123":{- "Name":"app",- "EndpointID":"ep1",- "IPv4Address":" 172.18.0.20/16 ",- "IPv6Address":" fdd0:0:0:c::10/64 "- }- }- }`)-- normalized, changed, err := normalizeNetworkInspectRawJSONInternal(raw)- require.NoError(t, err)- require.True(t, changed)-- var inspect networktypes.Inspect- require.NoError(t, json.Unmarshal(normalized, &inspect))- endpoint := inspect.Containers["abc123"]- assert.Equal(t, netip.MustParsePrefix("172.18.0.20/16"), endpoint.IPv4Address)- assert.Equal(t, netip.MustParsePrefix("fdd0:0:0:c::10/64"), endpoint.IPv6Address)-}--func TestNormalizeNetworkListRawJSONInternal(t *testing.T) {- raw := []byte(`[- {- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{- "Driver":"default",- "Config":[- {- "Subnet":"fdd0:0:0:c::/64",- "Gateway":"fdd0:0:0:c::1/64",- "AuxiliaryAddresses":{- "router":"fdd0:0:0:c::2/64"- }- }- ]- }- }- ]`)-- normalized, changed, err := normalizeNetworkListRawJSONInternal(raw)- require.NoError(t, err)- require.True(t, changed)-- var networks []networktypes.Summary- require.NoError(t, json.Unmarshal(normalized, &networks))- require.Len(t, networks, 1)- require.Len(t, networks[0].IPAM.Config, 1)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), networks[0].IPAM.Config[0].Gateway)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::2"), networks[0].IPAM.Config[0].AuxAddress["router"])-}--func TestNormalizeAddressStringInternal_TrimsWhitespaceAroundValidAddress(t *testing.T) {- normalized, changed := normalizeAddressStringInternal(" 172.18.0.1 ").Get()- assert.True(t, changed)- assert.Equal(t, "172.18.0.1", normalized)-}--func TestNormalizeAddressWithPrefixFieldInternal_TrimsWhitespaceAroundValidAddress(t *testing.T) {- obj := map[string]any{- "IPAddress": " 172.18.0.20 ",- "IPPrefixLen": 24,- }-- changed := normalizeAddressWithPrefixFieldInternal(obj, "IPAddress", "IPPrefixLen")- assert.True(t, changed)- assert.Equal(t, "172.18.0.20", obj["IPAddress"])- assert.Equal(t, 24, obj["IPPrefixLen"])-}--func TestIsInspectAddressParseErrorInternal_MatchesPrefixErrors(t *testing.T) {- _, err := netip.ParsePrefix(" 172.18.0.20/16 ")- assert.True(t, isInspectAddressParseErrorInternal(err))-}--func TestContainerInspectWithCompatibility(t *testing.T) {- containerJSON := `{- "Id":"abc123",- "Name":"/app",- "Config":{"Image":"test:latest"},- "HostConfig":{"NetworkMode":"bridge"},- "NetworkSettings":{- "Networks":{- "bridge":{- "IPAMConfig":{"IPv6Address":"fdd0:0:0:c::10/64"},- "IPv6Gateway":"fdd0:0:0:c::1/64",- "GlobalIPv6Address":"fdd0:0:0:c::10/64",- "GlobalIPv6PrefixLen":0- }- }- }- }`-- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- assert.Equal(t, "/v1.41/containers/test-container/json", r.URL.Path)- _, _ = w.Write([]byte(containerJSON))- })-- result, err := ContainerInspectWithCompatibility(context.Background(), dockerClient, "test-container", client.ContainerInspectOptions{})- require.NoError(t, err)- assert.Equal(t, "abc123", result.Container.ID)- endpoint := result.Container.NetworkSettings.Networks["bridge"]- require.NotNil(t, endpoint)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), endpoint.IPv6Gateway)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::10"), endpoint.GlobalIPv6Address)- assert.Equal(t, 64, endpoint.GlobalIPv6PrefixLen)-}--func TestNetworkInspectWithCompatibility(t *testing.T) {- networkJSON := `{- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{- "Driver":"default",- "Config":[- {- "Subnet":"fdd0:0:0:c::/64",- "Gateway":"fdd0:0:0:c::1/64"- }- ]- },- "Containers":{}- }`-- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- assert.Equal(t, "/v1.41/networks/test-net", r.URL.Path)- _, _ = w.Write([]byte(networkJSON))- })-- result, err := NetworkInspectWithCompatibility(context.Background(), dockerClient, "test-net", client.NetworkInspectOptions{})- require.NoError(t, err)- require.Len(t, result.Network.IPAM.Config, 1)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), result.Network.IPAM.Config[0].Gateway)-}--func TestNetworkListWithCompatibility(t *testing.T) {- networkJSON := `[- {- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{- "Driver":"default",- "Config":[- {- "Subnet":"fdd0:0:0:c::/64",- "Gateway":"fdd0:0:0:c::1/64",- "AuxiliaryAddresses":{- "router":"fdd0:0:0:c::2/64"- }- }- ]- }- }- ]`-- callCount := 0- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- callCount++- assert.Equal(t, "/v1.41/networks", r.URL.Path)- assert.JSONEq(t, `{"name":{"test-net":true}}`, r.URL.Query().Get("filters"))- _, _ = w.Write([]byte(networkJSON))- })-- result, err := NetworkListWithCompatibility(context.Background(), dockerClient, client.NetworkListOptions{- Filters: make(client.Filters).Add("name", "test-net"),- })- require.NoError(t, err)- require.Len(t, result.Items, 1)- require.Len(t, result.Items[0].IPAM.Config, 1)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), result.Items[0].IPAM.Config[0].Gateway)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::2"), result.Items[0].IPAM.Config[0].AuxAddress["router"])- assert.Equal(t, 2, callCount)-}--func TestNetworkListWithCompatibility_SuccessSkipsFallback(t *testing.T) {- networkJSON := `[- {- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{- "Driver":"default",- "Config":[- {- "Subnet":"fdd0:0:0:c::/64",- "Gateway":"fdd0:0:0:c::1"- }- ]- }- }- ]`-- callCount := 0- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- callCount++- assert.Equal(t, "/v1.41/networks", r.URL.Path)- _, _ = w.Write([]byte(networkJSON))- })-- result, err := NetworkListWithCompatibility(context.Background(), dockerClient, client.NetworkListOptions{})- require.NoError(t, err)- require.Len(t, result.Items, 1)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), result.Items[0].IPAM.Config[0].Gateway)- assert.Equal(t, 1, callCount)-}--func TestContainerInspectWithCompatibility_TLSRemote(t *testing.T) {- containerJSON := `{- "Id":"abc123",- "Name":"/app",- "Config":{"Image":"test:latest"},- "HostConfig":{"NetworkMode":"bridge"},- "NetworkSettings":{- "Networks":{- "bridge":{- "IPv6Gateway":"fdd0:0:0:c::1/64"- }- }- }- }`-- server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- assert.Equal(t, "/v1.41/containers/test-container/json", r.URL.Path)- _, _ = w.Write([]byte(containerJSON))- }))- defer server.Close()-- dockerClient, err := client.New(- client.WithHTTPClient(server.Client()),- client.WithHost("tcp://"+strings.TrimPrefix(server.URL, "https://")),- client.WithScheme("https"),- client.WithAPIVersion("1.41"),- )- require.NoError(t, err)- defer func() {- _ = dockerClient.Close()- }()-- result, err := ContainerInspectWithCompatibility(context.Background(), dockerClient, "test-container", client.ContainerInspectOptions{})- require.NoError(t, err)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), result.Container.NetworkSettings.Networks["bridge"].IPv6Gateway)-}--func TestInspectCompatibilityLeavesInvalidValuesFailing(t *testing.T) {- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte(`{- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{"Driver":"default","Config":[{"Subnet":"fdd0:0:0:c::/64","Gateway":"definitely-not-an-ip"}]},- "Containers":{}- }`))- })-- _, err := NetworkInspectWithCompatibility(context.Background(), dockerClient, "test-net", client.NetworkInspectOptions{})- require.Error(t, err)- assert.Contains(t, err.Error(), `ParseAddr("definitely-not-an-ip")`)-}--func TestNetworkListWithCompatibility_LeavesInvalidValuesFailing(t *testing.T) {- callCount := 0- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- callCount++- assert.Equal(t, "/v1.41/networks", r.URL.Path)- _, _ = w.Write([]byte(`[- {- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{"Driver":"default","Config":[{"Subnet":"fdd0:0:0:c::/64","Gateway":"definitely-not-an-ip"}]}- }- ]`))- })-- _, err := NetworkListWithCompatibility(context.Background(), dockerClient, client.NetworkListOptions{})- require.Error(t, err)- assert.Contains(t, err.Error(), `ParseAddr("definitely-not-an-ip")`)- assert.Equal(t, 2, callCount)-}--func TestWrapDockerAPIClientForInspectCompatibility(t *testing.T) {- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte(`{- "Id":"abc123",- "Name":"/app",- "Config":{"Image":"test:latest"},- "HostConfig":{"NetworkMode":"bridge"},- "NetworkSettings":{"Networks":{"bridge":{"IPv6Gateway":"fdd0:0:0:c::1/64"}}}- }`))- })-- wrapped := WrapDockerAPIClientForInspectCompatibility(dockerClient)- result, err := wrapped.ContainerInspect(context.Background(), "test-container", client.ContainerInspectOptions{})- require.NoError(t, err)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), result.Container.NetworkSettings.Networks["bridge"].IPv6Gateway)-}--func TestWrapDockerAPIClientForInspectCompatibility_NetworkList(t *testing.T) {- callCount := 0- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- callCount++- assert.Equal(t, "/v1.41/networks", r.URL.Path)- _, _ = w.Write([]byte(`[- {- "Name":"test-net",- "Id":"net123",- "Created":"2026-03-11T00:00:00Z",- "Scope":"local",- "Driver":"bridge",- "IPAM":{"Driver":"default","Config":[{"Subnet":"fdd0:0:0:c::/64","Gateway":"fdd0:0:0:c::1/64"}]}- }- ]`))- })-- wrapped := WrapDockerAPIClientForInspectCompatibility(dockerClient)- result, err := wrapped.NetworkList(context.Background(), client.NetworkListOptions{})- require.NoError(t, err)- require.Len(t, result.Items, 1)- assert.Equal(t, netip.MustParseAddr("fdd0:0:0:c::1"), result.Items[0].IPAM.Config[0].Gateway)- assert.Equal(t, 2, callCount)-}--func TestWrapDockerAPIClientForInspectCompatibility_ContainerCreateLegacyNetworks(t *testing.T) {- type createRequest struct {- NetworkingConfig networktypes.NetworkingConfig `json:"NetworkingConfig"`- }- type connectRequest struct {- Container string `json:"Container"`- EndpointConfig *networktypes.EndpointSettings `json:"EndpointConfig"`- }-- var createPayload createRequest- connectPayloads := map[string]connectRequest{}-- dockerClient := newTestDockerClient(t, func(w http.ResponseWriter, r *http.Request) {- switch {- case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/containers/create"):- body, err := io.ReadAll(r.Body)- if !assert.NoError(t, err) {- return- }- if !assert.NoError(t, json.Unmarshal(body, &createPayload)) {- return- }- w.Header().Set("Content-Type", "application/json")- _, _ = w.Write([]byte(`{"Id":"new-container-id","Warnings":[]}`))- case r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/networks/") && strings.HasSuffix(r.URL.Path, "/connect"):- networkName := r.URL.Path- networkName = strings.TrimSuffix(networkName, "/connect")- networkName = networkName[strings.LastIndex(networkName, "/networks/")+len("/networks/"):]- body, err := io.ReadAll(r.Body)- if !assert.NoError(t, err) {- return- }-- var payload connectRequest- if !assert.NoError(t, json.Unmarshal(body, &payload)) {- return- }- connectPayloads[networkName] = payload- w.WriteHeader(http.StatusOK)- default:- if !assert.Failf(t, "unexpected failure", "unexpected request: %s %s", r.Method, r.URL.Path) {- return- }- }- })-- wrapped := WrapDockerAPIClientForInspectCompatibility(dockerClient)- result, err := wrapped.ContainerCreate(context.Background(), client.ContainerCreateOptions{- Config: &containertypes.Config{- Image: "nginx:alpine",- },- HostConfig: &containertypes.HostConfig{- NetworkMode: "synobridge",- },- NetworkingConfig: &networktypes.NetworkingConfig{- EndpointsConfig: map[string]*networktypes.EndpointSettings{- "synobridge": {- Aliases: []string{"app"},- },- "nginx-proxy-manager_zbridge": {- Aliases: []string{"proxy"},- },- },- },- Name: "test-app",- })- require.NoError(t, err)- assert.Equal(t, "new-container-id", result.ID)-- require.Len(t, createPayload.NetworkingConfig.EndpointsConfig, 1)- require.Contains(t, createPayload.NetworkingConfig.EndpointsConfig, "synobridge")- assert.Equal(t, []string{"app"}, createPayload.NetworkingConfig.EndpointsConfig["synobridge"].Aliases)-- require.Len(t, connectPayloads, 1)- require.Contains(t, connectPayloads, "nginx-proxy-manager_zbridge")- assert.Equal(t, "new-container-id", connectPayloads["nginx-proxy-manager_zbridge"].Container)- require.NotNil(t, connectPayloads["nginx-proxy-manager_zbridge"].EndpointConfig)- assert.Equal(t, []string{"proxy"}, connectPayloads["nginx-proxy-manager_zbridge"].EndpointConfig.Aliases)-}--func newTestDockerClient(t *testing.T, handler http.HandlerFunc) *client.Client {- t.Helper()-- server := httptest.NewServer(handler)- t.Cleanup(server.Close)-- dockerClient, err := client.New(- client.WithHost("tcp://"+strings.TrimPrefix(server.URL, "http://")),- client.WithAPIVersion("1.41"),- )- require.NoError(t, err)- t.Cleanup(func() {- _ = dockerClient.Close()- })-- return dockerClient-}diff --git a/backend/pkg/libarcane/internal_resource.go b/backend/pkg/libarcane/internal_resource.goindex 98636e8cc..82f49e905 100644--- a/backend/pkg/libarcane/internal_resource.go+++ b/backend/pkg/libarcane/internal_resource.go@@ -1,6 +1,7 @@package libarcaneimport (+ "cmp""context""log/slog""os"@@ -9,6 +10,7 @@ import ("emperror.dev/errors""github.com/moby/moby/api/types/container""github.com/moby/moby/client"+ "go.getarcane.app/docker/compat""go.getarcane.app/sys/cgroup""go.getarcane.app/updater/labels")@@ -48,9 +50,7 @@ func FindArcaneContainerIDByLabel(ctx context.Context, dockerClient *client.Clieif c.State == container.StateRunning {return c.ID}- if fallbackID == "" {- fallbackID = c.ID- }+ fallbackID = cmp.Or(fallbackID, c.ID)}slog.DebugContext(ctx, "find arcane container by label", "candidates", len(list.Items), "selected", fallbackID)@@ -74,7 +74,7 @@ func InspectCurrentArcaneContainer(ctx context.Context, dockerClient *client.Cli// behind a sidecar stay undetectable and must carry the label themselves.var unlabeled *container.InspectResponseif target, err := CurrentContainerInspectTarget(cgroup.CurrentContainerID, os.Hostname); err == nil && target != "" {- if inspect, inspectErr := ContainerInspectWithCompatibility(ctx, dockerClient, target, client.ContainerInspectOptions{}); inspectErr == nil {+ if inspect, inspectErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, target, client.ContainerInspectOptions{}); inspectErr == nil {if inspect.Container.Config != nil && strings.EqualFold(strings.TrimSpace(inspect.Container.Config.Labels[labels.LabelArcane]), "true") {return &inspect.Container, nil}@@ -83,7 +83,7 @@ func InspectCurrentArcaneContainer(ctx context.Context, dockerClient *client.Cli}if containerID := FindArcaneContainerIDByLabel(ctx, dockerClient); containerID != "" {- inspect, err := ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {return nil, errors.WrapIf(err, "inspect Arcane container")}@@ -123,7 +123,7 @@ func sharesNetworkNamespaceInternal(candidate, owner *container.InspectResponse)// otherwise. Neither source is authoritative β under network_mode:// container:<sidecar> both can resolve the netns-owning sidecar β so callers// must validate the inspected container (see InspectCurrentArcaneContainer).-func CurrentContainerInspectTarget(currentContainerID func() (string, error), hostname func() (string, error)) (string, error) {+func CurrentContainerInspectTarget(currentContainerID, hostname func() (string, error)) (string, error) {if currentContainerID != nil {if containerID, err := currentContainerID(); err == nil {if containerID = strings.TrimSpace(containerID); containerID != "" {diff --git a/backend/pkg/libarcane/internal_resource_test.go b/backend/pkg/libarcane/internal_resource_test.goindex 1421a53a8..62a70a760 100644--- a/backend/pkg/libarcane/internal_resource_test.go+++ b/backend/pkg/libarcane/internal_resource_test.go@@ -3,10 +3,12 @@ package libarcaneimport ("context""net/http"+ "net/http/httptest""strings""testing""emperror.dev/errors"+ "github.com/moby/moby/client""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -101,3 +103,19 @@ func TestInspectCurrentArcaneContainer_KeepsUnlabeledHitOverUnrelatedLabeledInstrequire.NoError(t, err)assert.Equal(t, "custom123", got.ID)}++func newTestDockerClient(t *testing.T, handler http.HandlerFunc) *client.Client {+ t.Helper()++ server := httptest.NewServer(handler)+ t.Cleanup(server.Close)++ dockerClient, err := client.New(+ client.WithHost("tcp://"+strings.TrimPrefix(server.URL, "http://")),+ client.WithAPIVersion("1.41"),+ )+ require.NoError(t, err)+ t.Cleanup(func() { _ = dockerClient.Close() })++ return dockerClient+}diff --git a/backend/pkg/libarcane/ratelimit/registry_rate_limiter.go b/backend/pkg/libarcane/ratelimit/registry_rate_limiter.goindex 1a01bd9e1..807687c6d 100644--- a/backend/pkg/libarcane/ratelimit/registry_rate_limiter.go+++ b/backend/pkg/libarcane/ratelimit/registry_rate_limiter.go@@ -5,6 +5,7 @@ import ("strings""sync"+ kit "go.getarcane.app/kit/pkg""golang.org/x/sync/semaphore")@@ -82,8 +83,5 @@ func (r *RegistryRateLimiter) limitForRegistryInternal(registry string) int64 {func normalizeRegistryKeyInternal(registry string) string {normalized := strings.ToLower(strings.TrimSpace(registry))- if normalized == "registry-1.docker.io" || normalized == "index.docker.io" {- return "docker.io"- }- return normalized+ return kit.Ternary(normalized == "registry-1.docker.io" || normalized == "index.docker.io", "docker.io", normalized)}diff --git a/backend/pkg/libarcane/registryauth/helpers.go b/backend/pkg/libarcane/registryauth/helpers.goindex acfa6312a..fab854a6e 100644--- a/backend/pkg/libarcane/registryauth/helpers.go+++ b/backend/pkg/libarcane/registryauth/helpers.go@@ -1,13 +1,15 @@package registryauthimport (- "sort"+ "maps"+ "slices""strings""emperror.dev/errors"ref "github.com/distribution/reference"dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"dockerregistry "github.com/moby/moby/api/types/registry"+ kit "go.getarcane.app/kit/pkg")func GetRegistryAddress(imageRef string) (string, error) {@@ -16,10 +18,7 @@ func GetRegistryAddress(imageRef string) (string, error) {return "", err}addr := ref.Domain(named)- if addr == DefaultRegistryDomain {- return DefaultRegistryHost, nil- }- return addr, nil+ return kit.Ternary(addr == DefaultRegistryDomain, DefaultRegistryHost, addr), nil}func ExtractRegistryHost(imageRef string) string {@@ -32,10 +31,7 @@ func ExtractRegistryHost(imageRef string) string {return "docker.io"}- if !strings.Contains(hostCandidate, ".") && !strings.Contains(hostCandidate, ":") {- return "docker.io"- }- return hostCandidate+ return kit.Ternary(!strings.Contains(hostCandidate, ".") && !strings.Contains(hostCandidate, ":"), "docker.io", hostCandidate)}// SplitRegistryURL separates a registry URL into its comparison host and an@@ -66,10 +62,7 @@ func NormalizeRegistryURL(url string) string {if host == "docker.io" {return "https://index.docker.io/v1/"}- if namespace != "" {- return host + "/" + namespace- }- return host+ return kit.Ternary(namespace != "", host+"/"+namespace, host)}func IsRegistryMatch(left, right string) bool {@@ -113,10 +106,6 @@ func LookupKeys(url string) []string {keys["index.docker.io"] = struct{}{}}- out := make([]string, 0, len(keys))- for key := range keys {- out = append(out, key)- }- sort.Strings(out)+ out := slices.Sorted(maps.Keys(keys))return out}diff --git a/backend/pkg/libarcane/rustic/image.go b/backend/pkg/libarcane/rustic/image.goindex 21ee4b295..27e20fbac 100644--- a/backend/pkg/libarcane/rustic/image.go+++ b/backend/pkg/libarcane/rustic/image.go@@ -1,8 +1,10 @@// Package rustic provides shared Rustic runtime configuration.package rustic-// DefaultImage is the official Rustic container image used by backup and recovery flows.-const DefaultImage = "ghcr.io/rustic-rs/rustic:v0.11.2"+const (+ // DefaultImage is the official Rustic container image used by backup and recovery flows.+ DefaultImage = "ghcr.io/rustic-rs/rustic:v0.11.2"-// CacheVolume persists Rustic's repository cache across ephemeral runtime containers.-const CacheVolume = "arcane-rustic-cache"+ // CacheVolume persists Rustic's repository cache across ephemeral runtime containers.+ CacheVolume = "arcane-rustic-cache"+)diff --git a/backend/pkg/libarcane/rustic/run.go b/backend/pkg/libarcane/rustic/run.goindex c9d2b413f..24e0c61ab 100644--- a/backend/pkg/libarcane/rustic/run.go+++ b/backend/pkg/libarcane/rustic/run.go@@ -2,6 +2,7 @@ package rusticimport ("bytes"+ "cmp""context""fmt""strings"@@ -73,10 +74,7 @@ func Run(ctx context.Context, dockerClient *client.Client, password string, commreturn "", fmt.Errorf("failed to decode Rustic output: %w", err)}if status.StatusCode != 0 {- message := strings.TrimSpace(stderr.String())- if message == "" {- message = strings.TrimSpace(stdout.String())- }+ message := cmp.Or(strings.TrimSpace(stderr.String()), strings.TrimSpace(stdout.String()))return "", fmt.Errorf("rustic exited with code %d: %s", status.StatusCode, message)}return strings.TrimSpace(stdout.String()), nildiff --git a/backend/pkg/libarcane/settings.go b/backend/pkg/libarcane/settings.goindex e66420af2..81d38391b 100644--- a/backend/pkg/libarcane/settings.go+++ b/backend/pkg/libarcane/settings.go@@ -5,21 +5,19 @@ import ("strings""github.com/robfig/cron/v3"+ kit "go.getarcane.app/kit/pkg")-const DepotTokenSettingKey = "depotToken"-const (+ DepotTokenSettingKey = "depotToken"+GHCRRegistryHost = "ghcr.io"DockerHubRegistryHost = "docker.io")// ArcaneRegistryHost normalizes a registry setting to a host that mirrors the getarcaneapp images, defaulting to GHCR.func ArcaneRegistryHost(registry string) string {- if strings.TrimSpace(registry) == DockerHubRegistryHost {- return DockerHubRegistryHost- }- return GHCRRegistryHost+ return kit.Ternary(strings.TrimSpace(registry) == DockerHubRegistryHost, DockerHubRegistryHost, GHCRRegistryHost)}type SettingUpdate struct {diff --git a/backend/pkg/libarcane/startup/runtime_identity.go b/backend/pkg/libarcane/startup/runtime_identity.goindex f41202451..d9cecffb4 100644--- a/backend/pkg/libarcane/startup/runtime_identity.go+++ b/backend/pkg/libarcane/startup/runtime_identity.go@@ -1,16 +1,19 @@package startupimport (+ "cmp""context""log/slog""net/url""os""path/filepath"+ "strconv""strings""emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")const (@@ -126,10 +129,12 @@ func loadRuntimeIdentityRequestInternal(cfg *RuntimeIdentityConfig, inContainerif puid == "" || pgid == "" {req := defaultRuntimeIdentityRequestInternal(cfg.DockerHost, inContainer)- if inContainer {- return req, "PUID and PGID must both be set to override the default non-root runtime user; continuing with the default non-root runtime user", nil- }- return req, "PUID and PGID must both be set to enable runtime identity outside containers; continuing without runtime identity", nil+ warning := kit.Ternary(+ inContainer,+ "PUID and PGID must both be set to override the default non-root runtime user; continuing with the default non-root runtime user",+ "PUID and PGID must both be set to enable runtime identity outside containers; continuing without runtime identity",+ )+ return req, warning, nil}uid, credentialUID, err := parseRuntimeIdentityValueInternal(puid, "PUID")@@ -171,7 +176,7 @@ func defaultRuntimeIdentityRequestInternal(dockerHost string, inContainer bool)}func runningInContainerInternal(getenv func(string) string, stat func(string) (os.FileInfo, error)) bool {- if utils.BoolOrDefault(strings.TrimSpace(getenv("ARCANE_IN_CONTAINER")), false) {+ if kit.ParseOrDefault(strings.TrimSpace(getenv("ARCANE_IN_CONTAINER")), false, strconv.ParseBool) {return true}@@ -188,7 +193,7 @@ func runningInContainerInternal(getenv func(string) string, stat func(string) (oreturn false}-func ensureRuntimeDockerConfigInternal(cfg *RuntimeIdentityConfig, setenv func(string, string) error, uid int, gid int, inContainer bool) error {+func ensureRuntimeDockerConfigInternal(cfg *RuntimeIdentityConfig, setenv func(string, string) error, uid, gid int, inContainer bool) error {configDir, err := configureRuntimeDockerConfigEnvInternal(cfg, setenv, uid, gid, inContainer)if err != nil {return err@@ -210,7 +215,7 @@ func ensureRuntimeDockerConfigInternal(cfg *RuntimeIdentityConfig, setenv func(sreturn nil}-func configureRuntimeDockerConfigEnvInternal(cfg *RuntimeIdentityConfig, setenv func(string, string) error, uid int, gid int, inContainer bool) (string, error) {+func configureRuntimeDockerConfigEnvInternal(cfg *RuntimeIdentityConfig, setenv func(string, string) error, uid, gid int, inContainer bool) (string, error) {if cfg == nil {cfg = &RuntimeIdentityConfig{}}@@ -248,7 +253,6 @@ func runtimeIdentitySupplementaryGroupsInternal(dockerHost string, resolveSocketif !ok {return nil}-return []uint32{socketGID}}@@ -283,7 +287,7 @@ func dockerSocketPathInternal(raw string) mo.Option[string] {return mo.Some(filepath.Clean(socketPath))}-func prepareWritablePathsWithRootsInternal(uid int, gid int, mountpoints map[string]struct{}, projectsDir string, dataDirectory string, buildsDirectory string) error {+func prepareWritablePathsWithRootsInternal(uid, gid int, mountpoints map[string]struct{}, projectsDir, dataDirectory, buildsDirectory string) error {if err := os.MkdirAll(dataDirectory, utils.DirPerm); err != nil {return errors.WrapIf(err, "create data directory")}@@ -368,10 +372,7 @@ func ensureSQLiteFilesExistInternal(databaseURL string) error {}func sqliteDatabasePathInternal(databaseURL string) (string, bool, error) {- value := strings.TrimSpace(databaseURL)- if value == "" {- value = defaultDatabaseURL- }+ value := cmp.Or(strings.TrimSpace(databaseURL), defaultDatabaseURL)if !strings.HasPrefix(value, "file:") {return "", false, nil}@@ -399,7 +400,7 @@ func sqliteDatabasePathInternal(databaseURL string) (string, bool, error) {return filepath.Clean(pathPart), true, nil}-func chownRecursiveInternal(path string, uid int, gid int, mountpoints map[string]struct{}, projectsDir string) error {+func chownRecursiveInternal(path string, uid, gid int, mountpoints map[string]struct{}, projectsDir string) error {return filepath.Walk(path, func(currentPath string, info os.FileInfo, err error) error {if err != nil {return errdiff --git a/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go b/backend/pkg/libarcane/startup/runtime_identity_int_32bit.goindex 0200ec55d..672a4d5f2 100644--- a/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go+++ b/backend/pkg/libarcane/startup/runtime_identity_int_32bit.go@@ -8,7 +8,7 @@ import ("emperror.dev/errors")-func parseRuntimeIdentityValueInternal(raw string, key string) (int, uint32, error) {+func parseRuntimeIdentityValueInternal(raw, key string) (int, uint32, error) {value, err := strconv.ParseInt(raw, 10, 32)if err != nil {return 0, 0, errors.WrapIff(err, "parse %s", key)diff --git a/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go b/backend/pkg/libarcane/startup/runtime_identity_int_64bit.goindex b1e104f8f..cf5e76018 100644--- a/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go+++ b/backend/pkg/libarcane/startup/runtime_identity_int_64bit.go@@ -9,7 +9,7 @@ import ("emperror.dev/errors")-func parseRuntimeIdentityValueInternal(raw string, key string) (int, uint32, error) {+func parseRuntimeIdentityValueInternal(raw, key string) (int, uint32, error) {value, err := strconv.Atoi(raw)if err != nil {return 0, 0, errors.WrapIff(err, "parse %s", key)diff --git a/backend/pkg/libarcane/startup/runtime_identity_linux.go b/backend/pkg/libarcane/startup/runtime_identity_linux.goindex 1ec27ed9e..1d242ac5d 100644--- a/backend/pkg/libarcane/startup/runtime_identity_linux.go+++ b/backend/pkg/libarcane/startup/runtime_identity_linux.go@@ -10,7 +10,6 @@ import ("syscall""emperror.dev/errors"-"github.com/samber/mo")diff --git a/backend/pkg/libarcane/startup/runtime_identity_test.go b/backend/pkg/libarcane/startup/runtime_identity_test.goindex 92b054978..6e3846294 100644--- a/backend/pkg/libarcane/startup/runtime_identity_test.go+++ b/backend/pkg/libarcane/startup/runtime_identity_test.go@@ -9,6 +9,7 @@ import ("github.com/samber/mo""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")func TestLoadRuntimeIdentityRequest(t *testing.T) {@@ -99,10 +100,7 @@ func TestRunningInContainerInternal(t *testing.T) {t.Run("explicit arcane env enables container mode", func(t *testing.T) {inContainer := runningInContainerInternal(func(key string) string {- if key == "ARCANE_IN_CONTAINER" {- return "true"- }- return ""+ return kit.Ternary(key == "ARCANE_IN_CONTAINER", "true", "")},func(string) (os.FileInfo, error) {return nil, os.ErrNotExist@@ -115,10 +113,7 @@ func TestRunningInContainerInternal(t *testing.T) {t.Run("container env enables container mode", func(t *testing.T) {inContainer := runningInContainerInternal(func(key string) string {- if key == "container" {- return "podman"- }- return ""+ return kit.Ternary(key == "container", "podman", "")},func(string) (os.FileInfo, error) {return nil, os.ErrNotExist@@ -132,10 +127,7 @@ func TestRunningInContainerInternal(t *testing.T) {inContainer := runningInContainerInternal(func(string) string { return "" },func(path string) (os.FileInfo, error) {- if path == "/run/.containerenv" {- return nil, nil- }- return nil, os.ErrNotExist+ return nil, kit.Ternary(path == "/run/.containerenv", nil, os.ErrNotExist)},)@@ -161,7 +153,7 @@ func TestConfigureRuntimeDockerConfigEnv(t *testing.T) {configDir, err := configureRuntimeDockerConfigEnvInternal(cfg,- func(key string, value string) error {+ func(key, value string) error {env[key] = valuereturn nil},@@ -183,7 +175,7 @@ func TestConfigureRuntimeDockerConfigEnv(t *testing.T) {configDir, err := configureRuntimeDockerConfigEnvInternal(cfg,- func(key string, value string) error {+ func(key, value string) error {setCalled = trueenv[key] = valuereturn nil@@ -207,7 +199,7 @@ func TestConfigureRuntimeDockerConfigEnv(t *testing.T) {configDir, err := configureRuntimeDockerConfigEnvInternal(cfg,- func(key string, value string) error {+ func(key, value string) error {setCalled = trueenv[key] = valuereturn nil@@ -231,7 +223,7 @@ func TestConfigureRuntimeDockerConfigEnv(t *testing.T) {configDir, err := configureRuntimeDockerConfigEnvInternal(cfg,- func(key string, value string) error {+ func(key, value string) error {setCalled = trueenv[key] = valuereturn nil@@ -254,7 +246,7 @@ func TestConfigureRuntimeDockerConfigEnv(t *testing.T) {configDir, err := configureRuntimeDockerConfigEnvInternal(cfg,- func(key string, value string) error {+ func(key, value string) error {env[key] = valuereturn nil},@@ -438,14 +430,14 @@ func TestChownRecursiveInternalSkipsProjects(t *testing.T) {keepFile := filepath.Join(demoDir, "keep.txt")databaseDir := filepath.Join(tempDir, "database")- require.NoError(t, os.MkdirAll(demoDir, 0755))- require.NoError(t, os.WriteFile(keepFile, []byte("keep"), 0644))- require.NoError(t, os.MkdirAll(databaseDir, 0755))+ require.NoError(t, os.MkdirAll(demoDir, 0o755))+ require.NoError(t, os.WriteFile(keepFile, []byte("keep"), 0o644))+ require.NoError(t, os.MkdirAll(databaseDir, 0o755))// Track visited paths using mocked lchownFnvisited := make(map[string]bool)oldLchownFn := lchownFn- lchownFn = func(path string, uid int, gid int) error {+ lchownFn = func(path string, uid, gid int) error {visited[filepath.Clean(path)] = truereturn nil}@@ -484,13 +476,13 @@ func TestPrepareWritablePathsInternalChownsTopLevelProjectsShallowly(t *testing.keepFile := filepath.Join(demoDir, "keep.txt")databaseDir := filepath.Join(dataDir, "database")- require.NoError(t, os.MkdirAll(demoDir, 0755))- require.NoError(t, os.WriteFile(keepFile, []byte("keep"), 0644))- require.NoError(t, os.MkdirAll(databaseDir, 0755))+ require.NoError(t, os.MkdirAll(demoDir, 0o755))+ require.NoError(t, os.WriteFile(keepFile, []byte("keep"), 0o644))+ require.NoError(t, os.MkdirAll(databaseDir, 0o755))visited := make(map[string]bool)oldLchownFn := lchownFn- lchownFn = func(path string, uid int, gid int) error {+ lchownFn = func(path string, uid, gid int) error {visited[filepath.Clean(path)] = truereturn nil}diff --git a/backend/pkg/libarcane/startup/startup_test.go b/backend/pkg/libarcane/startup/startup_test.goindex 96460c465..c876d47c1 100644--- a/backend/pkg/libarcane/startup/startup_test.go+++ b/backend/pkg/libarcane/startup/startup_test.go@@ -6,6 +6,7 @@ import ("testing""github.com/stretchr/testify/assert"+ kit "go.getarcane.app/kit/pkg")type mockSettingsManager struct {@@ -50,11 +51,8 @@ func TestLoadAgentToken(t *testing.T) {AgentMode: true,AgentToken: "",}- getSettingFunc := func(ctx context.Context, key string, def string) string {- if key == "agentToken" {- return "loaded-token"- }- return def+ getSettingFunc := func(ctx context.Context, key, def string) string {+ return kit.Ternary(key == "agentToken", "loaded-token", def)}LoadAgentToken(ctx, cfg, getSettingFunc)@@ -68,7 +66,7 @@ func TestLoadAgentToken(t *testing.T) {AgentToken: "",}called := false- getSettingFunc := func(ctx context.Context, key string, def string) string {+ getSettingFunc := func(ctx context.Context, key, def string) string {called = truereturn ""}@@ -85,7 +83,7 @@ func TestLoadAgentToken(t *testing.T) {AgentToken: "existing-token",}called := false- getSettingFunc := func(ctx context.Context, key string, def string) string {+ getSettingFunc := func(ctx context.Context, key, def string) string {called = truereturn ""}diff --git a/backend/pkg/libarcane/swarm/cleanup.go b/backend/pkg/libarcane/swarm/cleanup.goindex 53a209bbf..4a565b055 100644--- a/backend/pkg/libarcane/swarm/cleanup.go+++ b/backend/pkg/libarcane/swarm/cleanup.go@@ -9,10 +9,10 @@ import ("time""emperror.dev/errors"-cerrdefs "github.com/containerd/errdefs"swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm"dockerclient "github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg")// Swarm tears tasks down asynchronously, so a config, secret, or network can@@ -129,10 +129,7 @@ func cleanupStaleManagedResourcesInternal(// otherwise the stack is being deleted and a lingering resource must surface as an error// instead of being silently orphaned.func removeStaleSwarmResourceInternal(ctx context.Context, tolerateInUse bool, remove func(context.Context) error) error {- attempts := staleSwarmResourceRemoveAttemptsInternal- if tolerateInUse {- attempts = 1- }+ attempts := kit.Ternary(tolerateInUse, 1, staleSwarmResourceRemoveAttemptsInternal)var err errorfor attempt := range attempts {@@ -153,10 +150,7 @@ func removeStaleSwarmResourceInternal(ctx context.Context, tolerateInUse bool, r}}- if tolerateInUse {- return nil- }- return err+ return kit.Ternary(tolerateInUse, nil, err)}// RemoveStackResources removes configs, secrets, and networks owned by a stack.diff --git a/backend/pkg/libarcane/swarm/convert_mounts.go b/backend/pkg/libarcane/swarm/convert_mounts.goindex ecbddab7b..02daef237 100644--- a/backend/pkg/libarcane/swarm/convert_mounts.go+++ b/backend/pkg/libarcane/swarm/convert_mounts.go@@ -1,16 +1,15 @@package swarmimport (+ "cmp""math""os""sort""strings""emperror.dev/errors"-composegotypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/moby/moby/api/types/mount""github.com/moby/moby/api/types/swarm")@@ -116,10 +115,7 @@ func resolveServiceFileReferencesInternal(if !ok {return nil, errors.Errorf("undefined %s %q", resourceType, reference.Source)}- target := reference.Target- if target == "" {- target = reference.Source- }+ target := cmp.Or(reference.Target, reference.Source)mode, err := fileModeOrDefaultInternal(reference.Mode)if err != nil {return nil, errors.WrapIff(err, "invalid %s %q mode", resourceType, reference.Source)@@ -127,8 +123,8 @@ func resolveServiceFileReferencesInternal(resolved = append(resolved, resolvedFileReferenceInternal{meta: meta,target: target,- uid: utils.StringOrDefault(reference.UID, "0"),- gid: utils.StringOrDefault(reference.GID, "0"),+ uid: cmp.Or(strings.TrimSpace(reference.UID), "0"),+ gid: cmp.Or(strings.TrimSpace(reference.GID), "0"),mode: mode,})}@@ -217,7 +213,7 @@ func resolveFileObjectContentInternal(func fileModeOrDefaultInternal(mode *composegotypes.FileMode) (os.FileMode, error) {if mode == nil {- return 0444, nil+ return 0o444, nil}if *mode < 0 || *mode > composegotypes.FileMode(math.MaxUint32) {return 0, errors.Errorf("file mode %d is outside the uint32 range", *mode)diff --git a/backend/pkg/libarcane/swarm/convert_service.go b/backend/pkg/libarcane/swarm/convert_service.goindex e439d7f46..e0d89589a 100644--- a/backend/pkg/libarcane/swarm/convert_service.go+++ b/backend/pkg/libarcane/swarm/convert_service.go@@ -14,13 +14,13 @@ import ("time""emperror.dev/errors"-composegotypes "github.com/compose-spec/compose-go/v2/types"dockeropts "github.com/docker/cli/opts""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/network""github.com/moby/moby/api/types/swarm""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")func buildServiceSpecInternal(@@ -76,8 +76,8 @@ func buildServiceSpecInternal(TaskTemplate: swarm.TaskSpec{ContainerSpec: &swarm.ContainerSpec{Image: service.Image,- Command: toStringSliceInternal(service.Entrypoint),- Args: toStringSliceInternal(service.Command),+ Command: kit.Ternary(len(service.Entrypoint) == 0, nil, service.Entrypoint),+ Args: kit.Ternary(len(service.Command) == 0, nil, service.Command),Env: convertEnvInternal(service.Environment),Dir: service.WorkingDir,User: service.User,@@ -204,10 +204,7 @@ func convertPrivilegesInternal(}}- if !hasPrivileges {- return nil, runtimeConfigRef, nil- }- return privileges, runtimeConfigRef, nil+ return kit.Ternary(!hasPrivileges, nil, privileges), runtimeConfigRef, nil}func convertCredentialSpecInternal(@@ -659,10 +656,7 @@ func parsePrefixInternal(value string) netip.Prefix {return netip.Prefix{}}prefix, err := netip.ParsePrefix(value)- if err != nil {- return netip.Prefix{}- }- return prefix+ return kit.Ternary(err != nil, netip.Prefix{}, prefix)}func parseAuxAddressesInternal(values map[string]string) map[string]netip.Addr {@@ -694,13 +688,6 @@ func convertEnvInternal(env composegotypes.MappingWithEquals) []string {return result}-func toStringSliceInternal(command composegotypes.ShellCommand) []string {- if len(command) == 0 {- return nil- }- return command-}-func convertDurationPtrInternal(duration *composegotypes.Duration) *time.Duration {if duration == nil {return nildiff --git a/backend/pkg/libarcane/swarm/convert_test.go b/backend/pkg/libarcane/swarm/convert_test.goindex 95ddd5b5e..0e6482797 100644--- a/backend/pkg/libarcane/swarm/convert_test.go+++ b/backend/pkg/libarcane/swarm/convert_test.go@@ -13,6 +13,7 @@ import ("github.com/moby/moby/api/types/mount""github.com/moby/moby/api/types/swarm""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")func TestConvertServiceMountsResolvesComposeResourceNames(t *testing.T) {@@ -90,7 +91,7 @@ configs:plans, err := planConfigsInternal(project, namespace{name: "stack"})require.NoError(t, err)require.Empty(t, plans["app_config"].Data)- require.Equal(t, managedResourceNameInternal("stack_app_config", hashManagedResourceInternal(nil)), plans["app_config"].Meta.Name)+ require.Equal(t, managedResourceNameInternal("stack_app_config", kit.SHA256Hex[[]byte](nil)), plans["app_config"].Meta.Name)}func TestBuildServiceSpecConformance(t *testing.T) {diff --git a/backend/pkg/libarcane/swarm/deploy.go b/backend/pkg/libarcane/swarm/deploy.goindex 17fd7ebcb..3e493fe2f 100644--- a/backend/pkg/libarcane/swarm/deploy.go+++ b/backend/pkg/libarcane/swarm/deploy.go@@ -1,6 +1,7 @@package swarmimport (+ "cmp""context""fmt""maps"@@ -8,7 +9,6 @@ import ("strings""emperror.dev/errors"-composegotypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"@@ -170,9 +170,7 @@ func reconcileStackServicesInternal(for _, key := range slices.Sorted(maps.Keys(project.Services)) {service := project.Services[key]- if service.Name == "" {- service.Name = key- }+ service.Name = cmp.Or(service.Name, key)spec, err := buildServiceSpecInternal(service, ns, stackLabels, networkNameByKey, configMetaByKey, secretMetaByKey, project.Volumes)if err != nil {return nil, invalidStackErrorInternal(errors.WrapIff(err, "service %s", service.Name))@@ -226,9 +224,7 @@ func createSwarmServiceInternal(Spec: spec,QueryRegistry: queryRegistry,}- if encodedRegistryAuth != "" {- opts.EncodedRegistryAuth = encodedRegistryAuth- }+ opts.EncodedRegistryAuth = cmp.Or(encodedRegistryAuth, opts.EncodedRegistryAuth)if _, err := dockerClient.ServiceCreate(ctx, opts); err != nil {return errors.WrapIff(err, "failed to create swarm service %s", spec.Name)}diff --git a/backend/pkg/libarcane/swarm/namespace.go b/backend/pkg/libarcane/swarm/namespace.goindex bf2b1a39b..9f9728790 100644--- a/backend/pkg/libarcane/swarm/namespace.go+++ b/backend/pkg/libarcane/swarm/namespace.go@@ -10,8 +10,8 @@ import ("strings""emperror.dev/errors"-composegotypes "github.com/compose-spec/compose-go/v2/types"+ kit "go.getarcane.app/kit/pkg")const (@@ -25,10 +25,12 @@ const (resourceNameMaxHash = 12)-var stackNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`)+var (+ stackNamePattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]*$`)-// ErrInvalidStack identifies invalid stack source or conversion input.-var ErrInvalidStack = errors.Sentinel("invalid swarm stack")+ // ErrInvalidStack identifies invalid stack source or conversion input.+ ErrInvalidStack = errors.Sentinel("invalid swarm stack")+)type namespace struct {name string@@ -45,7 +47,7 @@ func (n namespace) Resolve(key, configuredName string) string {return n.Scope(key)}-func mergeLabelsInternal(primary map[string]string, secondary map[string]string) map[string]string {+func mergeLabelsInternal(primary, secondary map[string]string) map[string]string {out := map[string]string{}maps.Copy(out, primary)maps.Copy(out, secondary)@@ -70,14 +72,9 @@ func invalidStackErrorInternal(err error) error {return fmt.Errorf("%w: %w", ErrInvalidStack, err)}-func hashManagedResourceInternal(data []byte) string {- sum := sha256.Sum256(data)- return hex.EncodeToString(sum[:])-}-func hashManagedFileResourceInternal(config composegotypes.FileObjectConfig, data []byte) string {if config.Driver == "" && config.TemplateDriver == "" && len(config.DriverOpts) == 0 {- return hashManagedResourceInternal(data)+ return kit.SHA256Hex(data)}hasher := sha256.New()diff --git a/backend/pkg/libarcane/swarm/render.go b/backend/pkg/libarcane/swarm/render.goindex 190584bf5..2a4952a12 100644--- a/backend/pkg/libarcane/swarm/render.go+++ b/backend/pkg/libarcane/swarm/render.go@@ -1,13 +1,13 @@package swarmimport (+ "cmp""context""maps""slices""strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/pkg/projects"projecttypes "github.com/getarcaneapp/arcane/types/v2/project")@@ -83,10 +83,7 @@ func RenderStackConfig(ctx context.Context, opts StackRenderOptions) (*StackRendserviceNames := make([]string, 0, len(project.Services))for _, key := range slices.Sorted(maps.Keys(project.Services)) {service := project.Services[key]- name := service.Name- if name == "" {- name = key- }+ name := cmp.Or(service.Name, key)serviceNames = append(serviceNames, ns.Scope(name))}diff --git a/backend/pkg/libarcane/swarm/resources.go b/backend/pkg/libarcane/swarm/resources.goindex 72639aae8..923f8a86b 100644--- a/backend/pkg/libarcane/swarm/resources.go+++ b/backend/pkg/libarcane/swarm/resources.go@@ -1,13 +1,13 @@package swarmimport (+ "cmp""context""maps""slices""strings""emperror.dev/errors"-composegotypes "github.com/compose-spec/compose-go/v2/types"cerrdefs "github.com/containerd/errdefs""github.com/moby/moby/api/types/swarm"@@ -148,10 +148,7 @@ func ensureSwarmNetworksInternal(ctx context.Context, dockerClient *dockerclientreturn nil, errors.WrapIff(err, "failed to inspect network %s", networkName)}- driver := strings.TrimSpace(cfg.Driver)- if driver == "" {- driver = "overlay"- }+ driver := cmp.Or(strings.TrimSpace(cfg.Driver), "overlay")labels := mergeLabelsInternal(cfg.Labels, stackLabels)createOpts := dockerclient.NetworkCreateOptions{@@ -201,10 +198,7 @@ func ensureSwarmVolumesInternal(ctx context.Context, dockerClient *dockerclient.return errors.WrapIff(err, "failed to inspect volume %s", name)}- driver := cfg.Driver- if driver == "" {- driver = "local"- }+ driver := cmp.Or(cfg.Driver, "local")labels := mergeLabelsInternal(cfg.Labels, stackLabels)if _, err := dockerClient.VolumeCreate(ctx, dockerclient.VolumeCreateOptions{Name: name,diff --git a/backend/pkg/libarcane/system/gpu.go b/backend/pkg/libarcane/system/gpu.goindex 369a69c6e..93eb94fc6 100644--- a/backend/pkg/libarcane/system/gpu.go+++ b/backend/pkg/libarcane/system/gpu.go@@ -15,7 +15,6 @@ import ("time""emperror.dev/errors"-systemtypes "github.com/getarcaneapp/arcane/types/v2/system""github.com/samber/hot")diff --git a/backend/pkg/libarcane/timeouts/timeouts.go b/backend/pkg/libarcane/timeouts/timeouts.goindex 8e0389367..15af6e5c6 100644--- a/backend/pkg/libarcane/timeouts/timeouts.go+++ b/backend/pkg/libarcane/timeouts/timeouts.go@@ -2,6 +2,8 @@ package timeoutsimport ("time"++ kit "go.getarcane.app/kit/pkg")const (@@ -34,8 +36,5 @@ const ()func GetDuration(settingSeconds int, defaultDuration time.Duration) time.Duration {- if settingSeconds > 0 {- return time.Duration(settingSeconds) * time.Second- }- return defaultDuration+ return kit.Ternary(settingSeconds > 0, time.Duration(settingSeconds)*time.Second, defaultDuration)}diff --git a/backend/pkg/libarcane/volumehelper/helper.go b/backend/pkg/libarcane/volumehelper/helper.goindex 082365109..5a957779b 100644--- a/backend/pkg/libarcane/volumehelper/helper.go+++ b/backend/pkg/libarcane/volumehelper/helper.go@@ -9,12 +9,13 @@ import ("emperror.dev/errors"ref "github.com/distribution/reference"-"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/moby/moby/client""github.com/samber/mo"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg")// RuntimeImage describes the Arcane runtime image that can run internal helper@@ -103,7 +104,7 @@ func ResolveHelperImage(ctx context.Context, dockerClient *client.Client, toolsIfunc ResolveArcaneRuntimeImage(ctx context.Context, dockerClient *client.Client) mo.Option[RuntimeImage] {hostname, _ := os.Hostname()if hostname != "" {- if inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, hostname, client.ContainerInspectOptions{}); err == nil && inspect.Container.Config != nil && strings.TrimSpace(inspect.Container.Config.Image) != "" {+ if inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, hostname, client.ContainerInspectOptions{}); err == nil && inspect.Container.Config != nil && strings.TrimSpace(inspect.Container.Config.Image) != "" {return mo.Some(buildRuntimeImageInternal(inspect.Container.Config.Image, inspect.Container.Config.Entrypoint, inspect.Container.Config.Cmd, "hostname"))}}@@ -128,10 +129,7 @@ func ResolveArcaneRuntimeImage(ctx context.Context, dockerClient *client.Client)}func resolveRuntimeImageFromContainersInternal(ctx context.Context, dockerClient *client.Client, containers []container.Summary, label string, runningOnly bool) mo.Option[RuntimeImage] {- source := "arcane-label"- if strings.Contains(label, ".agent=") {- source = "arcane-agent-label"- }+ source := kit.Ternary(strings.Contains(label, ".agent="), "arcane-agent-label", "arcane-label")for _, c := range containers {if runningOnly && c.State != container.StateRunning {@@ -140,7 +138,7 @@ func resolveRuntimeImageFromContainersInternal(ctx context.Context, dockerClientif !runningOnly && c.State == container.StateRunning {continue}- inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})+ inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})if err == nil && inspect.Container.Config != nil && strings.TrimSpace(inspect.Container.Config.Image) != "" {return mo.Some(buildRuntimeImageInternal(inspect.Container.Config.Image, inspect.Container.Config.Entrypoint, inspect.Container.Config.Cmd, source))}@@ -152,7 +150,7 @@ func resolveRuntimeImageFromContainersInternal(ctx context.Context, dockerClientreturn mo.None[RuntimeImage]()}-func buildRuntimeImageInternal(image string, entrypoint []string, command []string, source string) RuntimeImage {+func buildRuntimeImageInternal(image string, entrypoint, command []string, source string) RuntimeImage {return RuntimeImage{Image: strings.TrimSpace(image),Entrypoint: append([]string(nil), entrypoint...),diff --git a/backend/pkg/libarcane/volumes/volume_rename.go b/backend/pkg/libarcane/volumes/volume_rename.goindex e55535757..f3adea09a 100644--- a/backend/pkg/libarcane/volumes/volume_rename.go+++ b/backend/pkg/libarcane/volumes/volume_rename.go@@ -15,10 +15,10 @@ 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/libarcane/volumehelper"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/moby/moby/api/types/container""github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg")type dockerProjectVolumeRenameMigrationInternal struct {@@ -44,11 +44,17 @@ func NewMigration(dockerClient *client.Client, entries []volumetypes.RenameEntryif len(entries) == 0 {return nil}- return &dockerProjectVolumeRenameMigrationInternal{dockerClient: dockerClient, entries: entries, oldComposeName: oldProject, newComposeName: newProject, toolsImage: toolsImage}+ return &dockerProjectVolumeRenameMigrationInternal{+ dockerClient: dockerClient,+ entries: entries,+ oldComposeName: oldProject,+ newComposeName: newProject,+ toolsImage: toolsImage,+ }}// PlanRename validates and prepares an unused Docker volume for a copy-based rename.-func PlanRename(ctx context.Context, dockerClient *client.Client, oldName, newName string, toolsImage string) (volumetypes.Migration, error) {+func PlanRename(ctx context.Context, dockerClient *client.Client, oldName, newName, toolsImage string) (volumetypes.Migration, error) {if dockerClient == nil {return nil, errors.New("docker service unavailable")}@@ -110,8 +116,9 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Apply(ctx context.Context)m.createdNew = append(m.createdNew, entry)if err := copyProjectVolumeDataInternal(ctx, dockerClient, copyRuntime, entry.OldName, entry.NewName); err != nil {- return stderrors.Join(errors.- WrapIff(err, "copy volume data from %s to %s", entry.OldName, entry.NewName), m.rollbackCreatedTargetsInternal(ctx, dockerClient),+ return stderrors.Join(+ errors.+ WrapIff(err, "copy volume data from %s to %s", entry.OldName, entry.NewName), m.rollbackCreatedTargetsInternal(ctx, dockerClient),)}}@@ -305,7 +312,7 @@ func removeProjectVolumeHelperContainersInternal(ctx context.Context, dockerClie}func isProjectVolumeHelperContainerInternal(c container.Summary) bool {- if internal, _ := utils.ParseBool(c.Labels[libarcane.InternalResourceLabel]); !internal {+ if internal, _ := kit.ParseBool(c.Labels[libarcane.InternalResourceLabel]); !internal {return false}if strings.EqualFold(c.Labels[volumehelper.ContainerLabel], "true") {@@ -560,7 +567,7 @@ func cleanupProjectRenameRollbackTargetVolumeInternal(ctx context.Context, dockereturn nil}-func removeProjectRenameJournalTargetVolumeInternal(ctx context.Context, dockerClient *client.Client, newName string, oldExists bool, newExists bool) error {+func removeProjectRenameJournalTargetVolumeInternal(ctx context.Context, dockerClient *client.Client, newName string, oldExists, newExists bool) error {if !oldExists || !newExists {return nil}diff --git a/backend/pkg/libarcane/volumes/volume_rename_followup_test.go b/backend/pkg/libarcane/volumes/volume_rename_followup_test.goindex ffb9e1ccf..269c63a59 100644--- a/backend/pkg/libarcane/volumes/volume_rename_followup_test.go+++ b/backend/pkg/libarcane/volumes/volume_rename_followup_test.go@@ -10,7 +10,6 @@ import ("testing"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"-"github.com/stretchr/testify/assert""github.com/stretchr/testify/require")diff --git a/backend/pkg/libarcane/volumes/volume_rename_safety_test.go b/backend/pkg/libarcane/volumes/volume_rename_safety_test.goindex f5cc61350..195b7d411 100644--- a/backend/pkg/libarcane/volumes/volume_rename_safety_test.go+++ b/backend/pkg/libarcane/volumes/volume_rename_safety_test.go@@ -11,9 +11,8 @@ import ("syscall""testing"- volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"-"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"+ volumetypes "github.com/getarcaneapp/arcane/types/v2/volume""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/mount""github.com/stretchr/testify/assert"diff --git a/backend/pkg/libarcane/volumes/volume_rename_test.go b/backend/pkg/libarcane/volumes/volume_rename_test.goindex 0fa9e5742..9791f21ca 100644--- a/backend/pkg/libarcane/volumes/volume_rename_test.go+++ b/backend/pkg/libarcane/volumes/volume_rename_test.go@@ -9,11 +9,11 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/volume""github.com/moby/moby/client""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")func newTestDockerClientInternal(t *testing.T, server *httptest.Server) *client.Client {@@ -82,7 +82,7 @@ func TestContainerSummaryMountsVolumeInternal(t *testing.T) {},}- internal, valid := utils.ParseBool(summary.Labels[libarcane.InternalResourceLabel])+ internal, valid := kit.ParseBool(summary.Labels[libarcane.InternalResourceLabel])require.True(t, valid)require.True(t, internal)require.True(t, containerSummaryMountsVolumeInternal(summary, "web_data"))diff --git a/backend/pkg/libarcane/vuln/driver.go b/backend/pkg/libarcane/vuln/driver.goindex 8d7ac9df7..58cd27008 100644--- a/backend/pkg/libarcane/vuln/driver.go+++ b/backend/pkg/libarcane/vuln/driver.go@@ -3,6 +3,7 @@ package vulnimport ("archive/tar""bytes"+ "cmp""context""encoding/json/jsontext""encoding/json/v2"@@ -20,13 +21,13 @@ import ("emperror.dev/errors"cerrdefs "github.com/containerd/errdefs"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"+ "github.com/getarcaneapp/arcane/types/v2/vulnerability""github.com/moby/moby/api/pkg/stdcopy"containertypes "github.com/moby/moby/api/types/container"mounttypes "github.com/moby/moby/api/types/mount""github.com/moby/moby/client"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"- "github.com/getarcaneapp/arcane/types/v2/vulnerability"+ kit "go.getarcane.app/kit/pkg")const (@@ -149,10 +150,7 @@ func BuildHostConfig(func SelectDefaultNetworkMode(networkMode string) string {networkMode = strings.TrimSpace(networkMode)- if networkMode == "" {- return DefaultNetworkMode- }- return networkMode+ return kit.Ternary(networkMode == "", DefaultNetworkMode, networkMode)}func ApplyRuntimeSecurity(hostConfig *containertypes.HostConfig, securityOpts []string, privileged bool) {@@ -233,10 +231,7 @@ func MountSummaries(hostConfig *containertypes.HostConfig) []string {summaries := make([]string, 0, len(hostConfig.Mounts))for _, mount := range hostConfig.Mounts {- source := mount.Source- if source == "" {- source = string(mount.Type)- }+ source := cmp.Or(mount.Source, string(mount.Type))summaries = append(summaries, fmt.Sprintf("%s:%s", source, mount.Target))}@@ -389,11 +384,7 @@ func ParseCPULimit(raw string, fallback float64) float64 {return fallback}- if limit < 0 {- return 0- }-- return limit+ return kit.Ternary(limit < 0, 0, limit)}func ParseMemoryLimitMB(raw string, fallback int64) int64 {@@ -407,11 +398,7 @@ func ParseMemoryLimitMB(raw string, fallback int64) int64 {return fallback}- if limit < 0 {- return 0- }-- return limit+ return kit.Ternary(limit < 0, 0, limit)}func ContainerWaitTimeout(trivyTimeoutArg string) time.Duration {@@ -424,7 +411,6 @@ func ContainerWaitTimeout(trivyTimeoutArg string) time.Duration {if err != nil || timeout <= 0 {return timeouts.DefaultTrivyScan + timeouts.DefaultDockerAPI}-return timeout + timeouts.DefaultDockerAPI}diff --git a/backend/pkg/libarcane/vuln/driver_test.go b/backend/pkg/libarcane/vuln/driver_test.goindex 8d666bbca..1fd64a61b 100644--- a/backend/pkg/libarcane/vuln/driver_test.go+++ b/backend/pkg/libarcane/vuln/driver_test.go@@ -10,12 +10,11 @@ import ("time""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"+ "github.com/getarcaneapp/arcane/types/v2/vulnerability"containertypes "github.com/moby/moby/api/types/container"mounttypes "github.com/moby/moby/api/types/mount""github.com/stretchr/testify/require"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"- "github.com/getarcaneapp/arcane/types/v2/vulnerability")func TestDecodeTrivyReportFromFileInternal_LargePayload(t *testing.T) {diff --git a/backend/pkg/libarcane/vuln/risk.go b/backend/pkg/libarcane/vuln/risk.goindex c016d2b49..edb19edce 100644--- a/backend/pkg/libarcane/vuln/risk.go+++ b/backend/pkg/libarcane/vuln/risk.go@@ -6,10 +6,9 @@ import ("slices""strings"- "golang.org/x/mod/semver"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/vulnerability"+ kit "go.getarcane.app/kit/pkg"+ "golang.org/x/mod/semver")const (@@ -155,10 +154,7 @@ func (r *RiskScore) AddFinding(vulnerabilityID string, fixable bool, base float6if !fixable || (priority <= 0 && !IsCVE(vulnerabilityID)) {return priority}- status := vulnerability.ScoreStatusComplete- if priority <= 0 {- status = vulnerability.ScoreStatusUnavailable- }+ status := kit.Ternary(priority <= 0, vulnerability.ScoreStatusUnavailable, vulnerability.ScoreStatusComplete)r.addScoreInternal(vulnerabilityID, priority, 1, status)if intel.KnownExploited && (exposure == vulnerability.ImageExposureRunning || exposure == vulnerability.ImageExposureUnknown) {r.exploitedRunning = true@@ -272,7 +268,7 @@ func isNewerFixedVersionInternal(candidate, current string) bool {if current == "" {return true}- a, b := utils.EnsureVPrefix(candidate), utils.EnsureVPrefix(current)+ a, b := kit.EnsurePrefix(candidate, "v"), kit.EnsurePrefix(current, "v")return semver.IsValid(a) && semver.IsValid(b) && semver.Compare(a, b) > 0}diff --git a/backend/pkg/libarcane/vuln/risk_test.go b/backend/pkg/libarcane/vuln/risk_test.goindex e8ccead43..8f3fa3825 100644--- a/backend/pkg/libarcane/vuln/risk_test.go+++ b/backend/pkg/libarcane/vuln/risk_test.go@@ -5,9 +5,8 @@ import ("math""testing"- "github.com/stretchr/testify/require"-"github.com/getarcaneapp/arcane/types/v2/vulnerability"+ "github.com/stretchr/testify/require")func TestBuildScanInsights(t *testing.T) {diff --git a/backend/pkg/libarcane/vuln/trivy.go b/backend/pkg/libarcane/vuln/trivy.goindex 62391304e..cc5f48098 100644--- a/backend/pkg/libarcane/vuln/trivy.go+++ b/backend/pkg/libarcane/vuln/trivy.go@@ -6,6 +6,7 @@package vulnimport (+ "cmp""encoding/base64""encoding/json/v2""net/url"@@ -16,6 +17,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"containertypes "github.com/moby/moby/api/types/container"dockerregistry "github.com/moby/moby/api/types/registry"+ kit "go.getarcane.app/kit/pkg")const (@@ -57,31 +59,14 @@ func ParseSecurityOpts(value string) []string {parts := strings.FieldsFunc(value, func(r rune) bool {return r == ',' || r == '\n'})- if len(parts) == 0 {- return nil- }-- opts := make([]string, 0, len(parts))- for _, part := range parts {- if opt := strings.TrimSpace(part); opt != "" {- opts = append(opts, opt)- }- }-- if len(opts) == 0 {- return nil- }-- return opts+ opts := kit.TrimNonEmpty(parts)+ return kit.Ternary(len(opts) == 0, nil, opts)}// ParseDockerHost validates and decomposes a Docker host URI into its scheme and,// for unix sockets, the socket path. An empty host falls back to DefaultDockerHostURI.-func ParseDockerHost(dockerHost string) (scheme string, socketPath string, err error) {- dockerHost = strings.TrimSpace(dockerHost)- if dockerHost == "" {- dockerHost = DefaultDockerHostURI- }+func ParseDockerHost(dockerHost string) (scheme, socketPath string, err error) {+ dockerHost = cmp.Or(strings.TrimSpace(dockerHost), DefaultDockerHostURI)if strings.HasPrefix(dockerHost, "/") {return "unix", dockerHost, nil@@ -113,7 +98,6 @@ func BuildDockerHostEnv(dockerHost string) []string {if dockerHost == "" {return nil}-return []string{"DOCKER_HOST=" + dockerHost}}@@ -127,10 +111,7 @@ func ProxyEnv(httpProxy, httpsProxy, noProxy string) []string {env = append(env, kv[0]+"="+value)}}- if len(env) == 0 {- return nil- }- return env+ return kit.Ternary(len(env) == 0, nil, env)}// ScanCacheBackendArgsForArch returns the Trivy cache-backend flags for a GOARCH.@@ -167,7 +148,7 @@ func RepositoryArgs(registry string) []string {// memory-mapped. With an empty serverURL it falls back to the standalone// local-database flags. The server token is passed via ServerTokenEnv rather than// a flag so it is not exposed in the process arguments.-func ScanSourceArgs(serverURL string, registry string) []string {+func ScanSourceArgs(serverURL, registry string) []string {serverURL = strings.TrimSpace(serverURL)if serverURL == "" {return append(ScanCacheBackendArgs(), RepositoryArgs(registry)...)@@ -184,7 +165,6 @@ func ServerTokenEnv(token string) []string {if token == "" {return nil}-return []string{"TRIVY_TOKEN=" + token}}@@ -231,7 +211,7 @@ func BuildDockerConfigJSON(authConfigs map[string]dockerregistry.AuthConfig) ([]}// BuildContainerConfig assembles the container.Config for a Trivy scan container.-func BuildContainerConfig(scannerImage string, cmdArgs []string, env []string) *containertypes.Config {+func BuildContainerConfig(scannerImage string, cmdArgs, env []string) *containertypes.Config {return &containertypes.Config{Image: scannerImage,Entrypoint: []string{"trivy"},diff --git a/backend/pkg/libarcane/ws/benchmark_test.go b/backend/pkg/libarcane/ws/benchmark_test.goindex 949be08d9..a8bce1604 100644--- a/backend/pkg/libarcane/ws/benchmark_test.go+++ b/backend/pkg/libarcane/ws/benchmark_test.go@@ -48,7 +48,7 @@ func benchWSServer(b *testing.B) (url string, cleanup func()) {// benchHub creates a hub with N connected clients whose send channels are drained.// Returns the hub, a context cancel func, and a cleanup func.-func benchHub(b *testing.B, numClients int, hubBuf int) (*Hub, context.CancelFunc, func()) {+func benchHub(b *testing.B, numClients, hubBuf int) (*Hub, context.CancelFunc, func()) {b.Helper()h := NewHub(hubBuf)diff --git a/backend/pkg/libarcane/ws/hub_test.go b/backend/pkg/libarcane/ws/hub_test.goindex 16c39caf0..a1562a955 100644--- a/backend/pkg/libarcane/ws/hub_test.go+++ b/backend/pkg/libarcane/ws/hub_test.go@@ -18,7 +18,7 @@ import ()// newTestWSPair creates a connected client/server WebSocket pair using httptest.-func newTestWSPair(t *testing.T) (clientConn *websocket.Conn, serverConn *websocket.Conn, cleanup func()) {+func newTestWSPair(t *testing.T) (clientConn, serverConn *websocket.Conn, cleanup func()) {t.Helper()serverReady := make(chan *websocket.Conn, 1)diff --git a/backend/pkg/libarcane/ws/parse.go b/backend/pkg/libarcane/ws/parse.goindex 450f85495..cc9c83c15 100644--- a/backend/pkg/libarcane/ws/parse.go+++ b/backend/pkg/libarcane/ws/parse.go@@ -1,6 +1,7 @@package wsimport (+ "cmp""regexp""strings""time"@@ -55,16 +56,14 @@ func trimTrailingNewlinesInternal(raw string) string {// NormalizeContainerLine parses a raw container log line into level + cleaned message.// It extracts Docker's timestamp if present (when timestamps=true in Docker API).-func NormalizeContainerLine(raw string) (level string, msg string, timestamp string) {+func NormalizeContainerLine(raw string) (level, msg, timestamp string) {level = "stdout"line, sawStderr, ts := stripStreamMetadataInternal(trimTrailingNewlinesInternal(raw), true)if sawStderr {level = "stderr"}- if ts != "" {- timestamp = ts- }+ timestamp = cmp.Or(ts, timestamp)return level, strings.TrimSpace(line), timestamp}@@ -90,9 +89,7 @@ func NormalizeProjectLine(raw string) (level, service, msg, timestamp string) {if sawMessageStderr || sawHeadStderr {level = "stderr"}- if messageTS != "" {- timestamp = messageTS- }+ timestamp = cmp.Or(messageTS, timestamp)base = message} else if sawHeadStderr {level = "stderr"diff --git a/backend/pkg/pagination/db_utils.go b/backend/pkg/pagination/db_utils.goindex 335df1502..858ccb91f 100644--- a/backend/pkg/pagination/db_utils.go+++ b/backend/pkg/pagination/db_utils.go@@ -4,31 +4,27 @@ import ("strings""emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"+ kit "go.getarcane.app/kit/pkg"+ "go.getarcane.app/kit/pkg/mapping""gorm.io/gorm")// ApplyFilter adds a WHERE clause to the GORM query.// It detects comma-separated values and uses IN (?) for multiple values,// or = ? for single values.-func ApplyFilter(q *gorm.DB, column string, value string) *gorm.DB {+func ApplyFilter(q *gorm.DB, column, value string) *gorm.DB {if value == "" {return q}if strings.Contains(value, ",") {- values := strings.Split(value, ",")- for i := range values {- values[i] = strings.TrimSpace(values[i])- }- return q.Where(column+" IN ?", values)+ return q.Where(column+" IN ?", kit.TrimNonEmpty(strings.Split(value, ",")))}return q.Where(column+" = ?", value)}// ApplyLikeSearch adds a LIKE search condition using the same wildcard pattern// for every placeholder in condition.-func ApplyLikeSearch(q *gorm.DB, search string, condition string) *gorm.DB {+func ApplyLikeSearch(q *gorm.DB, search, condition string) *gorm.DB {term := strings.TrimSpace(search)if term == "" {return q@@ -44,13 +40,13 @@ func ApplyLikeSearch(q *gorm.DB, search string, condition string) *gorm.DB {}// PaginateSortAndMapDB paginates DB records and maps them to API DTOs.-func (params QueryParams) PaginateSortAndMapDB[M any, D any](query *gorm.DB, records *[]M) ([]D, Response, error) {+func (params QueryParams) PaginateSortAndMapDB[M, D any](query *gorm.DB, records *[]M) ([]D, Response, error) {paginationResp, err := PaginateAndSortDB(params, query, records)if err != nil {return nil, Response{}, errors.WrapIf(err, "paginate db records")}- out, err := mapper.MapSlice[M, D](*records)+ out, err := mapping.MapSlice[M, D](*records)if err != nil {return nil, Response{}, errors.WrapIf(err, "map db records")}@@ -60,7 +56,7 @@ func (params QueryParams) PaginateSortAndMapDB[M any, D any](query *gorm.DB, rec// ApplyBooleanFilter adds a WHERE clause for boolean columns.// It detects comma-separated values and maps "true"/"1" to true and "false"/"0" to false.-func ApplyBooleanFilter(q *gorm.DB, column string, value string) *gorm.DB {+func ApplyBooleanFilter(q *gorm.DB, column, value string) *gorm.DB {if value == "" {return q}@@ -69,7 +65,7 @@ func ApplyBooleanFilter(q *gorm.DB, column string, value string) *gorm.DB {var boolValues []boolfor _, part := range parts {- if value, valid := utils.ParseBool(part); valid {+ if value, valid := kit.ParseBool(part); valid {boolValues = append(boolValues, value)}}diff --git a/backend/pkg/pagination/reflect.go b/backend/pkg/pagination/reflect.goindex 61b262b71..ba5db5e20 100644--- a/backend/pkg/pagination/reflect.go+++ b/backend/pkg/pagination/reflect.go@@ -1,33 +1,30 @@package paginationimport (+ "cmp""reflect""strconv"- stringutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm""gorm.io/gorm/clause")func PaginateAndSortDB[M any](params QueryParams, query *gorm.DB, result *[]M) (Response, error) {sortColumn := params.Sort- sortDirection := string(params.Order)-- if sortDirection == "" {- sortDirection = "asc"- }+ sortDirection := cmp.Or(string(params.Order), "asc")modelType := reflect.TypeFor[M]()- capitalizedSortColumn := stringutils.CapitalizeFirstLetter(sortColumn)+ capitalizedSortColumn := kit.Capitalize(sortColumn)sortField, sortFieldFound := modelType.FieldByName(capitalizedSortColumn)isSortable, _ := strconv.ParseBool(sortField.Tag.Get("sortable"))- sortDirection = normalizeSortDirection(sortDirection)+ sortDirection = kit.Ternary(sortDirection != "asc" && sortDirection != "desc", "asc", sortDirection)var orderColumns []clause.OrderByColumncolumnName := ""if sortFieldFound && isSortable {- columnName = stringutils.CamelCaseToSnakeCase(sortColumn)+ columnName = kit.SnakeCase(sortColumn)orderColumns = append(orderColumns, clause.OrderByColumn{Column: clause.Column{Name: columnName},Desc: sortDirection == "desc",@@ -99,7 +96,7 @@ func paginateDBAll[M any](query *gorm.DB, result *[]M, skipCount bool) (Response// 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[M any](offset int, pageSize int, query *gorm.DB, result *[]M, skipCount bool) (Response, error) {+func paginateDB[M any](offset, pageSize int, query *gorm.DB, result *[]M, skipCount bool) (Response, error) {if offset < 0 {offset = 0}@@ -144,10 +141,3 @@ func paginateDB[M any](offset int, pageSize int, query *gorm.DB, result *[]M, skItemsPerPage: pageSize,}, nil}--func normalizeSortDirection(direction string) string {- if direction != "asc" && direction != "desc" {- return "asc"- }- return direction-}diff --git a/backend/pkg/pagination/types.go b/backend/pkg/pagination/types.goindex 39a759e4b..f21a43091 100644--- a/backend/pkg/pagination/types.go+++ b/backend/pkg/pagination/types.go@@ -1,5 +1,7 @@package pagination+import "cmp"+type Response struct {TotalPages int64 `json:"totalPages"`TotalItems int64 `json:"totalItems"`@@ -10,7 +12,7 @@ type Response struct {// BuildResponse creates a pagination Response from raw counts.// Handles the special case where limit = -1 means "show all".-func BuildResponse(totalCount int64, totalAvailable int64, params QueryParams) Response {+func BuildResponse(totalCount, totalAvailable int64, params QueryParams) Response {limit := params.Limitvar totalPages int64@@ -34,9 +36,7 @@ func BuildResponse(totalCount int64, totalAvailable int64, params QueryParams) RitemsPerPage = int(totalCount)}- if totalPages == 0 {- totalPages = 1- }+ totalPages = cmp.Or(totalPages, 1)return Response{TotalPages: totalPages,diff --git a/backend/pkg/projects/build.go b/backend/pkg/projects/build.goindex 5670d5309..b14e6f028 100644--- a/backend/pkg/projects/build.go+++ b/backend/pkg/projects/build.go@@ -1,6 +1,7 @@package projectsimport (+ "cmp""fmt""maps""path/filepath"@@ -13,6 +14,7 @@ import (projecttypes "github.com/getarcaneapp/arcane/types/v2/project""go.getarcane.app/builds/pkg/contextsource"buildtypes "go.getarcane.app/builds/types"+ kit "go.getarcane.app/kit/pkg")// ResolveBuildContext resolves a service build context against workingDir.@@ -37,10 +39,7 @@ func ResolveBuildContext(workingDir string, svc composetypes.ServiceConfig, serv// ResolveDockerfilePath returns the configured Dockerfile path or Dockerfile.// The service config must have a non-nil Build field.func ResolveDockerfilePath(svc composetypes.ServiceConfig) string {- dockerfilePath := strings.TrimSpace(svc.Build.Dockerfile)- if dockerfilePath == "" {- dockerfilePath = "Dockerfile"- }+ dockerfilePath := cmp.Or(strings.TrimSpace(svc.Build.Dockerfile), "Dockerfile")return dockerfilePath}@@ -89,51 +88,19 @@ func UlimitsFromCompose(ulimits map[string]*composetypes.UlimitsConfig) map[stri}}- if len(out) == 0 {- return nil- }-- return out+ return kit.Ternary(len(out) == 0, nil, out)}// MergeBuildTags combines a primary image tag with compose tags, trimming blanks// and de-duplicating while preserving order (primary first).func MergeBuildTags(primaryImage string, composeTags []string) []string {- seen := map[string]struct{}{}- merged := make([]string, 0, len(composeTags)+1)-- appendTag := func(tag string) {- tag = strings.TrimSpace(tag)- if tag == "" {- return- }- if _, ok := seen[tag]; ok {- return- }- seen[tag] = struct{}{}- merged = append(merged, tag)- }-- appendTag(primaryImage)- for _, tag := range composeTags {- appendTag(tag)- }-- return merged+ return kit.Unique(kit.TrimNonEmpty(append([]string{primaryImage}, composeTags...)))}// BuildPlatformsFromCompose returns the build platforms for a service, falling// back to the service platform when no build platforms are declared.func BuildPlatformsFromCompose(svc composetypes.ServiceConfig) []string {- platforms := make([]string, 0, len(svc.Build.Platforms)+1)- for _, platform := range svc.Build.Platforms {- platform = strings.TrimSpace(platform)- if platform == "" {- continue- }- platforms = append(platforms, platform)- }-+ platforms := kit.TrimNonEmpty(svc.Build.Platforms)if len(platforms) == 0 {if servicePlatform := strings.TrimSpace(svc.Platform); servicePlatform != "" {platforms = append(platforms, servicePlatform)@@ -149,14 +116,8 @@ func BuildLocalImageTag(projectID, projectName, serviceName string) string {if len(shortID) > 8 {shortID = shortID[:8]}- projectPart := SanitizeImageComponent(projectName)- if projectPart == "" {- projectPart = "project"- }- servicePart := SanitizeImageComponent(serviceName)- if servicePart == "" {- servicePart = "service"- }+ projectPart := cmp.Or(SanitizeImageComponent(projectName), "project")+ servicePart := cmp.Or(SanitizeImageComponent(serviceName), "service")return fmt.Sprintf("%s/%s-%s/%s:latest", imageref.LocalBuildRegistry, projectPart, shortID, servicePart)}@@ -188,11 +149,7 @@ func resolveEffectiveBuildProviderInternal(override, defaultProvider string) strreturn provider}- provider = strings.ToLower(strings.TrimSpace(defaultProvider))-- if provider == "" {- provider = "local"- }+ provider = cmp.Or(strings.ToLower(strings.TrimSpace(defaultProvider)), "local")return provider}diff --git a/backend/pkg/projects/cmds.go b/backend/pkg/projects/cmds.goindex bb86e9a20..7137b6756 100644--- a/backend/pkg/projects/cmds.go+++ b/backend/pkg/projects/cmds.go@@ -1,6 +1,7 @@package projectsimport (+ "cmp""context""fmt""io"@@ -8,7 +9,6 @@ import ("time"composetypes "github.com/compose-spec/compose-go/v2/types"-"github.com/docker/compose/v5/pkg/api""github.com/docker/compose/v5/pkg/compose"docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -17,6 +17,7 @@ import ("github.com/moby/moby/api/types/container""github.com/moby/moby/api/types/registry""github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg")// defaultComposeTimeout is applied to compose operations that have been@@ -67,7 +68,7 @@ func ComposeStop(ctx context.Context, proj *composetypes.Project, services []strreturn c.svc.Stop(stopCtx, proj.Name, api.StopOptions{Services: services})}-func ComposeUp(ctx context.Context, proj *composetypes.Project, services []string, removeOrphans bool, forceRecreate bool, recreateVolumes bool, authConfigs map[string]registry.AuthConfig, waitTimeout time.Duration) error {+func ComposeUp(ctx context.Context, proj *composetypes.Project, services []string, removeOrphans, forceRecreate, recreateVolumes bool, authConfigs map[string]registry.AuthConfig, waitTimeout time.Duration) error {selected, err := SelectServices(proj, services)if err != nil {return err@@ -134,11 +135,8 @@ func ComposeCreate(ctx context.Context, proj *composetypes.Project, services []sreturn c.svc.Create(createCtx, selected, api.CreateOptions{Services: services, Recreate: api.RecreateForce, RecreateDependencies: api.RecreateDiverged})}-func composeUpOptionsInternal(proj *composetypes.Project, services []string, removeOrphans bool, forceRecreate bool, waitTimeout time.Duration, envOpts ComposeEnvOptions) (api.CreateOptions, api.StartOptions) {- recreatePolicy := api.RecreateDiverged- if forceRecreate {- recreatePolicy = api.RecreateForce- }+func composeUpOptionsInternal(proj *composetypes.Project, services []string, removeOrphans, forceRecreate bool, waitTimeout time.Duration, envOpts ComposeEnvOptions) (api.CreateOptions, api.StartOptions) {+ recreatePolicy := kit.Ternary(forceRecreate, api.RecreateForce, api.RecreateDiverged)upOptions := api.CreateOptions{Services: services,@@ -264,9 +262,7 @@ func FindComposeServiceContainerID(ctx context.Context, dockerHost, projectName,if c.Service != serviceName {continue}- if firstMatch == "" {- firstMatch = c.ID- }+ firstMatch = cmp.Or(firstMatch, c.ID)if c.State == "running" {return c.ID, nil}diff --git a/backend/pkg/projects/compose.go b/backend/pkg/projects/compose.goindex 959bcb363..d01f9fe00 100644--- a/backend/pkg/projects/compose.go+++ b/backend/pkg/projects/compose.go@@ -15,11 +15,11 @@ import ("github.com/docker/compose/v5/cmd/display""github.com/docker/compose/v5/pkg/api""github.com/docker/compose/v5/pkg/compose"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"+ dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/moby/moby/api/types/registry""github.com/moby/moby/client"-- dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg")type Client struct {@@ -177,11 +177,7 @@ func buildComposeAuthConfigsInternal(authConfigs map[string]registry.AuthConfig)RegistryToken: authConfig.RegistryToken,}}- if len(composeAuthConfigs) == 0 {- return nil- }-- return composeAuthConfigs+ return kit.Ternary(len(composeAuthConfigs) == 0, nil, composeAuthConfigs)}type inspectCompatibleDockerCli struct {@@ -201,7 +197,7 @@ func wrapDockerCLIWithInspectCompatibilityInternal(cli command.Cli) command.Clireturn &inspectCompatibleDockerCli{Cli: cli,- apiClient: libarcane.WrapDockerAPIClientForInspectCompatibility(cli.Client()),+ apiClient: compat.WrapDockerAPIClientForInspectCompatibility(cli.Client()),}}@@ -253,10 +249,7 @@ func (w *writerConsumer) write(container, msg string) {if w.out == nil {return}- output := msg- if container != "" {- output = container + " | " + msg- }+ output := kit.Ternary(container != "", container+" | "+msg, msg)if !strings.HasSuffix(output, "\n") {output += "\n"}diff --git a/backend/pkg/projects/coordinator.go b/backend/pkg/projects/coordinator.goindex 30a9d1bcc..16d89a841 100644--- a/backend/pkg/projects/coordinator.go+++ b/backend/pkg/projects/coordinator.go@@ -1,6 +1,7 @@package projectsimport (+ "cmp""context""io""log/slog"@@ -13,6 +14,7 @@ import (composetypes "github.com/compose-spec/compose-go/v2/types""github.com/docker/compose/v5/pkg/api"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"+ kit "go.getarcane.app/kit/pkg")type composeCoordinatorInternal struct {@@ -62,9 +64,7 @@ func (c *composeCoordinatorInternal) Deploy(ctx context.Context, request projectif pullPolicy == "" {pullPolicy = NormalizeDeployPullPolicy(request.DefaultPullPolicy)}- if pullPolicy == "" {- pullPolicy = "missing"- }+ pullPolicy = cmp.Or(pullPolicy, "missing")if err := c.PrepareImagesForDeploy(ctx, request.ProjectID, model, request.Progress, operations, pullPolicy); err != nil {return nil, errors.WrapIf(err, "failed to prepare project images for deploy")}@@ -498,24 +498,10 @@ func SelectedImageRefs(compProj *composetypes.Project, servicesToUpdate []stringselected := NormalizeBuildSelections(servicesToUpdate)refs := make([]string, 0, len(compProj.Services))- seen := make(map[string]struct{}, len(compProj.Services))-for name, svc := range compProj.Services {- if !ServiceSelected(selected, name) || svc.Build != nil {- continue+ if ServiceSelected(selected, name) && svc.Build == nil {+ refs = append(refs, svc.Image)}-- imageRef := strings.TrimSpace(svc.Image)- if imageRef == "" {- continue- }- if _, exists := seen[imageRef]; exists {- continue- }-- seen[imageRef] = struct{}{}- refs = append(refs, imageRef)}-- return refs+ return kit.Unique(kit.TrimNonEmpty(refs))}diff --git a/backend/pkg/projects/coordinator_test.go b/backend/pkg/projects/coordinator_test.goindex 18c683333..4fa878711 100644--- a/backend/pkg/projects/coordinator_test.go+++ b/backend/pkg/projects/coordinator_test.go@@ -95,7 +95,7 @@ func TestCoordinatorUpdateServicesScopesDependents(t *testing.T) {calls = append(calls, "stop")return nil},- Up: func(_ context.Context, selected *composetypes.Project, services []string, _ bool, force bool, _ bool, _ map[string]registry.AuthConfig, _ time.Duration) error {+ Up: func(_ context.Context, selected *composetypes.Project, services []string, _, force, _ bool, _ map[string]registry.AuthConfig, _ time.Duration) error {upped = servicesselectedNames = selected.ServiceNames()forceRecreate = forcediff --git a/backend/pkg/projects/custom_labels.go b/backend/pkg/projects/custom_labels.goindex 1e21c4e8d..87350d4ea 100644--- a/backend/pkg/projects/custom_labels.go+++ b/backend/pkg/projects/custom_labels.go@@ -1,6 +1,7 @@package projectsimport (+ "cmp""context"stderrors "errors""fmt"@@ -13,15 +14,14 @@ import ("strings""unicode"- updaterlabels "go.getarcane.app/updater/labels"-"emperror.dev/errors""github.com/compose-spec/compose-go/v2/loader"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/iconcatalog"projecttypes "github.com/getarcaneapp/arcane/types/v2/project"+ kit "go.getarcane.app/kit/pkg"+ updaterlabels "go.getarcane.app/updater/labels""go.yaml.in/yaml/v4")@@ -40,6 +40,11 @@ const (arcaneIconDarkKey = "icon-dark"arcaneURLsKey = "urls"arcaneTagsKey = "tags"++ // ProjectTagMaxLength is the maximum number of Unicode characters in a tag name.+ ProjectTagMaxLength = 64+ // ProjectTagsPerSourceLimit is the maximum number of UI or Compose tags on one project.+ ProjectTagsPerSourceLimit = 50)type IconSet = iconcatalog.IconSet@@ -87,9 +92,9 @@ func ParseArcaneComposeMetadata(ctx context.Context, composeFilePath, projectsDiif err != nil {return meta, err}- meta.ComposeFiles = utils.UniqueNonEmptyStrings(append(meta.ComposeFiles, slices.Collect(maps.Keys(visited))...))+ meta.ComposeFiles = kit.Unique(kit.TrimNonEmpty(append(meta.ComposeFiles, slices.Collect(maps.Keys(visited))...)))slices.Sort(meta.ComposeFiles)- meta.EnvFiles = utils.UniqueNonEmptyStrings(append(meta.EnvFiles, resolveComposeEnvFilesInternal(workdir, envMap)...))+ meta.EnvFiles = kit.Unique(kit.TrimNonEmpty(append(meta.EnvFiles, resolveComposeEnvFilesInternal(workdir, envMap)...)))return meta, nil}@@ -191,19 +196,19 @@ func extractArcaneComposeMetadata(project *composetypes.Project) ArcaneComposeMe}func parseArcaneBlockInternal(block any) (IconSet, []string, []projecttypes.TagOption, bool) {- arcaneBlock, ok := utils.AsStringMap(block).Get()+ arcaneBlock, ok := kit.AsStringMap(block)if !ok {return IconSet{}, nil, nil, false}icon := IconSet{- Icon: utils.FirstNonEmpty(- utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconKey], utils.ToString)...),- utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconsKey], utils.ToString)...),+ Icon: cmp.Or(+ cmp.Or(kit.Collect(arcaneBlock[arcaneIconKey], kit.ToString)...),+ cmp.Or(kit.Collect(arcaneBlock[arcaneIconsKey], kit.ToString)...),),- Light: utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconLightKey], utils.ToString)...),- Dark: utils.FirstNonEmpty(utils.Collect(arcaneBlock[arcaneIconDarkKey], utils.ToString)...),+ Light: cmp.Or(kit.Collect(arcaneBlock[arcaneIconLightKey], kit.ToString)...),+ Dark: cmp.Or(kit.Collect(arcaneBlock[arcaneIconDarkKey], kit.ToString)...),}- urls := utils.UniqueNonEmptyStrings(utils.Collect(arcaneBlock[arcaneURLsKey], utils.ToString))+ urls := kit.Unique(kit.TrimNonEmpty(kit.Collect(arcaneBlock[arcaneURLsKey], kit.ToString)))tags, tagsAuthoritative := parseComposeTagsInternal(arcaneBlock[arcaneTagsKey])return icon, urls, tags, tagsAuthoritative}@@ -222,14 +227,14 @@ func parseComposeTagsInternal(value any) ([]projecttypes.TagOption, bool) {seen := make(map[string]struct{}, len(values))authoritative := truefor index, value := range values {- definition, ok := utils.AsStringMap(value).Get()+ definition, ok := kit.AsStringMap(value)if !ok {slog.Warn("skipping invalid x-arcane tag; expected a name/color object", "index", index)authoritative = falsecontinue}- nameValue := utils.ToString(definition["name"])- colorValue := utils.ToString(definition["color"])+ nameValue := kit.ToString(definition["name"])+ colorValue := kit.ToString(definition["color"])if nameValue == "" || colorValue == "" {slog.Warn("skipping invalid x-arcane tag; name and color are required", "index", index)authoritative = false@@ -285,7 +290,7 @@ func mergeArcaneComposeMetadata(target *ArcaneComposeMetadata, source ArcaneComptarget.ProjectIcon = mergeIconSetFieldsInternal(target.ProjectIcon, source.ProjectIcon)- target.ProjectURLS = utils.UniqueNonEmptyStrings(append(target.ProjectURLS, source.ProjectURLS...))+ target.ProjectURLS = kit.Unique(kit.TrimNonEmpty(append(target.ProjectURLS, source.ProjectURLS...)))target.ProjectTags = mergeComposeTagsInternal(target.ProjectTags, source.ProjectTags)target.ProjectTagsAuthoritative = target.ProjectTagsAuthoritative && source.ProjectTagsAuthoritativetarget.ComposeFiles = append(target.ComposeFiles, source.ComposeFiles...)@@ -460,14 +465,14 @@ func parseIncludePaths(composeFilePath string) ([]string, error) {// It supports both map[string]string and []string label formats.func FindArcaneIconSet(labels any) IconSet {iconSet := IconSet{}- if labelMap, ok := utils.AsStringMap(labels).Get(); ok {+ if labelMap, ok := kit.AsStringMap(labels); ok {for key, value := range labelMap {- assignArcaneIconValueInternal(&iconSet, key, utils.ToString(value))+ assignArcaneIconValueInternal(&iconSet, key, kit.ToString(value))}return iconSet}- for _, s := range utils.Collect(labels, utils.ToString) {+ for _, s := range kit.Collect(labels, kit.ToString) {if key, value, ok := parseLabelPair(s); ok {assignArcaneIconValueInternal(&iconSet, key, value)}@@ -476,7 +481,7 @@ func FindArcaneIconSet(labels any) IconSet {return iconSet}-func assignArcaneIconValueInternal(iconSet *IconSet, key string, value string) {+func assignArcaneIconValueInternal(iconSet *IconSet, key, value string) {if iconSet == nil {return}@@ -514,13 +519,6 @@ func parseLabelPair(raw string) (string, string, bool) {return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), true}-const (- // ProjectTagMaxLength is the maximum number of Unicode characters in a tag name.- ProjectTagMaxLength = 64- // ProjectTagsPerSourceLimit is the maximum number of UI or Compose tags on one project.- ProjectTagsPerSourceLimit = 50-)-var projectTagColorsInternal = map[projecttypes.TagColor]struct{}{projecttypes.TagColorGray: {},projecttypes.TagColorPurple: {},@@ -630,7 +628,7 @@ func applyServiceLabelMetadataInternal(project *composetypes.Project) error {}func updaterMetadataLabelsInternal(block any) (map[string]string, error) {- arcane, ok := utils.AsStringMap(block).Get()+ arcane, ok := kit.AsStringMap(block)if !ok {return nil, nil}@@ -638,7 +636,7 @@ func updaterMetadataLabelsInternal(block any) (map[string]string, error) {if !present {return nil, nil}- config, ok := utils.AsStringMap(raw).Get()+ config, ok := kit.AsStringMap(raw)if !ok {return nil, errors.New("expected an updater mapping")}@@ -677,7 +675,7 @@ func updaterMetadataLabelsInternal(block any) (map[string]string, error) {}func hiddenMetadataLabelInternal(block any) (map[string]string, error) {- arcane, ok := utils.AsStringMap(block).Get()+ arcane, ok := kit.AsStringMap(block)if !ok {return nil, nil}diff --git a/backend/pkg/projects/custom_labels_test.go b/backend/pkg/projects/custom_labels_test.goindex 6fefbdb0d..70c622b22 100644--- a/backend/pkg/projects/custom_labels_test.go+++ b/backend/pkg/projects/custom_labels_test.go@@ -8,10 +8,9 @@ import ("testing"composetypes "github.com/compose-spec/compose-go/v2/types"- updaterlabels "go.getarcane.app/updater/labels"-projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/stretchr/testify/require"+ updaterlabels "go.getarcane.app/updater/labels")func TestParseArcaneComposeMetadata_InterpolationAndAnchor(t *testing.T) {diff --git a/backend/pkg/projects/discovery.go b/backend/pkg/projects/discovery.goindex f22601835..a05dd205b 100644--- a/backend/pkg/projects/discovery.go+++ b/backend/pkg/projects/discovery.go@@ -12,6 +12,7 @@ import ("emperror.dev/errors""github.com/compose-spec/compose-go/v2/loader""github.com/getarcaneapp/arcane/backend/v2/internal/common"+ kit "go.getarcane.app/kit/pkg""go.yaml.in/yaml/v4")@@ -102,7 +103,7 @@ func DiscoverProjectDirectories(ctx context.Context, root string, followSymlinksreturn discovered, nil}-func walkProjectDirectoriesInternal(ctx context.Context, root, path string, isRoot bool, currentDepth int, maxDepth int, followSymlinks bool, ancestors map[string]struct{}, discovered *[]DiscoveredProjectDir) error {+func walkProjectDirectoriesInternal(ctx context.Context, root, path string, isRoot bool, currentDepth, maxDepth int, followSymlinks bool, ancestors map[string]struct{}, discovered *[]DiscoveredProjectDir) error {if !isRoot {name := filepath.Base(path)if IsIgnoredProjectDirName(name) {@@ -304,10 +305,7 @@ func NormalizeProjectName(name string) string {return ""}normalized := loader.NormalizeProjectName(name)- if normalized == "" {- return name- }- return normalized+ return kit.Ternary(normalized == "", name, normalized)}// ResolveDirectoryIdentityInternal stays on os.*: it resolves symlinks thatdiff --git a/backend/pkg/projects/discovery_test.go b/backend/pkg/projects/discovery_test.goindex b18c50acd..fe789edf4 100644--- a/backend/pkg/projects/discovery_test.go+++ b/backend/pkg/projects/discovery_test.go@@ -278,7 +278,6 @@ func TestComposeContentProjectName(t *testing.T) {assert.Equal(t, tt.want, got,"ComposeContentProjectName() = %q, want %q", got, tt.want)}-})}}@@ -312,7 +311,6 @@ func TestNormalizeProjectName(t *testing.T) {require.Equal(t, tt.expected, got,"NormalizeProjectName() = %q, want %q", got, tt.expected)-})}}diff --git a/backend/pkg/projects/env.go b/backend/pkg/projects/env.goindex 7ac74b51a..d3e091dd7 100644--- a/backend/pkg/projects/env.go+++ b/backend/pkg/projects/env.go@@ -2,14 +2,12 @@ package projectsimport ("context"- "crypto/sha256"- "encoding/hex""log/slog""maps""os""path/filepath""regexp"- "sort"+ "slices""strconv""strings""syscall"@@ -22,6 +20,7 @@ import (projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/samber/hot""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg")const (@@ -31,6 +30,15 @@ const (OverrideEnvFileName = "project.env"ProjectEnvModeDirect ProjectEnvMode = "direct"ProjectEnvModeOverride ProjectEnvMode = "override"++ // Docker Compose pre-defined variable names that compose-go's consts package+ // does not export. See https://docs.docker.com/compose/how-tos/environment-variables/envvars.+ composeEnvFilesKey = "COMPOSE_ENV_FILES"+ composeRemoveOrphansKey = "COMPOSE_REMOVE_ORPHANS"+ composeIgnoreOrphansKey = "COMPOSE_IGNORE_ORPHANS"+ composeParallelLimitKey = "COMPOSE_PARALLEL_LIMIT"++ defaultComposePathSeparator = ":")type EnvMap = map[string]string@@ -110,7 +118,7 @@ func allowedProcessEnvInternal() EnvMap {// 3. Project-specific .env file (from workdir)// The rest of the Arcane process environment is intentionally excluded so its// own variables never leak into compose interpolation of managed projects.-func (l *EnvLoader) LoadEnvironment(ctx context.Context) (envMap EnvMap, injectionVars EnvMap, err error) {+func (l *EnvLoader) LoadEnvironment(ctx context.Context) (envMap, injectionVars EnvMap, err error) {envMap = allowedProcessEnvInternal()injectionVars = make(EnvMap)@@ -150,15 +158,12 @@ func (l *EnvLoader) LoadEnvironment(ctx context.Context) (envMap EnvMap, injectifunc (l *EnvLoader) mergeComposeEnvFilesInternal(ctx context.Context, envMap, injectionVars EnvMap) {parse := func(path string, contextEnv EnvMap) (EnvMap, error) {- key := strings.Join([]string{path, l.projectsDir, strconv.FormatBool(l.autoInjectEnv), envContextFingerprintInternal(contextEnv)}, "\x00")+ key := strings.Join([]string{path, l.projectsDir, strconv.FormatBool(l.autoInjectEnv), strconv.FormatUint(kit.Fingerprint(contextEnv), 16)}, "\x00")entry, err := loadCachedEnvFileInternal(ctx, projectEnvFileCache, key, path, contextEnv)if err != nil {return nil, err}- if !entry.exists {- return nil, nil- }- return entry.values, nil+ return kit.Ternary(!entry.exists, nil, entry.values), nil}onMerged := func(values EnvMap) {if l.autoInjectEnv {@@ -187,7 +192,7 @@ func (l *EnvLoader) loadAndMergeGlobalEnv(ctx context.Context, path string, envM}func (l *EnvLoader) loadAndMergeProjectEnv(ctx context.Context, path string, envMap, injectionVars EnvMap) error {- key := strings.Join([]string{path, l.projectsDir, strconv.FormatBool(l.autoInjectEnv), envContextFingerprintInternal(envMap)}, "\x00")+ key := strings.Join([]string{path, l.projectsDir, strconv.FormatBool(l.autoInjectEnv), strconv.FormatUint(kit.Fingerprint(envMap), 16)}, "\x00")entry, err := loadCachedEnvFileInternal(ctx, projectEnvFileCache, key, path, envMap)if err != nil {return err@@ -248,26 +253,6 @@ func loadCachedEnvFileInternal(_ context.Context, envCache *hot.HotCache[string,return entry, nil}-func envContextFingerprintInternal(envMap EnvMap) string {- if len(envMap) == 0 {- return ""- }- keys := make([]string, 0, len(envMap))- for key := range envMap {- keys = append(keys, key)- }- sort.Strings(keys)- var b strings.Builder- for _, key := range keys {- b.WriteString(key)- b.WriteByte('=')- b.WriteString(envMap[key])- b.WriteByte('\n')- }- sum := sha256.Sum256([]byte(b.String()))- return hex.EncodeToString(sum[:])-}-func validEnvFileCacheEntryInternal(entry envFileCacheEntry) bool {// os.Stat rather than acfs: env files may be symlinks resolving outside// any confinement root (a supported setup).@@ -414,10 +399,8 @@ func BuildEffectiveEnvContent(gitContent, overrideContent string) (string, errorreturn gitContent, nil}- concatenated := gitContent + "\n" + overrideContent- if strings.HasSuffix(gitContent, "\n") || strings.HasPrefix(overrideContent, "\n") {- concatenated = gitContent + overrideContent- }+ separated := strings.HasSuffix(gitContent, "\n") || strings.HasPrefix(overrideContent, "\n")+ concatenated := kit.Ternary(separated, gitContent+overrideContent, gitContent+"\n"+overrideContent)candidate, ok := mergeEnvOverridesInPlaceInternal(gitContent, overrideContent, overrideEnv)if !ok {@@ -429,7 +412,6 @@ func BuildEffectiveEnvContent(gitContent, overrideContent string) (string, errorif candidateErr == nil && expectedErr == nil && maps.Equal(candidateEnv, expectedEnv) {return candidate, nil}-return concatenated, nil}@@ -748,11 +730,7 @@ func formatEnvMapInternal(envMap EnvMap) string {return ""}- keys := make([]string, 0, len(envMap))- for key := range envMap {- keys = append(keys, key)- }- sort.Strings(keys)+ keys := slices.Sorted(maps.Keys(envMap))var builder strings.Builderfor _, key := range keys {@@ -787,17 +765,6 @@ func formatEnvValueInternal(value string) string {return `"` + escaped + `"`}-// Docker Compose pre-defined variable names that compose-go's consts package-// does not export. See https://docs.docker.com/compose/how-tos/environment-variables/envvars.-const (- composeEnvFilesKey = "COMPOSE_ENV_FILES"- composeRemoveOrphansKey = "COMPOSE_REMOVE_ORPHANS"- composeIgnoreOrphansKey = "COMPOSE_IGNORE_ORPHANS"- composeParallelLimitKey = "COMPOSE_PARALLEL_LIMIT"-- defaultComposePathSeparator = ":"-)-// ComposeEnvOptions holds the deployment-relevant Docker Compose pre-defined// environment variables parsed from a project's merged environment.type ComposeEnvOptions struct {@@ -834,7 +801,7 @@ func ParseComposeEnvOptions(workdir string, env EnvMap) (ComposeEnvOptions, erroopts.ConfigFiles = filesif raw := strings.TrimSpace(env[consts.ComposeProfiles]); raw != "" {- opts.Profiles = splitAndTrimInternal(raw, ",")+ opts.Profiles = kit.TrimNonEmpty(strings.Split(raw, ","))}for _, entry := range ComposeEnvFileEntriesFromEnv(env) {@@ -910,7 +877,7 @@ func ComposeFileEntriesFromEnv(env EnvMap) []string {separator = custom}- return splitAndTrimInternal(raw, separator)+ return kit.TrimNonEmpty(strings.Split(raw, separator))}// ComposeEnvFileEntriesFromEnv returns the raw COMPOSE_ENV_FILES entries@@ -921,7 +888,7 @@ func ComposeEnvFileEntriesFromEnv(env EnvMap) []string {if raw == "" {return nil}- return splitAndTrimInternal(raw, ",")+ return kit.TrimNonEmpty(strings.Split(raw, ","))}// resolveComposeFileSelectionInternal parses COMPOSE_FILE from env into an@@ -1004,17 +971,6 @@ func mergeComposeEnvFilesInternal(ctx context.Context, workdir string, envMap En}}-func splitAndTrimInternal(raw, sep string) []string {- parts := strings.Split(raw, sep)- out := make([]string, 0, len(parts))- for _, p := range parts {- if trimmed := strings.TrimSpace(p); trimmed != "" {- out = append(out, trimmed)- }- }- return out-}-func parseComposeBoolInternal(env EnvMap, key string) bool {raw := strings.TrimSpace(env[key])if raw == "" {diff --git a/backend/pkg/projects/fs_util.go b/backend/pkg/projects/fs_util.goindex 9a426a970..ebaadb896 100644--- a/backend/pkg/projects/fs_util.go+++ b/backend/pkg/projects/fs_util.go@@ -2,6 +2,7 @@ package projectsimport ("bytes"+ "cmp""context""fmt""io/fs"@@ -12,20 +13,17 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg""go.yaml.in/yaml/v4")func ResolveConfiguredContainerDirectory(configuredPath, defaultPath string) string {- directory := strings.TrimSpace(configuredPath)- if directory == "" {- directory = defaultPath- }+ directory := cmp.Or(strings.TrimSpace(configuredPath), defaultPath)// Handle mapping format: "container_path:host_path"if parts := strings.SplitN(directory, ":", 2); len(parts) == 2 {@@ -184,10 +182,7 @@ func syncedProjectFileMatchesInternal(ctx context.Context, projectPath string, flogicalPath := "/" + filepath.ToSlash(file.RelativePath)entry, err := acfs.Stat(ctx, projectPath, logicalPath, false)if err != nil {- if errors.Is(err, fs.ErrNotExist) {- return false, nil- }- return false, err+ return false, kit.Ternary(errors.Is(err, fs.ErrNotExist), nil, err)}if entry.IsDirectory {return false, nil@@ -195,10 +190,7 @@ func syncedProjectFileMatchesInternal(ctx context.Context, projectPath string, fexistingContent, err := acfs.ReadFile(ctx, projectPath, logicalPath)if err != nil {- if errors.Is(err, fs.ErrNotExist) {- return false, nil- }- return false, err+ return false, kit.Ternary(errors.Is(err, fs.ErrNotExist), nil, err)}return bytes.Equal(existingContent, file.Content), nil@@ -211,10 +203,7 @@ func pathExistsInternal(path string) (bool, error) {if err == nil {return true, nil}- if os.IsNotExist(err) {- return false, nil- }- return false, err+ return false, kit.Ternary(os.IsNotExist(err), nil, err)}func DirectorySyncContentsChanged(ctx context.Context, projectPath string, syncFiles []SyncFile, oldSyncedFiles []string, composeFileName string) (bool, error) {@@ -285,10 +274,7 @@ func StaleComposeFiles(ctx context.Context, projectPath, composeFileName string,entries, err := acfs.List(ctx, projectPath, "/")if err != nil {- if errors.Is(err, fs.ErrNotExist) {- return nil, nil- }- return nil, err+ return nil, kit.Ternary(errors.Is(err, fs.ErrNotExist), nil, err)}var stale []string@@ -386,10 +372,7 @@ func CreateExactDir(ctx context.Context, projectsRoot, basePath, name string, pe}if err := acfs.Mkdir(ctx, projectsRoot, logicalPath, perm); err != nil {- if errors.Is(err, os.ErrExist) {- return "", "", ErrProjectDirExists- }- return "", "", err+ return "", "", kit.Ternary[error](errors.Is(err, os.ErrExist), ErrProjectDirExists, err)}return basePath, sanitized, nildiff --git a/backend/pkg/projects/fs_writer.go b/backend/pkg/projects/fs_writer.goindex cfc99392b..e40b42ca2 100644--- a/backend/pkg/projects/fs_writer.go+++ b/backend/pkg/projects/fs_writer.go@@ -17,11 +17,23 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""go.getarcane.app/acfs""go.getarcane.app/acfs/atomic"+ kit "go.getarcane.app/kit/pkg")-// DefaultComposeFileName is the compose filename Arcane writes when a project-// has no existing compose file.-const DefaultComposeFileName = "compose.yaml"+const (+ // DefaultComposeFileName is the compose filename Arcane writes when a project+ // has no existing compose file.+ DefaultComposeFileName = "compose.yaml"++ // DefaultComposeOverrideFileName is the override filename Arcane writes when a+ // project gains an override but has none on disk. It is deliberately+ // composeOverrideFileCandidates[1] ("compose.override.yaml"), NOT [0]+ // ("compose.override.yml"), so the default override extension matches Arcane's+ // ".yaml" base default (DefaultComposeFileName = "compose.yaml"). Do not "fix"+ // this to [0]: `docker compose` has no preference between the two, and keeping+ // ".yaml" avoids a mismatched base/override extension pair.+ DefaultComposeOverrideFileName = "compose.override.yaml"+)// composeFileCandidates lists supported base compose filenames in Arcane's// detection order. This order is intentionally explicit rather than sourced@@ -46,10 +58,7 @@ func ComposeFileCandidates() []string {// detectExistingComposeFileInternal finds an existing compose file in the directoryfunc detectExistingComposeFileInternal(ctx context.Context, projectsRoot, dir string) string {composePath, err := DetectComposeFile(ctx, projectsRoot, dir)- if err == nil {- return composePath- }- return ""+ return kit.Ternary(err == nil, composePath, "")}// WriteComposeFile writes a compose file to the specified directory.@@ -378,10 +387,7 @@ func WriteSyncedDirectory(ctx context.Context, projectsRoot, projectPath string,// Write the file. Honor the source's executable bit so scripts arrive// runnable for lifecycle hooks and similar consumers.- perm := utils.FilePerm- if file.Executable {- perm = 0o755- }+ perm := kit.Ternary(file.Executable, 0o755, utils.FilePerm)if err := acfs.Write(ctx, projectPath, logicalPath, file.Content, acfs.WriteOptions{Mode: perm, InPlace: true}); err != nil {return nil, errors.WrapIff(err, "failed to write file %s", file.RelativePath)}@@ -457,15 +463,6 @@ func cleanupEmptyDirs(ctx context.Context, projectPath, startLogical string) {// detection order, sourced from compose-go.var composeOverrideFileCandidates = slices.Clone(cli.DefaultOverrideFileNames)-// DefaultComposeOverrideFileName is the override filename Arcane writes when a-// project gains an override but has none on disk. It is deliberately-// composeOverrideFileCandidates[1] ("compose.override.yaml"), NOT [0]-// ("compose.override.yml"), so the default override extension matches Arcane's-// ".yaml" base default (DefaultComposeFileName = "compose.yaml"). Do not "fix"-// this to [0]: `docker compose` has no preference between the two, and keeping-// ".yaml" avoids a mismatched base/override extension pair.-const DefaultComposeOverrideFileName = "compose.override.yaml"-// ComposeOverrideFileCandidates returns the supported compose override filenames// in detection order. A copy is returned so callers can't mutate package state.func ComposeOverrideFileCandidates() []string {@@ -524,10 +521,7 @@ func ReadComposeOverrideContent(dir string) string {return ""}content, err := os.ReadFile(overridePath)- if err != nil {- return ""- }- return string(content)+ return kit.Ternary(err != nil, "", string(content))}// ResolveComposeOverride finds the highest-preference compose override file among@@ -537,7 +531,7 @@ func ReadComposeOverrideContent(dir string) string {// When multiple candidates exist it warns and uses the highest-preference match,// mirroring DetectComposeOverrideFile. found is false (with empty name/content)// when no candidate exists.-func ResolveComposeOverride(exists func(name string) bool, read func(name string) (string, error)) (fileName string, content string, found bool, err error) {+func ResolveComposeOverride(exists func(name string) bool, read func(name string) (string, error)) (fileName, content string, found bool, err error) {matches := findComposeOverrideCandidatesInternal(exists)if len(matches) == 0 {return "", "", false, nildiff --git a/backend/pkg/projects/fs_writer_test.go b/backend/pkg/projects/fs_writer_test.goindex 70bc636e4..aa177c3cf 100644--- a/backend/pkg/projects/fs_writer_test.go+++ b/backend/pkg/projects/fs_writer_test.go@@ -12,6 +12,7 @@ import ("github.com/stretchr/testify/assert""github.com/stretchr/testify/require""go.getarcane.app/acfs"+ kit "go.getarcane.app/kit/pkg")func TestWriteFilesPermissions(t *testing.T) {@@ -189,10 +190,7 @@ func TestWriteProjectFile_StillRejectsNonEnvSymlink(t *testing.T) {targetPath := filepath.Join(t.TempDir(), "compose.yaml")require.NoError(t, os.WriteFile(targetPath, []byte("services: {}\n"), 0o600))- fileName := DefaultComposeFileName- if writer == "project" {- fileName = OverrideEnvFileName- }+ fileName := kit.Ternary(writer == "project", OverrideEnvFileName, DefaultComposeFileName)linkPath := filepath.Join(projectDir, fileName)if err := os.Symlink(targetPath, linkPath); err != nil {t.Skipf("symlink creation is unavailable: %v", err)diff --git a/backend/pkg/projects/image_refs.go b/backend/pkg/projects/image_refs.goindex 9b303abec..fb450b1dd 100644--- a/backend/pkg/projects/image_refs.go+++ b/backend/pkg/projects/image_refs.go@@ -1,17 +1,19 @@package projectsimport (+ "cmp""encoding/json/v2"- "sort"+ "maps"+ "slices""strings"composetypes "github.com/compose-spec/compose-go/v2/types""github.com/containerd/platforms"composeapi "github.com/docker/compose/v5/pkg/api"-projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/moby/moby/api/types/image""github.com/moby/moby/client"+ kit "go.getarcane.app/kit/pkg")// ParseImageRefsJSON parses a JSON array of image references, returning nil@@ -35,20 +37,13 @@ func MarshalImageRefsJSON(refs []string) string {return ""}data, err := json.Marshal(refs)- if err != nil {- return ""- }- return string(data)+ return kit.Ternary(err != nil, "", string(data))}// ImageRefsFromComposeServices returns unique, non-empty image references from// a compose service map in stable service-name order.func ImageRefsFromComposeServices(services composetypes.Services) []string {- serviceNames := make([]string, 0, len(services))- for name := range services {- serviceNames = append(serviceNames, name)- }- sort.Strings(serviceNames)+ serviceNames := slices.Sorted(maps.Keys(services))serviceConfigs := make([]composetypes.ServiceConfig, 0, len(services))for _, name := range serviceNames {@@ -66,11 +61,7 @@ func BuildImageRefsFromComposeProject(project *composetypes.Project) []string {return nil}- serviceNames := make([]string, 0, len(project.Services))- for name := range project.Services {- serviceNames = append(serviceNames, name)- }- sort.Strings(serviceNames)+ serviceNames := slices.Sorted(maps.Keys(project.Services))return uniqueImageRefsInternal(len(serviceNames), func(yield func(string)) {for _, name := range serviceNames {@@ -78,9 +69,7 @@ func BuildImageRefsFromComposeProject(project *composetypes.Project) []string {if svc.Build == nil {continue}- if svc.Name == "" {- svc.Name = name- }+ svc.Name = cmp.Or(svc.Name, name)yield(composeapi.GetImageNameOrDefault(svc, project.Name))}})@@ -108,21 +97,8 @@ func ImageRefsFromRuntimeServices(services []projecttypes.RuntimeService) []strifunc uniqueImageRefsInternal(size int, collect func(yield func(string))) []string {refs := make([]string, 0, size)- seen := make(map[string]struct{}, size)-- collect(func(image string) {- ref := strings.TrimSpace(image)- if ref == "" {- return- }- if _, exists := seen[ref]; exists {- return- }- seen[ref] = struct{}{}- refs = append(refs, ref)- })-- return refs+ collect(func(image string) { refs = append(refs, image) })+ return kit.Unique(kit.TrimNonEmpty(refs))}// PullableImageRefs includes service images and registry-only hook and volume images.diff --git a/backend/pkg/projects/includes.go b/backend/pkg/projects/includes.goindex 8efc1a8a1..6b1e9c0df 100644--- a/backend/pkg/projects/includes.go+++ b/backend/pkg/projects/includes.go@@ -8,7 +8,6 @@ import ("strings""emperror.dev/errors"-"github.com/samber/mo""go.getarcane.app/acfs""go.yaml.in/yaml/v4"diff --git a/backend/pkg/projects/includes_test.go b/backend/pkg/projects/includes_test.goindex 2a52d497b..835e9cbb1 100644--- a/backend/pkg/projects/includes_test.go+++ b/backend/pkg/projects/includes_test.go@@ -21,7 +21,6 @@ func TestParseIncludes_NormalizesRelativePaths(t *testing.T) {require.NoError(t, err,"unexpected error: %v", err)-}requireNoError(os.MkdirAll(filepath.Dir(includePath), 0o755))@@ -36,7 +35,6 @@ func TestParseIncludes_NormalizesRelativePaths(t *testing.T) {require.Equal(t, "includes/config.yaml", includes[0].RelativePath,"unexpected relative path: got %q, want %q", includes[0].RelativePath, "includes/config.yaml")-}func TestParseIncludes_ExpandsArrayPathForm(t *testing.T) {@@ -50,7 +48,6 @@ func TestParseIncludes_ExpandsArrayPathForm(t *testing.T) {require.NoError(t, err,"unexpected error: %v", err)-}requireNoError(os.WriteFile(composePath, []byte("include:\n - path:\n - ./base.yaml\n - ./override.yaml\n"), 0o600))@@ -63,7 +60,6 @@ func TestParseIncludes_ExpandsArrayPathForm(t *testing.T) {require.False(t, includes[0].RelativePath != "base.yaml" || includes[1].RelativePath != "override.yaml","unexpected relative paths: %q, %q", includes[0].RelativePath, includes[1].RelativePath)-}func TestValidateIncludePathForWriteRejectsSymlinkEscape(t *testing.T) {diff --git a/backend/pkg/projects/load.go b/backend/pkg/projects/load.goindex 8ae7b6fbd..67f9cd58e 100644--- a/backend/pkg/projects/load.go+++ b/backend/pkg/projects/load.go@@ -1,6 +1,7 @@package projectsimport (+ "cmp""context""log/slog""maps"@@ -549,15 +550,11 @@ func harvestRawSourcesInternal(ctx context.Context, cfg composetypes.ConfigDetai}for name, secret := range project.Secrets {- if secret.File != "" {- rawSources["secret:"+name] = secret.File- }+ rawSources["secret:"+name] = cmp.Or(secret.File, rawSources["secret:"+name])}for name, config := range project.Configs {- if config.File != "" {- rawSources["config:"+name] = config.File- }+ rawSources["config:"+name] = cmp.Or(config.File, rawSources["config:"+name])}return rawSources@@ -584,7 +581,7 @@ func recoverComposeLoadPanicInternal(ctx context.Context, source string, project}}-func applyCustomLabelsInternal(projectName string, serviceName string, workingDirectory string, composeFiles []string) composetypes.Labels {+func applyCustomLabelsInternal(projectName, serviceName, workingDirectory string, composeFiles []string) composetypes.Labels {return composetypes.Labels{api.ProjectLabel: projectName,api.ServiceLabel: serviceName,@@ -686,7 +683,7 @@ func recordComposeDependenciesInternal(project *composetypes.Project, dependenci// ValidateComposeContentForUpdate validates proposed editor content without persisting it.// Missing includes are tolerated here; deployment uses strict executable loading.-func ValidateComposeContentForUpdate(ctx context.Context, projectsDirectory, projectPath, projectName, composeContent string, effectiveEnvContent *string, overrideContent *string, overrideFileName string, lenient bool) (err error) {+func ValidateComposeContentForUpdate(ctx context.Context, projectsDirectory, projectPath, projectName, composeContent string, effectiveEnvContent, overrideContent *string, overrideFileName string, lenient bool) (err error) {defer func() {if panicErr := emperror.Recover(recover()); panicErr != nil {err = errors.WrapIf(panicErr, "compose file contains invalid syntax")@@ -715,10 +712,7 @@ func ValidateComposeContentForUpdate(ctx context.Context, projectsDirectory, pro// that exact path is listed in the selection (docker skips auto-overrides// for an explicit file set); a same-named file in a subdirectory is not// the managed override.- overrideName := strings.TrimSpace(overrideFileName)- if overrideName == "" {- overrideName = DefaultComposeOverrideFileName- }+ overrideName := cmp.Or(strings.TrimSpace(overrideFileName), DefaultComposeOverrideFileName)overridePath := ""if absProjectPath, absErr := filepath.Abs(filepath.Clean(projectPath)); absErr == nil {overridePath = filepath.Join(absProjectPath, overrideName)@@ -741,10 +735,7 @@ func ValidateComposeContentForUpdate(ctx context.Context, projectsDirectory, pro// compose` would deploy it. Overrides can add services and are layered on// top (listed after the base so the override wins).if overrideContent != nil {- overrideName := strings.TrimSpace(overrideFileName)- if overrideName == "" {- overrideName = DefaultComposeOverrideFileName- }+ overrideName := cmp.Or(strings.TrimSpace(overrideFileName), DefaultComposeOverrideFileName)configFiles = append(configFiles, composetypes.ConfigFile{Filename: filepath.Join(projectPath, overrideName),Content: []byte(*overrideContent),diff --git a/backend/pkg/projects/logs_demux.go b/backend/pkg/projects/logs_demux.goindex 85a5877ab..c5cd26f52 100644--- a/backend/pkg/projects/logs_demux.go+++ b/backend/pkg/projects/logs_demux.go@@ -12,8 +12,8 @@ import ("github.com/docker/cli/cli/command""github.com/moby/moby/api/pkg/stdcopy""github.com/moby/moby/client"-- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg")// logsDemuxCompatibleDockerCliInternal exposes an API client that keeps@@ -35,7 +35,7 @@ func wrapDockerCLIWithLogsDemuxInternal(cli command.Cli) command.Cli {}return &logsDemuxCompatibleDockerCliInternal{Cli: cli,- apiClient: &logsDemuxDockerClientInternal{APIClient: libarcane.WrapDockerAPIClientForInspectCompatibility(cli.Client())},+ apiClient: &logsDemuxDockerClientInternal{APIClient: compat.WrapDockerAPIClientForInspectCompatibility(cli.Client())},}}@@ -85,7 +85,7 @@ func (c *logsDemuxDockerClientInternal) recordContainerTTYInternal(containerID sc.containerTty[key] = tty}-func (c *logsDemuxDockerClientInternal) containerTTYInternal(containerID string) (tty bool, known bool) {+func (c *logsDemuxDockerClientInternal) containerTTYInternal(containerID string) (tty, known bool) {key := strings.ToLower(strings.TrimSpace(containerID))c.ttyMu.RLock()defer c.ttyMu.RUnlock()@@ -137,10 +137,7 @@ func (s *stderrMarkedDemuxedStreamInternal) ingestFrameInternal() {return}- stream := 0- if header[0] == byte(stdcopy.Stderr) {- stream = 1- }+ stream := kit.Ternary(header[0] == byte(stdcopy.Stderr), 1, 0)s.pending[stream] = append(s.pending[stream], payload...)buf := s.pending[stream]for len(buf) > 0 {diff --git a/backend/pkg/projects/path_mapper.go b/backend/pkg/projects/path_mapper.goindex 98e60f2df..d79b72881 100644--- a/backend/pkg/projects/path_mapper.go+++ b/backend/pkg/projects/path_mapper.go@@ -1,6 +1,7 @@package projectsimport (+ "cmp""context""log/slog""path"@@ -14,6 +15,7 @@ import (mounttypes "github.com/moby/moby/api/types/mount""github.com/moby/moby/client""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")// HostMount is one containerβhost mount (bind or named volume) from Arcane's own@@ -72,10 +74,7 @@ func NewPathMapperFromMounts(mounts []HostMount) *PathMapper {// directory mapping and falls back to Docker mount discovery when no explicit// host path is configured.func NewPathMapperForConfiguredDirectory(ctx context.Context, configuredPath, defaultDir string, dockerClient *client.Client) *PathMapper {- configuredPath = strings.TrimSpace(configuredPath)- if configuredPath == "" {- configuredPath = defaultDir- }+ configuredPath = cmp.Or(strings.TrimSpace(configuredPath), defaultDir)containerDir := configuredPathhostDir := ""@@ -94,10 +93,7 @@ func NewPathMapperForConfiguredDirectory(ctx context.Context, configuredPath, deif strings.TrimSpace(hostDir) != "" {pathMapper := NewPathMapper(containerDir, filepath.Clean(strings.TrimSpace(hostDir)))- if pathMapper.IsNonMatchingMount() {- return pathMapper- }- return nil+ return kit.Ternary(pathMapper.IsNonMatchingMount(), pathMapper, nil)}mounts, err := GetCurrentContainerMounts(ctx, dockerClient)@@ -106,10 +102,7 @@ func NewPathMapperForConfiguredDirectory(ctx context.Context, configuredPath, de}pathMapper := NewPathMapperFromMounts(mounts)- if pathMapper.IsNonMatchingMount() {- return pathMapper- }- return nil+ return kit.Ternary(pathMapper.IsNonMatchingMount(), pathMapper, nil)}// ResolveHostPath returns the host-side path for containerPath by selecting thediff --git a/backend/pkg/projects/pull_policy.go b/backend/pkg/projects/pull_policy.goindex d32edf591..36f8276b3 100644--- a/backend/pkg/projects/pull_policy.go+++ b/backend/pkg/projects/pull_policy.go@@ -7,6 +7,7 @@ import (composetypes "github.com/compose-spec/compose-go/v2/types"composeapi "github.com/docker/compose/v5/pkg/api"+ kit "go.getarcane.app/kit/pkg")// ImagePullMode describes when Arcane should pull an image for a project.@@ -81,15 +82,6 @@ func ResolveServiceImagePullMode(svc composetypes.ServiceConfig) ImagePullStep {}}-// morePullEagerInternal reports whether a beats b in a pull plan: a higher-// mode wins, and between two refresh policies the shorter window does.-func morePullEagerInternal(a, b ImagePullStep) bool {- if a.Mode != b.Mode {- return a.Mode > b.Mode- }- return a.Mode == ImagePullModeRefresh && a.RefreshAfter < b.RefreshAfter-}-// BuildImagePullPlan builds a deduplicated image pull plan covering non-build// service images, pre_start hook images, and type:image volume sources.func BuildImagePullPlan(project *composetypes.Project) map[string]ImagePullStep {@@ -99,7 +91,14 @@ func BuildImagePullPlan(project *composetypes.Project) map[string]ImagePullStepif img == "" {return}- if existing, exists := plan[img]; !exists || morePullEagerInternal(step, existing) {+ existing, exists := plan[img]+ // A higher mode wins; between two refresh policies the shorter window does.+ moreEager := kit.Ternary(+ step.Mode != existing.Mode,+ step.Mode > existing.Mode,+ step.Mode == ImagePullModeRefresh && step.RefreshAfter < existing.RefreshAfter,+ )+ if !exists || moreEager {plan[img] = step}}@@ -127,10 +126,7 @@ func BuildImagePullPlan(project *composetypes.Project) map[string]ImagePullStep// NormalizePullPolicy normalizes compose pull policy aliases.func NormalizePullPolicy(policy string) string {policy = strings.ToLower(strings.TrimSpace(policy))- if policy == "if_not_present" {- return "missing"- }- return policy+ return kit.Ternary(policy == "if_not_present", "missing", policy)}// NormalizeDeployPullPolicy returns a supported deploy pull policy or empty string.diff --git a/backend/pkg/projects/volume_migration.go b/backend/pkg/projects/volume_migration.goindex 76acd4894..c33d686f1 100644--- a/backend/pkg/projects/volume_migration.go+++ b/backend/pkg/projects/volume_migration.go@@ -22,7 +22,7 @@ import ("go.yaml.in/yaml/v4")-func PlanVolumeMigration(ctx context.Context, dockerClient *client.Client, composeProject *composetypes.Project, oldComposeName, newComposeName string, toolsImage string) (volumetypes.Migration, error) {+func PlanVolumeMigration(ctx context.Context, dockerClient *client.Client, composeProject *composetypes.Project, oldComposeName, newComposeName, toolsImage string) (volumetypes.Migration, error) {if dockerClient == nil {return nil, errors.New("docker service unavailable")}diff --git a/backend/pkg/projects/workspace.go b/backend/pkg/projects/workspace.goindex 9c9792760..f98446f0e 100644--- a/backend/pkg/projects/workspace.go+++ b/backend/pkg/projects/workspace.go@@ -15,17 +15,17 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace""github.com/getarcaneapp/arcane/types/v2/project"workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"+ kit "go.getarcane.app/kit/pkg")-const ProjectWorkspaceUseScanDepth = -1-const (+ ProjectWorkspaceUseScanDepth = -1+ErrProjectWorkspaceRevisionConflict = errors.Sentinel("project workspace changed; refresh it and try again")ErrProjectWorkspaceOutsideProjectDirectory = errors.Sentinel("path is outside project directory")ErrProjectWorkspaceProtectedPath = errors.Sentinel("protected project configuration cannot be modified through the workspace")@@ -85,10 +85,7 @@ func ReadProjectWorkspace(projectPath string, maxDepth int, skipDirectories, comslices.SortFunc(walker.files, func(a, b workspacetypes.FileEntry) int {if a.IsDirectory != b.IsDirectory {- if a.IsDirectory {- return -1- }- return 1+ return kit.Ternary(a.IsDirectory, -1, 1)}return strings.Compare(a.RelativePath, b.RelativePath)})@@ -137,10 +134,7 @@ func (w *projectWorkspaceTreeWalkerInternal) visit(rel string, entry fs.DirEntrydepth := strings.Count(rel, "/") + 1if depth > w.maxDepth {- if entry.IsDir() {- return fs.SkipDir- }- return nil+ return kit.Ternary(entry.IsDir(), fs.SkipDir, nil)}if entry.IsDir() && w.skipDirs[entry.Name()] {@@ -157,10 +151,7 @@ func (w *projectWorkspaceTreeWalkerInternal) visit(rel string, entry fs.DirEntryreturn err}slog.Debug("Skipping unreadable project workspace entry", "relativePath", rel, "error", err)- if entry.IsDir() {- return fs.SkipDir- }- return nil+ return kit.Ternary(entry.IsDir(), fs.SkipDir, nil)}isProtected := w.protected[rel]@@ -185,7 +176,7 @@ func (w *projectWorkspaceTreeWalkerInternal) visit(rel string, entry fs.DirEntry// so keying on mtime/size would invalidate every workspace draft for a// live project and make saves 409 forever (#3199). Structural changes β// files appearing, disappearing, or changing kind β still conflict.- utils.WriteFileTreeRevisionEntry(w.revisionHash, rel, kind, 0, 0, "", false)+ kit.WriteRecord(w.revisionHash, rel, kind)w.entryCount++size := info.Size()@@ -311,7 +302,7 @@ func ProtectedProjectFilePaths(composeFileName string) map[string]bool {}func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool, change project.WorkspaceFileChange, uploads map[int][]byte, maxFileSizeBytes int64) error {- rel, err := utils.NormalizeRelativePath(change.RelativePath)+ rel, err := kit.NormalizeRelativePath(change.RelativePath)if err != nil {return errors.WrapIf(err, "invalid project workspace path")}@@ -328,7 +319,7 @@ func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool,}return updateProjectWorkspaceFileInternal(root, protected, rel, uploads[*change.UploadIndex], baseline, change.BaselineIndex != nil, maxFileSizeBytes)case project.FileOpRename:- newName, err := utils.ValidateFileName(change.NewName)+ newName, err := kit.ValidateFileName(change.NewName)if err != nil {return errors.WrapIf(err, "invalid project workspace file name")}@@ -494,7 +485,7 @@ func normalizeOptionalProjectParentPathInternal(input string) (string, error) {if strings.TrimSpace(input) == "" {return "", nil}- return utils.NormalizeRelativePath(input)+ return kit.NormalizeRelativePath(input)}func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool, rel, newParentPath string) error {@@ -525,7 +516,7 @@ func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool,if sourceInfo.Mode()&os.ModeSymlink != 0 {return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink paths are not supported")}- if sourceInfo.IsDir() && parentRel != "" && utils.FilePathMatches(parentRel, rel) {+ if sourceInfo.IsDir() && parentRel != "" && kit.FilePathMatches(parentRel, rel) {return errors.New("folder cannot be moved into itself or a descendant")}diff --git a/backend/pkg/projects/workspace_test.go b/backend/pkg/projects/workspace_test.goindex 66f76355a..d169cd4dd 100644--- a/backend/pkg/projects/workspace_test.go+++ b/backend/pkg/projects/workspace_test.go@@ -7,10 +7,10 @@ import ("strings""testing"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/project""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")func TestReadProjectWorkspace_ExcludesProtectedFilesAndReturnsFolders(t *testing.T) {@@ -342,7 +342,7 @@ func TestApplyProjectWorkspaceChangesRejectsUnusedUploadsForEmptyManifest(t *tesfunc TestValidateProjectWorkspaceFileName_RejectsPathSeparators(t *testing.T) {t.Parallel()- _, err := utils.ValidateFileName(strings.Join([]string{"folder", "name"}, string(filepath.Separator)))+ _, err := kit.ValidateFileName(strings.Join([]string{"folder", "name"}, string(filepath.Separator)))require.Error(t, err)}diff --git a/backend/pkg/scheduler/activity_sweep_job.go b/backend/pkg/scheduler/activity_sweep_job.goindex f8c0792f0..ae804b7a6 100644--- a/backend/pkg/scheduler/activity_sweep_job.go+++ b/backend/pkg/scheduler/activity_sweep_job.go@@ -4,9 +4,8 @@ import ("context""log/slog"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")const ActivitySweepJobName = "activity-sweep"diff --git a/backend/pkg/scheduler/actor_test.go b/backend/pkg/scheduler/actor_test.goindex 99b080a1c..e89aaba0c 100644--- a/backend/pkg/scheduler/actor_test.go+++ b/backend/pkg/scheduler/actor_test.go@@ -2,7 +2,6 @@ package schedulerimport ("context"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""sync""testing""time"@@ -10,6 +9,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/stretchr/testify/require""go.uber.org/fx/fxtest")@@ -88,6 +88,7 @@ func (d *testDispatcherInternal) Submit(ctx context.Context, request schedulertydefer lock.Unlock()return schedulertypes.Run{JobID: request.JobID}, d.run(ctx, request)}+func (*testDispatcherInternal) Checkpoint(context.Context, string, string, time.Time) error {return nil}diff --git a/backend/pkg/scheduler/analytics_job.go b/backend/pkg/scheduler/analytics_job.goindex 821ce6b8c..90a412d32 100644--- a/backend/pkg/scheduler/analytics_job.go+++ b/backend/pkg/scheduler/analytics_job.go@@ -11,14 +11,13 @@ import ("sync""time"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"emperror.dev/errors"-"github.com/cenkalti/backoff/v5""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/kv""github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")const (@@ -49,10 +48,7 @@ func NewAnalyticsJob(if httpClient == nil {httpClient = &http.Client{Timeout: 30 * time.Second}}- heartbeatURL := defaultHeartbeatEndpoint- if !cfg.Environment.IsProdEnvironment() {- heartbeatURL = devHeartbeatEndpoint- }+ heartbeatURL := kit.Ternary(!cfg.Environment.IsProdEnvironment(), devHeartbeatEndpoint, defaultHeartbeatEndpoint)return &AnalyticsJob{settingsService: settingsService,kvService: kvService,@@ -99,7 +95,7 @@ func (j *AnalyticsJob) Run(ctx context.Context) (schedulertypes.Outcome, error)}{Version: getAnalyticsVersion(),InstanceID: instanceID,- ServerType: j.getServerType(),+ ServerType: kit.Ternary(j.cfg.AgentMode, "agent", "manager"),}body, err := json.Marshal(payload)@@ -251,13 +247,6 @@ func (j *AnalyticsJob) claimHeartbeatAttemptWindowInternal(ctx context.Context)return true, nil}-func (j *AnalyticsJob) getServerType() string {- if j.cfg.AgentMode {- return "agent"- }- return "manager"-}-func getAnalyticsVersion() string {if v := strings.TrimSpace(config.Version); v != "" && v != "dev" {return vdiff --git a/backend/pkg/scheduler/analytics_job_test.go b/backend/pkg/scheduler/analytics_job_test.goindex 9b570d957..4306668a4 100644--- a/backend/pkg/scheduler/analytics_job_test.go+++ b/backend/pkg/scheduler/analytics_job_test.go@@ -11,15 +11,14 @@ import ("testing""time"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/kv""github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ "github.com/libtnb/sqlite""github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm")func setupAnalyticsStateServicesInternal(t *testing.T) (*database.DB, *settings.SettingsService, *kv.KVService) {@@ -68,9 +67,7 @@ func TestAnalyticsJob_Run_ManagerPayload(t *testing.T) {job.heartbeatURL = server.URLif _, err := job.Run(ctx); !assert.NoError(t, err) {-return-}var body []byte@@ -98,9 +95,7 @@ func TestAnalyticsJob_Run_AgentPayload(t *testing.T) {job.heartbeatURL = server.URLif _, err := job.Run(ctx); !assert.NoError(t, err) {-return-}var body []byte@@ -126,9 +121,7 @@ func TestAnalyticsJob_Run_SkipsWhenDisabled(t *testing.T) {job.heartbeatURL = server.URLif _, err := job.Run(ctx); !assert.NoError(t, err) {-return-}select {@@ -149,9 +142,7 @@ func TestAnalyticsJob_Run_SkipsWhenTestEnv(t *testing.T) {job.heartbeatURL = server.URLif _, err := job.Run(ctx); !assert.NoError(t, err) {-return-}select {diff --git a/backend/pkg/scheduler/apns_outbox_job.go b/backend/pkg/scheduler/apns_outbox_job.goindex adad24a17..cff6c32d3 100644--- a/backend/pkg/scheduler/apns_outbox_job.go+++ b/backend/pkg/scheduler/apns_outbox_job.go@@ -3,10 +3,9 @@ package schedulerimport ("context"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/apns""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")const ApnsOutboxJobName = "apns-outbox"diff --git a/backend/pkg/scheduler/auto_heal_job.go b/backend/pkg/scheduler/auto_heal_job.goindex 66c319735..316d260bf 100644--- a/backend/pkg/scheduler/auto_heal_job.go+++ b/backend/pkg/scheduler/auto_heal_job.go@@ -1,10 +1,7 @@package schedulerimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-+ "cmp""context""log/slog""slices"@@ -12,28 +9,33 @@ import ("sync""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/docker"- "github.com/getarcaneapp/arcane/backend/v2/internal/notification"-"emperror.dev/errors"- scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule"- "github.com/moby/moby/api/types/container"- "github.com/moby/moby/client"- "golang.org/x/sync/errgroup"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"+ "github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"+ scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ "github.com/moby/moby/api/types/container"+ "github.com/moby/moby/client"+ "go.getarcane.app/docker/compat"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/sys/cgroup"+ "golang.org/x/sync/errgroup")-const AutoHealJobName = "auto-heal"-const autoHealDefaultSchedule = "0 */5 * * * *"-const autoHealInspectConcurrency = 4-const autoHealAdmissionScopeInternal = "auto-heal"+const (+ AutoHealJobName = "auto-heal"+ autoHealDefaultSchedule = "0 */5 * * * *"+ autoHealInspectConcurrency = 4+ autoHealAdmissionScopeInternal = "auto-heal"+)// restartRecord tracks restart timestamps for a single container.type restartRecord struct {@@ -89,10 +91,7 @@ func (j *AutoHealJob) ShouldSchedule(ctx context.Context) bool {}func (j *AutoHealJob) Schedule(ctx context.Context) string {- schedule := j.settingsService.GetStringSetting(ctx, "autoHealInterval", autoHealDefaultSchedule)- if schedule == "" {- schedule = autoHealDefaultSchedule- }+ schedule := cmp.Or(j.settingsService.GetStringSetting(ctx, "autoHealInterval", autoHealDefaultSchedule), autoHealDefaultSchedule)parser := scheduleutil.Parser()if _, err := parser.Parse(schedule); err != nil {@@ -200,7 +199,7 @@ func (j *AutoHealJob) filterCandidatesInternal(containers []container.Summary, econtinue}- if internal, _ := utils.ParseBool(c.Labels[libarcane.InternalResourceLabel]); internal {+ if internal, _ := kit.ParseBool(c.Labels[libarcane.InternalResourceLabel]); internal {continue}@@ -254,7 +253,8 @@ func (j *AutoHealJob) processCandidateInternal(releaseSlot, reserved := j.reserveRestartSlotInternal(containerID, maxRestarts, restartWindow)if !reserved {- slog.WarnContext(ctx, "auto-heal restart-loop protection: skipping container",+ slog.WarnContext(+ ctx, "auto-heal restart-loop protection: skipping container","container", containerName,"max_restarts", maxRestarts,"window_minutes", restartWindowMinutes,@@ -435,7 +435,7 @@ func (j *AutoHealJob) inspectContainerInternal(ctx context.Context, dockerClientreturn j.inspectContainer(ctx, dockerClient, containerID)}- inspect, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})+ inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {return container.InspectResponse{}, err}diff --git a/backend/pkg/scheduler/auto_heal_job_test.go b/backend/pkg/scheduler/auto_heal_job_test.goindex 3141ea4cb..b352dcf53 100644--- a/backend/pkg/scheduler/auto_heal_job_test.go+++ b/backend/pkg/scheduler/auto_heal_job_test.go@@ -1,14 +1,13 @@package schedulerimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"-"context""sync/atomic""testing""time""github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/libtnb/sqlite""github.com/moby/moby/api/types/container""github.com/moby/moby/client"diff --git a/backend/pkg/scheduler/auto_patch_job.go b/backend/pkg/scheduler/auto_patch_job.goindex e77346952..8aeef400f 100644--- a/backend/pkg/scheduler/auto_patch_job.go+++ b/backend/pkg/scheduler/auto_patch_job.go@@ -1,19 +1,19 @@package schedulerimport (+ "cmp""context""log/slog""emperror.dev/errors"- "github.com/getarcaneapp/arcane/types/v2/features"-- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/imagepatch""github.com/getarcaneapp/arcane/backend/v2/internal/settings"scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule""github.com/getarcaneapp/arcane/types/v2"+ "github.com/getarcaneapp/arcane/types/v2/features"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")const AutoPatchJobName = "auto-patch"@@ -48,10 +48,7 @@ func (j *AutoPatchJob) ShouldSchedule(ctx context.Context) bool {// Schedule returns the cron expression for the job. Defaults to daily at 3 AM.func (j *AutoPatchJob) Schedule(ctx context.Context) string {- schedule := j.settingsService.GetStringSetting(ctx, "imageAutoPatchInterval", "0 0 3 * * *")- if schedule == "" {- schedule = "0 0 3 * * *"- }+ schedule := cmp.Or(j.settingsService.GetStringSetting(ctx, "imageAutoPatchInterval", "0 0 3 * * *"), "0 0 3 * * *")parser := scheduleutil.Parser()if _, err := parser.Parse(schedule); err != nil {@@ -72,10 +69,7 @@ func (j *AutoPatchJob) Run(ctx context.Context) (schedulertypes.Outcome, error)patched, skipped, err := j.imagePatchService.PatchFlaggedImages(ctx, types.LocalDockerEnvironmentID, autoPatchSystemUser)if errors.Is(err, common.ErrFeatureDisabled) {- status := schedulertypes.Skipped- if patched > 0 {- status = schedulertypes.Partial- }+ status := kit.Ternary(patched > 0, schedulertypes.Partial, schedulertypes.Skipped)return schedulertypes.Outcome{Status: status, Message: err.Error()}, nil}if err != nil {diff --git a/backend/pkg/scheduler/auto_update_job.go b/backend/pkg/scheduler/auto_update_job.goindex 8f724466c..73793e0c3 100644--- a/backend/pkg/scheduler/auto_update_job.go+++ b/backend/pkg/scheduler/auto_update_job.go@@ -1,19 +1,19 @@package schedulerimport (+ "cmp""context""log/slog""strings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-- "github.com/getarcaneapp/arcane/backend/v2/internal/settings"- "github.com/getarcaneapp/arcane/backend/v2/internal/updater"-"emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ "github.com/getarcaneapp/arcane/backend/v2/internal/updater"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"updatertypes "github.com/getarcaneapp/arcane/types/v2/updater"+ kit "go.getarcane.app/kit/pkg")const autoUpdateAdmissionScopeInternal = "auto-update"@@ -53,10 +53,7 @@ func (j *AutoUpdateJob) ShouldSchedule(ctx context.Context) bool {func (j *AutoUpdateJob) Schedule(ctx context.Context) string {s := j.settingsService.GetStringSetting(ctx, "autoUpdateInterval", "0 0 0 * * *")- if s == "" {- return "0 0 0 * * *"- }- return s+ return kit.Ternary(s == "", "0 0 0 * * *", s)}func (j *AutoUpdateJob) Run(ctx context.Context) (schedulertypes.Outcome, error) {@@ -66,9 +63,7 @@ func (j *AutoUpdateJob) Run(ctx context.Context) (schedulertypes.Outcome, error)var priorOutcome schedulertypes.Outcomeoptions, priorOutcome, unresolvedTargets = autoUpdateRetryOptionsInternal(previous)if priorOutcome.Status != "" {- if priorOutcome.ActivityID == "" {- priorOutcome.ActivityID = previous.Outcome.ActivityID- }+ priorOutcome.ActivityID = cmp.Or(priorOutcome.ActivityID, previous.Outcome.ActivityID)if priorOutcome.Status == schedulertypes.NeedsAttention && previous.Outcome.Message != "" {priorOutcome.Message += ": " + previous.Outcome.Message}@@ -197,10 +192,7 @@ func autoUpdateOutcomeInternal(ctx context.Context, result *updatertypes.Result,outcome.ActivityID = *result.ActivityID}for _, item := range result.Items {- status := schedulertypes.Succeeded- if item.Status == "failed" {- status = schedulertypes.Failed- }+ status := kit.Ternary(item.Status == "failed", schedulertypes.Failed, schedulertypes.Succeeded)if item.Status == "skipped" {status = schedulertypes.Skipped}diff --git a/backend/pkg/scheduler/auto_update_job_test.go b/backend/pkg/scheduler/auto_update_job_test.goindex 7585db15e..73861840d 100644--- a/backend/pkg/scheduler/auto_update_job_test.go+++ b/backend/pkg/scheduler/auto_update_job_test.go@@ -119,5 +119,4 @@ func TestAutoUpdateJob_OverlappingRunIsSkippedInternal(t *testing.T) {require.NoError(t, err)require.Equal(t, schedulertypes.NeedsAttention, outcome.Status)require.Equal(t, int32(2), applier.calls.Load())-}diff --git a/backend/pkg/scheduler/docker_client_refresh_job.go b/backend/pkg/scheduler/docker_client_refresh_job.goindex c65b4334e..5a4fb64df 100644--- a/backend/pkg/scheduler/docker_client_refresh_job.go+++ b/backend/pkg/scheduler/docker_client_refresh_job.go@@ -1,19 +1,20 @@package schedulerimport (+ "cmp""context""log/slog"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/docker"-"github.com/getarcaneapp/arcane/backend/v2/internal/settings"scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")-const DockerClientRefreshJobName = "docker-client-refresh"-const dockerClientRefreshDefaultSchedule = "0 */5 * * * *"+const (+ DockerClientRefreshJobName = "docker-client-refresh"+ dockerClientRefreshDefaultSchedule = "0 */5 * * * *"+)// DockerClientRefreshJob keeps the cached Docker client aligned with the daemon// API version after daemon restarts or upgrades.@@ -35,10 +36,7 @@ func (j *DockerClientRefreshJob) Name() string {}func (j *DockerClientRefreshJob) Schedule(ctx context.Context) string {- schedule := j.settingsService.GetStringSetting(ctx, "dockerClientRefreshInterval", dockerClientRefreshDefaultSchedule)- if schedule == "" {- schedule = dockerClientRefreshDefaultSchedule- }+ schedule := cmp.Or(j.settingsService.GetStringSetting(ctx, "dockerClientRefreshInterval", dockerClientRefreshDefaultSchedule), dockerClientRefreshDefaultSchedule)parser := scheduleutil.Parser()if _, err := parser.Parse(schedule); err != nil {diff --git a/backend/pkg/scheduler/entityjobs/entityjobs.go b/backend/pkg/scheduler/entityjobs/entityjobs.goindex 855df80a6..9bc1038bf 100644--- a/backend/pkg/scheduler/entityjobs/entityjobs.go+++ b/backend/pkg/scheduler/entityjobs/entityjobs.go@@ -9,9 +9,8 @@ import ("log/slog""emperror.dev/errors"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")// GitOpsSyncJobPrefix is shared by the GitOps registry and environment cleanup.diff --git a/backend/pkg/scheduler/event_cleanup_job.go b/backend/pkg/scheduler/event_cleanup_job.goindex 949cdb7d4..ef7e6b4c8 100644--- a/backend/pkg/scheduler/event_cleanup_job.go+++ b/backend/pkg/scheduler/event_cleanup_job.go@@ -5,11 +5,11 @@ import ("log/slog""time"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")const EventCleanupJobName = "event-cleanup"@@ -34,10 +34,7 @@ func (j *EventCleanupJob) Name() string {func (j *EventCleanupJob) Schedule(ctx context.Context) string {s := j.settingsService.GetStringSetting(ctx, "eventCleanupInterval", "0 0 */6 * * *")- if s == "" {- return "0 0 */6 * * *"- }- return s+ return kit.Ternary(s == "", "0 0 */6 * * *", s)}func (j *EventCleanupJob) Run(ctx context.Context) (schedulertypes.Outcome, error) {diff --git a/backend/pkg/scheduler/expired_sessions_cleanup_job.go b/backend/pkg/scheduler/expired_sessions_cleanup_job.goindex 078b92c72..36ef620c1 100644--- a/backend/pkg/scheduler/expired_sessions_cleanup_job.go+++ b/backend/pkg/scheduler/expired_sessions_cleanup_job.go@@ -5,10 +5,10 @@ import ("log/slog""time"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")const ExpiredSessionsCleanupJobName = "expired-sessions-cleanup"@@ -31,10 +31,7 @@ func (j *ExpiredSessionsCleanupJob) Name() string {func (j *ExpiredSessionsCleanupJob) Schedule(ctx context.Context) string {s := j.settingsService.GetStringSetting(ctx, "expiredSessionsCleanupInterval", "0 0 0 * * *")- if s == "" {- return "0 0 0 * * *"- }- return s+ return kit.Ternary(s == "", "0 0 0 * * *", s)}func (j *ExpiredSessionsCleanupJob) Run(ctx context.Context) (schedulertypes.Outcome, error) {diff --git a/backend/pkg/scheduler/git_clone_cleanup_job.go b/backend/pkg/scheduler/git_clone_cleanup_job.goindex 2150462d5..2ce7ba8b4 100644--- a/backend/pkg/scheduler/git_clone_cleanup_job.go+++ b/backend/pkg/scheduler/git_clone_cleanup_job.go@@ -5,21 +5,22 @@ import ("log/slog""time"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo""github.com/getarcaneapp/arcane/backend/v2/internal/settings"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")-// GitCloneCleanupJobName identifies the hourly purge of leaked git clone-// scratch directories.-const GitCloneCleanupJobName = "git-clone-scratch-cleanup"+const (+ // GitCloneCleanupJobName identifies the hourly purge of leaked git clone+ // scratch directories.+ GitCloneCleanupJobName = "git-clone-scratch-cleanup"-// gitCloneScratchMinAge is the base mtime cutoff for purging clone scratch dirs.-const gitCloneScratchMinAge = 2 * time.Hour+ // gitCloneScratchMinAge is the base mtime cutoff for purging clone scratch dirs.+ gitCloneScratchMinAge = 2 * time.Hour-// gitCloneScratchBuildHold pads the configured build timeout.-const gitCloneScratchBuildHold = 30 * time.Minute+ // gitCloneScratchBuildHold pads the configured build timeout.+ gitCloneScratchBuildHold = 30 * time.Minute+)// GitCloneCleanupJob purges orphaned "gitops-*" clone dirs under the git work// dir. Internal job: no job_metadata entry, invisible in the Jobs UI.diff --git a/backend/pkg/scheduler/image_update_watcher.go b/backend/pkg/scheduler/image_update_watcher.goindex 94e486f58..65a857932 100644--- a/backend/pkg/scheduler/image_update_watcher.go+++ b/backend/pkg/scheduler/image_update_watcher.go@@ -7,16 +7,14 @@ import ("sync/atomic""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/docker"- "github.com/getarcaneapp/arcane/backend/v2/internal/environment"- "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"- "github.com/getarcaneapp/arcane/backend/v2/internal/project"-"emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/docker"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"+ "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/types/v2/containerregistry"imageupdatetypes "github.com/getarcaneapp/arcane/types/v2/imageupdate"@@ -26,6 +24,15 @@ import ()const (+ imageUpdateTriggerMessageInternal imageUpdateMessageKindInternal = 0+ imageUpdateScheduleRefreshMessageInternal imageUpdateMessageKindInternal = 1+ imageUpdateBackfillCompletedMessageInternal imageUpdateMessageKindInternal = 2+ imageUpdateDebounceElapsedMessageInternal imageUpdateMessageKindInternal = 3+ imageUpdateScheduledPollMessageInternal imageUpdateMessageKindInternal = 4+ imageUpdateScanCompletedMessageInternal imageUpdateMessageKindInternal = 5+ imageUpdateManualScanRequestMessageInternal imageUpdateMessageKindInternal = 6+ imageUpdateManualScanAdmissionMessageInternal imageUpdateMessageKindInternal = 7+imageUpdateWatcherDebounce = 2 * time.SecondimageUpdateWatcherBackfillRetry = 5 * time.SecondimageUpdateWatcherDefaultSchedule = "0 0 * * * *"@@ -56,17 +63,6 @@ type projectImageRefsBackfillerInternal interface {type imageUpdateMessageKindInternal uint8-const (- imageUpdateTriggerMessageInternal imageUpdateMessageKindInternal = iota- imageUpdateScheduleRefreshMessageInternal- imageUpdateBackfillCompletedMessageInternal- imageUpdateDebounceElapsedMessageInternal- imageUpdateScheduledPollMessageInternal- imageUpdateScanCompletedMessageInternal- imageUpdateManualScanRequestMessageInternal- imageUpdateManualScanAdmissionMessageInternal-)-type imageUpdateScanCompletionInternal struct {automatic booltriggerGeneration uint64diff --git a/backend/pkg/scheduler/image_update_watcher_test.go b/backend/pkg/scheduler/image_update_watcher_test.goindex 8d84ff6d7..d682fce30 100644--- a/backend/pkg/scheduler/image_update_watcher_test.go+++ b/backend/pkg/scheduler/image_update_watcher_test.go@@ -4,7 +4,6 @@ import ("bytes""context""fmt"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""log/slog""sync""testing"@@ -16,6 +15,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/getarcaneapp/arcane/types/v2/imageupdate"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/moby/moby/api/types/events""github.com/stretchr/testify/require""go.getarcane.app/streams/bus"@@ -105,7 +105,7 @@ func (s *pollingSettingReaderFakeInternal) GetBoolSetting(_ context.Context, key}}-func (s *pollingSettingReaderFakeInternal) GetStringSetting(_ context.Context, _ string, defaultValue string) string {+func (s *pollingSettingReaderFakeInternal) GetStringSetting(_ context.Context, _, defaultValue string) string {s.mu.RLock()defer s.mu.RUnlock()if s.schedule == "" {diff --git a/backend/pkg/scheduler/jobcontext/context.go b/backend/pkg/scheduler/jobcontext/context.goindex a75662b0c..1390341df 100644--- a/backend/pkg/scheduler/jobcontext/context.go+++ b/backend/pkg/scheduler/jobcontext/context.go@@ -7,8 +7,10 @@ import (schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")-type progressKeyInternal struct{}-type runKeyInternal struct{}+type (+ progressKeyInternal struct{}+ runKeyInternal struct{}+)func WithExecution(ctx context.Context, run schedulertypes.Run, persist func(schedulertypes.TargetOutcome) error) context.Context {ctx = context.WithValue(ctx, runKeyInternal{}, run)diff --git a/backend/pkg/scheduler/queue/activity.go b/backend/pkg/scheduler/queue/activity.goindex c171456e7..25a25e523 100644--- a/backend/pkg/scheduler/queue/activity.go+++ b/backend/pkg/scheduler/queue/activity.go@@ -5,15 +5,16 @@ import ("log/slog""time"- st "github.com/getarcaneapp/arcane/types/v2/scheduler"+ "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")// SetObserver connects activity projection before the queue starts accepting work.-func (q *Queue) SetObserver(observer st.RunObserver) {+func (q *Queue) SetObserver(observer scheduler.RunObserver) {q.observer = observer}-func (q *Queue) associateActivityInternal(run *st.Run) {+func (q *Queue) associateActivityInternal(run *scheduler.Run) {if q.observer != nil && run.ActivityID == "" {run.ActivityID = q.observer.ActivityID(*run)}@@ -22,7 +23,7 @@ func (q *Queue) associateActivityInternal(run *st.Run) {}}-func (q *Queue) observeRunInternal(ctx context.Context, run st.Run) {+func (q *Queue) observeRunInternal(ctx context.Context, run scheduler.Run) {if q.observer == nil {return}@@ -36,13 +37,13 @@ func (q *Queue) observeRunInternal(ctx context.Context, run st.Run) {}}-func (q *Queue) syncActivityInternal(ctx context.Context, run st.Run) {+func (q *Queue) syncActivityInternal(ctx context.Context, run scheduler.Run) {ctx, cancel := context.WithTimeout(ctx, 5*time.Second)defer cancel()- key := queueKeyInternal(run.EnvironmentID, run.JobID) + "/" + run.ID+ key := queuePrefixInternal + kit.SHA256Hex(run.EnvironmentID+"\x00"+run.JobID) + "/" + run.IDif err := q.observer.SyncRunActivity(ctx, run); err != nil {if q.pendingSync == nil {- q.pendingSync = make(map[string]st.Run)+ q.pendingSync = make(map[string]scheduler.Run)}q.pendingSync[key] = runslog.ErrorContext(ctx, "Job activity synchronization failed; will retry", "runId", run.ID, "error", err)diff --git a/backend/pkg/scheduler/queue/queue.go b/backend/pkg/scheduler/queue/queue.goindex 290b4b49d..3897e416f 100644--- a/backend/pkg/scheduler/queue/queue.go+++ b/backend/pkg/scheduler/queue/queue.go@@ -2,6 +2,7 @@package queueimport (+ "cmp""context""crypto/rand""io"@@ -14,6 +15,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/kv"st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/google/uuid"+ kit "go.getarcane.app/kit/pkg")// Queue persists work before dispatching it to the owning domain.@@ -48,15 +50,11 @@ func (q *Queue) Submit(ctx context.Context, request st.Request) (st.Run, error)if q.stopping {return st.Run{}, errors.New("job queue is stopping")}- if request.EnvironmentID == "" {- request.EnvironmentID = "0"- }+ request.EnvironmentID = cmp.Or(request.EnvironmentID, "0")if request.JobID == "" {return st.Run{}, errors.New("job ID required")}- if request.Trigger == "" {- request.Trigger = "manual"- }+ request.Trigger = cmp.Or(request.Trigger, "manual")if request.RunID == "" {request.RunID = uuid.NewString()}@@ -236,7 +234,7 @@ func (q *Queue) dispatchReadyInternal(ctx context.Context) (time.Time, error) {}var nextRetry time.Timefor _, record := range records {- key := queueKeyInternal(record.EnvironmentID, record.JobID)+ key := queuePrefixInternal + kit.SHA256Hex(record.EnvironmentID+"\x00"+record.JobID)reserved := strings.HasPrefix(record.JobID, "environment-health") || record.JobID == "docker-client-refresh" || record.JobID == "activity-sweep"q.mu.Lock()if q.active[key] || q.stopping || (!reserved && q.ordinary >= 4) || (reserved && q.health >= 2) {@@ -304,11 +302,7 @@ func (q *Queue) executeInternal(ctx context.Context, key string, run st.Run, res}()outcome, err := q.invokeInternal(ctx, run, reconcile)if outcome.Status == "" {- if err != nil {- outcome.Status = st.Failed- } else {- outcome.Status = st.Succeeded- }+ outcome.Status = kit.Ternary(err != nil, st.Failed, st.Succeeded)}if err != nil && outcome.Message == "" {outcome.Message = err.Error()@@ -479,8 +473,6 @@ func mergeTargetProgressInternal(previous, outcome st.Outcome) st.Outcome {outcome.Targets = append(outcome.Targets, target)}}- if outcome.ActivityID == "" {- outcome.ActivityID = previous.ActivityID- }+ outcome.ActivityID = cmp.Or(outcome.ActivityID, previous.ActivityID)return outcome}diff --git a/backend/pkg/scheduler/queue/queue_store.go b/backend/pkg/scheduler/queue/queue_store.goindex 4dceaa00f..71e648fa7 100644--- a/backend/pkg/scheduler/queue/queue_store.go+++ b/backend/pkg/scheduler/queue/queue_store.go@@ -2,8 +2,6 @@ package queueimport ("context"- "crypto/sha256"- "encoding/hex""encoding/json/v2""slices""sort"@@ -13,17 +11,13 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/kv"st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/google/uuid"+ kit "go.getarcane.app/kit/pkg")const queuePrefixInternal = "jobs."-func queueKeyInternal(environmentID, jobID string) string {- sum := sha256.Sum256([]byte(environmentID + "\x00" + jobID))- return queuePrefixInternal + hex.EncodeToString(sum[:])-}-func (q *Queue) mutateInternal(ctx context.Context, environmentID, jobID string, change func(*st.QueueRecord) error) error {- key := queueKeyInternal(environmentID, jobID)+ key := queuePrefixInternal + kit.SHA256Hex(environmentID+"\x00"+jobID)for range 20 {previous, found, err := q.store.Get(ctx, key)if err != nil {@@ -88,7 +82,7 @@ func (q *Queue) Records(ctx context.Context) ([]st.QueueRecord, error) {// Get retrieves a run by environment, job, and run ID, including compacted// idempotency receipts. It returns ErrRunNotFound when no matching record exists.func (q *Queue) Get(ctx context.Context, environmentID, jobID, runID string) (st.Run, error) {- raw, found, err := q.store.Get(ctx, queueKeyInternal(environmentID, jobID))+ raw, found, err := q.store.Get(ctx, queuePrefixInternal+kit.SHA256Hex(environmentID+"\x00"+jobID))if err != nil {return st.Run{}, err}diff --git a/backend/pkg/scheduler/queue/resolution.go b/backend/pkg/scheduler/queue/resolution.goindex f1cec1cee..3ccde9f39 100644--- a/backend/pkg/scheduler/queue/resolution.go+++ b/backend/pkg/scheduler/queue/resolution.go@@ -6,13 +6,14 @@ import ("emperror.dev/errors"st "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")// Resolve releases reviewed, inactive work without discarding its execution evidence.func (q *Queue) Resolve(ctx context.Context, environmentID, jobID, runID, resolvedBy string) (st.Run, error) {q.mu.Lock()defer q.mu.Unlock()- if q.active[queueKeyInternal(environmentID, jobID)] {+ if q.active[queuePrefixInternal+kit.SHA256Hex(environmentID+"\x00"+jobID)] {return st.Run{}, errors.New("job is still active")}run, err := q.Get(ctx, environmentID, jobID, runID)diff --git a/backend/pkg/scheduler/queue/resolution_test.go b/backend/pkg/scheduler/queue/resolution_test.goindex 80a8ad015..5b854ba87 100644--- a/backend/pkg/scheduler/queue/resolution_test.go+++ b/backend/pkg/scheduler/queue/resolution_test.go@@ -9,6 +9,7 @@ import (st "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/libtnb/sqlite""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg""gorm.io/gorm")@@ -92,7 +93,7 @@ func TestResolveRejectsUnsafeStates(t *testing.T) {current.RemoteDeliveryAttempted = test.deliveredreturn nil}))- q.active[queueKeyInternal(test.environment, "auto-update")] = test.active+ q.active[queuePrefixInternal+kit.SHA256Hex(test.environment+"\x00"+"auto-update")] = test.active_, err = q.Resolve(context.Background(), test.environment, "auto-update", run.ID, "operator")require.Error(t, err)stored, err := q.Get(t.Context(), test.environment, "auto-update", run.ID)diff --git a/backend/pkg/scheduler/schedule/cron.go b/backend/pkg/scheduler/schedule/cron.goindex cf91062a3..bbeb05963 100644--- a/backend/pkg/scheduler/schedule/cron.go+++ b/backend/pkg/scheduler/schedule/cron.go@@ -5,7 +5,6 @@ import ("strings""emperror.dev/errors"-"github.com/robfig/cron/v3")diff --git a/backend/pkg/scheduler/scheduled_prune_job.go b/backend/pkg/scheduler/scheduled_prune_job.goindex 7c058b407..c5e2c6806 100644--- a/backend/pkg/scheduler/scheduled_prune_job.go+++ b/backend/pkg/scheduler/scheduled_prune_job.go@@ -1,18 +1,17 @@package schedulerimport (+ "cmp""context""log/slog"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/settings"- systemtypes "github.com/getarcaneapp/arcane/types/v2/system"-"github.com/getarcaneapp/arcane/backend/v2/internal/system"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext"scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ systemtypes "github.com/getarcaneapp/arcane/types/v2/system")const ScheduledPruneJobName = "scheduled-prune"@@ -40,10 +39,7 @@ func (j *ScheduledPruneJob) ShouldSchedule(ctx context.Context) bool {}func (j *ScheduledPruneJob) Schedule(ctx context.Context) string {- schedule := j.settingsService.GetStringSetting(ctx, "scheduledPruneInterval", "0 0 0 * * *")- if schedule == "" {- schedule = "0 0 0 * * *"- }+ schedule := cmp.Or(j.settingsService.GetStringSetting(ctx, "scheduledPruneInterval", "0 0 0 * * *"), "0 0 0 * * *")parser := scheduleutil.Parser()if _, err := parser.Parse(schedule); err != nil {@@ -162,7 +158,6 @@ func buildScheduledVolumePruneOptionsInternal(ctx context.Context, settingsServiif mode == "" || mode == string(systemtypes.PruneVolumeModeNone) {return nil}-return &systemtypes.PruneVolumesOptions{Mode: systemtypes.PruneVolumeMode(mode)}}diff --git a/backend/pkg/scheduler/scheduled_prune_job_test.go b/backend/pkg/scheduler/scheduled_prune_job_test.goindex de3c76697..a900cb224 100644--- a/backend/pkg/scheduler/scheduled_prune_job_test.go+++ b/backend/pkg/scheduler/scheduled_prune_job_test.go@@ -4,13 +4,12 @@ import ("context""testing"- "github.com/libtnb/sqlite"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-"github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/types/v2/system"+ "github.com/libtnb/sqlite"+ "github.com/stretchr/testify/require"+ "gorm.io/gorm")func setupScheduledPruneSettingsServiceInternal(t *testing.T) *settings.SettingsService {diff --git a/backend/pkg/scheduler/upload_sessions_cleanup_job.go b/backend/pkg/scheduler/upload_sessions_cleanup_job.goindex 6d4600aad..075bb8df5 100644--- a/backend/pkg/scheduler/upload_sessions_cleanup_job.go+++ b/backend/pkg/scheduler/upload_sessions_cleanup_job.go@@ -5,16 +5,17 @@ import ("log/slog""time"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/upload"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")-// UploadSessionsCleanupJobName identifies the hourly purge of idle chunked-// upload sessions.-const UploadSessionsCleanupJobName = "upload-sessions-cleanup"+const (+ // UploadSessionsCleanupJobName identifies the hourly purge of idle chunked+ // upload sessions.+ UploadSessionsCleanupJobName = "upload-sessions-cleanup"-const uploadSessionMaxAge = 24 * time.Hour+ uploadSessionMaxAge = 24 * time.Hour+)// UploadSessionsCleanupJob purges upload sessions that have been idle for// longer than uploadSessionMaxAge. It runs on managers and agents alike,diff --git a/backend/pkg/scheduler/volume_helper_reaper_job.go b/backend/pkg/scheduler/volume_helper_reaper_job.goindex eea29cd8e..1813bf66e 100644--- a/backend/pkg/scheduler/volume_helper_reaper_job.go+++ b/backend/pkg/scheduler/volume_helper_reaper_job.go@@ -5,10 +5,9 @@ import ("log/slog""time"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-"github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/volume"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler")const (diff --git a/backend/pkg/scheduler/vulnerability_scan_job.go b/backend/pkg/scheduler/vulnerability_scan_job.goindex 6c4f3af1b..d3c735772 100644--- a/backend/pkg/scheduler/vulnerability_scan_job.go+++ b/backend/pkg/scheduler/vulnerability_scan_job.go@@ -1,18 +1,19 @@package schedulerimport (- "emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/types/v2/features"- schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"-+ "cmp""context""log/slog"+ "emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"scheduleutil "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/schedule""github.com/getarcaneapp/arcane/types/v2"+ "github.com/getarcaneapp/arcane/types/v2/features"+ schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"+ kit "go.getarcane.app/kit/pkg")const VulnerabilityScanJobName = "vulnerability-scan"@@ -47,10 +48,7 @@ func (j *VulnerabilityScanJob) ShouldSchedule(ctx context.Context) bool {// Schedule returns the cron expression for the job. Defaults to daily at midnight.func (j *VulnerabilityScanJob) Schedule(ctx context.Context) string {- schedule := j.settingsService.GetStringSetting(ctx, "vulnerabilityScanInterval", "0 0 0 * * *")- if schedule == "" {- schedule = "0 0 0 * * *"- }+ schedule := cmp.Or(j.settingsService.GetStringSetting(ctx, "vulnerabilityScanInterval", "0 0 0 * * *"), "0 0 0 * * *")parser := scheduleutil.Parser()if _, err := parser.Parse(schedule); err != nil {@@ -80,10 +78,7 @@ func (j *VulnerabilityScanJob) Run(ctx context.Context) (schedulertypes.Outcome,scanned, failed, err := j.vulnerabilityService.ScanAllImages(ctx, types.LocalDockerEnvironmentID, vulnerabilityScanSystemUser, false)if errors.Is(err, common.ErrFeatureDisabled) {- status := schedulertypes.Skipped- if scanned > 0 {- status = schedulertypes.Partial- }+ status := kit.Ternary(scanned > 0, schedulertypes.Partial, schedulertypes.Skipped)return schedulertypes.Outcome{Status: status, Message: err.Error()}, nil}if err != nil {diff --git a/backend/pkg/utils/activity_context.go b/backend/pkg/utils/activity_context.goindex cc74b1e32..18e50e393 100644--- a/backend/pkg/utils/activity_context.go+++ b/backend/pkg/utils/activity_context.go@@ -11,8 +11,10 @@ import (type appLifecycleContextKey struct{}-type activityBatchIDContextKey struct{}-type updateInitiatorContextKeyInternal struct{}+type (+ activityBatchIDContextKey struct{}+ updateInitiatorContextKeyInternal struct{}+)// WithUpdateInitiator carries manager-authenticated attribution through an// agent request without changing the authenticated agent identity.@@ -81,7 +83,7 @@ func IsAppLifecycleContext(ctx context.Context) bool {}// ActivityRuntimeContext returns a context suitable for activity-backed work.-func ActivityRuntimeContext(requestCtx context.Context, appCtx context.Context) context.Context {+func ActivityRuntimeContext(requestCtx, appCtx context.Context) context.Context {if appCtx != nil {if requestCtx == nil || requestCtx == appCtx {return appCtxdiff --git a/backend/pkg/utils/auth.go b/backend/pkg/utils/auth.godeleted file mode 100644index bb7f6eeeb..000000000--- a/backend/pkg/utils/auth.go+++ /dev/null@@ -1,20 +0,0 @@-package utils--// Auth header names and path prefixes shared between the Echo middleware-// (WebSocket/diagnostics) and the Huma auth bridge (REST). Keep these in one-// place so a change to a header name applies to every route type at once.-const (- HeaderAgentBootstrap = "X-Arcane-Agent-Bootstrap"- HeaderAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential- HeaderApiKey = "X-Api-Key" // #nosec G101: header name, not a credential- HeaderActivityBatchID = "X-Arcane-Batch-Id"- HeaderUpdateInitiatorID = "X-Arcane-Update-Initiator-Id"- HeaderUpdateInitiatorName = "X-Arcane-Update-Initiator-Name"- HeaderUpdateInitiatorDisplayName = "X-Arcane-Update-Initiator-Display-Name"- // HeaderIconCatalog carries the requesting user's icon catalog preference to- // remote environments. Agents authenticate proxied calls as a synthetic user- // with no preferences, so without it every remote environment would resolve- // container/project icons against the default catalog.- HeaderIconCatalog = "X-Arcane-Icon-Catalog"- AgentPairingPrefix = "/api/environments/0/agent/pair"-)diff --git a/backend/pkg/utils/backupbrowser/browser.go b/backend/pkg/utils/backupbrowser/browser.goindex 898182a51..2d6263615 100644--- a/backend/pkg/utils/backupbrowser/browser.go+++ b/backend/pkg/utils/backupbrowser/browser.go@@ -12,8 +12,8 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"+ kit "go.getarcane.app/kit/pkg")// NormalizePath validates and normalizes a path relative to a backup root.@@ -29,7 +29,7 @@ func NormalizePath(value string, allowEmpty bool) (string, error) {if slices.Contains(strings.Split(trimmed, "/"), "..") {return "", errors.New("backup path must stay within the restore root")}- cleaned, err := utils.NormalizeRelativePath(trimmed)+ cleaned, err := kit.NormalizeRelativePath(trimmed)if err != nil {return "", errors.New("backup path must stay within the restore root")}@@ -65,7 +65,7 @@ func BuildEntries(paths []string, browsePath string, recursive bool) []backuptyp}relative := candidateif root != "" {- if candidate == root || !utils.FilePathMatches(candidate, root) {+ if candidate == root || !kit.FilePathMatches(candidate, root) {continue}relative = strings.TrimPrefix(candidate, root+"/")@@ -95,10 +95,7 @@ func BuildEntries(paths []string, browsePath string, recursive bool) []backuptypfunc compareEntriesInternal(left, right backuptypes.BackupFileEntry) int {if left.IsDirectory != right.IsDirectory {- if left.IsDirectory {- return -1- }- return 1+ return kit.Ternary(left.IsDirectory, -1, 1)}if result := cmp.Compare(strings.ToLower(left.Name), strings.ToLower(right.Name)); result != 0 {return resultdiff --git a/backend/pkg/utils/bool.go b/backend/pkg/utils/bool.godeleted file mode 100644index 38cb650bd..000000000--- a/backend/pkg/utils/bool.go+++ /dev/null@@ -1,17 +0,0 @@-package utils--import "strings"--// ParseBool recognizes true/1/yes/on and false/0/no/off, ignoring case and whitespace.-// The second result reports whether the value is recognized.-// This will be moved into go.getarcane.app/kit at some point.-func ParseBool(value string) (bool, bool) {- switch strings.ToLower(strings.TrimSpace(value)) {- case "true", "1", "yes", "on":- return true, true- case "false", "0", "no", "off":- return false, true- default:- return false, false- }-}diff --git a/backend/pkg/utils/cookie/cookie_util.go b/backend/pkg/utils/cookie/cookie_util.goindex 7adfa3454..cc1f0efb7 100644--- a/backend/pkg/utils/cookie/cookie_util.go+++ b/backend/pkg/utils/cookie/cookie_util.go@@ -5,6 +5,8 @@ import ("fmt""net/http""strings"++ kit "go.getarcane.app/kit/pkg")var (@@ -97,10 +99,7 @@ func BuildTokenCookieStringFor(maxAgeInSeconds int, token string, secure bool) [if maxAgeInSeconds < 0 {maxAgeInSeconds = 0}- base := InsecureTokenCookieName- if secure {- base = TokenCookieName- }+ base := kit.Ternary(secure, TokenCookieName, InsecureTokenCookieName)var chunks []stringfor len(token) > tokenCookieChunkSize {diff --git a/backend/pkg/utils/dbutil/dbutil.go b/backend/pkg/utils/dbutil/dbutil.goindex 3db9db97e..7507caf26 100644--- a/backend/pkg/utils/dbutil/dbutil.go+++ b/backend/pkg/utils/dbutil/dbutil.go@@ -7,7 +7,6 @@ import ("strings""emperror.dev/errors"-"gorm.io/gorm")diff --git a/backend/pkg/utils/env_util.go b/backend/pkg/utils/env_util.goindex 546c49b68..f944865ac 100644--- a/backend/pkg/utils/env_util.go+++ b/backend/pkg/utils/env_util.go@@ -10,7 +10,7 @@ import (// or NAME_FILE (checked in that order) names a readable file, its trimmed// contents stand in for NAME. An unreadable file falls back to NAME.// The booleans report whether a value was found and whether it came from a file.-func LookupEnvOrFile(name string) (value string, found bool, fromFile bool) {+func LookupEnvOrFile(name string) (value string, found, fromFile bool) {for _, suffix := range []string{"__FILE", "_FILE"} {filePath := os.Getenv(name + suffix)if filePath == "" {diff --git a/backend/pkg/utils/fingerprint.go b/backend/pkg/utils/fingerprint.godeleted file mode 100644index c1fff4bdb..000000000--- a/backend/pkg/utils/fingerprint.go+++ /dev/null@@ -1,190 +0,0 @@-package utils--import (- "context"- "crypto/sha256"- "encoding/binary"- "hash"- "hash/fnv"- "sync"- "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()-}--// Slice 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 (f *Fingerprint) Slice[T any](items []T, write func(*Fingerprint, *T)) *Fingerprint {- f.Int(int64(len(items)))- for i := range items {- write(f, &items[i])- }- return f-}--// SyncGate remembers the SHA-256 of the last payload delivered per scope and-// key so periodic re-syncs skip the network when nothing changed, and-// serializes deliveries for one key so overlapping pushes reach the target in-// the order they are remembered. Only the digest is retained. Expiry bounds-// how long a delivery is trusted (zero means forever) so a target rebuilt-// behind an unchanged status still converges. The zero value is ready to use.-type SyncGate struct {- Expiry time.Duration-- mu sync.Mutex- locks KeyedMutex- sent map[string]map[string]syncGateEntryInternal- epochs map[string]uint64-}--type syncGateEntryInternal struct {- digest [sha256.Size]byte- sentAt time.Time-}--// Begin reports whether body is already delivered for scope and key. When it-// is not, the key stays locked until finish runs; finish(true) remembers the-// delivery unless the scope was forgotten in between. Callers must invoke-// finish exactly once. Waiting for an in-flight delivery ends with ctx.-func (g *SyncGate) Begin(ctx context.Context, scope, key string, body []byte) (unchanged bool, finish func(delivered bool), err error) {- unlock, err := g.locks.LockContext(ctx, scope+"\x00"+key)- if err != nil {- return false, nil, err- }- g.mu.Lock()- epoch := g.epochs[scope]- entry, ok := g.sent[scope][key]- unchanged = ok && entry.digest == sha256.Sum256(body) && (g.Expiry <= 0 || time.Since(entry.sentAt) < g.Expiry)- g.mu.Unlock()- if unchanged {- unlock()- return true, func(bool) {}, nil- }- return false, func(delivered bool) {- defer unlock()- if !delivered {- return- }- g.mu.Lock()- defer g.mu.Unlock()- if g.epochs[scope] != epoch {- return- }- if g.sent == nil {- g.sent = make(map[string]map[string]syncGateEntryInternal)- }- if g.sent[scope] == nil {- g.sent[scope] = make(map[string]syncGateEntryInternal)- }- g.sent[scope][key] = syncGateEntryInternal{digest: sha256.Sum256(body), sentAt: time.Now()}- }, nil-}--// Forget drops every remembered payload for scope so the next sync resends,-// and discards the outcome of deliveries still in flight for it.-func (g *SyncGate) Forget(scope string) {- g.mu.Lock()- defer g.mu.Unlock()- delete(g.sent, scope)- if g.epochs == nil {- g.epochs = make(map[string]uint64)- }- g.epochs[scope]++-}diff --git a/backend/pkg/utils/handlerutil/handlerutil.go b/backend/pkg/utils/handlerutil/handlerutil.goindex 6dd5e580a..667e6c334 100644--- a/backend/pkg/utils/handlerutil/handlerutil.go+++ b/backend/pkg/utils/handlerutil/handlerutil.go@@ -1,8 +1,6 @@package handlerutilimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/common"-"context""encoding/json/v2""fmt"@@ -12,11 +10,12 @@ import ("strings""github.com/danielgtaylor/huma/v2"+ "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper""github.com/getarcaneapp/arcane/types/v2/auth""github.com/getarcaneapp/arcane/types/v2/base"+ "go.getarcane.app/kit/pkg/mapping")// Out is the huma response envelope for endpoints returning base.ApiResponse[T].@@ -173,8 +172,8 @@ func CurrentActor(ctx context.Context) common.User {return actor}-func MapOneAPIResponse[S any, D any](source S, mappingMessage func(error) string) (base.ApiResponse[D], error) {- out, err := mapper.MapOne[S, D](source)+func MapOneAPIResponse[S, D any](source S, mappingMessage func(error) string) (base.ApiResponse[D], error) {+ out, err := mapping.MapOne[S, D](source)if err != nil {return base.ApiResponse[D]{}, huma.Error500InternalServerError(mappingMessage(err))}diff --git a/backend/pkg/utils/httpx/base_url.go b/backend/pkg/utils/httpx/base_url.goindex 5353090ca..b6f90766d 100644--- a/backend/pkg/utils/httpx/base_url.go+++ b/backend/pkg/utils/httpx/base_url.go@@ -4,6 +4,8 @@ import ("net""net/url""strings"++ kit "go.getarcane.app/kit/pkg")// NormalizeBaseURL validates an outbound HTTP URL and strips endpoint-specific components.@@ -49,11 +51,7 @@ func ManagerGRPCAddr(rawURL string) string {port := parsed.Port()if port == "" {- if strings.EqualFold(parsed.Scheme, "https") {- port = "443"- } else {- port = "80"- }+ port = kit.Ternary(strings.EqualFold(parsed.Scheme, "https"), "443", "80")}return net.JoinHostPort(host, port)diff --git a/backend/pkg/utils/httpx/request.go b/backend/pkg/utils/httpx/request.goindex 024578316..d11c3b962 100644--- a/backend/pkg/utils/httpx/request.go+++ b/backend/pkg/utils/httpx/request.go@@ -1,6 +1,7 @@package httpximport (+ "cmp""fmt""net/http""net/url"@@ -11,7 +12,7 @@ import ()type HeaderSetter interface {- SetHeader(key string, value string)+ SetHeader(key, value string)}func SetJSONStreamHeaders(headers HeaderSetter) {@@ -54,11 +55,7 @@ func ValidateWebSocketOrigin(appURL string) func(r *http.Request) bool {return true}- if isLocalhost(originURL.Host) && isLocalhost(r.Host) {- return true- }-- return false+ return isLocalhost(originURL.Host) && isLocalhost(r.Host)}}@@ -124,9 +121,7 @@ func GetClientBaseURL(origin, forwardedHost, forwardedProto, host, appURL stringscheme = u.Scheme}- if forwardedProto != "" {- scheme = forwardedProto- }+ scheme = cmp.Or(forwardedProto, scheme)// 2. Check X-Forwarded-Hostif forwardedHost != "" {diff --git a/backend/pkg/utils/httpx/request_test.go b/backend/pkg/utils/httpx/request_test.goindex bb0650267..a75e547c6 100644--- a/backend/pkg/utils/httpx/request_test.go+++ b/backend/pkg/utils/httpx/request_test.go@@ -36,7 +36,6 @@ func TestIsWebSocketUpgradeRequest(t *testing.T) {assert.Equal(t, tt.want, got,"IsWebSocketUpgradeRequest() = %v, want %v", got, tt.want)}-})}}diff --git a/backend/pkg/utils/httpx/safe_remote.go b/backend/pkg/utils/httpx/safe_remote.goindex fb5226f6f..fff398de9 100644--- a/backend/pkg/utils/httpx/safe_remote.go+++ b/backend/pkg/utils/httpx/safe_remote.go@@ -10,7 +10,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/backend/v2/internal/common")diff --git a/backend/pkg/utils/iconcatalog/iconcatalog.go b/backend/pkg/utils/iconcatalog/iconcatalog.goindex 96904adae..3cc4923f4 100644--- a/backend/pkg/utils/iconcatalog/iconcatalog.go+++ b/backend/pkg/utils/iconcatalog/iconcatalog.go@@ -2,9 +2,12 @@package iconcatalogimport (+ "cmp""fmt""net/url""strings"++ kit "go.getarcane.app/kit/pkg")const (@@ -30,18 +33,6 @@ func (s IconSet) IsEmpty() bool {strings.TrimSpace(s.Dark) == ""}-// FirstNonEmpty returns the first set that defines any icon value. Levels are-// isolated: a set that defines one variant never inherits the others from-// lower-precedence sets.-func FirstNonEmpty(sets ...IconSet) IconSet {- for _, set := range sets {- if !set.IsEmpty() {- return set- }- }- return IconSet{}-}-func Resolve(catalog string, set IconSet) ResolvedIconSet {selectedCatalog := Normalize(catalog)if strings.TrimSpace(set.Light) == "" && strings.TrimSpace(set.Dark) == "" {@@ -52,8 +43,8 @@ func Resolve(catalog string, set IconSet) ResolvedIconSet {}}- light := firstNonEmptyValueInternal(set.Light, set.Icon, set.Dark)- dark := firstNonEmptyValueInternal(set.Dark, set.Icon, set.Light)+ light := cmp.Or(kit.TrimNonEmpty([]string{set.Light, set.Icon, set.Dark})...)+ dark := cmp.Or(kit.TrimNonEmpty([]string{set.Dark, set.Icon, set.Light})...)return ResolvedIconSet{IconLightURL: resolveValueInternal(selectedCatalog, light, "light"),@@ -61,15 +52,6 @@ func Resolve(catalog string, set IconSet) ResolvedIconSet {}}-func firstNonEmptyValueInternal(values ...string) string {- for _, v := range values {- if trimmed := strings.TrimSpace(v); trimmed != "" {- return trimmed- }- }- return ""-}-// Normalize maps a raw catalog preference onto one of the known catalog// constants, falling back to the default for unknown values.func Normalize(catalog string) string {diff --git a/backend/pkg/utils/iconcatalog/iconcatalog_test.go b/backend/pkg/utils/iconcatalog/iconcatalog_test.goindex 350c35f83..8586e5e82 100644--- a/backend/pkg/utils/iconcatalog/iconcatalog_test.go+++ b/backend/pkg/utils/iconcatalog/iconcatalog_test.go@@ -6,14 +6,6 @@ import ("github.com/stretchr/testify/require")-func TestFirstNonEmpty_LevelIsolation(t *testing.T) {- containerSet := IconSet{Light: "postgres"}- projectSet := IconSet{Light: "umami", Dark: "umami"}-- require.Equal(t, containerSet, FirstNonEmpty(containerSet, IconSet{}, projectSet))- require.Equal(t, projectSet, FirstNonEmpty(IconSet{}, IconSet{}, projectSet))-}-func TestResolve_SingleVariantFallsBackWithinLevel(t *testing.T) {resolved := Resolve(CatalogSelfhst, IconSet{Light: "postgres"})require.Equal(t, "https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/postgres-light.svg", resolved.IconLightURL)diff --git a/backend/pkg/utils/image/image_util.go b/backend/pkg/utils/image/image_util.godeleted file mode 100644index 378e89928..000000000--- a/backend/pkg/utils/image/image_util.go+++ /dev/null@@ -1,24 +0,0 @@-package image--func GetImageMimeType(ext string) string {- switch ext {- case "jpg", "jpeg":- return "image/jpeg"- case "png":- return "image/png"- case "svg":- return "image/svg+xml"- case "ico":- return "image/x-icon"- case "gif":- return "image/gif"- case "webp":- return "image/webp"- case "avif":- return "image/avif"- case "heic":- return "image/heic"- default:- return ""- }-}diff --git a/backend/pkg/utils/imageref/update_lookup.go b/backend/pkg/utils/imageref/update_lookup.goindex b981a0f07..493c4eefb 100644--- a/backend/pkg/utils/imageref/update_lookup.go+++ b/backend/pkg/utils/imageref/update_lookup.go@@ -2,22 +2,27 @@package imagerefimport (+ "cmp""fmt""strings"+ ref "github.com/distribution/reference"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"+ kit "go.getarcane.app/kit/pkg""go.getarcane.app/updater""go.getarcane.app/updater/pkg/utils/tagpolicy""go.getarcane.app/updater/refs"-- ref "github.com/distribution/reference"- "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils")-// UpdateCheckLabel opts a container or service out of update checks and-// notifications. Automatic installation is governed separately by the-// updater label and the UI exclusion list.-const UpdateCheckLabel = "com.getarcaneapp.arcane.update-check"+const (+ // UpdateCheckLabel opts a container or service out of update checks and+ // notifications. Automatic installation is governed separately by the+ // updater label and the UI exclusion list.+ UpdateCheckLabel = "com.getarcaneapp.arcane.update-check"++ // LocalBuildRegistry is Arcane's reserved registry host for locally built image tags.+ LocalBuildRegistry = "arcane.local"+)// IsUpdateCheckDisabled reports whether labels opt the resource out of update// monitoring. Checks stay enabled unless the value parses as false.@@ -36,13 +41,10 @@ func IsUpdateCheckDisabled(labels map[string]string) bool {if !ok {return false}- enabled, parsed := utils.ParseBool(value)+ enabled, parsed := kit.ParseBool(value)return parsed && !enabled}-// LocalBuildRegistry is Arcane's reserved registry host for locally built image tags.-const LocalBuildRegistry = "arcane.local"-// ParseUpdateLookup normalizes an image reference into the repository and tag// candidates used to match persisted update records.func ParseUpdateLookup(imageRef string) (originalRef, tag string, repositoryCandidates map[string]struct{}, ok bool) {@@ -60,9 +62,7 @@ func ParseUpdateLookup(imageRef string) (originalRef, tag string, repositoryCandif tagged, taggedOK := named.(ref.NamedTagged); taggedOK {tag = strings.TrimSpace(tagged.Tag())}- if tag == "" {- tag = "latest"- }+ tag = cmp.Or(tag, "latest")registryHost := registryauth.NormalizeRegistryForComparison(ref.Domain(named))repositoryPath := strings.TrimSpace(ref.Path(named))diff --git a/backend/pkg/utils/jwtclaims/jwt.go b/backend/pkg/utils/jwtclaims/jwt.goindex 23c072552..b385c3189 100644--- a/backend/pkg/utils/jwtclaims/jwt.go+++ b/backend/pkg/utils/jwtclaims/jwt.go@@ -5,9 +5,9 @@ import ("maps""strings"- "github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/lestrrat-go/jwx/v4/jwt""github.com/samber/mo"+ kit "go.getarcane.app/kit/pkg")// GetStringClaim extracts a string claim from a map@@ -43,23 +43,6 @@ func GetBoolClaim(m map[string]any, key string) bool {return false}-// StringSliceFromValue flattens a claim value into a slice of strings.-// Accepts string (trimmed, single element), []string, []any (string elements-// only), or nil. Unlike GetStringSliceClaim it never splits a single string-// into multiple values, so it is safe for claims whose values may legally-// contain separators (e.g. aud URIs).-func StringSliceFromValue(v any) []string {- switch t := v.(type) {- case []string:- return stringSliceFromStringsInternal(t)- case []any:- return stringSliceFromInterfacesInternal(t)- case string:- return stringSliceFromStringsInternal([]string{t})- }- return nil-}-// GetStringSliceClaim extracts a string slice claim from a map. A single// string value is split on commas or spaces (group/role claims are commonly// delivered that way).@@ -74,43 +57,12 @@ func GetStringSliceClaim(m map[string]any, key string) []string {return nil}// Support comma or space separated strings- if strings.Contains(s, ",") {- parts := strings.Split(s, ",")- out := make([]string, 0, len(parts))- for _, p := range parts {- if ps := strings.TrimSpace(p); ps != "" {- out = append(out, ps)- }- }- if len(out) > 0 {- return out- }+ if out := kit.TrimNonEmpty(strings.Split(s, ",")); strings.Contains(s, ",") && len(out) > 0 {+ return out}return strings.Fields(s)}- return StringSliceFromValue(v)-}--func stringSliceFromStringsInternal[S ~string](items []S) []string {- out := make([]string, 0, len(items))- for _, item := range items {- if s := strings.TrimSpace(string(item)); s != "" {- out = append(out, s)- }- }- return utils.UniqueNonEmptyStrings(out)-}--func stringSliceFromInterfacesInternal[T any](items []T) []string {- out := make([]string, 0, len(items))- for _, item := range items {- if s, ok := any(item).(string); ok {- if trimmed := strings.TrimSpace(s); trimmed != "" {- out = append(out, trimmed)- }- }- }- return utils.UniqueNonEmptyStrings(out)+ return kit.Unique(kit.TrimNonEmpty(kit.Collect(v, func(item any) string { return kit.As(item, "") })))}// ParseJWTClaims parses unverified JWT metadata for pre-verification routing.diff --git a/backend/pkg/utils/logging/error_handler.go b/backend/pkg/utils/logging/error_handler.goindex 9c9273c55..2a145dfd5 100644--- a/backend/pkg/utils/logging/error_handler.go+++ b/backend/pkg/utils/logging/error_handler.go@@ -8,8 +8,10 @@ import ("emperror.dev/errors")-var _ emperror.ErrorHandler = (*SlogErrorHandler)(nil)-var _ emperror.ErrorHandlerContext = (*SlogErrorHandler)(nil)+var (+ _ emperror.ErrorHandler = (*SlogErrorHandler)(nil)+ _ emperror.ErrorHandlerContext = (*SlogErrorHandler)(nil)+)// SlogErrorHandler reports handled errors through the process slog logger.type SlogErrorHandler struct{}diff --git a/backend/pkg/utils/mapper/mapper.go b/backend/pkg/utils/mapper/mapper.godeleted file mode 100644index 9e398c135..000000000--- a/backend/pkg/utils/mapper/mapper.go+++ /dev/null@@ -1,111 +0,0 @@-package mapper--import (- "fmt"- "net/netip"- "strings"-- "emperror.dev/errors"- "github.com/jinzhu/copier"-)--var typeConverters = []copier.TypeConverter{- {- SrcType: "",- DstType: netip.Prefix{},- Fn: func(src any) (any, error) {- raw, ok := src.(string)- if !ok {- return nil, fmt.Errorf("expected string, got %T", src)- }- if strings.TrimSpace(raw) == "" {- return netip.Prefix{}, nil- }-- return netip.ParsePrefix(strings.TrimSpace(raw))- },- },- {- SrcType: "",- DstType: netip.Addr{},- Fn: func(src any) (any, error) {- raw, ok := src.(string)- if !ok {- return nil, fmt.Errorf("expected string, got %T", src)- }- if strings.TrimSpace(raw) == "" {- return netip.Addr{}, nil- }-- return netip.ParseAddr(strings.TrimSpace(raw))- },- },- {- SrcType: netip.Prefix{},- DstType: "",- Fn: func(src any) (any, error) {- prefix, ok := src.(netip.Prefix)- if !ok {- return nil, fmt.Errorf("expected netip.Prefix, got %T", src)- }- if !prefix.IsValid() {- return "", nil- }-- return prefix.String(), nil- },- },- {- SrcType: netip.Addr{},- DstType: "",- Fn: func(src any) (any, error) {- addr, ok := src.(netip.Addr)- if !ok {- return nil, fmt.Errorf("expected netip.Addr, got %T", src)- }- if !addr.IsValid() {- return "", nil- }-- return addr.String(), nil- },- },-}--func MapSlice[S any, D any](source []S) ([]D, error) {- dest := make([]D, len(source))- for i := range source {- if err := MapStruct(source[i], &dest[i]); err != nil {- return nil, errors.WrapIff(err, "failed to map field %d", i)- }- }- return dest, nil-}--func MapOne[S any, D any](source S) (D, error) {- var dest D- if err := MapStruct(source, &dest); err != nil {- return dest, err- }- return dest, nil-}--func MapStruct[S any, D any](source S, destination *D) error {- return copier.CopyWithOption(destination, source, copier.Option{- DeepCopy: true,- Converters: typeConverters,- })-}--// MapStructList maps a list of source structs to a list of destination structs-func MapStructList[S any, D any](source []S, destination *[]D) (err error) {- *destination = make([]D, len(source))-- for i, item := range source {- err = MapStruct(item, &((*destination)[i]))- if err != nil {- return errors.WrapIff(err, "failed to map field %d", i)- }- }- return nil-}diff --git a/backend/pkg/utils/mapper/mapper_test.go b/backend/pkg/utils/mapper/mapper_test.godeleted file mode 100644index b3260d6e4..000000000--- a/backend/pkg/utils/mapper/mapper_test.go+++ /dev/null@@ -1,42 +0,0 @@-package mapper--import (- "net/netip"- "testing"-- networktypes "github.com/getarcaneapp/arcane/types/v2/network"- dockernetwork "github.com/moby/moby/api/types/network"- "github.com/stretchr/testify/require"-)--func TestMapOneConvertsNetworkIPAMConfigInternal(t *testing.T) {- source := dockernetwork.Inspect{- IPAM: dockernetwork.IPAM{- Driver: "default",- Config: []dockernetwork.IPAMConfig{- {- Subnet: netip.MustParsePrefix("172.16.5.0/24"),- Gateway: netip.MustParseAddr("172.16.5.1"),- AuxAddress: map[string]netip.Addr{- "dns": netip.MustParseAddr("172.16.5.53"),- "unset": {},- },- },- },- },- }-- mapped, err := MapOne[dockernetwork.Inspect, networktypes.Inspect](source)- require.NoError(t, err)- require.Equal(t, "default", mapped.IPAM.Driver)- require.Len(t, mapped.IPAM.Config, 1)-- config := mapped.IPAM.Config[0]- require.Equal(t, "172.16.5.0/24", config.Subnet)- require.Equal(t, "172.16.5.1", config.Gateway)- require.Empty(t, config.IPRange)- require.Equal(t, map[string]string{- "dns": "172.16.5.53",- "unset": "",- }, config.AuxAddress)-}diff --git a/backend/pkg/utils/netutils/compare.go b/backend/pkg/utils/netutils/compare.godeleted file mode 100644index 09a18fbce..000000000--- a/backend/pkg/utils/netutils/compare.go+++ /dev/null@@ -1,57 +0,0 @@-package netutils--import (- "bytes"- "cmp"- "net"- "strings"-)--// CompareAddresses orders IP address strings numerically, ignoring any CIDR suffix.-// Empty values sort first and malformed values last in string order.-func CompareAddresses(a, b string) int {- if a == "" || b == "" {- return strings.Compare(a, b)- }-- hostA, _, _ := strings.Cut(a, "/")- hostB, _, _ := strings.Cut(b, "/")- ipA := net.ParseIP(hostA)- ipB := net.ParseIP(hostB)-- switch {- case ipA != nil && ipB != nil:- return bytes.Compare(ipA.To16(), ipB.To16())- case ipA != nil:- return -1- case ipB != nil:- return 1- }- return strings.Compare(a, b)-}--// CompareSubnets orders CIDR strings by masked network address, then prefix length.-// Empty values sort first and malformed values last in string order.-func CompareSubnets(a, b string) int {- if a == "" || b == "" {- return strings.Compare(a, b)- }-- _, netA, errA := net.ParseCIDR(a)- _, netB, errB := net.ParseCIDR(b)-- switch {- case errA == nil && errB == nil:- if c := bytes.Compare(netA.IP.To16(), netB.IP.To16()); c != 0 {- return c- }- onesA, bitsA := netA.Mask.Size()- onesB, bitsB := netB.Mask.Size()- return cmp.Compare(onesA+128-bitsA, onesB+128-bitsB)- case errA == nil:- return -1- case errB == nil:- return 1- }- return strings.Compare(a, b)-}diff --git a/backend/pkg/utils/notifications/config.go b/backend/pkg/utils/notifications/config.goindex 7bef0cbb9..21bf28220 100644--- a/backend/pkg/utils/notifications/config.go+++ b/backend/pkg/utils/notifications/config.go@@ -14,6 +14,22 @@ const (NotificationProviderMatrix NotificationProvider = "matrix"NotificationProviderGoogleChat NotificationProvider = "googlechat"NotificationProviderGeneric NotificationProvider = "generic"++ NotificationEventImageUpdate NotificationEventType = "image_update"+ NotificationEventContainerUpdate NotificationEventType = "container_update"+ NotificationEventVulnerabilityFound NotificationEventType = "vulnerability_found"+ NotificationEventPruneReport NotificationEventType = "prune_report"+ NotificationEventAutoHeal NotificationEventType = "auto_heal"++ EmailTLSModeNone EmailTLSMode = "none"+ EmailTLSModeStartTLS EmailTLSMode = "starttls"+ EmailTLSModeSSL EmailTLSMode = "ssl"++ EmailAuthModeNone EmailAuthMode = "none"+ EmailAuthModeAuto EmailAuthMode = "auto"+ EmailAuthModePlain EmailAuthMode = "plain"+ EmailAuthModeLogin EmailAuthMode = "login"+ EmailAuthModeCRAMMD5 EmailAuthMode = "crammd5")var validNotificationProviders = map[NotificationProvider]struct{}{@@ -37,14 +53,6 @@ func IsValidNotificationProvider(provider NotificationProvider) bool {type NotificationEventType string-const (- NotificationEventImageUpdate NotificationEventType = "image_update"- NotificationEventContainerUpdate NotificationEventType = "container_update"- NotificationEventVulnerabilityFound NotificationEventType = "vulnerability_found"- NotificationEventPruneReport NotificationEventType = "prune_report"- NotificationEventAutoHeal NotificationEventType = "auto_heal"-)-var AllNotificationEventTypes = []NotificationEventType{NotificationEventImageUpdate,NotificationEventContainerUpdate,@@ -55,22 +63,8 @@ var AllNotificationEventTypes = []NotificationEventType{type EmailTLSMode string-const (- EmailTLSModeNone EmailTLSMode = "none"- EmailTLSModeStartTLS EmailTLSMode = "starttls"- EmailTLSModeSSL EmailTLSMode = "ssl"-)-type EmailAuthMode string-const (- EmailAuthModeNone EmailAuthMode = "none"- EmailAuthModeAuto EmailAuthMode = "auto"- EmailAuthModePlain EmailAuthMode = "plain"- EmailAuthModeLogin EmailAuthMode = "login"- EmailAuthModeCRAMMD5 EmailAuthMode = "crammd5"-)-type DiscordConfig struct {WebhookID string `json:"webhookId"`Token string `json:"token"`diff --git a/backend/pkg/utils/notifications/config_credentials.go b/backend/pkg/utils/notifications/config_credentials.goindex 8896b95b0..6e0133f9e 100644--- a/backend/pkg/utils/notifications/config_credentials.go+++ b/backend/pkg/utils/notifications/config_credentials.go@@ -1,14 +1,12 @@package notificationsimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"encoding/base64""encoding/json/v2""log/slog""emperror.dev/errors"-+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""go.getarcane.app/sys/crypto")diff --git a/backend/pkg/utils/notifications/deliver.go b/backend/pkg/utils/notifications/deliver.goindex fb7b9ebff..19c594a1c 100644--- a/backend/pkg/utils/notifications/deliver.go+++ b/backend/pkg/utils/notifications/deliver.go@@ -1,12 +1,12 @@package notificationsimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-+ "cmp""context""net/mail""emperror.dev/errors"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database")// Content is the provider-independent description of one notification: the@@ -132,9 +132,7 @@ func deliverTelegram(ctx context.Context, config database.JSON, c Content) errorif err := DecryptStringCredential(&telegramConfig.BotToken); err != nil {return err}- if telegramConfig.ParseMode == "" {- telegramConfig.ParseMode = "HTML"- }+ telegramConfig.ParseMode = cmp.Or(telegramConfig.ParseMode, "HTML")if err := SendTelegram(ctx, telegramConfig, c.Text[MessageFormatHTML]); err != nil {return errors.WrapIf(err, "failed to send Telegram notification")}diff --git a/backend/pkg/utils/notifications/deliver_test.go b/backend/pkg/utils/notifications/deliver_test.goindex a57af7138..c6142d4fc 100644--- a/backend/pkg/utils/notifications/deliver_test.go+++ b/backend/pkg/utils/notifications/deliver_test.go@@ -1,11 +1,10 @@package notificationsimport (- "github.com/getarcaneapp/arcane/backend/v2/internal/database"-"context""testing"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/stretchr/testify/require")diff --git a/backend/pkg/utils/notifications/discord_sender.go b/backend/pkg/utils/notifications/discord_sender.goindex 3bc4ec161..0face41c8 100644--- a/backend/pkg/utils/notifications/discord_sender.go+++ b/backend/pkg/utils/notifications/discord_sender.go@@ -4,7 +4,6 @@ import ("context""emperror.dev/errors"-"github.com/nicholas-fedor/shoutrrr/pkg/services/chat/discord")diff --git a/backend/pkg/utils/notifications/email_sender.go b/backend/pkg/utils/notifications/email_sender.goindex abcc87a33..b924aa48d 100644--- a/backend/pkg/utils/notifications/email_sender.go+++ b/backend/pkg/utils/notifications/email_sender.go@@ -6,8 +6,8 @@ import ("time""emperror.dev/errors"-"github.com/wneessen/go-mail"+ kit "go.getarcane.app/kit/pkg")const (@@ -21,11 +21,7 @@ type smtpBuildOptions struct {}func smtpTimeoutFromOptionsInternal(options smtpBuildOptions) time.Duration {- if options.timeout > 0 {- return options.timeout- }-- return defaultSMTPTimeout+ return kit.Ternary(options.timeout > 0, options.timeout, defaultSMTPTimeout)}func smtpBuildOptionsFromContextInternal(ctx context.Context) smtpBuildOptions {diff --git a/backend/pkg/utils/notifications/email_sender_test.go b/backend/pkg/utils/notifications/email_sender_test.goindex a51c0b6ee..7bbedb4d6 100644--- a/backend/pkg/utils/notifications/email_sender_test.go+++ b/backend/pkg/utils/notifications/email_sender_test.go@@ -23,6 +23,7 @@ import ("github.com/stretchr/testify/assert""github.com/stretchr/testify/require"+ kit "go.getarcane.app/kit/pkg")const (@@ -196,10 +197,7 @@ func (s *smtpTestServer) ClientTLSConfig() *tls.Config {func (s *smtpTestServer) Wait() error {select {case err := <-s.done:- if err != nil && (isUseOfClosedNetworkConnInternal(err) || isConnectionTimeoutInternal(err)) {- return nil- }- return err+ return kit.Ternary(err != nil && (isUseOfClosedNetworkConnInternal(err) || isConnectionTimeoutInternal(err)), nil, err)case <-time.After(4 * time.Second):return fmt.Errorf("timed out waiting for SMTP test server")}@@ -272,10 +270,7 @@ func (s *smtpTestServer) handleConnection(conn net.Conn) error {for {line, err := reader.ReadLine()if err != nil {- if err == io.EOF {- return nil- }- return err+ return kit.Ternary(err == io.EOF, nil, err)}verb, rest, _ := strings.Cut(line, " ")diff --git a/backend/pkg/utils/notifications/generic_sender.go b/backend/pkg/utils/notifications/generic_sender.goindex af2824840..5f6081d4c 100644--- a/backend/pkg/utils/notifications/generic_sender.go+++ b/backend/pkg/utils/notifications/generic_sender.go@@ -2,6 +2,7 @@ package notificationsimport ("bytes"+ "cmp""context""encoding/json/jsontext""encoding/json/v2"@@ -14,9 +15,9 @@ import ("time""emperror.dev/errors"-"github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"+ kit "go.getarcane.app/kit/pkg")// genericPayloadTemplateID is the Shoutrrr template ID under which a user's@@ -45,10 +46,7 @@ func resolveWebhookURLInternal(config GenericConfig) (*url.URL, error) {hasScheme := strings.Contains(config.WebhookURL, "://")if parsed.Host == "" && !hasScheme {- scheme := "https"- if config.DisableTLS {- scheme = "http"- }+ scheme := kit.Ternary(config.DisableTLS, "http", "https")normalized := strings.TrimPrefix(config.WebhookURL, "//")parsed, err = url.Parse(fmt.Sprintf("%s://%s", scheme, normalized))if err != nil {@@ -177,14 +175,8 @@ func jsonEscapeString(value string) string {// under the configured titlekey/messagekey β mirroring how Shoutrrr's// createSendParams keys the send params β plus the escaped per-event vars.func genericTemplateDataInternal(config GenericConfig, title, message string, vars map[string]string) map[string]string {- titleKey := config.TitleKey- if titleKey == "" {- titleKey = "title"- }- messageKey := config.MessageKey- if messageKey == "" {- messageKey = "message"- }+ titleKey := cmp.Or(config.TitleKey, "title")+ messageKey := cmp.Or(config.MessageKey, "message")data := make(map[string]string, len(vars)+2)for key, value := range vars {@@ -288,9 +280,7 @@ func SendGenericWithTitle(ctx context.Context, config GenericConfig, title, mess// Build params with title. Always use "title" as the param key β Shoutrrr's// generic service maps it to the configured titlekey in the JSON payload.params := shoutrrrTypes.Params{}- if title != "" {- params["title"] = title- }+ params["title"] = cmp.Or(title, params["title"])errs := sender.Send(message, ¶ms)for _, err := range errs {@@ -372,19 +362,11 @@ func sendGenericDirectInternal(ctx context.Context, config GenericConfig, title,body = []byte(rendered)} else {// Build JSON payload using the configured message/title keys.- msgKey := config.MessageKey- if msgKey == "" {- msgKey = "message"- }- titleKey := config.TitleKey- if titleKey == "" {- titleKey = "title"- }+ msgKey := cmp.Or(config.MessageKey, "message")+ titleKey := cmp.Or(config.TitleKey, "title")payload := map[string]string{msgKey: message}- if title != "" {- payload[titleKey] = title- }+ payload[titleKey] = cmp.Or(title, payload[titleKey])body, err = json.Marshal(payload)if err != nil {@@ -392,20 +374,14 @@ func sendGenericDirectInternal(ctx context.Context, config GenericConfig, title,}}- method := strings.ToUpper(config.Method)- if method == "" {- method = http.MethodPost- }+ method := cmp.Or(strings.ToUpper(config.Method), http.MethodPost)req, err := http.NewRequestWithContext(ctx, method, webhookURL.String(), bytes.NewReader(body))if err != nil {return errors.WrapIf(err, "failed to create webhook request")}- contentType := config.ContentType- if contentType == "" {- contentType = "application/json"- }+ contentType := cmp.Or(config.ContentType, "application/json")req.Header.Set("Content-Type", contentType)for k, v := range config.CustomHeaders {diff --git a/backend/pkg/utils/notifications/googlechat_sender.go b/backend/pkg/utils/notifications/googlechat_sender.goindex b38f9c022..0523f86c8 100644--- a/backend/pkg/utils/notifications/googlechat_sender.go+++ b/backend/pkg/utils/notifications/googlechat_sender.go@@ -6,7 +6,6 @@ import ("strings""emperror.dev/errors"-shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")diff --git a/backend/pkg/utils/notifications/gotify_sender.go b/backend/pkg/utils/notifications/gotify_sender.goindex 1414cf9d5..85e5d5996 100644--- a/backend/pkg/utils/notifications/gotify_sender.go+++ b/backend/pkg/utils/notifications/gotify_sender.go@@ -8,7 +8,6 @@ import ("strings""emperror.dev/errors"-shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")diff --git a/backend/pkg/utils/notifications/matrix_sender.go b/backend/pkg/utils/notifications/matrix_sender.goindex fe0717eb0..6f7adb38c 100644--- a/backend/pkg/utils/notifications/matrix_sender.go+++ b/backend/pkg/utils/notifications/matrix_sender.go@@ -7,7 +7,6 @@ import ("strings""emperror.dev/errors"-shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")diff --git a/backend/pkg/utils/notifications/messages.go b/backend/pkg/utils/notifications/messages.goindex d2450bfbe..82e8318b2 100644--- a/backend/pkg/utils/notifications/messages.go+++ b/backend/pkg/utils/notifications/messages.go@@ -2,11 +2,14 @@ package notificationsimport ("fmt"+ "maps"+ "slices""sort""strings""github.com/getarcaneapp/arcane/types/v2/imageupdate""github.com/getarcaneapp/arcane/types/v2/system"+ kit "go.getarcane.app/kit/pkg")type MessageFormat string@@ -62,10 +65,7 @@ func formatNotificationCodeInternal(format MessageFormat, value string) string {}func BuildImageUpdateNotificationMessage(format MessageFormat, environmentName, imageRef string, updateInfo *imageupdate.Response) string {- updateStatus := "No Update"- if updateInfo != nil && updateInfo.HasUpdate {- updateStatus = "Update Available"- }+ updateStatus := kit.Ternary(updateInfo != nil && updateInfo.HasUpdate, "Update Available", "No Update")if format != MessageFormatPlain && updateStatus == "Update Available" {updateStatus = "β οΈ Update Available"}@@ -89,10 +89,7 @@ func BuildImageUpdateNotificationMessage(format MessageFormat, environmentName,}func BuildContainerUpdateNotificationMessage(format MessageFormat, environmentName, containerName, imageRef, oldDigest, newDigest string) string {- status := "Updated Successfully"- if format != MessageFormatPlain {- status = "β Updated Successfully"- }+ status := kit.Ternary(format != MessageFormatPlain, "β Updated Successfully", "Updated Successfully")var message strings.Builderfmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "β Container Successfully Updated"))@@ -118,11 +115,7 @@ func BuildBatchImageUpdateNotificationMessage(format MessageFormat, environmentNdescription = "1 container image has an update available."}- imageRefs := make([]string, 0, len(updates))- for imageRef := range updates {- imageRefs = append(imageRefs, imageRef)- }- sort.Strings(imageRefs)+ imageRefs := slices.Sorted(maps.Keys(updates))var message strings.Builderfmt.Fprintf(&message, "%s\n\n%s\n", formatNotificationTitleInternal(format, title), description)diff --git a/backend/pkg/utils/notifications/ntfy_sender.go b/backend/pkg/utils/notifications/ntfy_sender.goindex d8d3187dd..9c33cbc20 100644--- a/backend/pkg/utils/notifications/ntfy_sender.go+++ b/backend/pkg/utils/notifications/ntfy_sender.go@@ -1,13 +1,13 @@package notificationsimport (+ "cmp""context""fmt""net/url""strings""emperror.dev/errors"-shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -19,10 +19,7 @@ func BuildNtfyURL(config NtfyConfig) (string, error) {}// Default host to ntfy.sh if not specified- host := config.Host- if host == "" {- host = "ntfy.sh"- }+ host := cmp.Or(config.Host, "ntfy.sh")// Build the base URLu := &url.URL{diff --git a/backend/pkg/utils/notifications/signal_sender.go b/backend/pkg/utils/notifications/signal_sender.goindex 031843d9d..2a8bad9eb 100644--- a/backend/pkg/utils/notifications/signal_sender.go+++ b/backend/pkg/utils/notifications/signal_sender.go@@ -4,7 +4,6 @@ import ("context""emperror.dev/errors"-"github.com/nicholas-fedor/shoutrrr/pkg/services/chat/signal")diff --git a/backend/pkg/utils/notifications/slack_sender.go b/backend/pkg/utils/notifications/slack_sender.goindex a0b2b2f48..46c2c14f7 100644--- a/backend/pkg/utils/notifications/slack_sender.go+++ b/backend/pkg/utils/notifications/slack_sender.go@@ -4,7 +4,6 @@ import ("context""emperror.dev/errors"-"github.com/nicholas-fedor/shoutrrr/pkg/services/chat/slack")diff --git a/backend/pkg/utils/notifications/telegram_sender.go b/backend/pkg/utils/notifications/telegram_sender.goindex bbd7addba..df878205c 100644--- a/backend/pkg/utils/notifications/telegram_sender.go+++ b/backend/pkg/utils/notifications/telegram_sender.go@@ -4,7 +4,6 @@ import ("context""emperror.dev/errors"-"github.com/nicholas-fedor/shoutrrr/pkg/services/chat/telegram")diff --git a/backend/pkg/utils/oidcjwk/oidcjwk_test.go b/backend/pkg/utils/oidcjwk/oidcjwk_test.goindex 117dc3554..3b5336a35 100644--- a/backend/pkg/utils/oidcjwk/oidcjwk_test.go+++ b/backend/pkg/utils/oidcjwk/oidcjwk_test.go@@ -64,12 +64,16 @@ func TestKeySetVerifySignature(t *testing.T) {if tc.initialFailure == "http" {w.WriteHeader(http.StatusServiceUnavailable)} else {- fmt.Fprint(w, `{"keys":`)+ if _, err := fmt.Fprint(w, `{"keys":`); err != nil {+ t.Errorf("write malformed JWKS response: %v", err)+ }}return}w.Header().Set("Content-Type", "application/json")- fmt.Fprint(w, jwks)+ if _, err := fmt.Fprint(w, jwks); err != nil {+ t.Errorf("write JWKS response: %v", err)+ }}))defer srv.Close()diff --git a/backend/pkg/utils/path_util.go b/backend/pkg/utils/path_util.godeleted file mode 100644index 505ec6c8a..000000000--- a/backend/pkg/utils/path_util.go+++ /dev/null@@ -1,123 +0,0 @@-package utils--import (- "hash"- "io"- "net/url"- "path"- "path/filepath"- "strconv"- "strings"-- "emperror.dev/errors"-)--// SQLitePathFromDSN returns the filesystem portion of a SQLite file DSN.-// For "file:data/arcane.db?..." the path is carried in Opaque; for-// "file:/abs/path.db" it is in Path. In-memory DSNs yield ":memory:" or "".-func SQLitePathFromDSN(dsn string) (string, error) {- parsed, err := url.Parse(dsn)- if err != nil {- return "", err- }- if parsed.Opaque != "" {- return parsed.Opaque, nil- }- return parsed.Path, nil-}--// NormalizeRelativePath validates and normalizes a slash-delimited path rooted-// at a managed file tree. The returned path never begins with a slash.-func NormalizeRelativePath(input string) (string, error) {- trimmed := strings.TrimSpace(input)- if trimmed == "" {- return "", errors.New("path is required")- }- if strings.ContainsRune(trimmed, 0) {- return "", errors.New("path contains a null byte")- }- if strings.Contains(trimmed, "\\") {- return "", errors.New("path must use forward slashes")- }- if path.IsAbs(trimmed) || filepath.IsAbs(trimmed) {- return "", errors.New("absolute paths are not allowed")- }-- cleaned := path.Clean(trimmed)- if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") {- return "", errors.New("path traversal is not allowed")- }- for segment := range strings.SplitSeq(cleaned, "/") {- if segment == "" || segment == "." || segment == ".." {- return "", errors.New("path contains an invalid segment")- }- }-- return cleaned, nil-}--// ValidateFileName validates a single file-tree path segment.-func ValidateFileName(name string) (string, error) {- trimmed := strings.TrimSpace(name)- if trimmed == "" {- return "", errors.New("name is required")- }- if strings.ContainsRune(trimmed, 0) {- return "", errors.New("name contains a null byte")- }- if strings.Contains(trimmed, "/") || strings.Contains(trimmed, "\\") {- return "", errors.New("name must not contain path separators")- }- if filepath.VolumeName(trimmed) != "" {- return "", errors.New("name must not contain a volume prefix")- }- if trimmed == "." || trimmed == ".." || filepath.Base(trimmed) != trimmed {- return "", errors.New("invalid name")- }- return trimmed, nil-}--func FilePathMatches(relativePath, rootPath string) bool {- return relativePath == rootPath || strings.HasPrefix(relativePath, rootPath+"/")-}--func WriteFileTreeRevisionEntry(h hash.Hash, relativePath, kind string, size, modTimeUnixNano int64, mode string, protected bool) {- protectedFlag := ""- if protected {- protectedFlag = "protected"- }- entry := strings.Join([]string{- relativePath,- kind,- strconv.FormatInt(size, 10),- strconv.FormatInt(modTimeUnixNano, 10),- mode,- protectedFlag,- }, "\x00")- _, _ = io.WriteString(h, entry)- _, _ = h.Write([]byte{'\n'})-}--// SanitizeBrowsePath normalizes a path within a rooted file browser.-func SanitizeBrowsePath(input string) (string, error) {- trimmed := strings.TrimSpace(input)- if trimmed == "" || trimmed == "/" {- return "/", nil- }-- cleaned := path.Clean(trimmed)- if cleaned == ".." || strings.HasPrefix(cleaned, "../") {- return "", errors.New("invalid path: path traversal not allowed")- }- if !path.IsAbs(cleaned) {- cleaned = path.Clean("/" + cleaned)- }- if strings.Contains(cleaned, "/../") || strings.HasSuffix(cleaned, "/..") || cleaned == "/.." {- return "", errors.New("invalid path: path traversal not allowed")- }- if !strings.HasPrefix(cleaned, "/") {- return "", errors.New("invalid path: must be absolute")- }-- return cleaned, nil-}diff --git a/backend/pkg/utils/path_util_test.go b/backend/pkg/utils/path_util_test.godeleted file mode 100644index 68ca74a37..000000000--- a/backend/pkg/utils/path_util_test.go+++ /dev/null@@ -1,65 +0,0 @@-package utils--import (- "crypto/sha256"- "encoding/hex"- "testing"-- "github.com/stretchr/testify/require"-)--func TestNormalizeRelativePath(t *testing.T) {- for _, input := range []string{"", "/absolute", "../escape", "folder\\file", "name\x00"} {- _, err := NormalizeRelativePath(input)- require.Error(t, err, input)- }- got, err := NormalizeRelativePath("folder/file.txt")- require.NoError(t, err)- require.Equal(t, "folder/file.txt", got)-}--func TestValidateFileName(t *testing.T) {- for _, input := range []string{"", ".", "..", "folder/name", "folder\\name", "name\x00"} {- _, err := ValidateFileName(input)- require.Error(t, err, input)- }- got, err := ValidateFileName("notes.txt")- require.NoError(t, err)- require.Equal(t, "notes.txt", got)-}--func TestFileTreeRevisionEntryIsStable(t *testing.T) {- h := sha256.New()- WriteFileTreeRevisionEntry(h, "folder/file.txt", "file", 12, 1234, "-rw-r--r--", false)- require.Equal(t, "95f6a8dc033860a753fee2a04a21580d43087967d732a717d3e7a18f88ea4f65", hex.EncodeToString(h.Sum(nil)))-}--func TestSanitizeBrowsePath(t *testing.T) {- tests := []struct {- name string- input string- want string- wantErr bool- }{- {name: "current directory is root", input: ".", want: "/"},- {name: "parent traversal is rejected", input: "..", wantErr: true},- {name: "root stays root", input: "/", want: "/"},- {name: "empty is root", input: "", want: "/"},- {name: "relative path is rooted", input: "a/b", want: "/a/b"},- {name: "absolute path is cleaned", input: "/a/../b", want: "/b"},- {name: "escaping relative traversal is rejected", input: "a/../../../etc", wantErr: true},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- got, err := SanitizeBrowsePath(tt.input)- if tt.wantErr {- require.Error(t, err)- return- }-- require.NoError(t, err)- require.Equal(t, tt.want, got)- })- }-}diff --git a/backend/pkg/utils/s3/s3.go b/backend/pkg/utils/s3/s3.goindex 09c83ccad..04f9813c1 100644--- a/backend/pkg/utils/s3/s3.go+++ b/backend/pkg/utils/s3/s3.go@@ -5,6 +5,7 @@ package s3import ("bytes"+ "cmp""context""fmt""io"@@ -14,7 +15,6 @@ import ("strings""emperror.dev/errors"-"github.com/aws/aws-sdk-go-v2/aws"awsconfig "github.com/aws/aws-sdk-go-v2/config""github.com/aws/aws-sdk-go-v2/credentials"@@ -22,15 +22,15 @@ import ("github.com/aws/smithy-go"backuptypes "github.com/getarcaneapp/arcane/types/v2/backup""github.com/google/uuid"+ kit "go.getarcane.app/kit/pkg")const (RepositoryReasonMissingBucket = "missing_bucket"RepositoryReasonMissingRepository = "missing_repository"+ connectionTestPayload = "arcane-s3-connection-test")-const connectionTestPayload = "arcane-s3-connection-test"-// Configuration contains the credentials and addressing options for an S3 destination.type Configuration struct {ID string@@ -132,10 +132,7 @@ func (c Configuration) EndpointURL() string {return ""}endpoint = strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://")- scheme := "http://"- if c.UseSSL {- scheme = "https://"- }+ scheme := kit.Ternary(c.UseSSL, "https://", "http://")return scheme + strings.TrimRight(endpoint, "/")}@@ -143,10 +140,7 @@ func (c Configuration) EndpointURL() string {func (c Configuration) RusticEnvironment(rootParts ...string) []string {c = c.Normalized()repositoryParts := append([]string{"/", c.Prefix}, rootParts...)- region := c.Region- if region == "" {- region = "auto"- }+ region := cmp.Or(c.Region, "auto")environment := []string{"RUSTIC_REPOSITORY=opendal:s3","RUSTIC_REPO_OPT_BUCKET=" + c.Bucket,@@ -158,7 +152,8 @@ func (c Configuration) RusticEnvironment(rootParts ...string) []string {if endpoint := c.EndpointURL(); endpoint != "" {environment = append(environment, "RUSTIC_REPO_OPT_ENDPOINT="+endpoint)}- environment = append(environment,+ environment = append(+ environment,"RUSTIC_REPO_OPT_REGION="+region,"AWS_REGION="+region,)@@ -299,11 +294,9 @@ func isMissingResourceInternal(err error, codes ...string) bool {}func newClientInternal(ctx context.Context, configuration Configuration) (*awss3.Client, error) {- region := configuration.Region- if region == "" {- region = "us-east-1"- }- awsConfiguration, err := awsconfig.LoadDefaultConfig(ctx,+ region := cmp.Or(configuration.Region, "us-east-1")+ awsConfiguration, err := awsconfig.LoadDefaultConfig(+ ctx,awsconfig.WithRegion(region),awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(configuration.AccessKeyID, configuration.SecretAccessKey, "")),)diff --git a/backend/pkg/utils/signals/signals.go b/backend/pkg/utils/signals/signals.godeleted file mode 100644index 0cd8cb80d..000000000--- a/backend/pkg/utils/signals/signals.go+++ /dev/null@@ -1,54 +0,0 @@-package signals--import (- "context"- "log/slog"- "os"- "os/signal"- "syscall"- "time"-)--/*-This code is adapted from:-https://github.com/kubernetes-sigs/controller-runtime/blob/8499b67e316a03b260c73f92d0380de8cd2e97a1/pkg/manager/signals/signal.go-Copyright 2017 The Kubernetes Authors.-License: Apache2 (https://github.com/kubernetes-sigs/controller-runtime/blob/8499b67e316a03b260c73f92d0380de8cd2e97a1/LICENSE)--Also referenced from pocket-id/pocket-id-*/--var onlyOneSignalHandler = make(chan struct{})--const forcedShutdownTimeout = 30 * time.Second--// SignalContext returns a context that is canceled when the application receives an interrupt signal.-// A second signal or an expired graceful-shutdown deadline forces the process to exit.-func SignalContext(parentCtx context.Context) context.Context {- close(onlyOneSignalHandler) // Panics when called twice-- ctx, cancel := context.WithCancel(parentCtx)-- sigCh := make(chan os.Signal, 2)- signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)- go func() {- <-sigCh- slog.Info("Received interrupt signal. Shutting downβ¦")- cancel()-- shutdownTimer := time.NewTimer(forcedShutdownTimeout)- defer shutdownTimer.Stop()-- select {- case <-sigCh:- slog.Warn("Received a second interrupt signal. Forcing an immediate shutdown.")- case <-shutdownTimer.C:- slog.Error("Graceful shutdown timed out. Forcing process exit.", "timeout", forcedShutdownTimeout)- }- // Go cannot safely terminate a hung goroutine. Exit the process instead of- // allowing Bootstrap to close dependencies that goroutine may still use.- os.Exit(1)- }()-- return ctx-}diff --git a/backend/pkg/utils/string_util.go b/backend/pkg/utils/string_util.godeleted file mode 100644index c4cc4e79d..000000000--- a/backend/pkg/utils/string_util.go+++ /dev/null@@ -1,39 +0,0 @@-package utils--import (- "strconv"- "strings"-)--// StringOrDefault returns the trimmed value if non-empty, otherwise defaultValue.-func StringOrDefault(value, defaultValue string) string {- value = strings.TrimSpace(value)- if value == "" {- return defaultValue- }- return value-}--// BoolOrDefault parses value as a bool, falling back to defaultValue when empty or unparseable.-func BoolOrDefault(value string, defaultValue bool) bool {- if value == "" {- return defaultValue- }- v, err := strconv.ParseBool(value)- if err != nil {- return defaultValue- }- return v-}--// IntOrDefault parses value as an int, falling back to defaultValue when empty or unparseable.-func IntOrDefault(value string, defaultValue int) int {- if value == "" {- return defaultValue- }- v, err := strconv.Atoi(value)- if err != nil {- return defaultValue- }- return v-}diff --git a/backend/pkg/utils/strings.go b/backend/pkg/utils/strings.godeleted file mode 100644index 4517e5136..000000000--- a/backend/pkg/utils/strings.go+++ /dev/null@@ -1,180 +0,0 @@-package utils--import (- "crypto/rand"- "encoding/base64"- "fmt"- "reflect"- "strings"-- "github.com/samber/mo"-)--// ToString converts any value to a trimmed string.-func ToString(v any) string {- if v == nil {- return ""- }- var s string- switch val := v.(type) {- case string:- s = val- case fmt.Stringer:- s = val.String()- default:- s = fmt.Sprint(v)- }- return strings.TrimSpace(s)-}--// Collect transforms a value (single item or slice) into a slice of T using a mapper.-func Collect[T any](value any, mapper func(any) T) []T {- if value == nil {- return nil- }-- switch v := value.(type) {- case []any:- res := make([]T, len(v))- for i, item := range v {- res[i] = mapper(item)- }- return res- case []string:- res := make([]T, len(v))- for i, s := range v {- res[i] = mapper(s)- }- return res- default:- return []T{mapper(value)}- }-}--// AsStringMap attempts to convert any map-like interface to map[string]any.-func AsStringMap(value any) mo.Option[map[string]any] {- if value == nil {- return mo.None[map[string]any]()- }- switch v := value.(type) {- case map[string]any:- return mo.Some(v)- case map[string]string:- res := make(map[string]any, len(v))- for k, val := range v {- res[k] = val- }- return mo.Some(res)- case map[any]any:- res := make(map[string]any, len(v))- for k, val := range v {- if s, ok := k.(string); ok {- res[s] = val- }- }- if len(res) > 0 {- return mo.Some(res)- }- return mo.None[map[string]any]()- }- // Named map types (e.g. compose-go's types.Labels) don't match the cases above.- rv := reflect.ValueOf(value)- if rv.Kind() == reflect.Map && rv.Type().Key().Kind() == reflect.String {- res := make(map[string]any, rv.Len())- for iter := rv.MapRange(); iter.Next(); {- res[iter.Key().String()] = iter.Value().Interface()- }- return mo.Some(res)- }- return mo.None[map[string]any]()-}--// UniqueNonEmptyStrings returns unique, non-empty, trimmed strings.-func UniqueNonEmptyStrings(items []string) []string {- if len(items) == 0 {- return nil- }-- seen := make(map[string]struct{}, len(items))- result := make([]string, 0, len(items))- for _, item := range items {- s := strings.TrimSpace(item)- if s == "" {- continue- }- if _, exists := seen[s]; !exists {- seen[s] = struct{}{}- result = append(result, s)- }- }-- if len(result) == 0 {- return nil- }-- return result-}--// FirstNonEmpty returns the first non-empty string in a list of values.-func FirstNonEmpty(values ...string) string {- for _, v := range values {- if v != "" {- return v- }- }- return ""-}--func CapitalizeFirstLetter(str string) string {- if len(str) == 0 {- return str- }- return strings.ToUpper(str[:1]) + str[1:]-}--func CamelCaseToSnakeCase(str string) string {- var result strings.Builder- for i, r := range str {- if i > 0 && r >= 'A' && r <= 'Z' {- result.WriteRune('_')- }- result.WriteRune(r)- }- return strings.ToLower(result.String())-}--func GenerateRandomString(length int) string {- bytes := make([]byte, length)- if _, err := rand.Read(bytes); err != nil {- panic(err)- }- return base64.URLEncoding.EncodeToString(bytes)[:length]-}--func TrimQuotes(s string) string {- if len(s) >= 2 {- if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') {- return s[1 : len(s)-1]- }- }- return s-}--func GetStringOrDefault(m map[string]any, key, defaultValue string) string {- if val, ok := m[key]; ok {- if str, ok := val.(string); ok {- return str- }- }- return defaultValue-}--// EnsureVPrefix guarantees a version string carries the "v" prefix that-// semver comparisons and release tags expect.-func EnsureVPrefix(version string) string {- trimmed := strings.TrimSpace(version)- if strings.HasPrefix(trimmed, "v") {- return trimmed- }- return "v" + trimmed-}diff --git a/backend/pkg/utils/strings_test.go b/backend/pkg/utils/strings_test.godeleted file mode 100644index 730fdaf76..000000000--- a/backend/pkg/utils/strings_test.go+++ /dev/null@@ -1,100 +0,0 @@-package utils--import (- "testing"-- "github.com/stretchr/testify/assert"-)--func TestCapitalizeFirstLetter(t *testing.T) {- tests := []struct {- name string- input string- expected string- }{- {"empty string", "", ""},- {"single lowercase", "a", "A"},- {"single uppercase", "A", "A"},- {"word starting with lowercase", "hello", "Hello"},- {"word starting with uppercase", "Hello", "Hello"},- {"sentence", "hello world", "Hello world"},- {"starts with number", "123hello", "123hello"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- assert.Equal(t, tt.expected, CapitalizeFirstLetter(tt.input))- })- }-}--func TestCamelCaseToSnakeCase(t *testing.T) {- tests := []struct {- name string- input string- expected string- }{- {"empty string", "", ""},- {"simple", "camelCase", "camel_case"},- {"multiple words", "thisIsALongerString", "this_is_a_longer_string"},- {"already snake", "already_snake", "already_snake"},- {"single word", "word", "word"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- assert.Equal(t, tt.expected, CamelCaseToSnakeCase(tt.input))- })- }-}--func TestGenerateRandomString(t *testing.T) {- t.Run("length check", func(t *testing.T) {- length := 32- s := GenerateRandomString(length)- assert.Len(t, s, length)- })-- t.Run("randomness check", func(t *testing.T) {- s1 := GenerateRandomString(16)- s2 := GenerateRandomString(16)- assert.NotEqual(t, s1, s2, "Consecutive calls should produce different strings")- })-}--func TestTrimQuotes(t *testing.T) {- tests := []struct {- name string- input string- expected string- }{- {"empty string", "", ""},- {"no quotes", "hello", "hello"},- {"double quotes", "\"hello\"", "hello"},- {"single quotes", "'hello'", "hello"},- {"only starting double quote", "\"hello", "\"hello"},- {"only ending single quote", "hello'", "hello'"},- {"mismatched quotes", "'hello\"", "'hello\""},- {"long string with quotes", "\"this is a test\"", "this is a test"},- }-- for _, tt := range tests {- t.Run(tt.name, func(t *testing.T) {- assert.Equal(t, tt.expected, TrimQuotes(tt.input))- })- }-}--func TestUniqueNonEmptyStrings(t *testing.T) {- for _, tt := range []struct {- name string- input, want []string- }{- {name: "nil"},- {name: "empty tokens", input: []string{"", " \t "}},- {name: "stable order and case", input: []string{" beta ", "alpha", "beta", "Alpha", ""}, want: []string{"beta", "alpha", "Alpha"}},- {name: "does not split values", input: []string{"a,b", "a b"}, want: []string{"a,b", "a b"}},- } {- t.Run(tt.name, func(t *testing.T) { assert.Equal(t, tt.want, UniqueNonEmptyStrings(tt.input)) })- }-}diff --git a/backend/pkg/utils/sync_gate.go b/backend/pkg/utils/sync_gate.gonew file mode 100644index 000000000..5fb57244e--- /dev/null+++ b/backend/pkg/utils/sync_gate.go@@ -0,0 +1,78 @@+package utils++import (+ "context"+ "crypto/sha256"+ "sync"+ "time"+)++// SyncGate remembers the SHA-256 of the last payload delivered per scope and+// key so periodic re-syncs skip the network when nothing changed, and+// serializes deliveries for one key so overlapping pushes reach the target in+// the order they are remembered. Only the digest is retained. Expiry bounds+// how long a delivery is trusted (zero means forever) so a target rebuilt+// behind an unchanged status still converges. The zero value is ready to use.+type SyncGate struct {+ Expiry time.Duration++ mu sync.Mutex+ locks KeyedMutex+ sent map[string]map[string]syncGateEntryInternal+ epochs map[string]uint64+}++type syncGateEntryInternal struct {+ digest [sha256.Size]byte+ sentAt time.Time+}++// Begin reports whether body is already delivered for scope and key. When it+// is not, the key stays locked until finish runs; finish(true) remembers the+// delivery unless the scope was forgotten in between. Callers must invoke+// finish exactly once. Waiting for an in-flight delivery ends with ctx.+func (g *SyncGate) Begin(ctx context.Context, scope, key string, body []byte) (unchanged bool, finish func(delivered bool), err error) {+ unlock, err := g.locks.LockContext(ctx, scope+"\x00"+key)+ if err != nil {+ return false, nil, err+ }+ g.mu.Lock()+ epoch := g.epochs[scope]+ entry, ok := g.sent[scope][key]+ unchanged = ok && entry.digest == sha256.Sum256(body) && (g.Expiry <= 0 || time.Since(entry.sentAt) < g.Expiry)+ g.mu.Unlock()+ if unchanged {+ unlock()+ return true, func(bool) {}, nil+ }+ return false, func(delivered bool) {+ defer unlock()+ if !delivered {+ return+ }+ g.mu.Lock()+ defer g.mu.Unlock()+ if g.epochs[scope] != epoch {+ return+ }+ if g.sent == nil {+ g.sent = make(map[string]map[string]syncGateEntryInternal)+ }+ if g.sent[scope] == nil {+ g.sent[scope] = make(map[string]syncGateEntryInternal)+ }+ g.sent[scope][key] = syncGateEntryInternal{digest: sha256.Sum256(body), sentAt: time.Now()}+ }, nil+}++// Forget drops every remembered payload for scope so the next sync resends,+// and discards the outcome of deliveries still in flight for it.+func (g *SyncGate) Forget(scope string) {+ g.mu.Lock()+ defer g.mu.Unlock()+ delete(g.sent, scope)+ if g.epochs == nil {+ g.epochs = make(map[string]uint64)+ }+ g.epochs[scope]+++}diff --git a/backend/pkg/utils/fingerprint_test.go b/backend/pkg/utils/sync_gate_test.gosimilarity index 100%rename from backend/pkg/utils/fingerprint_test.gorename to backend/pkg/utils/sync_gate_test.godiff --git a/backend/pkg/utils/validation/email_test.go b/backend/pkg/utils/validation/email_test.goindex ef78b7610..1c50954c1 100644--- a/backend/pkg/utils/validation/email_test.go+++ b/backend/pkg/utils/validation/email_test.go@@ -22,7 +22,6 @@ func TestIsValidUserEmail_AllowsReportedFormats(t *testing.T) {require.True(t, IsValidUserEmail(email),"expected %q to be valid", email)-})}}@@ -51,7 +50,6 @@ func TestIsValidUserEmail_RejectsMalformedAddresses(t *testing.T) {require.False(t, IsValidUserEmail(email),"expected %q to be invalid", email)-})}}diff --git a/backend/pkg/workspace/workspace.go b/backend/pkg/workspace/workspace.goindex a9801d6d8..134edc9f4 100644--- a/backend/pkg/workspace/workspace.go+++ b/backend/pkg/workspace/workspace.go@@ -6,6 +6,7 @@ import ("unicode/utf8""emperror.dev/errors"+ kit "go.getarcane.app/kit/pkg")const DefaultMaxFileSizeMB = 10@@ -17,10 +18,7 @@ type UploadReference struct {}func EffectiveMaxFileSizeMB(configured int) int {- if configured <= 0 {- return DefaultMaxFileSizeMB- }- return configured+ return kit.Ternary(configured <= 0, DefaultMaxFileSizeMB, configured)}func MaxFileSizeBytes(configuredMB int) int64 {diff --git a/cli/go.mod b/cli/go.modindex f2f467922..e0df12adf 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -21,6 +21,7 @@ require (github.com/spf13/viper v1.21.0github.com/stretchr/testify v1.12.1go.getarcane.app/acfs v0.6.1+ go.getarcane.app/kit v0.3.1go.getarcane.app/sys/bytes v0.2.1)diff --git a/cli/go.sum b/cli/go.sumindex 180780c27..08c079d6e 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -170,6 +170,8 @@ go.getarcane.app/acfs v0.6.1 h1:xPDfof8Tbr3ZQ6ATcyFM4EtyUh+K657CThpGdg+dz50=go.getarcane.app/acfs v0.6.1/go.mod h1:Z+0Gs4LGNjvGMLq+TKv/oGKh29FRbAH6mcVPwY5KhFI=go.getarcane.app/builds v0.4.2 h1:pWrNrJ4pjLm2Dpwii4bkf0ptKrlE9N8j/EL1F6o15mA=go.getarcane.app/builds v0.4.2/go.mod h1:sOgXeqAcEUeblqdUOSPGZLYz3rlTJpTMXaSy0aQhmlQ=+go.getarcane.app/kit v0.3.1 h1:fuSl8ZMshuFPUvJl/9QwoI/ds1+zsfpixZYqk/hFLUE=+go.getarcane.app/kit v0.3.1/go.mod h1:KTjbXTEeC3i9e1QxZowDJWjFyABlD6UF3ISVtoIZs10=go.getarcane.app/sys/bytes v0.2.1 h1:Mm/VV1FAde3bVvzmSBxB7HVGkj7ZUw2Gbl1DPcUhlEo=go.getarcane.app/sys/bytes v0.2.1/go.mod h1:fcMYM7dknLk+KDXYAg6XOfRF22POYxcTnQeypFEjDbE=go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=diff --git a/cli/internal/ci/ci_detect.go b/cli/internal/ci/ci_detect.goindex ebef9b313..5958a4354 100644--- a/cli/internal/ci/ci_detect.go+++ b/cli/internal/ci/ci_detect.go@@ -10,6 +10,7 @@ import ("time""emperror.dev/errors"+ kit "go.getarcane.app/kit/pkg")const (@@ -20,7 +21,7 @@ const ()// DetectToken resolves a CI-issued OIDC token from the requested provider.-func DetectToken(ctx context.Context, provider string, audience string, getenv func(string) string, httpClient *http.Client) (string, string, error) {+func DetectToken(ctx context.Context, provider, audience string, getenv func(string) string, httpClient *http.Client) (string, string, error) {provider = normalizeFederatedProviderInternal(provider)if getenv == nil {getenv = func(string) string { return "" }@@ -110,8 +111,5 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenvfunc normalizeFederatedProviderInternal(provider string) string {provider = strings.ToLower(strings.TrimSpace(provider))- if provider == "" {- return ProviderAuto- }- return provider+ return kit.Ternary(provider == "", ProviderAuto, provider)}diff --git a/cli/internal/client/client.go b/cli/internal/client/client.goindex 6d76f0ae5..16c959710 100644--- a/cli/internal/client/client.go+++ b/cli/internal/client/client.go@@ -24,6 +24,7 @@ package clientimport ("bytes"+ "cmp""context""encoding/json/jsontext""encoding/json/v2"@@ -90,10 +91,7 @@ func New(cfg *types.Config) (*Client, error) {return nil, errors.WrapIf(err, "invalid server_url")}- envID := cfg.DefaultEnvironment- if envID == "" {- envID = defaultEnvID- }+ envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)return &Client{baseURL: cfg.ServerURL,@@ -120,10 +118,7 @@ func NewUnauthenticated(cfg *types.Config) (*Client, error) {return nil, errors.WrapIf(err, "invalid server_url")}- envID := cfg.DefaultEnvironment- if envID == "" {- envID = defaultEnvID- }+ envID := cmp.Or(cfg.DefaultEnvironment, defaultEnvID)return &Client{baseURL: cfg.ServerURL,diff --git a/cli/internal/client/client_test.go b/cli/internal/client/client_test.goindex 076ae010d..0d0233316 100644--- a/cli/internal/client/client_test.go+++ b/cli/internal/client/client_test.go@@ -42,7 +42,6 @@ func TestClient_UsesAPIKeyHeader(t *testing.T) {require.Equal(t, http.StatusOK, resp.StatusCode,"unexpected status: %d", resp.StatusCode)-}func TestClient_UsesBearerTokenHeader(t *testing.T) {@@ -76,7 +75,6 @@ func TestClient_UsesBearerTokenHeader(t *testing.T) {require.Equal(t, http.StatusOK, resp.StatusCode,"unexpected status: %d", resp.StatusCode)-}func TestClient_NewUnauthenticated_DoesNotSendAuthHeaders(t *testing.T) {@@ -106,7 +104,6 @@ func TestClient_NewUnauthenticated_DoesNotSendAuthHeaders(t *testing.T) {require.Equal(t, http.StatusOK, resp.StatusCode,"unexpected status: %d", resp.StatusCode)-}func TestClient_Request_DoesNotDoubleMarshalBytes(t *testing.T) {@@ -151,5 +148,4 @@ func TestClient_Request_DoesNotDoubleMarshalBytes(t *testing.T) {require.Equal(t, http.StatusOK, resp.StatusCode,"unexpected status: %d", resp.StatusCode)-}diff --git a/cli/internal/client/retry_test.go b/cli/internal/client/retry_test.goindex 464e2a08e..4dd13584f 100644--- a/cli/internal/client/retry_test.go+++ b/cli/internal/client/retry_test.go@@ -48,7 +48,6 @@ func TestClient_RetriesIdempotentRequests(t *testing.T) {require.Equal(t, int32(2), got,"expected 2 attempts, got %d", got)}-}func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {@@ -81,7 +80,6 @@ func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {require.Equal(t, int32(1), got,"expected 1 attempt, got %d", got)}-}func TestClient_DoJSON_StrictStatus(t *testing.T) {@@ -104,7 +102,6 @@ func TestClient_DoJSON_StrictStatus(t *testing.T) {require.Error(t, err,"expected strict status error")}-}func TestDecodeResponseStrict_RequiresSuccessEnvelope(t *testing.T) {@@ -120,7 +117,6 @@ func TestDecodeResponseStrict_RequiresSuccessEnvelope(t *testing.T) {require.Error(t, err,"expected envelope failure")}-}func TestClient_DoRaw_Success(t *testing.T) {@@ -145,5 +141,4 @@ func TestClient_DoRaw_Success(t *testing.T) {require.NotEmpty(t, b,"expected response payload")-}diff --git a/cli/internal/cmdutil/confirm.go b/cli/internal/cmdutil/confirm.goindex e51dfb9d9..950ec0a74 100644--- a/cli/internal/cmdutil/confirm.go+++ b/cli/internal/cmdutil/confirm.go@@ -6,7 +6,6 @@ import ("strings""emperror.dev/errors"-"github.com/spf13/cobra")diff --git a/cli/internal/cmdutil/context.go b/cli/internal/cmdutil/context.goindex d8890701e..30028047e 100644--- a/cli/internal/cmdutil/context.go+++ b/cli/internal/cmdutil/context.go@@ -2,7 +2,6 @@ package cmdutilimport ("emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client"runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime""github.com/spf13/cobra"diff --git a/cli/internal/cmdutil/limit.go b/cli/internal/cmdutil/limit.goindex ed05b21ec..f394cc44e 100644--- a/cli/internal/cmdutil/limit.go+++ b/cli/internal/cmdutil/limit.go@@ -7,6 +7,7 @@ import (runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types""github.com/spf13/cobra"+ kit "go.getarcane.app/kit/pkg")// EffectiveLimit resolves the final list limit with precedence:@@ -16,10 +17,7 @@ import (func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fallbackDefault int) int {if cmd != nil {if flag := cmd.Flags().Lookup(flagName); flag != nil && flag.Changed {- if flagValue > 0 || flagValue == ShowAllLimit {- return flagValue- }- return 0+ return kit.Ternary(flagValue > 0 || flagValue == ShowAllLimit, flagValue, 0)}}@@ -44,8 +42,5 @@ func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, faif fallbackDefault > 0 {return fallbackDefault}- if flagValue > 0 {- return flagValue- }- return 0+ return kit.Ternary(flagValue > 0, flagValue, 0)}diff --git a/cli/internal/cmdutil/pagination.go b/cli/internal/cmdutil/pagination.goindex c2d85170f..0792db530 100644--- a/cli/internal/cmdutil/pagination.go+++ b/cli/internal/cmdutil/pagination.go@@ -8,21 +8,23 @@ import ("github.com/spf13/cobra")-// ShowAllLimit is the sentinel the Arcane API uses for "return everything".-// The backend honours it on every list path: DB-backed lists short-circuit to-// paginateDBAll (bypassing the 100-item clamp), in-memory Docker lists return-// the full slice, and the handlers that coerce a zero limit to 20 test for-// exactly 0 so they leave it alone.-const ShowAllLimit = -1+const (+ // ShowAllLimit is the sentinel the Arcane API uses for "return everything".+ // The backend honours it on every list path: DB-backed lists short-circuit to+ // paginateDBAll (bypassing the 100-item clamp), in-memory Docker lists return+ // the full slice, and the handlers that coerce a zero limit to 20 test for+ // exactly 0 so they leave it alone.+ ShowAllLimit = -1-// AllFlagUsage is the shared help text for the --all flag on list commands.-const AllFlagUsage = "Return every item, ignoring pagination"+ // AllFlagUsage is the shared help text for the --all flag on list commands.+ AllFlagUsage = "Return every item, ignoring pagination"-// StartFlagUsage is the shared help text for the --start flag on list commands.-// Database-backed resources (projects, repos, gitops-syncs, environments,-// registries, users, events, api-keys, roles) derive a page number from-// start/limit, so an offset that is not a multiple of --limit is rounded down.-const StartFlagUsage = "Offset for pagination (rounded down to a multiple of --limit on database-backed resources)"+ // StartFlagUsage is the shared help text for the --start flag on list commands.+ // Database-backed resources (projects, repos, gitops-syncs, environments,+ // registries, users, events, api-keys, roles) derive a page number from+ // start/limit, so an offset that is not a multiple of --limit is rounded down.+ StartFlagUsage = "Offset for pagination (rounded down to a multiple of --limit on database-backed resources)"+)// AppendQuery merges extra query parameters into a path, preserving any that// are already present.diff --git a/cli/internal/cmdutil/upload.go b/cli/internal/cmdutil/upload.goindex 0d0cf0473..b192baa4c 100644--- a/cli/internal/cmdutil/upload.go+++ b/cli/internal/cmdutil/upload.go@@ -10,12 +10,12 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/logger""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"+ kit "go.getarcane.app/kit/pkg")const uploadChunkAttempts = 3@@ -63,10 +63,7 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath stbuf := make([]byte, session.ChunkSize)for index := range session.TotalChunks {- expected := session.ChunkSize- if index == session.TotalChunks-1 {- expected = session.Size - int64(index)*session.ChunkSize- }+ expected := kit.Ternary(index == session.TotalChunks-1, session.Size-int64(index)*session.ChunkSize, session.ChunkSize)if _, err := io.ReadFull(file, buf[:expected]); err != nil {deleteSession()return "", errors.WrapIf(err, "failed to read file")diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.goindex d4edee338..5372eab35 100644--- a/cli/internal/config/config_test.go+++ b/cli/internal/config/config_test.go@@ -25,7 +25,6 @@ func setTempConfigPath(t *testing.T) string {assert.NoError(t, err,"SetConfigPath(reset) failed: %v", err)}-})return path}@@ -61,7 +60,6 @@ func TestLoadReturnsDefaultsWhenFileMissing(t *testing.T) {require.Equal(t, "http://localhost:3552", cfg2.ServerURL,"cached config was mutated, ServerURL=%q", cfg2.ServerURL)-}func TestSaveAndLoadRoundTripPagination(t *testing.T) {@@ -126,7 +124,6 @@ func TestSaveAndLoadRoundTripPagination(t *testing.T) {require.Equal(t, "next", loaded.CLIUpdateChannel,"CLIUpdateChannel=%q, want next", loaded.CLIUpdateChannel)-}func TestLoadCanonicalPaginationBlock(t *testing.T) {@@ -176,7 +173,6 @@ pagination:require.Equal(t, 9, got,"registries limit=%d, want 9", got)}-}func TestInitDefaultFileCreatesTemplate(t *testing.T) {@@ -207,16 +203,12 @@ func TestInitDefaultFileCreatesTemplate(t *testing.T) {"pagination:",}for _, key := range requiredKeys {-require.Contains(t, text, key,"expected generated config to contain %q:\n%s", key, text)-}for _, resource := range []string{"containers", "images", "volumes", "networks", "projects", "environments", "registries", "templates", "users", "events", "apikeys"} {-require.Contains(t, text, resource+":","expected generated config to contain resource key %q:\n%s", resource, text)-}cfg, err := Load()@@ -233,7 +225,6 @@ func TestInitDefaultFileCreatesTemplate(t *testing.T) {require.Equal(t, defaultPaginationInitLimit, got,"LimitFor(%s)=%d, want %d", resource, got, defaultPaginationInitLimit)}-}}@@ -261,7 +252,6 @@ func TestInitDefaultFileDoesNotOverwriteExistingFile(t *testing.T) {require.Equal(t, original, string(raw),"existing file was modified:\nwant:\n%s\ngot:\n%s", original, string(raw))-}func TestBackupFileMovesConfig(t *testing.T) {@@ -297,7 +287,6 @@ func TestBackupFileMovesConfig(t *testing.T) {require.Equal(t, original, string(raw),"backup content mismatch:\nwant:\n%s\ngot:\n%s", original, string(raw))-}func TestBackupFileNoConfig(t *testing.T) {@@ -318,7 +307,6 @@ func TestBackupFileNoConfig(t *testing.T) {require.Equal(t, path+".bak", backupPath,"backup path = %q, want %q", backupPath, path+".bak")-}func TestBackupFileRotatesExistingBak(t *testing.T) {@@ -363,5 +351,4 @@ func TestBackupFileRotatesExistingBak(t *testing.T) {require.NotEmpty(t, rotated,"expected rotated backup matching %q", backupPath+".*")-}diff --git a/cli/internal/integrationtest/action_error_handling_test.go b/cli/internal/integrationtest/action_error_handling_test.goindex 3475be653..fdcb32ce7 100644--- a/cli/internal/integrationtest/action_error_handling_test.go+++ b/cli/internal/integrationtest/action_error_handling_test.go@@ -45,7 +45,6 @@ func TestContainerStartSurfacesServerError(t *testing.T) {require.NotContains(t, outBuf, "successfully","expected no success message on a denied start, got stdout=%s", outBuf)-}// TestSystemContainersStartAllSurfacesServerError verifies the same guard for a@@ -77,5 +76,4 @@ func TestSystemContainersStartAllSurfacesServerError(t *testing.T) {require.NotContains(t, outBuf, "Started all containers","expected no success message on a denied start-all, got stdout=%s", outBuf)-}diff --git a/cli/internal/integrationtest/json_contract_test.go b/cli/internal/integrationtest/json_contract_test.goindex 223327018..11f35d1af 100644--- a/cli/internal/integrationtest/json_contract_test.go+++ b/cli/internal/integrationtest/json_contract_test.go@@ -51,6 +51,5 @@ func TestContainersListJSONContract(t *testing.T) {require.True(t, ok,"missing key %q in output: %v", key, got)}-}}diff --git a/cli/internal/integrationtest/pagination_test.go b/cli/internal/integrationtest/pagination_test.goindex 96fb44b6b..c391705ed 100644--- a/cli/internal/integrationtest/pagination_test.go+++ b/cli/internal/integrationtest/pagination_test.go@@ -65,7 +65,6 @@ func TestContainersListSendsLimitAndStart(t *testing.T) {require.True(t, ok,"expected pagination in output: %v", got)}-}func TestContainersListExplicitStartZeroSendsStartZero(t *testing.T) {@@ -107,7 +106,6 @@ func TestContainersListExplicitStartZeroSendsStartZero(t *testing.T) {require.True(t, strings.Contains(gotQuery, "start=0") && strings.Contains(gotQuery, "limit=20"),"query = %q, want start=0 and limit=20", gotQuery)-}func TestContainersListTextShowsShowingSummary(t *testing.T) {@@ -134,7 +132,6 @@ func TestContainersListTextShowsShowingSummary(t *testing.T) {require.Contains(t, outBuf, "Showing: 1/26 containers","expected showing summary in output, got:\n%s", outBuf)-}// TestContainersListAllRequestsEveryItem pins the wire form of --all. The API@@ -180,7 +177,6 @@ func TestContainersListAllRequestsEveryItem(t *testing.T) {require.Equal(t, "limit=-1", gotQuery,"query = %q, want %q", gotQuery, "limit=-1")-}// TestProjectsListAllIncludesArchived covers the one resource where "everything"@@ -220,7 +216,6 @@ func TestProjectsListAllIncludesArchived(t *testing.T) {require.Equal(t, "archived=all&limit=-1", gotQuery,"query = %q, want %q", gotQuery, "archived=all&limit=-1")-}func TestAdminEventsListEnvSendsLimitAndStart(t *testing.T) {@@ -271,7 +266,6 @@ func TestAdminEventsListEnvSendsLimitAndStart(t *testing.T) {require.True(t, strings.Contains(gotQuery, "limit=3") && strings.Contains(gotQuery, "start=6"),"query = %q, want limit=3 and start=6", gotQuery)-}func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {@@ -342,7 +336,6 @@ func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {require.True(t, ok,"expected pagination key in output: %v", got)}-}func TestTemplatesListAllRejectsExplicitPaginationFlags(t *testing.T) {@@ -380,5 +373,4 @@ func TestTemplatesListAllRejectsExplicitPaginationFlags(t *testing.T) {require.False(t, called,"expected command to fail before issuing HTTP request")-}diff --git a/cli/internal/integrationtest/updates_commands_test.go b/cli/internal/integrationtest/updates_commands_test.goindex 1a4035a7e..fe3fca074 100644--- a/cli/internal/integrationtest/updates_commands_test.go+++ b/cli/internal/integrationtest/updates_commands_test.go@@ -65,7 +65,6 @@ func TestContainersListUpdatesJSONContract(t *testing.T) {require.True(t, ok,"missing key %q in output: %v", key, got)}-}}@@ -112,7 +111,6 @@ func TestContainersUpdatesCommandUsesHasUpdateFilter(t *testing.T) {require.NotEmpty(t, strings.TrimSpace(outBuf),"expected output from containers updates command")-}func TestProjectsListUpdatesJSONContract(t *testing.T) {@@ -172,7 +170,6 @@ func TestProjectsListUpdatesJSONContract(t *testing.T) {require.True(t, ok,"missing key %q in output: %v", key, got)}-}}@@ -222,7 +219,6 @@ func TestProjectsUpdatesCommandUsesHasUpdateFilter(t *testing.T) {require.NotEmpty(t, strings.TrimSpace(outBuf),"expected output from projects updates command")-}func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T) {@@ -281,7 +277,6 @@ func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T)require.False(t, !result.HasUpdate || result.CurrentVersion != "1.0.0" || result.LatestVersion != "1.1.0","unexpected single image update response: %+v", result)-}func TestImagesUpdatesCheckRequiresImageRef(t *testing.T) {@@ -292,7 +287,6 @@ func TestImagesUpdatesCheckRequiresImageRef(t *testing.T) {require.Contains(t, err.Error(), "at least one image reference","unexpected argument error: %v", err)-}func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {@@ -395,7 +389,6 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {require.False(t, summary.TotalImages != 4 || summary.ImagesWithUpdates != 2 || summary.DigestUpdates != 1,"unexpected summary response: %+v", summary)-}func TestImageUpdateCommandsRejectHTTPAndEnvelopeFailures(t *testing.T) {@@ -451,7 +444,6 @@ func TestImageUpdateCommandsRejectHTTPAndEnvelopeFailures(t *testing.T) {require.Empty(t, strings.TrimSpace(outBuf),"failed response produced success output: %q", outBuf)-})}})diff --git a/cli/internal/output/output.go b/cli/internal/output/output.goindex 4a67d7e63..5f8c6813b 100644--- a/cli/internal/output/output.go+++ b/cli/internal/output/output.go@@ -23,6 +23,7 @@ import ("charm.land/lipgloss/v2/table""github.com/charmbracelet/x/term""github.com/mattn/go-runewidth"+ kit "go.getarcane.app/kit/pkg")var (@@ -264,10 +265,7 @@ func Table(headers []string, rows [][]string) {})} else {t = t.StyleFunc(func(row, col int) lipgloss.Style {- if row == table.HeaderRow {- return tablePlainHead- }- return tablePlainCell+ return kit.Ternary(row == table.HeaderRow, tablePlainHead, tablePlainCell)})}@@ -309,12 +307,12 @@ func fitTableToTerminal(headers []string, rows [][]string) ([]string, [][]stringcolumnWidths := make([]int, columnCount)for i, header := range displayHeaders {- columnWidths[i] = maxInt(1, visibleWidth(header))+ columnWidths[i] = max(1, visibleWidth(header))}for _, row := range displayRows {for col := range columnCount {- columnWidths[col] = maxInt(columnWidths[col], visibleWidth(row[col]))+ columnWidths[col] = max(columnWidths[col], visibleWidth(row[col]))}}@@ -426,13 +424,6 @@ func sumInts(values []int) int {return total}-func maxInt(a, b int) int {- if a > b {- return a- }- return b-}-func normalizeTableRows(rows [][]string, width int) [][]string {if width == 0 || len(rows) == 0 {return rowsdiff --git a/cli/internal/output/tui.go b/cli/internal/output/tui.goindex 9b49a3341..eedb5286f 100644--- a/cli/internal/output/tui.go+++ b/cli/internal/output/tui.go@@ -2,7 +2,6 @@ package outputimport ("fmt"- "io""sync""charm.land/bubbles/v2/progress"@@ -144,22 +143,15 @@ func (m progressModel) View() tea.View {bar := m.progress.ViewAs(percent)if m.total > 0 {- return tea.NewView(fmt.Sprintf("%s\n%s %s/%s", m.label, bar, safeCapacity(m.current), safeCapacity(m.total)))+ return tea.NewView(fmt.Sprintf("%s\n%s %s/%s", m.label, bar, bytes.Capacity(uint64(max(m.current, 0))), bytes.Capacity(uint64(max(m.total, 0)))))}return tea.NewView(fmt.Sprintf("%s\n%s", m.label, bar))}-func safeCapacity(value int64) bytes.Capacity {- if value < 0 {- return bytes.Capacity(0)- }- return bytes.Capacity(uint64(value))-}-// Bytes renders a signed byte count in human-readable form. Negative values,// which bytes.Capacity would otherwise wrap into the exabyte range, render as 0.func Bytes(value int64) string {- return safeCapacity(value).String()+ return bytes.Capacity(uint64(max(value, 0))).String()}// UnsignedBytes renders an unsigned byte count in human-readable form.@@ -246,24 +238,3 @@ func (p *Progress) Stop() {<-p.donefmt.Println()}--// NewProgressReader wraps a reader to report progress updates.-func NewProgressReader(r io.Reader, progress *Progress) io.Reader {- if progress == nil {- return r- }- return &progressReader{reader: r, progress: progress}-}--type progressReader struct {- reader io.Reader- progress *Progress-}--func (p *progressReader) Read(buf []byte) (int, error) {- n, err := p.reader.Read(buf)- if n > 0 {- p.progress.Add(int64(n))- }- return n, err-}diff --git a/cli/internal/prompt/prompt.go b/cli/internal/prompt/prompt.goindex 29358e94b..1185b6b2b 100644--- a/cli/internal/prompt/prompt.go+++ b/cli/internal/prompt/prompt.go@@ -4,10 +4,9 @@ import ("fmt""os"- "emperror.dev/errors"-"charm.land/bubbles/v2/list"tea "charm.land/bubbletea/v2"+ "emperror.dev/errors""github.com/charmbracelet/x/term")diff --git a/cli/internal/runtime/context.go b/cli/internal/runtime/context.goindex b0c8eb994..2adc5cca8 100644--- a/cli/internal/runtime/context.go+++ b/cli/internal/runtime/context.go@@ -1,6 +1,7 @@package runtimeimport (+ "cmp""context""strings""sync"@@ -14,17 +15,17 @@ import (type contextKey string-// AppContextKey is the context key under which the CLI's AppContext is stored;-// set it with context.WithValue and read it back with From.-const AppContextKey contextKey = "arcane_app_context"--type OutputMode string-const (+ // AppContextKey is the context key under which the CLI's AppContext is stored;+ // set it with context.WithValue and read it back with From.+ AppContextKey contextKey = "arcane_app_context"+OutputModeText OutputMode = "text"OutputModeJSON OutputMode = "json")+type OutputMode string+type Options struct {EnvOverride stringOutputMode OutputMode@@ -56,10 +57,7 @@ func New(opts Options) (*AppContext, error) {return nil, errors.WrapIf(err, "failed to load config")}- mode := opts.OutputMode- if mode == "" {- mode = OutputModeText- }+ mode := cmp.Or(opts.OutputMode, OutputModeText)switch mode {case OutputModeText, OutputModeJSON:default:diff --git a/cli/internal/types/config_test.go b/cli/internal/types/config_test.goindex 0f7b21cc3..7cf18a4ef 100644--- a/cli/internal/types/config_test.go+++ b/cli/internal/types/config_test.go@@ -16,7 +16,6 @@ func TestConfigLimitForRepos(t *testing.T) {require.Equal(t, 42, got,"LimitFor(%q) = %d, want 42", resource, got)}-}}@@ -33,6 +32,5 @@ func TestNormalizePaginatedResourceGitOpsSyncAliases(t *testing.T) {require.Equal(t, "gitops-syncs", got,"NormalizePaginatedResource(%q) = %q, want %q", resource, got, "gitops-syncs")}-}}diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.goindex 5505f5702..a7ee6ee08 100644--- a/cli/internal/types/endpoints.go+++ b/cli/internal/types/endpoints.go@@ -90,45 +90,59 @@ func EnvironmentVersion(envID string) string {// Container endpointsfunc Containers(envID string) string { return pathf("/api/environments/%s/containers", envID) }+func Container(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s", envID, containerID)}+func ContainerStart(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/start", envID, containerID)}+func ContainerStop(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/stop", envID, containerID)}+func ContainerRestart(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/restart", envID, containerID)}+func ContainerKill(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/kill", envID, containerID)}+func ContainerPause(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/pause", envID, containerID)}+func ContainerUnpause(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/unpause", envID, containerID)}+func ContainerCommit(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/commit", envID, containerID)}+func ContainerUpdate(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/update", envID, containerID)}+func ContainerRedeploy(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/redeploy", envID, containerID)}+func ContainerEditConfig(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/edit-config", envID, containerID)}+func ContainerEdit(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/edit", envID, containerID)}+func ContainerAutoUpdate(envID, containerID string) string {return pathf("/api/environments/%s/containers/%s/auto-update", envID, containerID)}+func ContainersCounts(envID string) string {return pathf("/api/environments/%s/containers/counts", envID)}@@ -136,6 +150,7 @@ func ContainersCounts(envID string) string {// Image endpointsfunc Images(envID string) string { return pathf("/api/environments/%s/images", envID) }+func Image(envID, imageID string) string {return pathf("/api/environments/%s/images/%s", envID, imageID)}@@ -147,12 +162,15 @@ func ImagesSearch(envID string) string { return pathf("/api/environments/%s/imagfunc ImageHistory(envID, name string) string {return pathf("/api/environments/%s/images/%s/history", envID, name)}+func ImageTag(envID, name string) string {return pathf("/api/environments/%s/images/%s/tag", envID, name)}+func ImageExport(envID, name string) string {return pathf("/api/environments/%s/images/%s/export", envID, name)}+func ImageAttestations(envID, name string) string {return pathf("/api/environments/%s/images/%s/attestations", envID, name)}@@ -167,9 +185,11 @@ func ImageBuild(envID, buildID string) string {func UploadSessions(envID, kind string) string {return pathf("/api/environments/%s/uploads/%s", envID, kind)}+func UploadSession(envID, kind, uploadID string) string {return pathf("/api/environments/%s/uploads/%s/%s", envID, kind, uploadID)}+func UploadSessionChunk(envID, kind, uploadID string, index int) string {return pathf("/api/environments/%s/uploads/%s/%s/chunks/%d", envID, kind, uploadID, index)}@@ -181,15 +201,19 @@ func ImageUpdatesCheck(envID, imageRef string) string {query.Set("imageRef", imageRef)return pathf("/api/environments/%s/image-updates/check", envID) + "?" + query.Encode()}+func ImageUpdatesCheckAll(envID string) string {return pathf("/api/environments/%s/image-updates/check-all", envID)}+func ImageUpdatesCheckById(envID, imageID string) string {return pathf("/api/environments/%s/image-updates/check/%s", envID, imageID)}+func ImageUpdatesCheckBatch(envID string) string {return pathf("/api/environments/%s/image-updates/check-batch", envID)}+func ImageUpdatesSummary(envID string) string {return pathf("/api/environments/%s/image-updates/summary", envID)}@@ -197,19 +221,25 @@ func ImageUpdatesSummary(envID string) string {// Network endpointsfunc Networks(envID string) string { return pathf("/api/environments/%s/networks", envID) }+func Network(envID, networkID string) string {return pathf("/api/environments/%s/networks/%s", envID, networkID)}+func NetworksCounts(envID string) string {return pathf("/api/environments/%s/networks/counts", envID)}+func NetworksPrune(envID string) string { return pathf("/api/environments/%s/networks/prune", envID) }+func NetworksTopology(envID string) string {return pathf("/api/environments/%s/networks/topology", envID)}+func NetworkConnect(envID, networkID string) string {return pathf("/api/environments/%s/networks/%s/connect", envID, networkID)}+func NetworkDisconnect(envID, networkID string) string {return pathf("/api/environments/%s/networks/%s/disconnect", envID, networkID)}@@ -217,15 +247,21 @@ func NetworkDisconnect(envID, networkID string) string {// Volume endpointsfunc Volumes(envID string) string { return pathf("/api/environments/%s/volumes", envID) }+func Volume(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s", envID, volumeName)}+func VolumesCounts(envID string) string { return pathf("/api/environments/%s/volumes/counts", envID) }-func VolumesPrune(envID string) string { return pathf("/api/environments/%s/volumes/prune", envID) }-func VolumesSizes(envID string) string { return pathf("/api/environments/%s/volumes/sizes", envID) }++func VolumesPrune(envID string) string { return pathf("/api/environments/%s/volumes/prune", envID) }++func VolumesSizes(envID string) string { return pathf("/api/environments/%s/volumes/sizes", envID) }+func VolumeUsage(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/usage", envID, volumeName)}+func VolumeRename(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/rename", envID, volumeName)}@@ -235,27 +271,35 @@ func VolumeRename(envID, volumeName string) string {func VolumeBackupPolicy(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/backup-policy", envID, volumeName)}+func VolumeBackups(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/backups", envID, volumeName)}+func VolumeBackup(envID, backupID string) string {return pathf("/api/environments/%s/volumes/backups/%s", envID, backupID)}+func VolumeBackupRestore(envID, volumeName, backupID string) string {return pathf("/api/environments/%s/volumes/%s/backups/%s/restore", envID, volumeName, backupID)}+func VolumeBackupRestoreFiles(envID, volumeName, backupID string) string {return pathf("/api/environments/%s/volumes/%s/backups/%s/restore-files", envID, volumeName, backupID)}+func VolumeBackupUpload(envID, backupID string) string {return pathf("/api/environments/%s/volumes/backups/%s/upload", envID, backupID)}+func VolumeBackupDownload(envID, backupID string) string {return pathf("/api/environments/%s/volumes/backups/%s/download", envID, backupID)}+func VolumeBackupFiles(envID, backupID string) string {return pathf("/api/environments/%s/volumes/backups/%s/files", envID, backupID)}+func VolumeBackupUploadRestore(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/backups/upload", envID, volumeName)}@@ -265,9 +309,11 @@ func VolumeBackupUploadRestore(envID, volumeName string) string {func VolumeWorkspace(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/workspace", envID, volumeName)}+func VolumeWorkspaceFile(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/workspace/file", envID, volumeName)}+func VolumeWorkspaceFileDownload(envID, volumeName string) string {return pathf("/api/environments/%s/volumes/%s/workspace/file/download", envID, volumeName)}@@ -275,9 +321,11 @@ func VolumeWorkspaceFileDownload(envID, volumeName string) string {// Project endpointsfunc Projects(envID string) string { return pathf("/api/environments/%s/projects", envID) }+func Project(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s", envID, projectID)}+func ProjectsCounts(envID string) string {return pathf("/api/environments/%s/projects/counts", envID)}@@ -285,42 +333,55 @@ func ProjectsTags(envID string) string { return pathf("/api/environments/%s/projfunc ProjectTags(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/tags", envID, projectID)}+func ProjectDestroy(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/destroy", envID, projectID)}+func ProjectUp(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/up", envID, projectID)}+func ProjectDown(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/down", envID, projectID)}+func ProjectRestart(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/restart", envID, projectID)}+func ProjectRedeploy(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/redeploy", envID, projectID)}+func ProjectPull(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/pull", envID, projectID)}+func ProjectBuild(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/build", envID, projectID)}+func ProjectArchive(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/archive", envID, projectID)}+func ProjectUnarchive(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/unarchive", envID, projectID)}+func ProjectUpdateServices(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/update-services", envID, projectID)}+func ProjectWorkspace(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/workspace", envID, projectID)}+func ProjectWorkspaceFile(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/workspace/file", envID, projectID)}+func ProjectWorkspaceFileDownload(envID, projectID string) string {return pathf("/api/environments/%s/projects/%s/workspace/file/download", envID, projectID)}@@ -328,26 +389,35 @@ func ProjectWorkspaceFileDownload(envID, projectID string) string {// System endpointsfunc SystemPrune(envID string) string { return pathf("/api/environments/%s/system/prune", envID) }+func SystemDockerInfo(envID string) string {return pathf("/api/environments/%s/system/docker/info", envID)}+func SystemContainersStartAll(envID string) string {return pathf("/api/environments/%s/system/containers/start-all", envID)}+func SystemContainersStopAll(envID string) string {return pathf("/api/environments/%s/system/containers/stop-all", envID)}+func SystemStartStopped(envID string) string {return pathf("/api/environments/%s/system/containers/start-stopped", envID)}+func SystemConvert(envID string) string { return pathf("/api/environments/%s/system/convert", envID) }+func SystemUpgrade(envID string) string { return pathf("/api/environments/%s/system/upgrade", envID) }+func SystemUpgradeCheck(envID string) string {return pathf("/api/environments/%s/system/upgrade/check", envID)}+func SystemUpgradeAll(envID string) string {return pathf("/api/environments/%s/system/upgrade/all", envID)}+func SystemUpgradeAllStatus(envID string) string {return pathf("/api/environments/%s/system/upgrade/all/status", envID)}@@ -371,6 +441,7 @@ func JobRun(envID, jobID string) string {// Settings endpointsfunc Settings(envID string) string { return pathf("/api/environments/%s/settings", envID) }+func SettingsPublic(envID string) string {return pathf("/api/environments/%s/settings/public", envID)}@@ -380,9 +451,11 @@ func SettingsPublic(envID string) string {func NotificationsSettings(envID string) string {return pathf("/api/environments/%s/notifications/settings", envID)}+func NotificationSettingsProvider(envID, provider string) string {return pathf("/api/environments/%s/notifications/settings/%s", envID, provider)}+func NotificationsTestProvider(envID, provider string) string {return pathf("/api/environments/%s/notifications/test/%s", envID, provider)}@@ -448,6 +521,7 @@ func BackupsS3Test() string { return "/api/backups/s3/test" }func BackupsS3DestinationTest(id string) string {return pathf("/api/backups/s3/%s/test", id)}+func BackupsS3DestinationInUse(id string) string {return pathf("/api/backups/s3/%s/in-use", id)}@@ -457,33 +531,43 @@ func BackupsS3DestinationInUse(id string) string {func ImageVulnerabilitiesScan(envID, imageID string) string {return pathf("/api/environments/%s/images/%s/vulnerabilities/scan", envID, imageID)}+func ImageVulnerabilities(envID, imageID string) string {return pathf("/api/environments/%s/images/%s/vulnerabilities", envID, imageID)}+func ImageVulnerabilitiesSummary(envID, imageID string) string {return pathf("/api/environments/%s/images/%s/vulnerabilities/summary", envID, imageID)}+func ImageVulnerabilitiesList(envID, imageID string) string {return pathf("/api/environments/%s/images/%s/vulnerabilities/list", envID, imageID)}+func ImagesVulnerabilitiesSummaries(envID string) string {return pathf("/api/environments/%s/images/vulnerabilities/summaries", envID)}+func VulnerabilitiesScannerStatus(envID string) string {return pathf("/api/environments/%s/vulnerabilities/scanner-status", envID)}+func VulnerabilitiesSummary(envID string) string {return pathf("/api/environments/%s/vulnerabilities/summary", envID)}+func VulnerabilitiesAll(envID string) string {return pathf("/api/environments/%s/vulnerabilities/all", envID)}+func VulnerabilitiesIgnored(envID string) string {return pathf("/api/environments/%s/vulnerabilities/ignored", envID)}+func VulnerabilitiesIgnore(envID string) string {return pathf("/api/environments/%s/vulnerabilities/ignore", envID)}+func VulnerabilityIgnore(envID, ignoreID string) string {return pathf("/api/environments/%s/vulnerabilities/ignore/%s", envID, ignoreID)}@@ -491,12 +575,15 @@ func VulnerabilityIgnore(envID, ignoreID string) string {// Activity endpointsfunc Activities(envID string) string { return pathf("/api/environments/%s/activities", envID) }+func Activity(envID, activityID string) string {return pathf("/api/environments/%s/activities/%s", envID, activityID)}+func ActivityCancel(envID, activityID string) string {return pathf("/api/environments/%s/activities/%s/cancel", envID, activityID)}+func ActivitiesHistory(envID string) string {return pathf("/api/environments/%s/activities/history", envID)}@@ -504,6 +591,7 @@ func ActivitiesHistory(envID string) string {// Webhook endpointsfunc Webhooks(envID string) string { return pathf("/api/environments/%s/webhooks", envID) }+func Webhook(envID, webhookID string) string {return pathf("/api/environments/%s/webhooks/%s", envID, webhookID)}@@ -512,18 +600,23 @@ func WebhookTrigger(token string) string { return pathf("/api/webhooks/trigger/%// GitOps sync endpointsfunc GitOpsSyncs(envID string) string { return pathf("/api/environments/%s/gitops-syncs", envID) }+func GitOpsSync(envID, syncID string) string {return pathf("/api/environments/%s/gitops-syncs/%s", envID, syncID)}+func GitOpsSyncStatus(envID, syncID string) string {return pathf("/api/environments/%s/gitops-syncs/%s/status", envID, syncID)}+func GitOpsSyncTrigger(envID, syncID string) string {return pathf("/api/environments/%s/gitops-syncs/%s/sync", envID, syncID)}+func GitOpsSyncFiles(envID, syncID string) string {return pathf("/api/environments/%s/gitops-syncs/%s/files", envID, syncID)}+func GitOpsSyncsImport(envID string) string {return pathf("/api/environments/%s/gitops-syncs/import", envID)}@@ -535,9 +628,11 @@ func GitRepository(id string) string { return pathf("/api/customize/git-repositofunc GitRepositoryTest(id string) string {return pathf("/api/customize/git-repositories/%s/test", id)}+func GitRepositoryBranches(id string) string {return pathf("/api/customize/git-repositories/%s/branches", id)}+func GitRepositoryFiles(id string) string {return pathf("/api/customize/git-repositories/%s/files", id)}diff --git a/cli/pkg/activities/cmd.go b/cli/pkg/activities/cmd.goindex 230c60bcf..1ea33f394 100644--- a/cli/pkg/activities/cmd.go+++ b/cli/pkg/activities/cmd.go@@ -9,7 +9,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.goindex 854ecba0a..a2abbad0a 100644--- a/cli/pkg/admin/apikeys/cmd.go+++ b/cli/pkg/admin/apikeys/cmd.go@@ -7,7 +7,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -24,9 +23,7 @@ var (jsonOutput bool)-var (- apikeyCreatePermissions []string-)+var apikeyCreatePermissions []stringvar (apikeyUpdateName stringdiff --git a/cli/pkg/admin/federatedcredentials/cmd.go b/cli/pkg/admin/federatedcredentials/cmd.goindex 26e610ad1..f9dc633fa 100644--- a/cli/pkg/admin/federatedcredentials/cmd.go+++ b/cli/pkg/admin/federatedcredentials/cmd.go@@ -5,6 +5,7 @@package federatedcredentialsimport (+ "cmp""fmt""time"@@ -289,10 +290,7 @@ func printCredentialInternal(cred federatedtypes.FederatedCredential) {output.KeyValue("Subject claim", cred.SubjectClaim)output.KeyValue("Subject match", cred.SubjectMatch)output.KeyValue("Match type", cred.MatchType)- role := cred.RoleName- if role == "" {- role = cred.RoleID- }+ role := cmp.Or(cred.RoleName, cred.RoleID)output.KeyValue("Role", role)scope := "global"if cred.EnvironmentID != nil {diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.goindex 195a22e4c..8e0699deb 100644--- a/cli/pkg/admin/roles/cmd.go+++ b/cli/pkg/admin/roles/cmd.go@@ -11,7 +11,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"diff --git a/cli/pkg/auth/apikeys.go b/cli/pkg/auth/apikeys.goindex 93084a029..961e713eb 100644--- a/cli/pkg/auth/apikeys.go+++ b/cli/pkg/auth/apikeys.go@@ -5,7 +5,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.goindex 9e8ea09da..ab349db25 100644--- a/cli/pkg/auth/cmd.go+++ b/cli/pkg/auth/cmd.go@@ -11,7 +11,6 @@ import ("time""emperror.dev/errors"-"github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/config"diff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.goindex 9f7502f5f..209a51510 100644--- a/cli/pkg/auth/federated.go+++ b/cli/pkg/auth/federated.go@@ -11,7 +11,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/ci""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"@@ -20,6 +19,7 @@ import ("github.com/getarcaneapp/arcane/cli/v2/internal/types"federatedtypes "github.com/getarcaneapp/arcane/types/v2/federated""github.com/spf13/cobra"+ kit "go.getarcane.app/kit/pkg")const (@@ -136,7 +136,7 @@ func init() {federatedCmd.Flags().Bool("json", false, "Output in JSON format")}-func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider string, audience string) (string, string, error) {+func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider, audience string) (string, string, error) {token, _ := cmd.Flags().GetString("token")if strings.TrimSpace(token) != "" {return strings.TrimSpace(token), "flag", nil@@ -171,7 +171,7 @@ func resolveFederatedSubjectTokenInternal(cmd *cobra.Command, provider string, areturn ci.DetectToken(cmd.Context(), provider, audience, os.Getenv, &http.Client{Timeout: 10 * time.Second})}-func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjectToken string, audience string) (*federatedtypes.FederatedTokenResponse, error) {+func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjectToken, audience string) (*federatedtypes.FederatedTokenResponse, error) {form := url.Values{}form.Set("grant_type", federatedtypes.TokenExchangeGrantType)form.Set("subject_token", subjectToken)@@ -220,10 +220,7 @@ func redactedFederatedExchangeMessageInternal(body []byte) string {}}msg := strings.TrimSpace(string(body))- if msg == "" {- return "request rejected"- }- return msg+ return kit.Ternary(msg == "", "request rejected", msg)}func stdinHasDataInternal() bool {diff --git a/cli/pkg/backups/cmd.go b/cli/pkg/backups/cmd.goindex 3d9cdeab8..2af525369 100644--- a/cli/pkg/backups/cmd.go+++ b/cli/pkg/backups/cmd.go@@ -9,7 +9,6 @@ import ("strconv""emperror.dev/errors"-"github.com/charmbracelet/x/term""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil"@@ -19,6 +18,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/backup""github.com/getarcaneapp/arcane/types/v2/base""github.com/spf13/cobra"+ kit "go.getarcane.app/kit/pkg")var (@@ -371,10 +371,7 @@ var policiesCmd = &cobra.Command{func printPolicies(result backup.SystemBackupPolicyCollection) {output.Header("System Backup Policies")- recoveryKey := "Not configured"- if result.RecoveryKeyStored {- recoveryKey = "Configured"- }+ recoveryKey := kit.Ternary(result.RecoveryKeyStored, "Configured", "Not configured")output.KeyValue("Recovery Key", recoveryKey)headers := []string{"ID", "ENABLED", "SCHEDULE", "RETENTION", "LOCAL", "S3", "S3 DESTINATION", "LAST RUN"}diff --git a/cli/pkg/backups/resolve.go b/cli/pkg/backups/resolve.goindex caca9e249..d25067f27 100644--- a/cli/pkg/backups/resolve.go+++ b/cli/pkg/backups/resolve.go@@ -7,7 +7,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/types"diff --git a/cli/pkg/backups/s3.go b/cli/pkg/backups/s3.goindex 8d29d4c9f..29cca45bb 100644--- a/cli/pkg/backups/s3.go+++ b/cli/pkg/backups/s3.go@@ -6,7 +6,6 @@ import ("strconv""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/prompt"diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.goindex a1429583c..482a666b0 100644--- a/cli/pkg/config/cmd.go+++ b/cli/pkg/config/cmd.go@@ -1,6 +1,7 @@package configimport (+ "cmp""fmt""io""net/http"@@ -11,7 +12,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/config"clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types""github.com/spf13/cobra"@@ -45,15 +45,15 @@ var configShowCmd = &cobra.Command{path, _ := config.ConfigPath()fmt.Printf("Config file: %s\n\n", path)- fmt.Printf("Server URL: %s\n", maskIfEmpty(cfg.ServerURL, "(not set)"))+ fmt.Printf("Server URL: %s\n", cmp.Or(cfg.ServerURL, "(not set)"))fmt.Printf("API Key: %s\n", maskAPIKey(cfg.APIKey))fmt.Printf("JWT Token: %s\n", maskAPIKey(cfg.JWTToken))fmt.Printf("Refresh Token: %s\n", maskAPIKey(cfg.RefreshToken))- fmt.Printf("Default Environment: %s\n", maskIfEmpty(cfg.DefaultEnvironment, "0 (local)"))- fmt.Printf("Federated Audience: %s\n", maskIfEmpty(cfg.FederatedAudience, "(not set)"))- fmt.Printf("Log Level: %s\n", maskIfEmpty(cfg.LogLevel, "info (default)"))- fmt.Printf("CLI Update Channel: %s\n", maskIfEmpty(cfg.CLIUpdateChannel, "(auto)"))- fmt.Printf("Pagination Default: %s\n", maskIfEmpty(intToString(cfg.Pagination.Default.Limit), "(not set)"))+ fmt.Printf("Default Environment: %s\n", cmp.Or(cfg.DefaultEnvironment, "0 (local)"))+ fmt.Printf("Federated Audience: %s\n", cmp.Or(cfg.FederatedAudience, "(not set)"))+ fmt.Printf("Log Level: %s\n", cmp.Or(cfg.LogLevel, "info (default)"))+ fmt.Printf("CLI Update Channel: %s\n", cmp.Or(cfg.CLIUpdateChannel, "(auto)"))+ fmt.Printf("Pagination Default: %s\n", cmp.Or(intToString(cfg.Pagination.Default.Limit), "(not set)"))fmt.Println("\nPagination Resources:")printed := 0@@ -283,13 +283,6 @@ func init() {configSetCmd.Flags().StringSliceVar(&setResourceLimit, "resource-limit", nil, "Per-resource list limit in the form resource=limit (repeatable, 0 clears)")}-func maskIfEmpty(value, fallback string) string {- if value == "" {- return fallback- }- return value-}-func maskAPIKey(key string) string {if key == "" {return "(not set)"diff --git a/cli/pkg/config/cmd_test.go b/cli/pkg/config/cmd_test.goindex b501b1c00..a99563e06 100644--- a/cli/pkg/config/cmd_test.go+++ b/cli/pkg/config/cmd_test.go@@ -47,7 +47,6 @@ func TestApplyConfigSetArgs(t *testing.T) {require.Equal(t, 40, got,"LimitFor(volumes) = %d, want 40", got)}-}func TestApplyConfigSetArgs_OddArgs(t *testing.T) {@@ -59,7 +58,6 @@ func TestApplyConfigSetArgs_OddArgs(t *testing.T) {require.False(t, changed,"changed = true, want false")-}func TestApplyConfigSetArg_UnknownKey(t *testing.T) {@@ -74,7 +72,6 @@ func TestApplyConfigSetArg_UnknownKey(t *testing.T) {require.Contains(t, err.Error(), "unknown config key","unexpected error: %v", err)-}func TestApplyConfigSetArg_ResourceLimitPair(t *testing.T) {@@ -92,5 +89,4 @@ func TestApplyConfigSetArg_ResourceLimitPair(t *testing.T) {require.Equal(t, 55, got,"LimitFor(containers) = %d, want 55", got)}-}diff --git a/cli/pkg/containers/actions.go b/cli/pkg/containers/actions.goindex 75c4d637c..6c4aa33c7 100644--- a/cli/pkg/containers/actions.go+++ b/cli/pkg/containers/actions.go@@ -9,7 +9,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.goindex edc446a67..a0c1259bc 100644--- a/cli/pkg/containers/cmd.go+++ b/cli/pkg/containers/cmd.go@@ -1,6 +1,7 @@package containersimport (+ "cmp""encoding/json/v2""fmt""net/url"@@ -10,7 +11,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -664,13 +664,7 @@ func formatContainerOption(item container.Summary) string {if name == "" {name = shortID(item.ID)}- image := item.Image- if image == "" {- image = "<unknown>"- }- state := item.State- if state == "" {- state = "unknown"- }+ image := cmp.Or(item.Image, "<unknown>")+ state := cmp.Or(item.State, "unknown")return fmt.Sprintf("%s (%s, %s)", name, shortID(item.ID), image+" / "+state)}diff --git a/cli/pkg/doctor/cmd.go b/cli/pkg/doctor/cmd.goindex a2e215cc0..affedcfa2 100644--- a/cli/pkg/doctor/cmd.go+++ b/cli/pkg/doctor/cmd.go@@ -4,7 +4,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/output"diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.goindex 2e2f567f4..328a95228 100644--- a/cli/pkg/environments/cmd.go+++ b/cli/pkg/environments/cmd.go@@ -1,15 +1,15 @@package environmentsimport (+ "cmp""fmt""net/http""sort""strconv""strings"- "emperror.dev/errors"-"charm.land/lipgloss/v2"+ "emperror.dev/errors""github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/config"@@ -229,10 +229,7 @@ var switchCmd = &cobra.Command{options := make([]string, len(envs))for i, env := range envs {- displayName := strings.TrimSpace(env.Name)- if displayName == "" {- displayName = env.ID- }+ displayName := cmp.Or(strings.TrimSpace(env.Name), env.ID)status := strings.TrimSpace(env.Status)if status == "" {status = "unknown"diff --git a/cli/pkg/generate/api_key_test.go b/cli/pkg/generate/api_key_test.goindex b5ea1ade0..9f6012c26 100644--- a/cli/pkg/generate/api_key_test.go+++ b/cli/pkg/generate/api_key_test.go@@ -28,7 +28,6 @@ func TestAPIKeyDefaultOutput(t *testing.T) {require.NotContains(t, out, "ADMIN_STATIC_API_KEY","expected raw arc_ key in output, got: %q", out)-}func TestGenerateAPIKeyProducesArcanePrefix(t *testing.T) {@@ -42,5 +41,4 @@ func TestGenerateAPIKeyProducesArcanePrefix(t *testing.T) {require.Len(t, apiKey, 68,"expected 68-character key, got %d (%q)", len(apiKey), apiKey)-}diff --git a/cli/pkg/generate/certs.go b/cli/pkg/generate/certs.goindex 14ccd4daf..287e3de2f 100644--- a/cli/pkg/generate/certs.go+++ b/cli/pkg/generate/certs.go@@ -19,7 +19,6 @@ import ("time""emperror.dev/errors"-"github.com/spf13/cobra""go.getarcane.app/acfs/atomic")@@ -129,7 +128,7 @@ type serverTLSPaths struct {KeyPath string}-func generateEdgeMTLSBundleInternal(outDir, envID string, appURL string) (*edgeMTLSPaths, error) {+func generateEdgeMTLSBundleInternal(outDir, envID, appURL string) (*edgeMTLSPaths, error) {if envID == "" {return nil, errors.New("env ID is required")}@@ -190,7 +189,7 @@ func generateEdgeMTLSBundleInternal(outDir, envID string, appURL string) (*edgeMreturn paths, nil}-func generateServerTLSBundleInternal(outDir, commonName string, hosts []string, certName string, keyName string) (*serverTLSPaths, error) {+func generateServerTLSBundleInternal(outDir, commonName string, hosts []string, certName, keyName string) (*serverTLSPaths, error) {if commonName == "" {return nil, errors.New("common name is required")}@@ -335,7 +334,7 @@ func EdgeMTLSTrustDomain(appURL string) string {}// BuildEdgeMTLSURISAN returns the SPIFFE URI SAN for an edge environment ID.-func BuildEdgeMTLSURISAN(appURL string, envID string) *url.URL {+func BuildEdgeMTLSURISAN(appURL, envID string) *url.URL {trustDomain := EdgeMTLSTrustDomain(appURL)envID = strings.TrimSpace(envID)if trustDomain == "" || envID == "" {diff --git a/cli/pkg/generate/certs_test.go b/cli/pkg/generate/certs_test.goindex 161f05c94..f1a7fac5a 100644--- a/cli/pkg/generate/certs_test.go+++ b/cli/pkg/generate/certs_test.go@@ -36,7 +36,6 @@ func TestGenerateMTLSCommandWritesMLDSA87Assets(t *testing.T) {require.False(t, len(cert.URIs) == 0 || cert.URIs[0].String() != "spiffe://manager.example.com/edge/env-123","expected edge SPIFFE URI SAN, got %v", cert.URIs)-}func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {@@ -61,7 +60,6 @@ func TestGenerateTLSCommandWritesECDSAP384ServerCert(t *testing.T) {require.False(t, len(cert.IPAddresses) == 0 || !cert.IPAddresses[0].Equal(net.ParseIP("127.0.0.1")),"expected 127.0.0.1 IP SAN, got %v", cert.IPAddresses)-}func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {@@ -111,7 +109,6 @@ func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {require.Empty(t, tmpFiles,"expected atomic write temp files to be cleaned up, got %v", tmpFiles)-}func assertECDSAP384PrivateKey(t *testing.T, path string) {@@ -142,7 +139,6 @@ func assertECDSAP384PrivateKey(t *testing.T, path string) {require.Equal(t, elliptic.P384(), key.Curve,"expected P-384 private key for %s", path)-}func assertMLDSA87PrivateKey(t *testing.T, path string) {@@ -173,7 +169,6 @@ func assertMLDSA87PrivateKey(t *testing.T, path string) {require.Equal(t, mldsa.MLDSA87(), key.PublicKey().Parameters(),"expected ML-DSA-87 private key for %s", path)-}func assertMLDSA87Certificate(t *testing.T, path string) *x509.Certificate {diff --git a/cli/pkg/generate/secret_test.go b/cli/pkg/generate/secret_test.goindex b2866b9db..e4b093b32 100644--- a/cli/pkg/generate/secret_test.go+++ b/cli/pkg/generate/secret_test.go@@ -100,10 +100,8 @@ func TestSecretAllFormatContainsSections(t *testing.T) {"HEX",}for _, s := range mustContain {-require.Contains(t, out, s,"expected section %q not found in output:\n%s", s, out)-}// verify the hex value decodes to 32 bytesdiff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.goindex 355f3c016..d4d4fde59 100644--- a/cli/pkg/gitops/cmd.go+++ b/cli/pkg/gitops/cmd.go@@ -6,7 +6,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -555,10 +554,7 @@ func gitOpsSyncMatches(item gitops.GitOpsSync, identifierLower, original string)if strings.Contains(strings.ToLower(item.Name), identifierLower) {return true}- if strings.EqualFold(item.Name, original) {- return true- }- return false+ return strings.EqualFold(item.Name, original)}func flattenFileTree(nodes []gitops.FileTreeNode, depth int) [][]string {diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.goindex f802cdf92..68bea08b2 100644--- a/cli/pkg/images/cmd.go+++ b/cli/pkg/images/cmd.go@@ -43,7 +43,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/logger"diff --git a/cli/pkg/images/extra.go b/cli/pkg/images/extra.goindex 3c89f5dd8..f87544f83 100644--- a/cli/pkg/images/extra.go+++ b/cli/pkg/images/extra.go@@ -2,6 +2,7 @@ package imagesimport ("bufio"+ "cmp""encoding/json/v2""fmt""io"@@ -13,7 +14,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/logger""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -644,10 +644,7 @@ func splitImageRef(ref string) (string, string) {// reference, replacing separators with underscores.func exportFileName(imageName string) string {name := strings.NewReplacer("/", "_", ":", "_", "@", "_").Replace(strings.TrimSpace(imageName))- name = strings.Trim(name, "._-")- if name == "" {- name = "image"- }+ name = cmp.Or(strings.Trim(name, "._-"), "image")return name + ".tar"}diff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.goindex 17fb506c8..9d0c22d12 100644--- a/cli/pkg/images/updates/cmd.go+++ b/cli/pkg/images/updates/cmd.go@@ -2,7 +2,8 @@ package updatesimport ("fmt"- "sort"+ "maps"+ "slices""strconv""emperror.dev/errors"@@ -187,11 +188,7 @@ func printBatchResultsInternal(result imageupdate.BatchResponse) error {return cmdutil.PrintJSON(result)}- refs := make([]string, 0, len(result))- for imageRef := range result {- refs = append(refs, imageRef)- }- sort.Strings(refs)+ refs := slices.Sorted(maps.Keys(result))headers := []string{"IMAGE", "UPDATE", "CURRENT", "LATEST", "TYPE"}rows := make([][]string, 0, len(refs))diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.goindex 9c628957e..77284ea6d 100644--- a/cli/pkg/jobs/cmd.go+++ b/cli/pkg/jobs/cmd.go@@ -8,7 +8,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.goindex 8dfbd4625..434faaabc 100644--- a/cli/pkg/networks/cmd.go+++ b/cli/pkg/networks/cmd.go@@ -6,7 +6,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"diff --git a/cli/pkg/projects/actions.go b/cli/pkg/projects/actions.goindex 92faee07c..be42b340f 100644--- a/cli/pkg/projects/actions.go+++ b/cli/pkg/projects/actions.go@@ -11,7 +11,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.goindex 68ebc2987..5f8b0379a 100644--- a/cli/pkg/projects/cmd.go+++ b/cli/pkg/projects/cmd.go@@ -16,7 +16,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -737,8 +736,5 @@ func projectMatches(item project.Details, identifierLower, original string) boolif strings.EqualFold(item.Name, original) {return true}- if strings.Contains(strings.ToLower(item.Path), identifierLower) {- return true- }- return false+ return strings.Contains(strings.ToLower(item.Path), identifierLower)}diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.goindex c83943e2f..b83e2295a 100644--- a/cli/pkg/registries/cmd.go+++ b/cli/pkg/registries/cmd.go@@ -5,7 +5,6 @@ import ("strconv""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.goindex 8347832eb..6ce3e91f5 100644--- a/cli/pkg/repos/cmd.go+++ b/cli/pkg/repos/cmd.go@@ -8,7 +8,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -492,14 +491,14 @@ var repoRef = cmdutil.ResourceRef[gitops.GitRepository, gitops.GitRepository]{Plural: "repositories",IDHint: "the repository ID",ListCmd: "arcane repos list",- GetPath: func(_ string, identifier string) string { return types.GitRepository(identifier) },+ GetPath: func(_, identifier string) string { return types.GitRepository(identifier) },ListPath: func(string) string { return types.GitRepositories() },Matches: repoMatches,Label: func(match gitops.GitRepository) string {return fmt.Sprintf("%s (%s)", match.Name, match.ID)},Promote: func(match gitops.GitRepository) *gitops.GitRepository { return &match },- Exact: func(item gitops.GitRepository, _ string, original string) bool {+ Exact: func(item gitops.GitRepository, _, original string) bool {return strings.EqualFold(item.Name, original) || strings.EqualFold(item.ID, original)},}diff --git a/cli/pkg/root.go b/cli/pkg/root.goindex 3d6bad787..da9e33e9d 100644--- a/cli/pkg/root.go+++ b/cli/pkg/root.go@@ -33,6 +33,7 @@package cliimport (+ "cmp""context""fmt""os"@@ -219,10 +220,7 @@ func instrumentCommandTreeInternal(cmd *cobra.Command) {}cmd.Annotations["arcane:logging-wrapped"] = "true"- action := strings.TrimSpace(cmd.Short)- if action == "" {- action = "Running command"- }+ action := cmp.Or(strings.TrimSpace(cmd.Short), "Running command")if cmd.RunE != nil {originalRunE := cmd.RunEdiff --git a/cli/pkg/selfupdate/cmd.go b/cli/pkg/selfupdate/cmd.goindex 08a234cda..23c7eacc1 100644--- a/cli/pkg/selfupdate/cmd.go+++ b/cli/pkg/selfupdate/cmd.go@@ -19,7 +19,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/config""github.com/getarcaneapp/arcane/cli/v2/internal/output"diff --git a/cli/pkg/selfupdate/cmd_test.go b/cli/pkg/selfupdate/cmd_test.goindex 8f86cc3ca..8ee0acb2c 100644--- a/cli/pkg/selfupdate/cmd_test.go+++ b/cli/pkg/selfupdate/cmd_test.go@@ -17,7 +17,6 @@ func TestFindChecksumMatchesNextDistPath(t *testing.T) {require.Equal(t, "abc123", got,"findChecksum = %q, want abc123", got)-}func TestFindChecksumMatchesArchiveBasename(t *testing.T) {@@ -30,7 +29,6 @@ func TestFindChecksumMatchesArchiveBasename(t *testing.T) {require.Equal(t, "def456", got,"findChecksum = %q, want def456", got)-}func TestChecksumEntryNames(t *testing.T) {@@ -43,10 +41,8 @@ func TestChecksumEntryNames(t *testing.T) {"checksumEntryNames length = %d, want %d (%v)", len(got), len(want), got)}for i := range want {-require.Equal(t, want[i], got[i],"checksumEntryNames[%d] = %q, want %q", i, got[i], want[i])-}}@@ -66,5 +62,4 @@ func TestCLIArtifactNamesUseFlatR2BinaryNames(t *testing.T) {require.Equal(t, "arcane-cli_"+platformName, artifactName,"artifactName = %q, want %q", artifactName, "arcane-cli_"+platformName)-}diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.goindex 4d685b696..f80452734 100644--- a/cli/pkg/system/cmd.go+++ b/cli/pkg/system/cmd.go@@ -1,6 +1,7 @@package systemimport (+ "cmp""fmt""net/http""strconv"@@ -314,14 +315,8 @@ func printUpdateAllJobInternal(job environmentUpdateJob) {headers := []string{"ENVIRONMENT", "STATUS", "FROM", "TO", "ERROR"}rows := make([][]string, len(job.Results))for i, res := range job.Results {- name := res.EnvironmentName- if name == "" {- name = res.EnvironmentID- }- resErr := res.Error- if resErr == "" {- resErr = "-"- }+ name := cmp.Or(res.EnvironmentName, res.EnvironmentID)+ resErr := cmp.Or(res.Error, "-")rows[i] = []string{name, res.Status, res.FromVersion, res.ToVersion, resErr}}fmt.Println()diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.goindex bc62f4158..ae5f43bff 100644--- a/cli/pkg/templates/cmd.go+++ b/cli/pkg/templates/cmd.go@@ -13,7 +13,6 @@ import ("unicode""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -22,6 +21,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/base""github.com/getarcaneapp/arcane/types/v2/template""github.com/spf13/cobra"+ kit "go.getarcane.app/kit/pkg")var (@@ -401,14 +401,8 @@ func selectTemplateCandidateInternal(matches []template.Template, identifier str}func templateOptionLabelInternal(candidate template.Template) string {- source := "local"- if candidate.IsRemote {- source = "remote"- }- custom := "builtin"- if candidate.IsCustom {- custom = "custom"- }+ source := kit.Ternary(candidate.IsRemote, "remote", "local")+ custom := kit.Ternary(candidate.IsCustom, "custom", "builtin")return fmt.Sprintf("%s (id: %s, %s, %s)", candidate.Name, candidate.ID, source, custom)}@@ -431,10 +425,7 @@ func rankFuzzyTemplateMatchesInternal(query string, candidates []template.Templamatched := falseswitch {case nameMatches && idMatches:- score = nameScore- if idScore < nameScore {- score = idScore + 10- }+ score = kit.Ternary(idScore < nameScore, idScore+10, nameScore)matched = truecase nameMatches:score = nameScore@@ -536,10 +527,7 @@ func levenshteinDistanceInternal(left, right string) int {current := make([]int, len(rightRunes)+1)current[0] = leftIndexfor rightIndex := 1; rightIndex <= len(rightRunes); rightIndex++ {- cost := 0- if leftRunes[leftIndex-1] != rightRunes[rightIndex-1] {- cost = 1- }+ cost := kit.Ternary(leftRunes[leftIndex-1] != rightRunes[rightIndex-1], 1, 0)current[rightIndex] = min(current[rightIndex-1]+1,previous[rightIndex]+1,@@ -575,10 +563,7 @@ func topTemplatesFromRankedMatchesInternal(matches []rankedTemplateMatchInternal}func absIntInternal(value int) int {- if value < 0 {- return -value- }- return value+ return kit.Ternary(value < 0, -value, value)}func formatTemplateCandidatesInternal(matches []template.Template) string {diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.goindex 2535311da..e5b96e6f8 100644--- a/cli/pkg/variables/cmd.go+++ b/cli/pkg/variables/cmd.go@@ -1,13 +1,13 @@package variablesimport (+ "cmp""fmt""strconv""strings""time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -59,10 +59,7 @@ func printSyncStatuses(statuses []env.EnvironmentSyncStatus) {if status.LastSyncedAt != nil {lastSynced = status.LastSyncedAt.Format(time.RFC3339)}- syncError := status.Error- if syncError == "" {- syncError = "-"- }+ syncError := cmp.Or(status.Error, "-")rows[i] = []string{status.EnvironmentID,status.EnvironmentName,diff --git a/cli/pkg/volumes/backup.go b/cli/pkg/volumes/backup.goindex 715431e4c..90692cfa2 100644--- a/cli/pkg/volumes/backup.go+++ b/cli/pkg/volumes/backup.go@@ -1,6 +1,7 @@package volumesimport (+ "cmp""encoding/json/v2""fmt""io"@@ -11,7 +12,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -21,6 +21,7 @@ import (uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload""github.com/getarcaneapp/arcane/types/v2/volume""github.com/spf13/cobra"+ kit "go.getarcane.app/kit/pkg")var (@@ -252,10 +253,7 @@ func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollecheaders := []string{"ID", "ENABLED", "SCHEDULE", "RETENTION", "STOP CONTAINERS", "LOCAL", "S3", "S3 DESTINATION"}rows := make([][]string, len(collection.Policies))for i, p := range collection.Policies {- s3Destination := p.S3DestinationName- if s3Destination == "" {- s3Destination = p.S3DestinationID- }+ s3Destination := cmp.Or(p.S3DestinationName, p.S3DestinationID)rows[i] = []string{p.ID,output.TintEnabled(yesNo(p.Enabled)),@@ -271,10 +269,7 @@ func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollec}func yesNo(v bool) string {- if v {- return "Yes"- }- return "No"+ return kit.Ternary(v, "Yes", "No")}var backupsCmd = &cobra.Command{diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.goindex c585d22ec..104a096b6 100644--- a/cli/pkg/volumes/cmd.go+++ b/cli/pkg/volumes/cmd.go@@ -7,7 +7,6 @@ import ("strings""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -415,8 +414,5 @@ func volumeMatches(item volume.Volume, identifierLower, original string) bool {return true}idLower := strings.ToLower(item.ID)- if idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower)) {- return true- }- return false+ return idLower == identifierLower || (len(identifierLower) >= 4 && strings.HasPrefix(idLower, identifierLower))}diff --git a/cli/pkg/volumes/workspace.go b/cli/pkg/volumes/workspace.goindex 63e521287..d02585ce1 100644--- a/cli/pkg/volumes/workspace.go+++ b/cli/pkg/volumes/workspace.go@@ -14,7 +14,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/prompt"diff --git a/cli/pkg/vulnerabilities/cmd.go b/cli/pkg/vulnerabilities/cmd.goindex 9516379e2..c6a25ae45 100644--- a/cli/pkg/vulnerabilities/cmd.go+++ b/cli/pkg/vulnerabilities/cmd.go@@ -8,6 +8,7 @@package vulnerabilitiesimport (+ "cmp""context""fmt""net/url"@@ -15,7 +16,6 @@ import ("time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/client""github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output"@@ -139,7 +139,7 @@ var listCmd = &cobra.Command{item.ImageName,item.PkgName,item.InstalledVersion,- orDash(item.FixedVersion),+ cmp.Or(item.FixedVersion, "-"),}},})@@ -229,7 +229,7 @@ var imageCmd = &cobra.Command{string(item.Severity),item.PkgName,item.InstalledVersion,- orDash(item.FixedVersion),+ cmp.Or(item.FixedVersion, "-"),}},})@@ -327,7 +327,7 @@ var ignoredCmd = &cobra.Command{item.VulnerabilityID,shortImageID(item.ImageID),item.PkgName,- orDash(reason),+ cmp.Or(reason, "-"),item.CreatedAt.Format(time.RFC3339),}},@@ -424,13 +424,6 @@ func printSeveritySummary(s *vulnerability.SeveritySummary) {output.KeyValue("Total", s.Total)}-func orDash(value string) string {- if value == "" {- return "-"- }- return value-}-func shortImageID(id string) string {trimmed := strings.TrimPrefix(id, "sha256:")if len(trimmed) > 12 {diff --git a/cli/pkg/webhooks/cmd.go b/cli/pkg/webhooks/cmd.goindex 0d574b3b8..45ecf5bdd 100644--- a/cli/pkg/webhooks/cmd.go+++ b/cli/pkg/webhooks/cmd.go@@ -3,12 +3,12 @@package webhooksimport (+ "cmp""fmt""net/http""time""emperror.dev/errors"-"github.com/getarcaneapp/arcane/cli/v2/internal/cmdutil""github.com/getarcaneapp/arcane/cli/v2/internal/output""github.com/getarcaneapp/arcane/cli/v2/internal/types"@@ -247,10 +247,7 @@ func init() {}func webhookTarget(item webhook.Summary) string {- name := item.TargetName- if name == "" {- name = item.TargetID- }+ name := cmp.Or(item.TargetName, item.TargetID)if name == "" {return item.TargetType}diff --git a/go.work.sum b/go.work.sumindex 838f98cdf..3d2fc8617 100644--- a/go.work.sum+++ b/go.work.sum@@ -1018,8 +1018,6 @@ github.com/containerd/containerd/v2 v2.1.4/go.mod h1:8C5QV9djwsYDNhxfTCFjWtTBZrqgithub.com/containerd/containerd/v2 v2.2.0-rc.0/go.mod h1:X7H17UATRidzfNzb5vS/l30qEJk0ktoTEU1thMh0Nbk=github.com/containerd/containerd/v2 v2.2.4/go.mod h1:YBcTO8D9149QY9zNmUjy04Mhuc4DlrZQ8FIOwKZEM7o=github.com/containerd/containerd/v2 v2.3.2/go.mod h1:rHKGm3VW6wNrINb3x8mNT+w7qYXFVElTt/8HTuxVhD4=-github.com/containerd/containerd/v2 v2.3.6 h1:huoqZXaDW1x1kgPvFC4rMwxv92vUJnqgq7I5b1rSddM=-github.com/containerd/containerd/v2 v2.3.6/go.mod h1:qaUSWKk9EchqbudSbhv1MxI8dXKGYHLpZtMQdkEkVZ4=github.com/containerd/continuity v0.4.1/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ=github.com/containerd/fuse-overlayfs-snapshotter/v2 v2.1.6 h1:gfW1JsN//B97zhsQ84Kkar7WJqod1fmWf8zKHmz+ieY=github.com/containerd/fuse-overlayfs-snapshotter/v2 v2.1.6/go.mod h1:Mau9LZ7ZnyKCIgcNT7sMG5fjaZ9YCOHU5RuolUikhBQ=@@ -2699,6 +2697,8 @@ go.getarcane.app/docker/convert v0.3.0 h1:yKsepx7UVQTXccZpMzxoySLrv0kE2qv7p7wfMPgo.getarcane.app/docker/convert v0.3.0/go.mod h1:RtKwdUxye+Ildzzc577qngIfhBeKuOM+XUfV9O1yyyg=go.getarcane.app/kit v0.1.0 h1:82oO/i1fS4xbzAG4Xc8ALOWOwW4kwQYDdBpVHE19QkI=go.getarcane.app/kit v0.1.0/go.mod h1:oiH4hLowxfQYFtmldyk/y79XYBHYfzgd86MrSQS9UEg=+go.getarcane.app/kit v0.2.0 h1:3PPHo5nHuns1vjqmCMFPFdnmbH/qQOserONCba/gBi4=+go.getarcane.app/kit v0.2.0/go.mod h1:TGqQCbAJs3ldzkFncXZ93wTVSDhAMQlqyNdVO2CNjIk=go.getarcane.app/streams v0.4.0 h1:MtBX1SVgt3nrcRNr5SYAvckGp9a5qeSjMTw/LAGwlzk=go.getarcane.app/streams v0.4.0/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=go.getarcane.app/streams v0.4.2 h1:+xrRHiOt25cLbFTDpPLzv7eFkk7biwDz5YjBXkbWUPw=diff --git a/types/activity/activity.go b/types/activity/activity.goindex 3bdb819ed..07393d2f6 100644--- a/types/activity/activity.go+++ b/types/activity/activity.go@@ -11,11 +11,7 @@ const (StatusSuccess Status = "success"StatusFailed Status = "failed"StatusCancelled Status = "cancelled"-)--type Type string-const (TypeImagePull Type = "image_pull"TypeImageBuild Type = "image_build"TypeImageUpdateCheck Type = "image_update_check"@@ -40,17 +36,17 @@ const (TypeAutoUpdate Type = "auto_update"TypeSystemPrune Type = "system_prune"TypeResourceAction Type = "resource_action"-)--type MessageLevel string-const (MessageLevelInfo MessageLevel = "info"MessageLevelWarning MessageLevel = "warning"MessageLevelError MessageLevel = "error"MessageLevelSuccess MessageLevel = "success")+type Type string++type MessageLevel string+type Activity struct {ID string `json:"id"`EnvironmentID string `json:"environmentId"`diff --git a/types/backup/system_volume_backup.go b/types/backup/system_volume_backup.goindex d0879d10a..20cb2a54c 100644--- a/types/backup/system_volume_backup.go+++ b/types/backup/system_volume_backup.go@@ -8,20 +8,18 @@ type ManagementType stringconst (ManagementTypeSystem ManagementType = "system"ManagementTypeVolume ManagementType = "volume"-)--// SystemVolumePolicyPrefix marks volume-backup records created by the centralized system policy.-const SystemVolumePolicyPrefix = "system-volume:"-// SystemVolumeSelectionMode controls how configured volume names affect live Docker volumes.-type SystemVolumeSelectionMode string+ // SystemVolumePolicyPrefix marks volume-backup records created by the centralized system policy.+ SystemVolumePolicyPrefix = "system-volume:"-const (SystemVolumeSelectionAll SystemVolumeSelectionMode = "all"SystemVolumeSelectionAllowlist SystemVolumeSelectionMode = "allowlist"SystemVolumeSelectionBlocklist SystemVolumeSelectionMode = "blocklist")+// SystemVolumeSelectionMode controls how configured volume names affect live Docker volumes.+type SystemVolumeSelectionMode string+// SystemVolumeBackupPolicy is one manager-owned policy for local Docker volumes.type SystemVolumeBackupPolicy struct {ID string `json:"id"`diff --git a/types/container/container.go b/types/container/container.goindex 29a0c4720..b5a0bfc07 100644--- a/types/container/container.go+++ b/types/container/container.go@@ -1739,7 +1739,7 @@ type EditConfig struct {}// NewEditConfigFromInspect builds an EditConfig from a docker inspect response.-func NewEditConfigFromInspect(c *container.InspectResponse, isCompose bool, editDisabled bool) EditConfig {+func NewEditConfigFromInspect(c *container.InspectResponse, isCompose, editDisabled bool) EditConfig {cfg := EditConfig{ID: c.ID,Name: strings.TrimPrefix(c.Name, "/"),diff --git a/types/dashboard/dashboard.go b/types/dashboard/dashboard.goindex 5dd73e347..9e95c97cf 100644--- a/types/dashboard/dashboard.go+++ b/types/dashboard/dashboard.go@@ -21,15 +21,16 @@ const (ActionItemKindImageUpdates ActionItemKind = "image_updates"ActionItemKindActionableVulnerabilities ActionItemKind = "actionable_vulnerabilities"ActionItemKindExpiringKeys ActionItemKind = "expiring_keys"-)--type ActionItemSeverity string-const (ActionItemSeverityWarning ActionItemSeverity = "warning"ActionItemSeverityCritical ActionItemSeverity = "critical"++ StreamErrorCodeAgentIncompatible = "agent_incompatible"+ StreamErrorCodeUnreachable = "unreachable")+type ActionItemSeverity string+type ActionItem struct {// Kind identifies the type of dashboard action item.//@@ -131,11 +132,6 @@ type Snapshot struct {VersionInfo *versiontypes.Info `json:"versionInfo,omitempty"`}-const (- StreamErrorCodeAgentIncompatible = "agent_incompatible"- StreamErrorCodeUnreachable = "unreachable"-)-type StreamEvent struct {Type string `json:"type"`EnvironmentID string `json:"environmentId,omitempty"`diff --git a/types/dockerinfo/docker_info_test.go b/types/dockerinfo/docker_info_test.goindex a8e67afa7..6606f79bc 100644--- a/types/dockerinfo/docker_info_test.go+++ b/types/dockerinfo/docker_info_test.go@@ -38,12 +38,10 @@ func TestInfoMarshalsEmbeddedDockerFieldsAtTopLevel(t *testing.T) {require.Equal(t, want, got,"payload[%q] = %#v, want %#v; payload: %s", name, got, want, data)}-}{_, nested := payload["Info"]require.False(t, nested,"Docker fields were nested under Info: %s", data)}-}diff --git a/types/features/features.go b/types/features/features.goindex f59cd9359..ebb295179 100644--- a/types/features/features.go+++ b/types/features/features.go@@ -4,11 +4,13 @@ package features// ID identifies a feature independently of permissions and build options.type ID string-// VulnerabilityManagement identifies scanning, reports, and scan-based patching.-const VulnerabilityManagement ID = "vulnerabilityManagement"+const (+ // VulnerabilityManagement identifies scanning, reports, and scan-based patching.+ VulnerabilityManagement ID = "vulnerabilityManagement"-// VulnerabilityManagementSettingKey is the persisted toggle for vulnerability management.-const VulnerabilityManagementSettingKey = "featureVulnerabilityManagementEnabled"+ // VulnerabilityManagementSettingKey is the persisted toggle for vulnerability management.+ VulnerabilityManagementSettingKey = "featureVulnerabilityManagementEnabled"+)// Definition connects a runtime feature to its persisted setting and default.type Definition struct {diff --git a/types/gitops/gitops.go b/types/gitops/gitops.goindex 00822ad9a..e880af9c2 100644--- a/types/gitops/gitops.go+++ b/types/gitops/gitops.go@@ -7,9 +7,7 @@ const (SyncModeDeploy = "deploy"// SyncModeBackup commits saved project configuration to the repository.SyncModeBackup = "backup"-)-const (BackupStateNever = "never"BackupStatePending = "pending"BackupStateBackingUp = "backing_up"@@ -17,9 +15,7 @@ const (BackupStatePaused = "paused"BackupStateFailed = "failed"BackupStateNeedsAttention = "needs_attention"-)-const (BackupFailureRepository = "repository"BackupFailureAuth = "auth"BackupFailureProjectMissing = "project_missing"@@ -29,11 +25,14 @@ const (BackupFailureConflict = "conflict"BackupFailureDestinationOccupied = "destination_occupied"BackupFailurePushRejected = "push_rejected"-)-const (// BackupConflictUseArcane replaces the remote backup files with Arcane's current files.BackupConflictUseArcane = "use_arcane"++ // FileTreeNodeTypeFile represents a file node.+ FileTreeNodeTypeFile FileTreeNodeType = "file"+ // FileTreeNodeTypeDirectory represents a directory node.+ FileTreeNodeTypeDirectory FileTreeNodeType = "directory")// GitRepository represents a reusable Git repository with credentials.@@ -110,7 +109,6 @@ type GitRepository struct {// GitOpsSync represents a GitOps sync configuration.type GitOpsSync struct {-// CreatedAt is the date and time at which the sync was created.//// Required: true@@ -834,13 +832,6 @@ type SyncResult struct {// FileTreeNodeType represents the type of a file tree node.type FileTreeNodeType string-const (- // FileTreeNodeTypeFile represents a file node.- FileTreeNodeTypeFile FileTreeNodeType = "file"- // FileTreeNodeTypeDirectory represents a directory node.- FileTreeNodeTypeDirectory FileTreeNodeType = "directory"-)-// FileTreeNode represents a file or directory in the repository.type FileTreeNode struct {// Name of the file or directory.diff --git a/types/imagepatch/imagepatch.go b/types/imagepatch/imagepatch.goindex 6b4fa3a24..a69cdf86c 100644--- a/types/imagepatch/imagepatch.go+++ b/types/imagepatch/imagepatch.go@@ -11,17 +11,15 @@ const (PatchModeUpdateAll PatchMode = "update-all"// PatchModeReport patches only packages flagged by a vulnerability scan report.PatchModeReport PatchMode = "report"-)--// PatchStatus is the lifecycle state of a patch run.-type PatchStatus string-const (PatchStatusPatching PatchStatus = "patching"PatchStatusCompleted PatchStatus = "completed"PatchStatusFailed PatchStatus = "failed")+// PatchStatus is the lifecycle state of a patch run.+type PatchStatus string+// PatchOptions are the caller-provided options for patching an image.type PatchOptions struct {// Suffix overrides the configured patched-tag suffix (e.g. "patched").diff --git a/types/jobschedule/runs.go b/types/jobschedule/runs.goindex c1c160e12..8e114eb9d 100644--- a/types/jobschedule/runs.go+++ b/types/jobschedule/runs.go@@ -17,8 +17,10 @@ type RunInput struct {JobID string `path:"jobId" minLength:"1"`RunID string `path:"runId" format:"uuid"`}-type RunOutput struct{ Body st.Run }-type ListRunsOutput struct{ Body st.RunList }+type (+ RunOutput struct{ Body st.Run }+ ListRunsOutput struct{ Body st.RunList }+)// ResolveRunInput accepts the original operator identity only from trusted agent transport.type ResolveRunInput struct {diff --git a/types/notification/notification.go b/types/notification/notification.goindex 1b82aa755..65731c793 100644--- a/types/notification/notification.go+++ b/types/notification/notification.go@@ -42,6 +42,14 @@ const (// NotificationProviderGeneric is the builtin Generic webhook notification provider.NotificationProviderGeneric Provider = "generic"++ DispatchKindImageUpdate DispatchKind = "image_update"+ DispatchKindBatchImageUpdate DispatchKind = "batch_image_update"+ DispatchKindContainerUpdate DispatchKind = "container_update"+ DispatchKindBatchContainerUpdate DispatchKind = "batch_container_update"+ DispatchKindVulnerabilityFound DispatchKind = "vulnerability_found"+ DispatchKindPruneReport DispatchKind = "prune_report"+ DispatchKindAutoHeal DispatchKind = "auto_heal")type Update struct {@@ -95,16 +103,6 @@ type TestResponse struct {type DispatchKind string-const (- DispatchKindImageUpdate DispatchKind = "image_update"- DispatchKindBatchImageUpdate DispatchKind = "batch_image_update"- DispatchKindContainerUpdate DispatchKind = "container_update"- DispatchKindBatchContainerUpdate DispatchKind = "batch_container_update"- DispatchKindVulnerabilityFound DispatchKind = "vulnerability_found"- DispatchKindPruneReport DispatchKind = "prune_report"- DispatchKindAutoHeal DispatchKind = "auto_heal"-)-type DispatchImageUpdate struct {ImageRef string `json:"imageRef"`UpdateInfo imageupdate.Response `json:"updateInfo"`diff --git a/types/project/marshal_utils_test.go b/types/project/marshal_utils_test.goindex c6a20765e..bdb544260 100644--- a/types/project/marshal_utils_test.go+++ b/types/project/marshal_utils_test.go@@ -39,7 +39,6 @@ func TestDetailsUnmarshalJSONAcceptsUnitBytesStringsAndNumbers(t *testing.T) {require.Equal(t, want, got,"mem_limit = %d, want %d", got, want)}-})}}diff --git a/types/swarm/lifecycle.go b/types/swarm/lifecycle.goindex 3b56fa012..2bb006bb7 100644--- a/types/swarm/lifecycle.go+++ b/types/swarm/lifecycle.go@@ -86,17 +86,15 @@ type SwarmJoinEnvironmentRole stringconst (SwarmJoinEnvironmentRoleWorker SwarmJoinEnvironmentRole = "worker"SwarmJoinEnvironmentRoleManager SwarmJoinEnvironmentRole = "manager"-)--type SwarmJoinEnvironmentResultState string-const (SwarmJoinEnvironmentResultJoined SwarmJoinEnvironmentResultState = "joined"SwarmJoinEnvironmentResultAlreadyMember SwarmJoinEnvironmentResultState = "already_member"SwarmJoinEnvironmentResultJoinedUnverified SwarmJoinEnvironmentResultState = "joined_unverified"SwarmJoinEnvironmentResultFailed SwarmJoinEnvironmentResultState = "failed")+type SwarmJoinEnvironmentResultState string+type SwarmJoinCandidate struct {EnvironmentID string `json:"environmentId"`EnvironmentName string `json:"environmentName"`diff --git a/types/swarm/node_test.go b/types/swarm/node_test.goindex 30a12d66e..47c27d1e4 100644--- a/types/swarm/node_test.go+++ b/types/swarm/node_test.go@@ -28,7 +28,6 @@ func TestNodeAgentStatusLegacyJSONCompatibility(t *testing.T) {require.Empty(t, status.Candidates,"candidates = %v, want empty", status.Candidates)-}func TestNodeAgentStatusAmbiguousJSON(t *testing.T) {@@ -61,7 +60,6 @@ func TestNodeAgentStatusAmbiguousJSON(t *testing.T) {require.True(t, reflect.DeepEqual(actual, expected),"JSON = %s, want ambiguous candidate payload", encoded)-}func TestSwarmJoinEnvironmentResultDoesNotExposeToken(t *testing.T) {@@ -73,5 +71,4 @@ func TestSwarmJoinEnvironmentResultDoesNotExposeToken(t *testing.T) {require.False(t, string(encoded) == "" || strings.Contains(string(encoded), "token"),"join result unexpectedly exposes a token field: %s", encoded)-}diff --git a/types/system/prune.go b/types/system/prune.goindex 0429dee79..421edf8e5 100644--- a/types/system/prune.go+++ b/types/system/prune.go@@ -11,42 +11,34 @@ const (PruneContainerModeNone PruneContainerMode = "none"PruneContainerModeStopped PruneContainerMode = "stopped"PruneContainerModeOlderThan PruneContainerMode = "olderThan"-)--type PruneImageMode string-const (PruneImageModeNone PruneImageMode = "none"PruneImageModeDangling PruneImageMode = "dangling"PruneImageModeAll PruneImageMode = "all"PruneImageModeOlderThan PruneImageMode = "olderThan"-)--type PruneVolumeMode string-const (PruneVolumeModeNone PruneVolumeMode = "none"PruneVolumeModeAnonymous PruneVolumeMode = "anonymous"PruneVolumeModeAll PruneVolumeMode = "all"-)-type PruneNetworkMode string--const (PruneNetworkModeNone PruneNetworkMode = "none"PruneNetworkModeUnused PruneNetworkMode = "unused"PruneNetworkModeOlderThan PruneNetworkMode = "olderThan"-)--type PruneBuildCacheMode string-const (PruneBuildCacheModeNone PruneBuildCacheMode = "none"PruneBuildCacheModeUnused PruneBuildCacheMode = "unused"PruneBuildCacheModeAll PruneBuildCacheMode = "all"PruneBuildCacheModeOlderThan PruneBuildCacheMode = "olderThan")+type PruneImageMode string++type PruneVolumeMode string++type PruneNetworkMode string++type PruneBuildCacheMode string+type PruneContainersOptions struct {Mode PruneContainerMode `json:"mode"`Until string `json:"until,omitempty"`diff --git a/types/upload/upload.go b/types/upload/upload.goindex 6581c98a8..ce5de0ac2 100644--- a/types/upload/upload.go+++ b/types/upload/upload.go@@ -4,17 +4,17 @@ package uploadimport "time"-// Session kinds tie an upload session to the domain endpoint allowed to-// consume it.const (+ // Session kinds tie an upload session to the domain endpoint allowed to+ // consume it.+KindImage = "image"KindVolumeBackup = "volume-backup"KindBuildWorkspace = "build-workspace"-)-// Chunk size bounds keep every chunk request safely under common reverse-proxy-// and WAF body limits (~100 MB).-const (+ // Chunk size bounds keep every chunk request safely under common reverse-proxy+ // and WAF body limits (~100 MB).+DefaultChunkSize int64 = 10 * 1024 * 1024MinChunkSize int64 = 1 * 1024 * 1024MaxChunkSize int64 = 50 * 1024 * 1024diff --git a/types/version/version.go b/types/version/version.goindex 3c5bcde83..ca2315dc6 100644--- a/types/version/version.go+++ b/types/version/version.go@@ -1,6 +1,10 @@package version-import "time"+import (+ "cmp"+ "strings"+ "time"+)// Info contains detailed version information about the application.type Info struct {@@ -135,3 +139,25 @@ type StreamEvent struct {// Required: trueTimestamp time.Time `json:"timestamp"`}++// AlreadyOnNewest reports whether the check is confident the environment already+// runs the newest image. Anything unresolved or contradictory reports false.+func (i *Info) AlreadyOnNewest() bool {+ if i == nil || i.UpdateAvailable {+ return false+ }++ currentDigest := strings.TrimSpace(i.CurrentDigest)+ newestDigest := strings.TrimSpace(i.NewestDigest)++ // Digests alone catch a mutable tag rebuilt at the same version. Once either side+ // resolves, both must resolve and agree; a matching version tag is not enough.+ switch {+ case cmp.Or(currentDigest, newestDigest) != "":+ return currentDigest == newestDigest+ case i.NewestVersion != "":+ return strings.TrimPrefix(i.NewestVersion, "v") == strings.TrimPrefix(i.CurrentVersion, "v")+ default:+ return false+ }+}diff --git a/types/volume/backup.go b/types/volume/backup.goindex 7d9cc064f..268ff7f38 100644--- a/types/volume/backup.go+++ b/types/volume/backup.go@@ -8,6 +8,9 @@ const (BackupDestinationLocal BackupDestination = "local"BackupDestinationS3 BackupDestination = "s3"BackupDestinationLocalS3 BackupDestination = "local_s3"++ BackupFormatArchive BackupFormat = "archive"+ BackupFormatRustic BackupFormat = "rustic")type CreateBackupRequest struct {@@ -31,11 +34,6 @@ type DiscoverBackupsResponse struct {type BackupFormat string-const (- BackupFormatArchive BackupFormat = "archive"- BackupFormatRustic BackupFormat = "rustic"-)-type BackupEntry struct {RemoteAvailable *bool `json:"remoteAvailable,omitempty"`ActivityID *string `json:"activityId,omitempty"`diff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.goindex 386b85c86..664b68ab7 100644--- a/types/vulnerability/vulnerability.go+++ b/types/vulnerability/vulnerability.go@@ -16,6 +16,31 @@ const (TrivyClassOSPackages = "os-pkgs"TrivyClassLangPackages = "lang-pkgs"++ RiskBandNone RiskBand = "none"+ RiskBandLow RiskBand = "low"+ RiskBandMedium RiskBand = "medium"+ RiskBandHigh RiskBand = "high"+ RiskBandCritical RiskBand = "critical"++ // ScoreStatusComplete means a score was computed.+ ScoreStatusComplete ScoreStatus = "complete"+ // ScoreStatusUnavailable means no score could be computed.+ ScoreStatusUnavailable ScoreStatus = "unavailable"++ ImageExposureRunning ImageExposure = "running"+ ImageExposureStopped ImageExposure = "stopped"+ ImageExposureUnused ImageExposure = "unused"+ ImageExposureUnknown ImageExposure = "unknown"++ ScanStatusPending ScanStatus = "pending"+ ScanStatusScanning ScanStatus = "scanning"+ ScanStatusCompleted ScanStatus = "completed"+ ScanStatusFailed ScanStatus = "failed"++ ScanPhaseCreatingContainer ScanPhase = "creating_container"+ ScanPhaseScanningImage ScanPhase = "scanning_image"+ ScanPhaseStoringResults ScanPhase = "storing_results")// Vulnerability represents a single vulnerability found in an image@@ -253,24 +278,9 @@ type ScanResult struct {// RiskBand is the qualitative label of a patch priority score, mirroring the CVSS ranges.type RiskBand string-const (- RiskBandNone RiskBand = "none"- RiskBandLow RiskBand = "low"- RiskBandMedium RiskBand = "medium"- RiskBandHigh RiskBand = "high"- RiskBandCritical RiskBand = "critical"-)-// ScoreStatus reports how complete the data behind a patch priority score is.type ScoreStatus string-const (- // ScoreStatusComplete means a score was computed.- ScoreStatusComplete ScoreStatus = "complete"- // ScoreStatusUnavailable means no score could be computed.- ScoreStatusUnavailable ScoreStatus = "unavailable"-)-// PatchPriority is a 0-100 risk score with its label and data status.type PatchPriority struct {// RiskScore is the 0-100 patch priority. An image weighs its worst fixable findings plus their count; an environment averages images by exposure and stays in the High band while a known-exploited fix is running.@@ -327,13 +337,6 @@ type ScanInsights struct {// ImageExposure describes how containers use an image.type ImageExposure string-const (- ImageExposureRunning ImageExposure = "running"- ImageExposureStopped ImageExposure = "stopped"- ImageExposureUnused ImageExposure = "unused"- ImageExposureUnknown ImageExposure = "unknown"-)-// PackageInsight aggregates the findings of one affected package.type PackageInsight struct {// PkgName is the affected package name.@@ -365,22 +368,9 @@ type PackageInsight struct {// ScanStatus represents the status of a vulnerability scantype ScanStatus string-const (- ScanStatusPending ScanStatus = "pending"- ScanStatusScanning ScanStatus = "scanning"- ScanStatusCompleted ScanStatus = "completed"- ScanStatusFailed ScanStatus = "failed"-)-// ScanPhase represents the current phase of an in-progress scan.type ScanPhase string-const (- ScanPhaseCreatingContainer ScanPhase = "creating_container"- ScanPhaseScanningImage ScanPhase = "scanning_image"- ScanPhaseStoringResults ScanPhase = "storing_results"-)-// ScanSummary contains a summary of a vulnerability scan for display in liststype ScanSummary struct {// ImageID is the Docker image ID that was scanneddiff --git a/types/workspace/workspace.go b/types/workspace/workspace.goindex 07a3107cc..321f34879 100644--- a/types/workspace/workspace.go+++ b/types/workspace/workspace.go@@ -9,9 +9,7 @@ const (FileOpRename = "rename"FileOpMove = "move"FileOpDelete = "delete"-)-const (FileReadOnlyBinary = "binary"FileReadOnlyTooLarge = "too_large"FileReadOnlySymlink = "symlink"