Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: replace google/wire DI with uber-go/fx (#3323)
Kyle Mendelldd3b5447195b
diff --git a/Justfile b/Justfileindex 4b3487594..5c126f9ee 100644--- a/Justfile+++ b/Justfile@@ -509,12 +509,7 @@ gomod action="tidy" target="all":_generate-proto:cd {{ edge_proto_dir }} && go run github.com/bufbuild/buf/cmd/buf@latest generate-# Generate Wire dependency injection code.-[group('codegen')]-_generate-wire:- cd backend && go tool wire ./...--# Generate targets. Valid: "proto", "wire".+# Generate targets. Valid: "proto".[group('codegen')]generate target:@just "_generate-{{ target }}"diff --git a/backend/api/api.go b/backend/api/api.goindex 8e8ddcbd2..f731e01a8 100644--- a/backend/api/api.go+++ b/backend/api/api.go@@ -14,8 +14,9 @@ import ("github.com/getarcaneapp/arcane/backend/v2/api/handlers""github.com/getarcaneapp/arcane/backend/v2/api/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/di"+ "github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/labstack/echo/v4"+ "go.uber.org/fx")const (@@ -97,7 +98,7 @@ func arcanePackageName(pkgPath string) (string, bool) {return "", false}- return capitalizeFirst(pkg), true+ return strings.ToUpper(pkg[:1]) + pkg[1:], true}func dockerSchemaPrefix(pkgPath, shortPkg string) (string, bool) {@@ -156,7 +157,7 @@ func qualifyGenericArcaneArgumentsInternal(pkgPath, typeName, schemaName string)replacement := ""if innerPackage != outerPackage {- replacement = capitalizeFirst(innerPackage)+ replacement = strings.ToUpper(innerPackage[:1]) + innerPackage[1:]}argumentTypeIndex := prefixIndex + len(arcaneTypesPrefix) + separator + 1@@ -167,16 +168,56 @@ func qualifyGenericArcaneArgumentsInternal(pkgPath, typeName, schemaName string)return schemaPrefix + huma.DefaultSchemaNamer(reflect.TypeFor[struct{}](), rewrittenTypeName)}-func capitalizeFirst(s string) string {- if s == "" {- return s- }-- return strings.ToUpper(s[:1]) + s[1:]+// HandlerDeps contains the services required to register HTTP API handlers.+//+// It intentionally contains only dependencies consumed by SetupAPI,+// registerHandlersInternal, and the authentication bridge.+type HandlerDeps struct {+ fx.In++ AppImages *services.ApplicationImagesService+ User *services.UserService+ Project *services.ProjectService+ Environment *services.EnvironmentService+ Settings *services.SettingsService+ JobSchedule *services.JobService+ SettingsSearch *services.SettingsSearchService+ CustomizeSearch *services.CustomizeSearchService+ Container *services.ContainerService+ Image *services.ImageService+ Build *services.BuildService+ BuildWorkspace *services.BuildWorkspaceService+ Volume *services.VolumeService+ Network *services.NetworkService+ Port *services.PortService+ Swarm *services.SwarmService+ ImageUpdate *services.ImageUpdateService+ Auth *services.AuthService+ Oidc *services.OidcService+ Docker *services.DockerClientService+ Template *services.TemplateService+ ContainerRegistry *services.ContainerRegistryService+ System *services.SystemService+ SystemUpgrade *services.SystemUpgradeService+ Diagnostics *services.DiagnosticsService+ Updater *services.UpdaterService+ Event *services.EventService+ Activity *services.ActivityService+ Version *services.VersionService+ Notification *services.NotificationService+ ApiKey *services.ApiKeyService+ Federated *services.FederatedCredentialService+ GitRepository *services.GitRepositoryService+ GitOpsSync *services.GitOpsSyncService+ Webhook *services.WebhookService+ Vulnerability *services.VulnerabilityService+ Dashboard *services.DashboardService+ Role *services.RoleService+ Variable *services.VariableService}// SetupAPI creates and configures the Huma API attached to the Echo router.-func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlers.ActivityAppContext, cfg *config.Config, svc *di.Services) huma.API {+func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlers.ActivityAppContext, cfg *config.Config, deps HandlerDeps) huma.API {e.JSONSerializer = jsonV2Serializer{}humaConfig := huma.DefaultConfig("Arcane API", config.Version)@@ -227,11 +268,11 @@ func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlers.ActivityAppConapi := humaecho.NewWithGroup(e, apiGroup, humaConfig)// Add authentication middleware- api.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, svc.Role, svc.Environment, cfg))+ api.UseMiddleware(middleware.NewAuthBridge(api, deps.Auth, deps.ApiKey, deps.Role, deps.Environment, cfg))api.UseMiddleware(middleware.NewActivityBatchID())// Register all Huma handlers- registerHandlersInternal(api, svc, appCtx, cfg)+ registerHandlersInternal(api, deps, appCtx, cfg)// Register Scalar API docs endpoint with dark moderegisterScalarDocs(apiGroup)@@ -309,59 +350,53 @@ func SetupAPIForSpec() huma.API {api := humaecho.NewWithGroup(e, apiGroup, humaConfig)- // Register handlers with nil services (just for schema)- registerHandlersInternal(api, nil, handlers.NewActivityAppContext(context.Background()), nil)+ // Register handlers with zero-value dependencies for schema discovery only.+ registerHandlersInternal(api, HandlerDeps{}, handlers.NewActivityAppContext(context.Background()), nil)return api}// registerHandlers registers all Huma-based API handlers.// Add new handlers here as they are migrated from Gin.-func registerHandlersInternal(api huma.API, svc *di.Services, handlerAppCtx handlers.ActivityAppContext, cfg *config.Config) {- // svc is nil during OpenAPI spec generation (SetupAPIForSpec); an empty- // container supplies typed nil dependencies because handlers are registered- // for schema discovery but are never invoked.- if svc == nil {- svc = &di.Services{}- }+func registerHandlersInternal(api huma.API, deps HandlerDeps, handlerAppCtx handlers.ActivityAppContext, cfg *config.Config) {handlers.RegisterHealth(api)- handlers.RegisterAuth(api, svc.User, svc.Auth, svc.Oidc, svc.Settings)- handlers.RegisterApiKeys(api, svc.ApiKey)- handlers.RegisterFederatedCredentials(api, svc.Federated)- handlers.RegisterRoles(api, svc.Role)- handlers.RegisterAppImages(api, svc.AppImages)- handlers.RegisterUsers(api, svc.User, svc.Auth)- handlers.RegisterProjects(api, svc.Project, svc.Activity, handlerAppCtx)- handlers.RegisterVersion(api, svc.Version)- handlers.RegisterEvents(api, svc.Event)- handlers.RegisterActivities(api, svc.Activity, svc.Environment)- handlers.RegisterOidc(api, svc.Auth, svc.Oidc, svc.Role, svc.User, cfg)- handlers.RegisterEnvironments(api, svc.Environment, svc.Settings, svc.ApiKey, svc.Event, cfg)- handlers.RegisterContainerRegistries(api, svc.ContainerRegistry, svc.Environment)- handlers.RegisterTemplates(api, svc.Template)+ handlers.RegisterAuth(api, deps.User, deps.Auth, deps.Oidc, deps.Settings)+ handlers.RegisterApiKeys(api, deps.ApiKey)+ handlers.RegisterFederatedCredentials(api, deps.Federated)+ handlers.RegisterRoles(api, deps.Role)+ handlers.RegisterAppImages(api, deps.AppImages)+ handlers.RegisterUsers(api, deps.User, deps.Auth)+ handlers.RegisterProjects(api, deps.Project, deps.Activity, handlerAppCtx)+ handlers.RegisterVersion(api, deps.Version)+ handlers.RegisterEvents(api, deps.Event)+ handlers.RegisterActivities(api, deps.Activity, deps.Environment)+ handlers.RegisterOidc(api, deps.Auth, deps.Oidc, deps.Role, deps.User, cfg)+ handlers.RegisterEnvironments(api, deps.Environment, deps.Settings, deps.ApiKey, deps.Event, cfg)+ handlers.RegisterContainerRegistries(api, deps.ContainerRegistry, deps.Environment)+ handlers.RegisterTemplates(api, deps.Template)if cfg != nil && cfg.AgentMode {- handlers.RegisterMaterializedVariables(api, svc.Variable, svc.Environment)+ handlers.RegisterMaterializedVariables(api, deps.Variable, deps.Environment)} else {- handlers.RegisterVariables(api, svc.Variable, svc.Environment)+ handlers.RegisterVariables(api, deps.Variable, deps.Environment)}- handlers.RegisterImages(api, svc.Docker, svc.Image, svc.ImageUpdate, svc.Settings, svc.Build, svc.Activity, handlerAppCtx)- handlers.RegisterBuildWorkspaces(api, svc.BuildWorkspace)- handlers.RegisterImageUpdates(api, svc.ImageUpdate, svc.Image, handlerAppCtx)- handlers.RegisterSettings(api, svc.Settings, svc.SettingsSearch, svc.Environment, cfg)- handlers.RegisterJobSchedules(api, svc.JobSchedule, svc.Environment)- handlers.RegisterVolumes(api, svc.Docker, svc.Volume, svc.Activity, handlerAppCtx)- handlers.RegisterContainers(api, svc.Container, svc.Docker, svc.Settings, svc.Activity, handlerAppCtx)- handlers.RegisterPorts(api, svc.Port)- handlers.RegisterNetworks(api, svc.Network, svc.Docker, svc.Activity, handlerAppCtx)- handlers.RegisterSwarm(api, svc.Swarm, svc.Environment, svc.Event, cfg)- handlers.RegisterNotifications(api, svc.Notification, cfg)- handlers.RegisterUpdater(api, svc.Updater, handlerAppCtx)- handlers.RegisterCustomize(api, svc.CustomizeSearch)- handlers.RegisterSystem(api, svc.Docker, svc.System, svc.SystemUpgrade, svc.Environment, cfg, svc.Activity, handlerAppCtx)- handlers.RegisterDiagnostics(api, svc.Diagnostics)- handlers.RegisterGitRepositories(api, svc.GitRepository)- handlers.RegisterGitOpsSyncs(api, svc.GitOpsSync)- handlers.RegisterWebhooks(api, svc.Webhook)- handlers.RegisterVulnerability(api, svc.Vulnerability, handlerAppCtx)- handlers.RegisterDashboard(api, svc.Dashboard, svc.Environment)+ handlers.RegisterImages(api, deps.Docker, deps.Image, deps.ImageUpdate, deps.Settings, deps.Build, deps.Activity, handlerAppCtx)+ handlers.RegisterBuildWorkspaces(api, deps.BuildWorkspace)+ handlers.RegisterImageUpdates(api, deps.ImageUpdate, deps.Image, handlerAppCtx)+ handlers.RegisterSettings(api, deps.Settings, deps.SettingsSearch, deps.Environment, cfg)+ handlers.RegisterJobSchedules(api, deps.JobSchedule, deps.Environment)+ handlers.RegisterVolumes(api, deps.Docker, deps.Volume, deps.Activity, handlerAppCtx)+ handlers.RegisterContainers(api, deps.Container, deps.Docker, deps.Settings, deps.Activity, handlerAppCtx)+ handlers.RegisterPorts(api, deps.Port)+ handlers.RegisterNetworks(api, deps.Network, deps.Docker, deps.Activity, handlerAppCtx)+ handlers.RegisterSwarm(api, deps.Swarm, deps.Environment, deps.Event, cfg)+ handlers.RegisterNotifications(api, deps.Notification, cfg)+ handlers.RegisterUpdater(api, deps.Updater, handlerAppCtx)+ handlers.RegisterCustomize(api, deps.CustomizeSearch)+ handlers.RegisterSystem(api, deps.Docker, deps.System, deps.SystemUpgrade, deps.Environment, cfg, deps.Activity, handlerAppCtx)+ handlers.RegisterDiagnostics(api, deps.Diagnostics)+ handlers.RegisterGitRepositories(api, deps.GitRepository)+ handlers.RegisterGitOpsSyncs(api, deps.GitOpsSync)+ handlers.RegisterWebhooks(api, deps.Webhook)+ handlers.RegisterVulnerability(api, deps.Vulnerability, handlerAppCtx)+ handlers.RegisterDashboard(api, deps.Dashboard, deps.Environment)}diff --git a/backend/api/api_test.go b/backend/api/api_test.goindex df47f71b8..024217a89 100644--- a/backend/api/api_test.go+++ b/backend/api/api_test.go@@ -11,7 +11,6 @@ import (humav2 "github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/api/handlers""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/di""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"basetypes "github.com/getarcaneapp/arcane/types/v2/base"containertypes "github.com/getarcaneapp/arcane/types/v2/container"@@ -105,6 +104,13 @@ func TestCustomSchemaNamer_DisambiguatesGenericDomainTypes(t *testing.T) {}}+func TestHandlerDeps_ZeroValue(t *testing.T) {+ var deps HandlerDeps++ require.Nil(t, deps.Auth)+ require.Nil(t, deps.Docker)+}+func TestSetupAPIForSpec_DefaultSecurity(t *testing.T) {api := SetupAPIForSpec()@@ -280,7 +286,7 @@ func TestVariableMaterializationRoutesAreAgentOnly(t *testing.T) {router.Group("/api"),handlers.NewActivityAppContext(context.Background()),&config.Config{AgentMode: true},- &di.Services{},+ HandlerDeps{},)require.Nil(t, agentAPI.OpenAPI().Paths["/variables"])materialized := agentAPI.OpenAPI().Paths["/environments/{id}/templates/variables"]diff --git a/backend/go.mod b/backend/go.modindex 69c7bc419..36951030b 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -7,8 +7,6 @@ replace (github.com/getarcaneapp/arcane/types/v2 => ../types)-tool github.com/google/wire/cmd/wire-require (github.com/aws/aws-sdk-go-v2/config v1.32.30github.com/aws/aws-sdk-go-v2/credentials v1.19.29@@ -24,14 +22,13 @@ require (github.com/docker/compose/v5 v5.3.1github.com/docker/go-units v0.5.0github.com/fsnotify/fsnotify v1.10.1- github.com/getarcaneapp/arcane/cli/v2 v2.3.2- github.com/getarcaneapp/arcane/types/v2 v2.4.0+ github.com/getarcaneapp/arcane/cli/v2 v2.5.0+ github.com/getarcaneapp/arcane/types/v2 v2.5.0github.com/go-git/go-git/v5 v5.19.1github.com/gofrs/flock v0.13.0github.com/golang-jwt/jwt/v5 v5.3.1github.com/google/go-containerregistry v0.21.7github.com/google/uuid v1.6.0- github.com/google/wire v0.7.0github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674github.com/jinzhu/copier v0.4.0github.com/klauspost/compress v1.19.0@@ -56,11 +53,12 @@ require (github.com/wneessen/go-mail v0.8.1go.getarcane.app/builds v0.2.0go.getarcane.app/docker/convert v0.1.0- go.getarcane.app/streams v0.3.0+ go.getarcane.app/streams v0.3.1go.getarcane.app/sys/atomic v0.1.0go.getarcane.app/sys/cgroup v0.1.0go.getarcane.app/sys/crypto v0.1.0go.getarcane.app/updater v0.6.0+ go.uber.org/fx v1.24.0go.yaml.in/yaml/v4 v4.0.0-rc.6golang.org/x/crypto v0.54.0golang.org/x/mod v0.38.0@@ -132,7 +130,6 @@ require (github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirectgithub.com/google/go-cmp v0.7.0 // indirectgithub.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect- github.com/google/subcommands v1.2.0 // indirectgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirectgithub.com/hashicorp/errwrap v1.1.0 // indirectgithub.com/hashicorp/go-cleanhttp v0.5.2 // indirect@@ -222,10 +219,11 @@ require (go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirectgo.opentelemetry.io/otel/trace v1.44.0 // indirectgo.opentelemetry.io/proto/otlp v1.10.0 // indirect+ go.uber.org/dig v1.19.0 // indirectgo.uber.org/multierr v1.11.0 // indirect+ go.uber.org/zap v1.26.0 // indirectgolang.org/x/sys v0.47.0 // indirectgolang.org/x/term v0.45.0 // indirect- golang.org/x/tools v0.47.0 // indirectgoogle.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirectgopkg.in/ini.v1 v1.67.2 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 5691d6a5e..7f1042671 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -257,12 +257,8 @@ github.com/google/pprof v0.0.0-20260604005048-7023385849c0 h1:h1QTMDl6q9wDvDCJVpgithub.com/google/pprof v0.0.0-20260604005048-7023385849c0/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=-github.com/google/subcommands v1.2.0 h1:vWQspBTo2nEqTUFita5/KeEWlUL8kQObDFbub/EN9oE=-github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=-github.com/google/wire v0.7.0 h1:JxUKI6+CVBgCO2WToKy/nQk0sS+amI9z9EjVmdaocj4=-github.com/google/wire v0.7.0/go.mod h1:n6YbUQD9cPKTnHXEBN2DXlOp/mVADhVErcMFb0v3J18=github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5THxAzdVpqr6/geYxZytqFMBCOtn/ujyeo=@@ -539,8 +535,8 @@ go.getarcane.app/builds v0.2.0 h1:IXl78t2Lpr4FJ+HQhAGbTgENyPr2WLBxAmFebRu5kuU=go.getarcane.app/builds v0.2.0/go.mod h1:korkB7gWCiWx00SbKtX0sTwxWYeL1pxeTKOYxohjJUA=go.getarcane.app/docker/convert v0.1.0 h1:prlIOs6dMx6CdnetsJFZ6ak0vcistM3DcH5lrZiFHBU=go.getarcane.app/docker/convert v0.1.0/go.mod h1:o9y4z/vah8HiHFtI+jJVFHbs8nLrkARYt88OaUlvGig=-go.getarcane.app/streams v0.3.0 h1:UM4Y8E0lpi0GEKSJ5zUyeho9aJoBIi/Pr3dJnnhCkK4=-go.getarcane.app/streams v0.3.0/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=+go.getarcane.app/streams v0.3.1 h1:Exs9a9G3paM9PnB6DQc8YvIKNbfaUTB7q271SD30zL8=+go.getarcane.app/streams v0.3.1/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=go.getarcane.app/sys/atomic v0.1.0 h1:0HhUeGXYdKAmMW24O+OaqcjDZx6twAuYPBu9T91zKsk=go.getarcane.app/sys/atomic v0.1.0/go.mod h1:QPb5eUXYKYG5acp9jJBAZ/PTbHbByDAQG6eDNAsZZ2w=go.getarcane.app/sys/cgroup v0.1.0 h1:SCAbuU+rZ/EjMU8kkVxmXZsMchiZp9eFdMQFnbU+asA=@@ -583,12 +579,18 @@ go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=+go.uber.org/dig v1.19.0 h1:BACLhebsYdpQ7IROQ1AGPjrXcP5dF80U3gKoFzbaq/4=+go.uber.org/dig v1.19.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE=+go.uber.org/fx v1.24.0 h1:wE8mruvpg2kiiL1Vqd0CC+tr0/24XIB10Iwp2lLWzkg=+go.uber.org/fx v1.24.0/go.mod h1:AmDeGyS+ZARGKM4tlH4FY2Jr63VjbEDJHtqXTGP5hbo=go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=+go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=+go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 9c47952d4..9f09e1c6a 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -6,13 +6,9 @@ import ("fmt""io""log/slog"- "net""net/http""os"- "os/signal""strings"- "sync"- "syscall""time""github.com/moby/moby/client"@@ -20,17 +16,18 @@ import ("github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/di""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"- tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/startup"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+ "github.com/labstack/echo/v4""go.getarcane.app/streams/logs"libcrypto "go.getarcane.app/sys/crypto"- "google.golang.org/grpc"+ "go.uber.org/fx"+ "go.uber.org/fx/fxevent")func Bootstrap(ctx context.Context) error {@@ -67,55 +64,65 @@ func Bootstrap(ctx context.Context) error {cancelApp()return fmt.Errorf("failed to initialize database: %w", err)}- var appServices *di.Services- defer func(ctx context.Context) {+ defer func() {cancelApp()- // appCtx is already canceled here, so derive the shutdown deadline from a- // non-canceled copy of it.- baseCtx := context.WithoutCancel(ctx)- shutdownCtx, shutdownCancel := context.WithTimeout(baseCtx, 10*time.Second)- defer shutdownCancel()- if appServices != nil {- if appServices.Volume != nil {- appServices.Volume.CleanupHelperContainers(shutdownCtx)- }- if appServices.Docker != nil {- appServices.Docker.Close()- }- }if err := db.Close(); err != nil {- slog.ErrorContext(shutdownCtx, "Error closing database", "error", err)+ slog.Error("Error closing database", "error", err)}- }(appCtx)+ }()- httpClient := newConfiguredHTTPClient(cfg)+ app := fx.New(applicationOptions(appCtx, cfg, db, cancelApp))- appServices, err = di.InitializeServices(appCtx, db, cfg, httpClient)- if err != nil {- return fmt.Errorf("failed to initialize services: %w", err)+ startCtx, cancelStart := context.WithTimeout(ctx, 5*time.Minute)+ defer cancelStart()+ if err := app.Start(startCtx); err != nil {+ return fmt.Errorf("start application: %w", err)}- dockerClientService := appServices.Docker-- initializeStartupState(appCtx, cfg, appServices, dockerClientService, httpClient)- cronLocation := cfg.GetLocation()- scheduler := scheduler.NewJobScheduler(appCtx, cronLocation)- appServices.JobSchedule.SetScheduler(appCtx, scheduler)- registerJobs(appCtx, scheduler, appServices, cfg)-- router, tunnelServer := setupRouter(appCtx, cfg, appServices)-- startEdgeTunnelClientIfConfigured(appCtx, cfg, router)+ select {+ case <-ctx.Done():+ slog.InfoContext(appCtx, "Context canceled")+ case signal := <-app.Done():+ slog.InfoContext(appCtx, "Received shutdown signal", "signal", signal)+ }- err = runServicesInternal(appCtx, cancelApp, cfg, router, tunnelServer, scheduler)- if err != nil {- return fmt.Errorf("failed to run services: %w", err)+ stopCtx, cancelStop := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)+ defer cancelStop()+ if err := app.Stop(stopCtx); err != nil {+ return fmt.Errorf("stop application: %w", err)}- slog.InfoContext(appCtx, "Arcane shutdown complete")+ slog.InfoContext(context.WithoutCancel(appCtx), "Arcane shutdown complete")return nil}+func applicationOptions(appCtx context.Context, cfg *config.Config, db *database.DB, cancelApp context.CancelFunc) fx.Option {+ return fx.Options(+ fx.Supply(cfg, db, cancelApp),+ fx.Provide(+ func() context.Context { return appCtx },+ newConfiguredHTTPClient,+ ),+ di.ServiceOptions,+ di.JobOptions,+ serverOptions,+ fx.Invoke(+ initializeStartupState,+ registerJobs,+ registerAppRollbackCancelHook,+ startEdgeTunnelClient,+ registerAppCancelHook,+ ),+ fx.WithLogger(func() fxevent.Logger {+ logger := &fxevent.SlogLogger{Logger: slog.Default()}+ logger.UseLogLevel(slog.LevelDebug)+ return logger+ }),+ fx.StartTimeout(5*time.Minute),+ fx.StopTimeout(30*time.Second),+ )+}+// isWeakProductionEncryptionKeyInternal reports whether an explicit// ENCRYPTION_KEY is an unprefixed passphrase shorter than 32 characters in// production. libcrypto derives a key from any non-empty passphrase, so this@@ -138,9 +145,33 @@ func newConfiguredHTTPClient(cfg *config.Config) *http.Client {return httputils.NewHTTPClient()}-func initializeStartupState(appCtx context.Context, cfg *config.Config, appServices *di.Services, dockerClientService *services.DockerClientService, httpClient *http.Client) {- if appServices.Volume != nil {- startup.CleanupOrphanedVolumeHelpers(appCtx, appServices.Volume.CleanupOrphanedVolumeHelpers)+type initializeStartupStateParams struct {+ fx.In++ AppCtx context.Context+ Config *config.Config+ HTTPClient *http.Client++ Volume *services.VolumeService+ Settings *services.SettingsService+ Environment *services.EnvironmentService+ GitOpsSync *services.GitOpsSyncService+ Project *services.ProjectService+ Variable *services.VariableService+ Docker *services.DockerClientService+ Swarm *services.SwarmService+ Role *services.RoleService+ User *services.UserService+ ApiKey *services.ApiKeyService+}++func initializeStartupState(p initializeStartupStateParams) {+ appCtx := p.AppCtx+ cfg := p.Config+ httpClient := p.HTTPClient++ if p.Volume != nil {+ startup.CleanupOrphanedVolumeHelpers(appCtx, p.Volume.CleanupOrphanedVolumeHelpers)}runtimeCfg := &startup.RuntimeConfig{@@ -152,8 +183,8 @@ func initializeStartupState(appCtx context.Context, cfg *config.Config, appServiAdminStaticAPIKey: cfg.AdminStaticAPIKey,}- startup.LoadAgentToken(appCtx, runtimeCfg, appServices.Settings.GetStringSetting)- startup.EnsureEncryptionKey(appCtx, runtimeCfg, appServices.Settings.EnsureEncryptionKey)+ startup.LoadAgentToken(appCtx, runtimeCfg, p.Settings.GetStringSetting)+ startup.EnsureEncryptionKey(appCtx, runtimeCfg, p.Settings.EnsureEncryptionKey)cfg.AgentToken = runtimeCfg.AgentTokencfg.EncryptionKey = runtimeCfg.EncryptionKey@@ -166,43 +197,43 @@ func initializeStartupState(appCtx context.Context, cfg *config.Config, appServiEnvironment: string(cfg.Environment),AgentMode: cfg.AgentMode,})- startup.InitializeDefaultSettings(appCtx, runtimeCfg, appServices.Settings)+ startup.InitializeDefaultSettings(appCtx, runtimeCfg, p.Settings)- if err := appServices.Settings.NormalizeProjectsDirectory(appCtx, cfg.ProjectsDirectory); err != nil {+ if err := p.Settings.NormalizeProjectsDirectory(appCtx, cfg.ProjectsDirectory); err != nil {slog.WarnContext(appCtx, "Failed to normalize projects directory", "error", err)}- if err := appServices.Settings.NormalizeBuildsDirectory(appCtx); err != nil {+ if err := p.Settings.NormalizeBuildsDirectory(appCtx); err != nil {slog.WarnContext(appCtx, "Failed to normalize builds directory", "error", err)}- if err := appServices.Environment.EnsureLocalEnvironment(appCtx, cfg.AppUrl); err != nil {+ if err := p.Environment.EnsureLocalEnvironment(appCtx, cfg.AppUrl); err != nil {slog.WarnContext(appCtx, "Failed to ensure local environment", "error", err)}- initializeGitOpsStartupStateInternal(appCtx, appServices.GitOpsSync)- if appServices.Project != nil {- if err := appServices.Project.RecoverProjectRenameJournals(appCtx); err != nil {+ initializeGitOpsStartupStateInternal(appCtx, p.GitOpsSync)+ if p.Project != nil {+ if err := p.Project.RecoverProjectRenameJournals(appCtx); err != nil {slog.WarnContext(appCtx, "Failed to recover interrupted project rename operations on startup", "error", err)}}if !cfg.AgentMode {- if err := appServices.Environment.ReconcileEdgeStatusesOnStartup(appCtx); err != nil {+ if err := p.Environment.ReconcileEdgeStatusesOnStartup(appCtx); err != nil {slog.WarnContext(appCtx, "Failed to reconcile edge environment statuses on startup", "error", err)}// Global variables are a manager resource: import any pre-existing local// .env.global once, then materialize the effective set everywhere. Agents// only serve the per-environment variables endpoint the manager pushes to.- appServices.Environment.SetVariableSyncer(appServices.Variable)- if err := appServices.Variable.ImportLegacyLocalEnvFile(appCtx); err != nil {+ p.Environment.SetVariableSyncer(p.Variable)+ if err := p.Variable.ImportLegacyLocalEnvFile(appCtx); err != nil {slog.WarnContext(appCtx, "Failed to import legacy global variables", "error", err)}- go appServices.Variable.SyncAll(appCtx)+ go p.Variable.SyncAll(appCtx)}startup.TestDockerConnection(appCtx, func(ctx context.Context) error {- dockerClient, err := dockerClientService.GetClient(ctx)+ dockerClient, err := p.Docker.GetClient(ctx)if err != nil {return err}@@ -219,27 +250,26 @@ func initializeStartupState(appCtx context.Context, cfg *config.Config, appServislog.InfoContext(ctx, "Docker API versions detected", "client_api_version", dockerClient.ClientVersion(), "server_api_version", version.APIVersion, "effective_api_version", effectiveAPIVersion)return nil})- go dockerClientService.WatchEvents(appCtx)- if appServices.Swarm != nil {- if err := appServices.Swarm.SyncSwarmEnabledState(appCtx); err != nil {+ if p.Swarm != nil {+ if err := p.Swarm.SyncSwarmEnabledState(appCtx); err != nil {slog.WarnContext(appCtx, "Failed to persist swarm enabled state", "error", err)}}startup.InitializeNonAgentFeatures(appCtx, runtimeCfg,- appServices.Role.EnsureBuiltInRoles,- appServices.User.CreateDefaultAdmin,+ p.Role.EnsureBuiltInRoles,+ p.User.CreateDefaultAdmin,func(ctx context.Context) error {- return appServices.ApiKey.ReconcileDefaultAdminAPIKey(ctx, runtimeCfg.AdminStaticAPIKey)+ return p.ApiKey.ReconcileDefaultAdminAPIKey(ctx, runtimeCfg.AdminStaticAPIKey)},func(ctx context.Context) error {startup.InitializeAutoLogin(ctx, runtimeCfg)return nil},)- startup.CleanupUnknownSettings(appCtx, appServices.Settings)+ startup.CleanupUnknownSettings(appCtx, p.Settings)- runRoleStartupTasks(appCtx, appServices.Role, cfg, cfg.AgentMode)+ runRoleStartupTasks(appCtx, p.Role, cfg, cfg.AgentMode)// Auto-pair only applies in Edge mode (where the agent's outbound tunnel is the// only path to the manager). Direct mode is passive — the manager dials the agent's@@ -300,6 +330,33 @@ func runRoleStartupTasks(ctx context.Context, roleService *services.RoleService,}}+func startEdgeTunnelClient(appCtx context.Context, lc fx.Lifecycle, cfg *config.Config, router *echo.Echo, _ *http.Server) {+ lc.Append(fx.Hook{+ OnStart: func(context.Context) error {+ startEdgeTunnelClientIfConfigured(appCtx, cfg, router)+ return nil+ },+ })+}++func registerAppRollbackCancelHook(lc fx.Lifecycle, cancelApp context.CancelFunc) {+ lc.Append(fx.Hook{+ OnStop: func(context.Context) error {+ cancelApp()+ return nil+ },+ })+}++func registerAppCancelHook(lc fx.Lifecycle, cancelApp context.CancelFunc) {+ lc.Append(fx.Hook{+ OnStop: func(context.Context) error {+ cancelApp()+ return nil+ },+ })+}+func startEdgeTunnelClientIfConfigured(appCtx context.Context, cfg *config.Config, router http.Handler) {managerEndpointConfigured := cfg.ManagerApiUrl != ""if !cfg.EdgeAgent || !managerEndpointConfigured || cfg.AgentToken == "" {@@ -397,270 +454,3 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpClreturn fmt.Errorf("pairing failed with status %d: %s", resp.StatusCode, string(body))}}--func runServicesInternal(appCtx context.Context, cancelApp context.CancelFunc, cfg *config.Config, router http.Handler, tunnelServer *edge.TunnelServer, schedulers ...interface {- Run(ctx context.Context) error-}) error {- var schedulerWaitGroup sync.WaitGroup- defer func() {- cancelApp()- schedulerWaitGroup.Wait()- }()-- listenAddr := cfg.ListenAddr()- useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(appCtx, cfg)- if err != nil {- return err- }- if tunnelServer != nil {- tunnelServer.SetConfig(edgeCfg)- }-- httpHandler, grpcServer := configureTunnelServerInternal(appCtx, cfg, router, tunnelServer, listenAddr)- httpHandler, protocols := configureHTTPProtocolsInternal(useTLS, httpHandler)-- // Base context for all request contexts. Derived from Background, NOT- // appCtx: appCtx carries the app-lifecycle marker value and inheriting it- // would make every request context pass utils.IsAppLifecycleContext (see- // pkg/projects/cmds.go).- baseCtx, cancelBase := context.WithCancel(context.Background())- defer cancelBase()-- srv, err := newHTTPServerInternal(baseCtx, listenAddr, httpHandler, protocols, useTLS, edgeCfg) //nolint:contextcheck // baseCtx is deliberately not derived from appCtx, see comment above- if err != nil {- return err- }- for _, serviceScheduler := range schedulers {- scheduler := serviceScheduler- schedulerWaitGroup.Go(func() {- slog.InfoContext(appCtx, "Starting scheduler")- if err := scheduler.Run(appCtx); err != nil {- if !errors.Is(err, context.Canceled) {- slog.ErrorContext(appCtx, "Job scheduler exited with error", "error", err)- }- }- slog.InfoContext(appCtx, "Scheduler stopped")- })- }-- go func() {- slog.InfoContext(appCtx, "Starting HTTP server", "addr", listenAddr, "listen", cfg.Listen, "port", cfg.Port, "tls_enabled", useTLS)-- var err error- if useTLS {- err = srv.ListenAndServeTLS(tlsCertFile, tlsKeyFile)- } else {- err = srv.ListenAndServe()- }-- if err != nil && !errors.Is(err, http.ErrServerClosed) {- slog.ErrorContext(appCtx, "Failed to start server", "error", err)- }- }()-- quit := make(chan os.Signal, 1)- signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)- defer signal.Stop(quit)-- select {- case <-quit:- slog.InfoContext(appCtx, "Received shutdown signal")- cancelApp()- case <-appCtx.Done():- slog.InfoContext(appCtx, "Context canceled")- }-- // http.Server.Shutdown waits for in-flight handlers but does not cancel- // their request contexts; streaming handlers (activity streams, JSON-lines- // progress) loop on ctx.Done() and would otherwise pin Shutdown until the- // deadline below.- cancelBase()-- // Use background context for shutdown as appCtx is already canceled- shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)- defer shutdownCancel()-- if err := srv.Shutdown(shutdownCtx); err != nil { //nolint:contextcheck- slog.ErrorContext(shutdownCtx, "Server forced to shutdown", "error", err) //nolint:contextcheck- return err- }-- if grpcServer != nil {- grpcServer.GracefulStop()- }-- // Wait for tunnel cleanup loop to finish- if tunnelServer != nil {- tunnelServer.WaitForCleanupDone()- }-- slog.InfoContext(shutdownCtx, "Server stopped gracefully") //nolint:contextcheck- return nil-}--func prepareServerTLSInternal(ctx context.Context, cfg *config.Config) (bool, string, string, *edge.Config, error) {- useTLS := cfg.TLSEnabled- tlsCertFile := strings.TrimSpace(cfg.TLSCertFile)- tlsKeyFile := strings.TrimSpace(cfg.TLSKeyFile)- edgeCfg := buildEdgeRuntimeConfigInternal(cfg)- if useTLS && (tlsCertFile == "" || tlsKeyFile == "") {- return false, "", "", nil, errors.New("TLS_ENABLED requires both TLS_CERT_FILE and TLS_KEY_FILE")- }-- if cfg.AgentMode {- return useTLS, tlsCertFile, tlsKeyFile, edgeCfg, nil- }-- if err := edge.PrepareManagerMTLSAssetsWithContext(ctx, edgeCfg); err != nil {- return false, "", "", nil, err- }-- if edge.NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) != edge.EdgeMTLSModeDisabled {- if err := edge.ValidateManagerMTLSConfig(edgeCfg); err != nil {- return false, "", "", nil, err- }- }-- return useTLS, tlsCertFile, tlsKeyFile, edgeCfg, nil-}--func configureTunnelServerInternal(appCtx context.Context, cfg *config.Config, router http.Handler, tunnelServer *edge.TunnelServer, listenAddr string) (http.Handler, *grpc.Server) {- httpHandler := router- var grpcServer *grpc.Server-- if !cfg.AgentMode && tunnelServer != nil {- grpcServer = grpc.NewServer(tunnelServer.GRPCServerOptions(appCtx)...)- tunnelpb.RegisterTunnelServiceServer(grpcServer, tunnelServer)-- httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if isTunnelGRPCRequestInternal(r) {- grpcReq := normalizeTunnelGRPCRequestPathInternal(r)- grpcServer.ServeHTTP(w, grpcReq)- return- }- router.ServeHTTP(w, r)- })- slog.InfoContext(appCtx, "Using shared HTTP/gRPC listener for edge tunnel", "addr", listenAddr)- }-- return httpHandler, grpcServer-}--func configureHTTPProtocolsInternal(useTLS bool, handler http.Handler) (http.Handler, *http.Protocols) {- var protocols http.Protocols- protocols.SetHTTP1(true)- if useTLS {- protocols.SetHTTP2(true)- return handler, &protocols- }-- protocols.SetUnencryptedHTTP2(true)- return handler, &protocols-}--func newHTTPServerInternal(baseCtx context.Context, listenAddr string, handler http.Handler, protocols *http.Protocols, useTLS bool, edgeCfg *edge.Config) (*http.Server, error) {- srv := &http.Server{- Addr: listenAddr,- Handler: handler,- Protocols: protocols,- ReadHeaderTimeout: 5 * time.Second,- // IdleTimeout closes idle keep-alive connections so upstream pools- // (e.g. Caddy) don't accumulate stale entries. ReadTimeout and- // WriteTimeout are intentionally unset — WebSocket upgrades and- // streaming endpoints (deploy/pull/build progress) need long-lived- // connections.- IdleTimeout: 120 * time.Second,- // BaseContext is canceled right before Shutdown so long-lived- // streaming request contexts unblock and graceful shutdown can- // complete within its deadline.- BaseContext: func(net.Listener) context.Context { return baseCtx },- }- if !useTLS {- return srv, nil- }-- tlsConfig, err := edge.BuildManagerServerTLSConfig(edgeCfg)- if err != nil {- return nil, err- }- if tlsConfig != nil {- srv.TLSConfig = tlsConfig- }- return srv, nil-}--func buildEdgeRuntimeConfigInternal(cfg *config.Config) *edge.Config {- return &edge.Config{- EdgeAgent: cfg.EdgeAgent,- EdgeTransport: cfg.EdgeTransport,- EdgeReconnectInterval: cfg.EdgeReconnectInterval,- EdgeMTLSMode: cfg.EdgeMTLSMode,- EdgeMTLSCAFile: cfg.EdgeMTLSCAFile,- EdgeMTLSCertFile: cfg.EdgeMTLSCertFile,- EdgeMTLSKeyFile: cfg.EdgeMTLSKeyFile,- EdgeMTLSServerName: cfg.EdgeMTLSServerName,- EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,- AppURL: cfg.GetAppURL(),- ManagerApiUrl: cfg.ManagerApiUrl,- AgentToken: cfg.AgentToken,- Port: cfg.Port,- Listen: cfg.Listen,- }-}--func normalizeTunnelGRPCRequestPathInternal(r *http.Request) *http.Request {- if r == nil {- return nil- }- if r.URL == nil {- return r- }-- connectMethodPath := tunnelpb.TunnelService_Connect_FullMethodName-- const tunnelConnectPath = "/api/tunnel/connect"- if strings.HasSuffix(r.URL.Path, tunnelConnectPath) {- clone := r.Clone(r.Context())- cloneURL := *clone.URL- cloneURL.Path = connectMethodPath- clone.URL = &cloneURL- clone.RequestURI = connectMethodPath- return clone- }-- idx := strings.Index(r.URL.Path, connectMethodPath)- if idx <= 0 {- return r- }-- normalizedPath := r.URL.Path[idx:]- if normalizedPath == r.URL.Path {- return r- }-- clone := r.Clone(r.Context())- cloneURL := *clone.URL- cloneURL.Path = normalizedPath- clone.URL = &cloneURL- clone.RequestURI = normalizedPath- return clone-}--func isTunnelGRPCRequestInternal(r *http.Request) bool {- if r == nil || r.URL == nil {- return false- }-- if r.Method != http.MethodPost {- return false- }-- path := r.URL.Path- fullMethodPath := tunnelpb.TunnelService_Connect_FullMethodName- if path == fullMethodPath || strings.HasSuffix(path, fullMethodPath) {- return true- }-- contentType := strings.ToLower(strings.TrimSpace(r.Header.Get("Content-Type")))- return strings.HasPrefix(contentType, "application/grpc")-}diff --git a/backend/internal/bootstrap/bootstrap_test.go b/backend/internal/bootstrap/bootstrap_test.goindex 9975e862c..771cd73b1 100644--- a/backend/internal/bootstrap/bootstrap_test.go+++ b/backend/internal/bootstrap/bootstrap_test.go@@ -3,47 +3,45 @@ package bootstrapimport ("context""crypto/tls"+ "errors""io""net""net/http""net/http/httptest""strconv"- "sync/atomic""testing""time"+ "github.com/getarcaneapp/arcane/backend/v2/api""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/di"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1"+ "github.com/labstack/echo/v4""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"libcrypto "go.getarcane.app/sys/crypto"+ "go.uber.org/fx"+ "go.uber.org/fx/fxtest""golang.org/x/net/http2")-type blockingServiceSchedulerInternal struct {- runCalls atomic.Int32- started chan struct{}- cancellationObserved chan struct{}- release <-chan struct{}+type blockingBusWatcherInternal struct {+ started chan struct{}+ stopped chan struct{}}-func (s *blockingServiceSchedulerInternal) Run(ctx context.Context) error {- s.runCalls.Add(1)- if s.started != nil {- s.started <- struct{}{}- }+func (w *blockingBusWatcherInternal) Name() string { return "blocking" }++func (w *blockingBusWatcherInternal) Start(ctx context.Context) error {+ close(w.started)<-ctx.Done()- if s.cancellationObserved != nil {- s.cancellationObserved <- struct{}{}- }- if s.release != nil {- <-s.release- }+ close(w.stopped)return nil}+func (w *blockingBusWatcherInternal) RunNow(context.Context) error { return nil }+func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {fullMethodPath := tunnelpb.TunnelService_Connect_FullMethodName@@ -175,10 +173,14 @@ func TestConfigureHTTPProtocolsInternal(t *testing.T) {func TestHTTP2APIResponsesDoNotUseAPIGzipInternal(t *testing.T) {cfg := &config.Config{+ AgentMode: true,AppUrl: "http://localhost:3552",Environment: config.AppEnvironmentTest,}- router, _ := setupRouter(context.Background(), cfg, &di.Services{+ router, _ := newRouter(RouterParams{+ Context: context.Background(),+ Config: cfg,+ HandlerDeps: api.HandlerDeps{},AuthMiddleware: middleware.NewAuthMiddleware(nil, cfg),})handler, protocols := configureHTTPProtocolsInternal(false, router)@@ -235,123 +237,145 @@ func TestHTTP2APIResponsesDoNotUseAPIGzipInternal(t *testing.T) {}}-func TestShutdownCancelsStreamingRequestContextsInternal(t *testing.T) {- baseCtx, cancelBase := context.WithCancel(context.Background())- defer cancelBase()+func TestHTTPServerStopCancelsStreamingRequestContextsInternal(t *testing.T) {+ appCtx, cancelApp := context.WithCancel(context.Background())+ defer cancelApp()handlerEntered := make(chan struct{})- handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.Header().Set("Content-Type", "application/x-json-stream")- w.WriteHeader(http.StatusOK)- if f, ok := w.(http.Flusher); ok {- f.Flush()- }+ router := echo.New()+ router.GET("/stream", func(c echo.Context) error {+ c.Response().Header().Set("Content-Type", "application/x-json-stream")+ c.Response().WriteHeader(http.StatusOK)+ c.Response().Flush()close(handlerEntered)- // Streaming handlers block until their request context ends; Shutdown- // alone never cancels it, so this models an open activity stream.- <-r.Context().Done()+ <-c.Request().Context().Done()+ return nil})- srv, err := newHTTPServerInternal(baseCtx, "127.0.0.1:0", handler, nil, false, nil)- require.NoError(t, err)-- listener, err := net.Listen("tcp", "127.0.0.1:0")+ cfg := &config.Config{+ AgentMode: true,+ Listen: "127.0.0.1",+ Port: "0",+ }+ lifecycle := fxtest.NewLifecycle(t)+ srv, err := NewHTTPServer(lifecycle, HTTPServerParams{+ AppCtx: appCtx,+ Config: cfg,+ Router: router,+ })require.NoError(t, err)+ require.NoError(t, lifecycle.Start(context.Background()))- errCh := make(chan error, 1)- go func() { errCh <- srv.Serve(listener) }()-- resp, err := http.Get("http://" + listener.Addr().String() + "/stream")+ resp, err := http.Get("http://" + srv.Addr + "/stream")require.NoError(t, err)defer func() { _ = resp.Body.Close() }()<-handlerEntered- cancelBase()-- shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)- defer cancel()+ shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancelShutdown()start := time.Now()- require.NoError(t, srv.Shutdown(shutdownCtx))+ require.NoError(t, lifecycle.Stop(shutdownCtx))require.Less(t, time.Since(start), time.Second)- require.ErrorIs(t, <-errCh, http.ErrServerClosed)}-func TestRunServicesInternalDoesNotStartSchedulersBeforeServerInitialization(t *testing.T) {- appCtx, cancelApp := context.WithCancel(context.Background())- scheduler := &blockingServiceSchedulerInternal{}+func TestNewHTTPServerRejectsInvalidTLSCertificateInternal(t *testing.T) {cfg := &config.Config{- AgentMode: true,- TLSEnabled: true,+ AgentMode: true,+ TLSEnabled: true,+ TLSCertFile: t.TempDir() + "/missing.crt",+ TLSKeyFile: t.TempDir() + "/missing.key",}- err := runServicesInternal(appCtx, cancelApp, cfg, http.NewServeMux(), nil, scheduler)- require.ErrorContains(t, err, "TLS_ENABLED requires both TLS_CERT_FILE and TLS_KEY_FILE")- require.Zero(t, scheduler.runCalls.Load())- require.ErrorIs(t, appCtx.Err(), context.Canceled)+ _, err := NewHTTPServer(fxtest.NewLifecycle(t), HTTPServerParams{+ AppCtx: context.Background(),+ Config: cfg,+ Router: echo.New(),+ })+ require.Error(t, err)}-func TestRunServicesInternalWaitsForSchedulersBeforeReleasingDependencies(t *testing.T) {+func TestRegisterAppCancelHookRunsBeforeEarlierStopHooks(t *testing.T) {appCtx, cancelApp := context.WithCancel(context.Background())- started := make(chan struct{}, 1)- cancellationObserved := make(chan struct{}, 1)- releaseScheduler := make(chan struct{}, 1)- scheduler := &blockingServiceSchedulerInternal{- started: started,- cancellationObserved: cancellationObserved,- release: releaseScheduler,- }- cfg := &config.Config{- AgentMode: true,- Environment: config.AppEnvironmentTest,- Listen: "127.0.0.1",- Port: "0",- }-- runDone := make(chan error, 1)- dependenciesReleased := make(chan struct{})- go func() {- err := runServicesInternal(appCtx, cancelApp, cfg, http.NewServeMux(), nil, scheduler)- close(dependenciesReleased)- runDone <- err- }()- t.Cleanup(func() {- cancelApp()- select {- case releaseScheduler <- struct{}{}:- default:- }+ lifecycle := fxtest.NewLifecycle(t)+ appCanceledBeforeDependencyStop := false+ lifecycle.Append(fx.Hook{+ OnStop: func(context.Context) error {+ appCanceledBeforeDependencyStop = errors.Is(appCtx.Err(), context.Canceled)+ return nil+ },})+ registerAppCancelHook(lifecycle, cancelApp)- select {- case <-started:- case <-time.After(time.Second):- t.Fatal("scheduler did not start")- }- cancelApp()- select {- case <-cancellationObserved:- case <-time.After(time.Second):- t.Fatal("scheduler did not observe lifecycle cancellation")- }+ lifecycle.RequireStart()+ lifecycle.RequireStop()+ require.True(t, appCanceledBeforeDependencyStop)+}- select {- case <-dependenciesReleased:- t.Fatal("service runner released dependencies before the scheduler stopped")- case <-time.After(100 * time.Millisecond):+func TestRollbackCancelHookRunsBeforeEarlierStopsInternal(t *testing.T) {+ appCtx, cancelApp := context.WithCancel(context.Background())+ appCanceledBeforeDependencyStop := false+ app := fxtest.New(t,+ fx.Supply(cancelApp),+ fx.Invoke(func(lc fx.Lifecycle) {+ lc.Append(fx.Hook{+ OnStop: func(context.Context) error {+ appCanceledBeforeDependencyStop = errors.Is(appCtx.Err(), context.Canceled)+ return nil+ },+ })+ }),+ fx.Invoke(registerAppRollbackCancelHook),+ fx.Invoke(func(lc fx.Lifecycle) {+ lc.Append(fx.Hook{+ OnStart: func(context.Context) error {+ return errors.New("listen failed")+ },+ })+ }),+ )++ require.Error(t, app.Start(context.Background()))+ require.True(t, appCanceledBeforeDependencyStop)+}++func TestJobSchedulerStopCancelsItsPrivateContextInternal(t *testing.T) {+ appCtx, cancelApp := context.WithCancel(context.Background())+ defer cancelApp()++ lifecycle := fxtest.NewLifecycle(t)+ jobScheduler := newJobScheduler(appCtx, lifecycle, &config.Config{}, nil, nil, nil)+ watcher := &blockingBusWatcherInternal{+ started: make(chan struct{}),+ stopped: make(chan struct{}),}+ jobScheduler.RegisterBusWatcher(watcher, false)- releaseScheduler <- struct{}{}+ lifecycle.RequireStart()select {- case <-dependenciesReleased:+ case <-watcher.started:case <-time.After(time.Second):- t.Fatal("service runner did not release dependencies after the scheduler stopped")+ t.Fatal("watcher did not start")}+ lifecycle.RequireStop()select {- case err := <-runDone:- require.NoError(t, err)+ case <-watcher.stopped:case <-time.After(time.Second):- t.Fatal("service runner did not return")+ t.Fatal("watcher did not stop")}+ require.NoError(t, appCtx.Err())+}++func TestApplicationOptionsValidate(t *testing.T) {+ appCtx, cancelApp := context.WithCancel(context.Background())+ defer cancelApp()++ err := fx.ValidateApp(applicationOptions(+ appCtx,+ &config.Config{},+ (*database.DB)(nil),+ cancelApp,+ ))+ require.NoError(t, err)}func TestPrepareServerTLSInternal_AgentModeSkipsManagerMTLSValidation(t *testing.T) {diff --git a/backend/internal/bootstrap/buildables_router_bootstrap.go b/backend/internal/bootstrap/buildables_router_bootstrap.goindex 909f6a6a3..637837ba2 100644--- a/backend/internal/bootstrap/buildables_router_bootstrap.go+++ b/backend/internal/bootstrap/buildables_router_bootstrap.go@@ -4,12 +4,11 @@ package bootstrapimport ("github.com/getarcaneapp/arcane/backend/v2/api"- "github.com/getarcaneapp/arcane/backend/v2/internal/di""github.com/labstack/echo/v4")func init() {- registerBuildableRoutes = append(registerBuildableRoutes, func(apiGroup *echo.Group, svc *di.Services) {- api.SetupBuildablesRoutes(apiGroup, svc.Auth)+ registerBuildableRoutes = append(registerBuildableRoutes, func(apiGroup *echo.Group, deps api.HandlerDeps) {+ api.SetupBuildablesRoutes(apiGroup, deps.Auth)})}diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.goindex 2efb4d9bc..b6a5397ec 100644--- a/backend/internal/bootstrap/edge_bootstrap.go+++ b/backend/internal/bootstrap/edge_bootstrap.go@@ -8,7 +8,6 @@ import ("log/slog""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/di""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/services"@@ -23,30 +22,31 @@ func registerEdgeTunnelRoutes(ctx context.Context,cfg *config.Config,apiGroup *echo.Group,- appServices *di.Services,+ environmentService *services.EnvironmentService,+ eventService *services.EventService,) *edge.TunnelServer {// Resolver that validates API key and returns the environment IDresolver := func(ctx context.Context, token string) (string, error) {- return appServices.Environment.ResolveEdgeEnvironmentByToken(ctx, token)+ return environmentService.ResolveEdgeEnvironmentByToken(ctx, token)}// Status callback to update environment status when agent connects/disconnectsstatusCallback := func(ctx context.Context, envID string, connected bool) {envName := envID- env, getErr := appServices.Environment.GetEnvironmentByID(ctx, envID)+ env, getErr := environmentService.GetEnvironmentByID(ctx, envID)if getErr != nil {slog.WarnContext(ctx, "Failed to load environment before edge status update", "environment_id", envID, "error", getErr)} else if env != nil && env.Name != "" {envName = env.Name}- if err := appServices.Environment.UpdateEnvironmentConnectionState(ctx, envID, connected); err != nil {+ if err := environmentService.UpdateEnvironmentConnectionState(ctx, envID, connected); err != nil {slog.WarnContext(ctx, "Failed to update environment status on edge connect/disconnect", "environment_id", envID, "connected", connected, "error", err)} else {slog.InfoContext(ctx, "Updated edge environment connection state", "environment_id", envID, "connected", connected)}- if err := createEdgeConnectionEvent(ctx, appServices.Event, envID, envName, connected); err != nil {+ if err := createEdgeConnectionEvent(ctx, eventService, envID, envName, connected); err != nil {slog.WarnContext(ctx, "Failed to create edge connection event", "environment_id", envID, "connected", connected, "error", err)}}@@ -77,7 +77,7 @@ func registerEdgeTunnelRoutes(EnvironmentID: &envID,Metadata: metadata,}- _, err := appServices.Event.CreateEvent(ctx, req)+ _, err := eventService.CreateEvent(ctx, req)if err != nil {return fmt.Errorf("failed to persist synced event: %w", err)}@@ -96,7 +96,7 @@ func registerEdgeTunnelRoutes(ManagerApiUrl: cfg.ManagerApiUrl,})server.SetEnvironmentNameResolver(func(ctx context.Context, envID string) (string, error) {- env, err := appServices.Environment.GetEnvironmentByID(ctx, envID)+ env, err := environmentService.GetEnvironmentByID(ctx, envID)if err != nil {return "", err}@@ -107,16 +107,16 @@ func registerEdgeTunnelRoutes(})server.SetEventCallback(eventCallback)server.SetEnrollmentCallback(func(ctx context.Context, envID, remoteAddr string, certIssued bool, caGenerated bool, reenrolled bool) {- if appServices.Event == nil {+ if eventService == nil {return}envName := ""- if env, err := appServices.Environment.GetEnvironmentByID(ctx, envID); err == nil && env != nil {+ if env, err := environmentService.GetEnvironmentByID(ctx, envID); err == nil && env != nil {envName = env.Name}envIDCopy := envIDenvNameCopy := envName- _, _ = appServices.Event.CreateEvent(ctx, services.CreateEventRequest{+ _, _ = eventService.CreateEvent(ctx, services.CreateEventRequest{Type: models.EventTypeEnvironmentMTLSEnroll,Severity: edgeMTLSEnrollmentSeverityInternal(reenrolled),Title: "Edge mTLS enrollment",@@ -127,7 +127,7 @@ func registerEdgeTunnelRoutes(EnvironmentID: &envIDCopy,Metadata: models.JSON{"remoteAddr": remoteAddr, "reenrollment": reenrolled},})- createEdgeMTLSIssueEventsInternal(ctx, appServices.Event, envIDCopy, envNameCopy, remoteAddr, certIssued, caGenerated, reenrolled)+ createEdgeMTLSIssueEventsInternal(ctx, eventService, envIDCopy, envNameCopy, remoteAddr, certIssued, caGenerated, reenrolled)})go server.StartCleanupLoop(ctx)apiGroup.POST("/tunnel/poll", server.HandlePoll)diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex d6c35985d..387a01fd2 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -7,150 +7,240 @@ import ("net/http""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/di"+ "github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"+ "go.uber.org/fx")-func registerJobs(appCtx context.Context, newScheduler *scheduler.JobScheduler, appServices *di.Services, appConfig *config.Config) {- // wire constructs every job from the built services; bootstrap owns registration,- // the agent-mode gating, the startup heartbeat, and the settings callbacks.- jobs := di.InitializeJobs(appCtx, appConfig, appServices)+func newJobScheduler(appCtx context.Context, lc fx.Lifecycle, cfg *config.Config, imageUpdateWatcher *scheduler.ImageUpdateWatcher, analytics *scheduler.AnalyticsJob, systemUpgrade *services.SystemUpgradeService) *scheduler.JobScheduler {+ schedulerCtx, cancelScheduler := context.WithCancel(appCtx)+ jobScheduler := scheduler.NewJobScheduler(schedulerCtx, cfg.GetLocation())+ lc.Append(fx.Hook{+ OnStart: func(context.Context) error {+ slog.InfoContext(appCtx, "Starting scheduler")+ jobScheduler.RegisterBusWatcher(imageUpdateWatcher, true)+ jobScheduler.StartScheduler()+ if analytics != nil {+ go analytics.Run(schedulerCtx)+ }+ if !cfg.AgentMode && systemUpgrade != nil {+ go systemUpgrade.ResumeUpdateAllOnStartup(schedulerCtx)+ }+ return nil+ },+ OnStop: func(ctx context.Context) error {+ cancelScheduler()+ err := jobScheduler.Stop(ctx)+ if err != nil {+ slog.ErrorContext(ctx, "Job scheduler exited with error", "error", err)+ return err+ }+ slog.InfoContext(ctx, "Scheduler stopped")+ return nil+ },+ })+ return jobScheduler+}++type registerJobsParams struct {+ fx.In++ AppCtx context.Context+ Config *config.Config+ Scheduler *scheduler.JobScheduler++ Activity *services.ActivityService+ GitOpsSync *services.GitOpsSyncService+ Environment *services.EnvironmentService+ JobSchedule *services.JobService+ Settings *services.SettingsService++ AutoUpdate *scheduler.AutoUpdateJob+ ImageUpdateWatcher *scheduler.ImageUpdateWatcher+ DockerClientRefresh *scheduler.DockerClientRefreshJob+ Analytics *scheduler.AnalyticsJob+ EventCleanup *scheduler.EventCleanupJob+ PruningVolumeHelper *scheduler.PruningVolumeHelperJob+ ExpiredSessionsCleanup *scheduler.ExpiredSessionsCleanupJob+ ScheduledPrune *scheduler.ScheduledPruneJob+ FilesystemWatcher *scheduler.FilesystemWatcherJob+ VulnerabilityScan *scheduler.VulnerabilityScanJob+ AutoHeal *scheduler.AutoHealJob+}- if appServices.Activity != nil {- failed, err := appServices.Activity.FailStaleImageUpdateChecks(appCtx)+func registerJobs(params registerJobsParams) {+ params.JobSchedule.SetScheduler(params.AppCtx, params.Scheduler)++ // Bootstrap owns registration, agent-mode gating, and settings callbacks.+ if params.Activity != nil {+ failed, err := params.Activity.FailStaleImageUpdateChecks(params.AppCtx)if err != nil {- slog.WarnContext(appCtx, "Failed to mark stale image update checks as failed", "count", failed, "error", err)+ slog.WarnContext(params.AppCtx, "Failed to mark stale image update checks as failed", "count", failed, "error", err)} else if failed > 0 {- slog.InfoContext(appCtx, "Marked stale image update checks as failed", "count", failed)+ slog.InfoContext(params.AppCtx, "Marked stale image update checks as failed", "count", failed)}- resolved, err := appServices.Activity.ResolveStaleAutoUpdateActivities(appCtx)+ resolved, err := params.Activity.ResolveStaleAutoUpdateActivities(params.AppCtx)if err != nil {- slog.WarnContext(appCtx, "Failed to resolve stale auto-update activities", "count", resolved, "error", err)+ slog.WarnContext(params.AppCtx, "Failed to resolve stale auto-update activities", "count", resolved, "error", err)} else if resolved > 0 {- slog.InfoContext(appCtx, "Resolved stale auto-update activities", "count", resolved)+ slog.InfoContext(params.AppCtx, "Resolved stale auto-update activities", "count", resolved)}- orphaned, err := appServices.Activity.ResolveOrphanedQueuedActivities(appCtx)+ orphaned, err := params.Activity.ResolveOrphanedQueuedActivities(params.AppCtx)if err != nil {- slog.WarnContext(appCtx, "Failed to resolve orphaned queued activities", "count", orphaned, "error", err)+ slog.WarnContext(params.AppCtx, "Failed to resolve orphaned queued activities", "count", orphaned, "error", err)} else if orphaned > 0 {- slog.InfoContext(appCtx, "Resolved orphaned queued activities", "count", orphaned)+ slog.InfoContext(params.AppCtx, "Resolved orphaned queued activities", "count", orphaned)}}- // Finalize a fleet-wide update-all job whose manager self-upgrade restarted the- // process as its final step (manager only). Runs off the app context so it does- // not block bootstrap.- if !appConfig.AgentMode && appServices.SystemUpgrade != nil {- go appServices.SystemUpgrade.ResumeUpdateAllOnStartup(appCtx)- }-- newScheduler.RegisterJob(jobs.AutoUpdate)- newScheduler.RegisterBusWatcher(jobs.ImageUpdateWatcher, true)- newScheduler.RegisterJob(jobs.DockerClientRefresh)- newScheduler.RegisterJob(jobs.Analytics)- // Send initial heartbeat on startup without blocking bootstrap.- go jobs.Analytics.Run(appCtx)- newScheduler.RegisterJob(jobs.EventCleanup)- newScheduler.RegisterJob(jobs.PruningVolumeHelper)- newScheduler.RegisterJob(jobs.ExpiredSessionsCleanup)- newScheduler.RegisterJob(jobs.ScheduledPrune)+ params.Scheduler.RegisterJob(params.AutoUpdate)+ params.Scheduler.RegisterJob(params.DockerClientRefresh)+ params.Scheduler.RegisterJob(params.Analytics)+ params.Scheduler.RegisterJob(params.EventCleanup)+ params.Scheduler.RegisterJob(params.PruningVolumeHelper)+ params.Scheduler.RegisterJob(params.ExpiredSessionsCleanup)+ params.Scheduler.RegisterJob(params.ScheduledPrune)// FilesystemWatcher is intentionally not scheduler-registered; it watches inline// and is only rebound on settings changes below.- newScheduler.RegisterJob(jobs.VulnerabilityScan)- newScheduler.RegisterJob(jobs.AutoHeal)+ params.Scheduler.RegisterJob(params.VulnerabilityScan)+ params.Scheduler.RegisterJob(params.AutoHeal)// GitOps sync and environment health are no longer single global jobs; each// entity registers its own dynamic job.- registerDynamicJobs(appCtx, newScheduler, appServices, appConfig)+ registerDynamicJobs(dynamicJobsParams{+ AppCtx: params.AppCtx,+ Config: params.Config,+ Scheduler: params.Scheduler,+ GitOpsSync: params.GitOpsSync,+ Environment: params.Environment,+ JobSchedule: params.JobSchedule,+ })++ setupSettingsCallbacks(settingsCallbacksParams{+ LifecycleCtx: params.AppCtx,+ Config: params.Config,+ Scheduler: params.Scheduler,+ Settings: params.Settings,+ Environment: params.Environment,+ AutoUpdate: params.AutoUpdate,+ ImageUpdateWatcher: params.ImageUpdateWatcher,+ FilesystemWatcher: params.FilesystemWatcher,+ ScheduledPrune: params.ScheduledPrune,+ VulnerabilityScan: params.VulnerabilityScan,+ AutoHeal: params.AutoHeal,+ })+}- setupSettingsCallbacks(appCtx, appServices, appConfig, newScheduler, jobs)+type dynamicJobsParams struct {+ AppCtx context.Context+ Config *config.Config+ Scheduler *scheduler.JobScheduler+ GitOpsSync *services.GitOpsSyncService+ Environment *services.EnvironmentService+ JobSchedule *services.JobService}// registerDynamicJobs injects the scheduler into the services that own per-entity// jobs and registers the jobs for already-existing entities at startup. AddJob is// an idempotent upsert, so these run safely before the scheduler is started.-func registerDynamicJobs(appCtx context.Context, newScheduler *scheduler.JobScheduler, appServices *di.Services, appConfig *config.Config) {+func registerDynamicJobs(params dynamicJobsParams) {// GitOps: one job per auto-sync-enabled sync (runs on manager and agents).- if appServices.GitOpsSync != nil {- appServices.GitOpsSync.SetScheduler(appCtx, newScheduler)- appServices.GitOpsSync.RegisterAutoSyncJobsOnStartup(appCtx)+ if params.GitOpsSync != nil {+ params.GitOpsSync.SetScheduler(params.AppCtx, params.Scheduler)+ params.GitOpsSync.RegisterAutoSyncJobsOnStartup(params.AppCtx)}// Environment health: one job per enabled environment (manager only). The Jobs// UI still addresses "environment-health" by ID, so bridge its reschedule and// run-now back to EnvironmentService.- if !appConfig.AgentMode && appServices.Environment != nil {- appServices.Environment.SetScheduler(appCtx, newScheduler)- appServices.JobSchedule.OnEnvironmentHealthReschedule = func(ctx context.Context) {- appServices.Environment.RescheduleHealthJobs(ctx)+ if !params.Config.AgentMode && params.Environment != nil {+ params.Environment.SetScheduler(params.AppCtx, params.Scheduler)+ params.JobSchedule.OnEnvironmentHealthReschedule = func(ctx context.Context) {+ params.Environment.RescheduleHealthJobs(ctx)}- appServices.JobSchedule.RunEnvironmentHealthNow = func(ctx context.Context) error {- return appServices.Environment.RunHealthChecksNow(ctx)+ params.JobSchedule.RunEnvironmentHealthNow = func(ctx context.Context) error {+ return params.Environment.RunHealthChecksNow(ctx)}- appServices.Environment.RegisterHealthJobsOnStartup(appCtx)+ params.Environment.RegisterHealthJobsOnStartup(params.AppCtx)}}-func setupSettingsCallbacks(lifecycleCtx context.Context, appServices *di.Services, appConfig *config.Config, newScheduler *scheduler.JobScheduler, jobs *di.Jobs) {- appServices.Settings.OnImagePollingSettingsChanged = func(_ context.Context) {- if jobs.ImageUpdateWatcher != nil {- jobs.ImageUpdateWatcher.RefreshSchedule()- jobs.ImageUpdateWatcher.Trigger()+type settingsCallbacksParams struct {+ LifecycleCtx context.Context+ Config *config.Config+ Scheduler *scheduler.JobScheduler+ Settings *services.SettingsService+ Environment *services.EnvironmentService++ AutoUpdate *scheduler.AutoUpdateJob+ ImageUpdateWatcher *scheduler.ImageUpdateWatcher+ FilesystemWatcher *scheduler.FilesystemWatcherJob+ ScheduledPrune *scheduler.ScheduledPruneJob+ VulnerabilityScan *scheduler.VulnerabilityScanJob+ AutoHeal *scheduler.AutoHealJob+}++//nolint:contextcheck // callbacks intentionally use the app lifecycle context so reschedules outlive the triggering request context.+func setupSettingsCallbacks(params settingsCallbacksParams) {+ params.Settings.OnImagePollingSettingsChanged = func(_ context.Context) {+ if params.ImageUpdateWatcher != nil {+ params.ImageUpdateWatcher.RefreshSchedule()+ params.ImageUpdateWatcher.Trigger()}- if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.AutoUpdate); err != nil {- slog.WarnContext(lifecycleCtx, "Failed to reschedule auto-update job", "error", err)+ if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.AutoUpdate); err != nil {+ slog.WarnContext(params.LifecycleCtx, "Failed to reschedule auto-update job", "error", err)}}- appServices.Settings.OnAutoUpdateSettingsChanged = func(ctx context.Context) {- slog.DebugContext(lifecycleCtx, "AutoUpdateSettingsChanged callback triggered", "triggerContextCanceled", ctx.Err() != nil)- if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.AutoUpdate); err != nil {- slog.WarnContext(lifecycleCtx, "Failed to reschedule auto-update job", "error", err)+ params.Settings.OnAutoUpdateSettingsChanged = func(ctx context.Context) {+ slog.DebugContext(params.LifecycleCtx, "AutoUpdateSettingsChanged callback triggered", "triggerContextCanceled", ctx.Err() != nil)+ if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.AutoUpdate); err != nil {+ slog.WarnContext(params.LifecycleCtx, "Failed to reschedule auto-update job", "error", err)}}- appServices.Settings.OnProjectsDirectoryChanged = func(_ context.Context) {- if jobs.FilesystemWatcher != nil {- if err := jobs.FilesystemWatcher.RestartProjectsWatcher(lifecycleCtx); err != nil {- slog.WarnContext(lifecycleCtx, "Failed to restart projects filesystem watcher", "error", err)+ params.Settings.OnProjectsDirectoryChanged = func(_ context.Context) {+ if params.FilesystemWatcher != nil {+ if err := params.FilesystemWatcher.RestartProjectsWatcher(params.LifecycleCtx); err != nil {+ slog.WarnContext(params.LifecycleCtx, "Failed to restart projects filesystem watcher", "error", err)}}}- appServices.Settings.OnTemplatesDirectoryChanged = func(_ context.Context) {- if jobs.FilesystemWatcher != nil {- if err := jobs.FilesystemWatcher.RestartTemplatesWatcher(lifecycleCtx); err != nil {- slog.WarnContext(lifecycleCtx, "Failed to restart templates filesystem watcher", "error", err)+ params.Settings.OnTemplatesDirectoryChanged = func(_ context.Context) {+ if params.FilesystemWatcher != nil {+ if err := params.FilesystemWatcher.RestartTemplatesWatcher(params.LifecycleCtx); err != nil {+ slog.WarnContext(params.LifecycleCtx, "Failed to restart templates filesystem watcher", "error", err)}}}- appServices.Settings.OnScheduledPruneSettingsChanged = func(_ context.Context) {- if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.ScheduledPrune); err != nil {- slog.WarnContext(lifecycleCtx, "Failed to reschedule scheduled-prune job", "error", err)+ params.Settings.OnScheduledPruneSettingsChanged = func(_ context.Context) {+ if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.ScheduledPrune); err != nil {+ slog.WarnContext(params.LifecycleCtx, "Failed to reschedule scheduled-prune job", "error", err)}}- appServices.Settings.OnVulnerabilityScanSettingsChanged = func(_ context.Context) {- if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.VulnerabilityScan); err != nil {- slog.WarnContext(lifecycleCtx, "Failed to reschedule vulnerability-scan job", "error", err)+ params.Settings.OnVulnerabilityScanSettingsChanged = func(_ context.Context) {+ if err := params.Scheduler.RescheduleJob(params.LifecycleCtx, params.VulnerabilityScan); err != nil {+ slog.WarnContext(params.LifecycleCtx, "Failed to reschedule vulnerability-scan job", "error", err)}}- appServices.Settings.OnAutoHealSettingsChanged = func(ctx context.Context) {- if err := newScheduler.RescheduleJob(ctx, jobs.AutoHeal); err != nil {+ params.Settings.OnAutoHealSettingsChanged = func(ctx context.Context) {+ if err := params.Scheduler.RescheduleJob(ctx, params.AutoHeal); err != nil {slog.WarnContext(ctx, "Failed to reschedule auto-heal job", "error", err)}}// Only set up timeout sync callback on main instance (not in agent mode)- if !appConfig.AgentMode {- appServices.Settings.OnTimeoutSettingsChanged = func(ctx context.Context, timeoutSettings []libarcane.SettingUpdate) {- go syncTimeoutSettingsToAgentsInternal(context.WithoutCancel(ctx), appServices, timeoutSettings)+ if !params.Config.AgentMode {+ params.Settings.OnTimeoutSettingsChanged = func(ctx context.Context, timeoutSettings []libarcane.SettingUpdate) {+ go syncTimeoutSettingsToAgentsInternal(context.WithoutCancel(ctx), params.Environment, timeoutSettings)}}}// syncTimeoutSettingsToAgentsInternal syncs timeout settings to all connected remote environments-func syncTimeoutSettingsToAgentsInternal(ctx context.Context, appServices *di.Services, timeoutSettings []libarcane.SettingUpdate) {- envs, err := appServices.Environment.ListRemoteEnvironments(ctx)+func syncTimeoutSettingsToAgentsInternal(ctx context.Context, environment *services.EnvironmentService, timeoutSettings []libarcane.SettingUpdate) {+ envs, err := environment.ListRemoteEnvironments(ctx)if err != nil {slog.WarnContext(ctx, "Failed to list remote environments for timeout sync", "error", err)return@@ -176,7 +266,7 @@ func syncTimeoutSettingsToAgentsInternal(ctx context.Context, appServices *di.Seslog.InfoContext(ctx, "Syncing environment settings to remote environments", "count", len(envs), "keys", keys)for _, env := range envs {- resp, err := appServices.Environment.ExecuteRemoteRequest(ctx, env.ID, http.MethodPut, "/api/environments/0/settings", body)+ resp, err := environment.ExecuteRemoteRequest(ctx, env.ID, http.MethodPut, "/api/environments/0/settings", body)if err != nil {slog.WarnContext(ctx, "Failed to sync timeout settings to environment", "environmentID", env.ID, "environmentName", env.Name, "error", err)continuediff --git a/backend/internal/bootstrap/playwright_router_bootstrap.go b/backend/internal/bootstrap/playwright_router_bootstrap.goindex 3537a3d66..9f094a9cd 100644--- a/backend/internal/bootstrap/playwright_router_bootstrap.go+++ b/backend/internal/bootstrap/playwright_router_bootstrap.go@@ -6,15 +6,14 @@ import ("log/slog""github.com/getarcaneapp/arcane/backend/v2/api"- "github.com/getarcaneapp/arcane/backend/v2/internal/di""github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/labstack/echo/v4")func init() {- registerPlaywrightRoutes = []func(apiGroup *echo.Group, services *di.Services){- func(apiGroup *echo.Group, svc *di.Services) {- playwrightService := services.NewPlaywrightService(svc.ApiKey, svc.User, svc.Federated)+ registerPlaywrightRoutes = []func(apiGroup *echo.Group, deps api.HandlerDeps){+ func(apiGroup *echo.Group, deps api.HandlerDeps) {+ playwrightService := services.NewPlaywrightService(deps.ApiKey, deps.User, deps.Federated)if playwrightService == nil {slog.Warn("Playwright service not available, skipping playwright routes")returndiff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex 8ef477982..e1492af74 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -18,18 +18,18 @@ import ("github.com/getarcaneapp/arcane/backend/v2/api/ws""github.com/getarcaneapp/arcane/backend/v2/frontend""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/di""github.com/getarcaneapp/arcane/backend/v2/internal/middleware""github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/getarcaneapp/arcane/types/v2"+ "go.uber.org/fx")var (- registerPlaywrightRoutes []func(apiGroup *echo.Group, services *di.Services)- registerBuildableRoutes []func(apiGroup *echo.Group, services *di.Services)+ registerPlaywrightRoutes []func(apiGroup *echo.Group, deps api.HandlerDeps)+ registerBuildableRoutes []func(apiGroup *echo.Group, deps api.HandlerDeps))var loggerSkipPatterns = []string{@@ -89,9 +89,9 @@ func requestLoggerMiddlewareInternal() echo.MiddlewareFunc {}}-func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValidator {+func createAuthValidatorInternal(deps api.HandlerDeps) middleware.AuthValidator {resolveUser := func(ctx context.Context, user *models.User) *authz.PermissionSet {- ps, err := appServices.Role.ResolvePermissions(ctx, user)+ ps, err := deps.Role.ResolvePermissions(ctx, user)if err != nil || ps == nil {slog.WarnContext(ctx, "failed to resolve user permissions for env proxy", "error", err)return authz.NewPermissionSet()@@ -99,7 +99,7 @@ func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValidareturn ps}resolveKey := func(ctx context.Context, keyID string) *authz.PermissionSet {- ps, err := appServices.Role.ResolveApiKeyPermissions(ctx, keyID)+ ps, err := deps.Role.ResolveApiKeyPermissions(ctx, keyID)if err != nil || ps == nil {slog.WarnContext(ctx, "failed to resolve api key permissions for env proxy", "error", err)return authz.NewPermissionSet()@@ -112,7 +112,7 @@ func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValidaif apiKey := req.Header.Get("X-Api-Key"); 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 := appServices.ApiKey.ValidateApiKeyWithID(ctx, apiKey); err == nil && user != nil {+ if user, key, err := deps.ApiKey.ValidateApiKeyWithID(ctx, apiKey); err == nil && user != nil {if key != nil && key.Kind != models.ApiKeyKindPersonal {return resolveKey(ctx, key.ID), true}@@ -120,7 +120,7 @@ func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValida}// Environment bootstrap key (user_id = NULL): used by the proxy when forwarding// requests to a remote env whose apiUrl resolves back to this manager.- if envID, err := appServices.ApiKey.GetEnvironmentByApiKey(ctx, apiKey); err == nil && envID != nil {+ if envID, err := deps.ApiKey.GetEnvironmentByApiKey(ctx, apiKey); err == nil && envID != nil {return authz.EnvironmentPermissionSet(*envID), true}return nil, false@@ -138,7 +138,7 @@ func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValidareturn nil, false}- user, _, err := appServices.Auth.VerifyToken(ctx, token)+ user, _, err := deps.Auth.VerifyToken(ctx, token)if err != nil || user == nil {return nil, false}@@ -146,7 +146,20 @@ func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValida}}-func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.Services) (*echo.Echo, *edge.TunnelServer) {+type RouterParams struct {+ fx.In++ Context context.Context+ Config *config.Config+ HandlerDeps api.HandlerDeps+ AuthMiddleware *middleware.AuthMiddleware+}++func newRouter(p RouterParams) (*echo.Echo, *edge.TunnelServer) {+ ctx := p.Context+ cfg := p.Config+ deps := p.HandlerDeps+e := echo.New()e.HideBanner = truee.HidePort = true@@ -166,12 +179,12 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.Servic}e.Use(echomiddleware.Recover())- e.Use(requestLoggerMiddlewareInternal()) //nolint:contextcheck- e.Use(secureCookieContextMiddlewareInternal(trustedProxyNets)) //nolint:contextcheck+ e.Use(requestLoggerMiddlewareInternal())+ e.Use(secureCookieContextMiddlewareInternal(trustedProxyNets))- authMiddleware := appServices.AuthMiddleware+ authMiddleware := p.AuthMiddlewaree.Use(middleware.NewCORSMiddleware(cfg).Add())- e.Use(middleware.NewCSRFMiddleware(cfg).Add()) //nolint:contextcheck // Echo middleware uses request context from echo.Context, not the app lifecycle context.+ e.Use(middleware.NewCSRFMiddleware(cfg).Add())apiGroup := e.Group("/api")@@ -193,7 +206,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.ServictunnelRegistry := edge.NewTunnelRegistry()edge.SetDefaultRegistry(tunnelRegistry)envResolver := func(ctx context.Context, id string) (string, *string, bool, error) {- env, err := appServices.Environment.GetEnvironmentByID(ctx, id)+ env, err := deps.Environment.GetEnvironmentByID(ctx, id)if err != nil || env == nil {return "", nil, false, err}@@ -201,23 +214,22 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.Servic}// Register public webhook trigger endpoint before auth middleware (token in URL is the sole auth)- api.RegisterWebhookTrigger(apiGroup, appServices.Webhook, handlerAppCtx) //nolint:contextcheck // app lifecycle context is intentionally wrapped for detached activity work.- handlers.RegisterFederatedTokenExchange(apiGroup, appServices.Federated) //nolint:contextcheck // public RFC 8693 form endpoint uses request context.- handlers.RegisterAgentEventIngestion(apiGroup, appServices.Event, cfg) //nolint:contextcheck // internal agent-token route; intentionally outside user/RBAC auth.+ api.RegisterWebhookTrigger(apiGroup, deps.Webhook, handlerAppCtx)+ handlers.RegisterFederatedTokenExchange(apiGroup, deps.Federated)+ handlers.RegisterAgentEventIngestion(apiGroup, deps.Event, cfg)permissionMatcher := authz.NewPermissionMatcher()- //nolint:contextcheck // Echo middleware reads context from echo.Context.Request().Context(), not a parameter.envProxyMiddleware := middleware.NewEnvProxyMiddlewareWithParam(types.LOCAL_DOCKER_ENVIRONMENT_ID,"id",envResolver,- createAuthValidatorInternal(appServices),+ createAuthValidatorInternal(deps),permissionMatcher,)apiGroup.Use(envProxyMiddleware)- humaAPI := api.SetupAPI(e, apiGroup, handlerAppCtx, cfg, appServices) //nolint:contextcheck // app lifecycle context is intentionally wrapped for detached activity work.+ humaAPI := api.SetupAPI(e, apiGroup, handlerAppCtx, cfg, deps)// Populate the proxy permission matcher from the registered API surface so// remote-environment requests are authorized with the same permissions@@ -227,22 +239,22 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.Servicws.AddProxiedPermissions(permissionMatcher)for _, register := range registerBuildableRoutes {- register(apiGroup, appServices)+ register(apiGroup, deps)}// Remaining echo handlers (WebSocket/streaming)- ws.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.Swarm, appServices.System, appServices.Diagnostics, authMiddleware, cfg) //nolint:contextcheck+ ws.NewWebSocketHandler(apiGroup, deps.Project, deps.Container, deps.Swarm, deps.System, deps.Diagnostics, authMiddleware, cfg)// Register edge tunnel endpoint for manager to accept agent connections// This is only registered when NOT in agent mode (i.e., running as manager)var tunnelServer *edge.TunnelServerif !cfg.AgentMode {- tunnelServer = registerEdgeTunnelRoutes(ctx, cfg, apiGroup, appServices)+ tunnelServer = registerEdgeTunnelRoutes(ctx, cfg, apiGroup, deps.Environment, deps.Event)}if cfg.Environment != "production" {for _, registerFunc := range registerPlaywrightRoutes {- registerFunc(apiGroup, appServices)+ registerFunc(apiGroup, deps)}}diff --git a/backend/internal/bootstrap/server_bootstrap.go b/backend/internal/bootstrap/server_bootstrap.gonew file mode 100644index 000000000..ad9152da5--- /dev/null+++ b/backend/internal/bootstrap/server_bootstrap.go@@ -0,0 +1,279 @@+package bootstrap++import (+ "context"+ "crypto/tls"+ "errors"+ "log/slog"+ "net"+ "net/http"+ "strings"+ "time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/config"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"+ tunnelpb "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge/proto/tunnel/v1"+ "github.com/labstack/echo/v4"+ "go.uber.org/fx"+ "google.golang.org/grpc"+)++var serverOptions = fx.Options(+ fx.Provide(+ newRouter,+ newJobScheduler,+ NewHTTPServer,+ ),+)++type HTTPServerParams struct {+ fx.In++ AppCtx context.Context+ Config *config.Config+ Router *echo.Echo+ TunnelServer *edge.TunnelServer+}++// NewHTTPServer builds the shared HTTP/gRPC server and registers its lifecycle.+func NewHTTPServer(lc fx.Lifecycle, p HTTPServerParams) (*http.Server, error) {+ listenAddr := p.Config.ListenAddr()+ useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(p.AppCtx, p.Config)+ if err != nil {+ return nil, err+ }+ if p.TunnelServer != nil {+ p.TunnelServer.SetConfig(edgeCfg)+ }++ httpHandler, grpcServer := configureTunnelServerInternal(p.AppCtx, p.Config, p.Router, p.TunnelServer, listenAddr)+ httpHandler, protocols := configureHTTPProtocolsInternal(useTLS, httpHandler)++ // Request contexts deliberately do not inherit the app lifecycle marker.+ baseCtx, cancelBase := context.WithCancel(context.Background())+ srv, err := newHTTPServerInternal(baseCtx, listenAddr, httpHandler, protocols, useTLS, edgeCfg)+ if err != nil {+ cancelBase()+ return nil, err+ }+ if useTLS {+ certificate, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile)+ if err != nil {+ cancelBase()+ return nil, err+ }+ if srv.TLSConfig == nil {+ srv.TLSConfig = &tls.Config{}+ } else {+ srv.TLSConfig = srv.TLSConfig.Clone()+ }+ srv.TLSConfig.Certificates = []tls.Certificate{certificate}+ }++ lc.Append(fx.Hook{+ OnStart: func(ctx context.Context) error {+ listener, err := new(net.ListenConfig).Listen(ctx, "tcp", listenAddr)+ if err != nil {+ cancelBase()+ return err+ }+ srv.Addr = listener.Addr().String()++ slog.InfoContext(ctx, "Starting HTTP server", "addr", listenAddr, "listen", p.Config.Listen, "port", p.Config.Port, "tls_enabled", useTLS)+ go func() {+ defer func() { _ = listener.Close() }()+ var serveErr error+ if useTLS {+ serveErr = srv.ServeTLS(listener, "", "")+ } else {+ serveErr = srv.Serve(listener)+ }+ if serveErr != nil && !errors.Is(serveErr, http.ErrServerClosed) {+ slog.ErrorContext(p.AppCtx, "HTTP server exited with error", "error", serveErr)+ }+ }()+ return nil+ },+ OnStop: func(ctx context.Context) error {+ // Shutdown does not cancel active request contexts, so unblock streaming+ // handlers before waiting for the server to drain.+ cancelBase()+ shutdownErr := srv.Shutdown(ctx)+ if shutdownErr != nil {+ slog.ErrorContext(ctx, "Server forced to shutdown", "error", shutdownErr)+ }++ if grpcServer != nil {+ grpcServer.GracefulStop()+ }+ if p.TunnelServer != nil {+ p.TunnelServer.WaitForCleanupDone()+ }+ if shutdownErr == nil {+ slog.InfoContext(ctx, "Server stopped gracefully")+ }+ return shutdownErr+ },+ })++ return srv, nil+}++func prepareServerTLSInternal(ctx context.Context, cfg *config.Config) (bool, string, string, *edge.Config, error) {+ useTLS := cfg.TLSEnabled+ tlsCertFile := strings.TrimSpace(cfg.TLSCertFile)+ tlsKeyFile := strings.TrimSpace(cfg.TLSKeyFile)+ edgeCfg := buildEdgeRuntimeConfigInternal(cfg)+ if useTLS && (tlsCertFile == "" || tlsKeyFile == "") {+ return false, "", "", nil, errors.New("TLS_ENABLED requires both TLS_CERT_FILE and TLS_KEY_FILE")+ }++ if cfg.AgentMode {+ return useTLS, tlsCertFile, tlsKeyFile, edgeCfg, nil+ }++ if err := edge.PrepareManagerMTLSAssetsWithContext(ctx, edgeCfg); err != nil {+ return false, "", "", nil, err+ }++ if edge.NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) != edge.EdgeMTLSModeDisabled {+ if err := edge.ValidateManagerMTLSConfig(edgeCfg); err != nil {+ return false, "", "", nil, err+ }+ }++ return useTLS, tlsCertFile, tlsKeyFile, edgeCfg, nil+}++func configureTunnelServerInternal(appCtx context.Context, cfg *config.Config, router http.Handler, tunnelServer *edge.TunnelServer, listenAddr string) (http.Handler, *grpc.Server) {+ httpHandler := router+ var grpcServer *grpc.Server++ if !cfg.AgentMode && tunnelServer != nil {+ grpcServer = grpc.NewServer(tunnelServer.GRPCServerOptions(appCtx)...)+ tunnelpb.RegisterTunnelServiceServer(grpcServer, tunnelServer)++ httpHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if isTunnelGRPCRequestInternal(r) {+ grpcReq := normalizeTunnelGRPCRequestPathInternal(r)+ grpcServer.ServeHTTP(w, grpcReq)+ return+ }+ router.ServeHTTP(w, r)+ })+ slog.InfoContext(appCtx, "Using shared HTTP/gRPC listener for edge tunnel", "addr", listenAddr)+ }++ return httpHandler, grpcServer+}++func configureHTTPProtocolsInternal(useTLS bool, handler http.Handler) (http.Handler, *http.Protocols) {+ var protocols http.Protocols+ protocols.SetHTTP1(true)+ if useTLS {+ protocols.SetHTTP2(true)+ return handler, &protocols+ }++ protocols.SetUnencryptedHTTP2(true)+ return handler, &protocols+}++func newHTTPServerInternal(baseCtx context.Context, listenAddr string, handler http.Handler, protocols *http.Protocols, useTLS bool, edgeCfg *edge.Config) (*http.Server, error) {+ srv := &http.Server{+ Addr: listenAddr,+ Handler: handler,+ Protocols: protocols,+ ReadHeaderTimeout: 5 * time.Second,+ IdleTimeout: 120 * time.Second,+ BaseContext: func(net.Listener) context.Context { return baseCtx },+ }+ if !useTLS {+ return srv, nil+ }++ tlsConfig, err := edge.BuildManagerServerTLSConfig(edgeCfg)+ if err != nil {+ return nil, err+ }+ if tlsConfig != nil {+ srv.TLSConfig = tlsConfig+ }+ return srv, nil+}++func buildEdgeRuntimeConfigInternal(cfg *config.Config) *edge.Config {+ return &edge.Config{+ EdgeAgent: cfg.EdgeAgent,+ EdgeTransport: cfg.EdgeTransport,+ EdgeReconnectInterval: cfg.EdgeReconnectInterval,+ EdgeMTLSMode: cfg.EdgeMTLSMode,+ EdgeMTLSCAFile: cfg.EdgeMTLSCAFile,+ EdgeMTLSCertFile: cfg.EdgeMTLSCertFile,+ EdgeMTLSKeyFile: cfg.EdgeMTLSKeyFile,+ EdgeMTLSServerName: cfg.EdgeMTLSServerName,+ EdgeMTLSAssetsDir: cfg.EdgeMTLSAssetsDir,+ AppURL: cfg.GetAppURL(),+ ManagerApiUrl: cfg.ManagerApiUrl,+ AgentToken: cfg.AgentToken,+ Port: cfg.Port,+ Listen: cfg.Listen,+ }+}++func normalizeTunnelGRPCRequestPathInternal(r *http.Request) *http.Request {+ if r == nil {+ return nil+ }+ if r.URL == nil {+ return r+ }++ connectMethodPath := tunnelpb.TunnelService_Connect_FullMethodName++ const tunnelConnectPath = "/api/tunnel/connect"+ if strings.HasSuffix(r.URL.Path, tunnelConnectPath) {+ clone := r.Clone(r.Context())+ cloneURL := *clone.URL+ cloneURL.Path = connectMethodPath+ clone.URL = &cloneURL+ clone.RequestURI = connectMethodPath+ return clone+ }++ idx := strings.Index(r.URL.Path, connectMethodPath)+ if idx <= 0 {+ return r+ }++ normalizedPath := r.URL.Path[idx:]+ if normalizedPath == r.URL.Path {+ return r+ }++ clone := r.Clone(r.Context())+ cloneURL := *clone.URL+ cloneURL.Path = normalizedPath+ clone.URL = &cloneURL+ clone.RequestURI = normalizedPath+ return clone+}++func isTunnelGRPCRequestInternal(r *http.Request) bool {+ if r == nil || r.URL == nil {+ return false+ }++ if r.Method != http.MethodPost {+ return false+ }++ path := r.URL.Path+ fullMethodPath := tunnelpb.TunnelService_Connect_FullMethodName+ if path == fullMethodPath || strings.HasSuffix(path, fullMethodPath) {+ return true+ }++ contentType := strings.ToLower(strings.TrimSpace(r.Header.Get("Content-Type")))+ return strings.HasPrefix(contentType, "application/grpc")+}diff --git a/backend/internal/di/di.go b/backend/internal/di/di.gonew file mode 100644index 000000000..3d9c7053f--- /dev/null+++ b/backend/internal/di/di.go@@ -0,0 +1,81 @@+// Package di owns the backend's dependency-injection graph.+package di++import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/services"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"+ "go.uber.org/fx"+)++// ServiceOptions provides the backend service graph.+var ServiceOptions = fx.Options(+ fx.Provide(+ // Infrastructure values consumed by services.+ provideResourcesFSInternal,++ // Services constructed directly through their public constructors.+ services.NewEventService,+ services.NewActivityService,+ services.NewSettingsService,+ services.NewKVService,+ services.NewJobService,+ services.NewSettingsSearchService,+ services.NewCustomizeSearchService,+ services.NewApplicationImagesService,+ provideDockerClientServiceInternal,+ services.NewRoleService,+ services.NewSessionService,+ services.NewEnvironmentService,+ services.NewNotificationService,+ services.NewVulnerabilityService,+ services.NewImageUpdateService,+ services.NewImageService,+ services.NewBuildService,+ services.NewBuildWorkspaceService,+ services.NewLifecycleService,+ provideProjectServiceInternal,+ services.NewContainerService,+ services.NewDashboardService,+ services.NewNetworkService,+ services.NewPortService,+ services.NewSwarmService,+ services.NewTemplateService,+ services.NewOidcService,+ services.NewSystemService,+ services.NewSystemUpgradeService,+ services.NewDiagnosticsService,+ services.NewGitOpsSyncService,+ services.NewWebhookService,+ services.NewVariableService,++ // Adapters for scalar config fields, unexported parameters, builders, and lifecycle hooks.+ provideVersionServiceInternal,+ provideGitRepositoryServiceInternal,+ provideVolumeServiceInternal,+ provideAuthServiceInternal,+ provideContainerRegistryServiceInternal,+ provideUpdaterServiceInternal,+ provideUserServiceInternal,+ provideApiKeyServiceInternal,+ provideFederatedCredentialServiceInternal,+ provideAuthMiddlewareInternal,+ ),+)++// JobOptions provides every scheduler job. Registration and settings callbacks+// remain bootstrap concerns because their ordering is application-specific.+var JobOptions = fx.Options(+ fx.Provide(+ scheduler.NewAutoUpdateJob,+ scheduler.NewImageUpdateWatcher,+ scheduler.NewDockerClientRefreshJob,+ provideAnalyticsJobInternal,+ scheduler.NewEventCleanupJob,+ scheduler.NewPruningVolumeHelperJob,+ scheduler.NewExpiredSessionsCleanupJob,+ scheduler.NewScheduledPruneJob,+ provideFilesystemWatcherJobInternal,+ scheduler.NewVulnerabilityScanJob,+ scheduler.NewAutoHealJob,+ ),+)diff --git a/backend/internal/di/di_test.go b/backend/internal/di/di_test.gonew file mode 100644index 000000000..f20fed7f9--- /dev/null+++ b/backend/internal/di/di_test.go@@ -0,0 +1,90 @@+package di++import (+ "context"+ "net/http"+ "testing"++ "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/services"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"+ "github.com/stretchr/testify/require"+ "go.uber.org/fx"+)++type graphParams struct {+ fx.In++ AppImages *services.ApplicationImagesService+ User *services.UserService+ Project *services.ProjectService+ Environment *services.EnvironmentService+ Settings *services.SettingsService+ KV *services.KVService+ JobSchedule *services.JobService+ SettingsSearch *services.SettingsSearchService+ CustomizeSearch *services.CustomizeSearchService+ Container *services.ContainerService+ Image *services.ImageService+ Build *services.BuildService+ BuildWorkspace *services.BuildWorkspaceService+ Lifecycle *services.LifecycleService+ Volume *services.VolumeService+ Network *services.NetworkService+ Port *services.PortService+ Swarm *services.SwarmService+ ImageUpdate *services.ImageUpdateService+ Session *services.SessionService+ Auth *services.AuthService+ Oidc *services.OidcService+ Docker *services.DockerClientService+ Template *services.TemplateService+ ContainerRegistry *services.ContainerRegistryService+ System *services.SystemService+ SystemUpgrade *services.SystemUpgradeService+ Diagnostics *services.DiagnosticsService+ Updater *services.UpdaterService+ Event *services.EventService+ Activity *services.ActivityService+ Version *services.VersionService+ Notification *services.NotificationService+ ApiKey *services.ApiKeyService+ Federated *services.FederatedCredentialService+ GitRepository *services.GitRepositoryService+ GitOpsSync *services.GitOpsSyncService+ Webhook *services.WebhookService+ Vulnerability *services.VulnerabilityService+ Dashboard *services.DashboardService+ Role *services.RoleService+ Variable *services.VariableService+ AuthMiddleware *middleware.AuthMiddleware++ AutoUpdate *scheduler.AutoUpdateJob+ ImageUpdateWatcher *scheduler.ImageUpdateWatcher+ DockerClientRefresh *scheduler.DockerClientRefreshJob+ Analytics *scheduler.AnalyticsJob+ EventCleanup *scheduler.EventCleanupJob+ PruningVolumeHelper *scheduler.PruningVolumeHelperJob+ ExpiredSessionsCleanup *scheduler.ExpiredSessionsCleanupJob+ ScheduledPrune *scheduler.ScheduledPruneJob+ FilesystemWatcher *scheduler.FilesystemWatcherJob+ VulnerabilityScan *scheduler.VulnerabilityScanJob+ AutoHeal *scheduler.AutoHealJob+}++func TestOptionsValidate(t *testing.T) {+ err := fx.ValidateApp(+ fx.Supply(+ &config.Config{},+ (*database.DB)(nil),+ &http.Client{},+ ),+ fx.Provide(func() context.Context { return context.Background() }),+ ServiceOptions,+ JobOptions,+ fx.Invoke(func(graphParams) {}),+ )+ require.NoError(t, err)+}diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.goindex 5fdd81dca..6f9241cef 100644--- a/backend/internal/di/providers.go+++ b/backend/internal/di/providers.go@@ -1,7 +1,3 @@-// Package di owns the backend's dependency-injection graph. The service-// construction order is generated by google/wire (see wire.go / wire_gen.go);-// this file holds the aggregate Services container and the small set of-// provider wrappers wire cannot synthesize on its own.package diimport (@@ -16,100 +12,51 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/services""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler""github.com/getarcaneapp/arcane/backend/v2/resources"+ "go.uber.org/fx")-// Services is the single aggregate of every constructed service. wire populates-// every field via wire.Struct(new(Services), "*"); it is the only service-// container in the backend (handlers, jobs, and the router all read from it).-type Services struct {- AppImages *services.ApplicationImagesService- User *services.UserService- Project *services.ProjectService- Environment *services.EnvironmentService- Settings *services.SettingsService- KV *services.KVService- JobSchedule *services.JobService- SettingsSearch *services.SettingsSearchService- CustomizeSearch *services.CustomizeSearchService- Container *services.ContainerService- Image *services.ImageService- Build *services.BuildService- BuildWorkspace *services.BuildWorkspaceService- Lifecycle *services.LifecycleService- Volume *services.VolumeService- Network *services.NetworkService- Port *services.PortService- Swarm *services.SwarmService- ImageUpdate *services.ImageUpdateService- Session *services.SessionService- Auth *services.AuthService- Oidc *services.OidcService- Docker *services.DockerClientService- Template *services.TemplateService- ContainerRegistry *services.ContainerRegistryService- System *services.SystemService- SystemUpgrade *services.SystemUpgradeService- Diagnostics *services.DiagnosticsService- Updater *services.UpdaterService- Event *services.EventService- Activity *services.ActivityService- Version *services.VersionService- Notification *services.NotificationService- ApiKey *services.ApiKeyService- Federated *services.FederatedCredentialService- GitRepository *services.GitRepositoryService- GitOpsSync *services.GitOpsSyncService- Webhook *services.WebhookService- Vulnerability *services.VulnerabilityService- Dashboard *services.DashboardService- Role *services.RoleService- Variable *services.VariableService- // AuthMiddleware is the shared Echo auth middleware. It's wired here so the- // router consumes it from the container instead of building the chain inline.- AuthMiddleware *middleware.AuthMiddleware-}--// DockerClient returns the Docker client service. Bootstrap needs the docker-// service on its own (for Close and startup state) before the rest of the-// container is consumed; this avoids a second return value from the injector.-func (s *Services) DockerClient() *services.DockerClientService {- return s.Docker-}--// provideResourcesFSInternal exposes the embedded resource filesystem to the graph so-// wire can call services.NewApplicationImagesService directly.func provideResourcesFSInternal() embed.FS {return resources.FS}-// The following wrappers exist only because wire cannot synthesize these-// constructors by type: they read scalar fields/package vars off the config,-// take parameters of unexported interface types, or apply a post-construction-// builder. Keeping them here (in the untagged file) lets the generated-// wire_gen.go call them in a normal build.+func provideDockerClientServiceInternal(ctx context.Context, lc fx.Lifecycle, db *database.DB, cfg *config.Config, settings *services.SettingsService) *services.DockerClientService {+ service := services.NewDockerClientService(ctx, db, cfg, settings)+ lc.Append(fx.Hook{+ OnStart: func(context.Context) error {+ go service.WatchEvents(ctx)+ return nil+ },+ OnStop: func(context.Context) error {+ service.Close()+ return nil+ },+ })+ return service+}-// provideVersionServiceInternal supplies the bool/string scalars wire can't inject by type.func provideVersionServiceInternal(httpClient *http.Client, cfg *config.Config, registry *services.ContainerRegistryService, docker *services.DockerClientService, imageUpdate *services.ImageUpdateService) *services.VersionService {return services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, registry, docker, imageUpdate)}-// provideGitRepositoryServiceInternal supplies cfg.GitWorkDir (bare string).func provideGitRepositoryServiceInternal(db *database.DB, cfg *config.Config, event *services.EventService, settings *services.SettingsService) *services.GitRepositoryService {return services.NewGitRepositoryService(db, cfg.GitWorkDir, event, settings)}-// provideVolumeServiceInternal supplies cfg.BackupVolumeName (bare string).-func provideVolumeServiceInternal(db *database.DB, docker *services.DockerClientService, event *services.EventService, settings *services.SettingsService, container *services.ContainerService, image *services.ImageService, cfg *config.Config) *services.VolumeService {- return services.NewVolumeService(db, docker, event, settings, container, image, cfg.BackupVolumeName)+func provideVolumeServiceInternal(lc fx.Lifecycle, db *database.DB, docker *services.DockerClientService, event *services.EventService, settings *services.SettingsService, container *services.ContainerService, image *services.ImageService, cfg *config.Config) *services.VolumeService {+ service := services.NewVolumeService(db, docker, event, settings, container, image, cfg.BackupVolumeName)+ lc.Append(fx.Hook{+ OnStop: func(ctx context.Context) error {+ service.CleanupHelperContainers(ctx)+ return nil+ },+ })+ return service}-// provideAuthServiceInternal supplies cfg.JWTSecret (bare string).func provideAuthServiceInternal(user *services.UserService, settings *services.SettingsService, event *services.EventService, session *services.SessionService, role *services.RoleService, cfg *config.Config) *services.AuthService {return services.NewAuthService(user, settings, event, session, role, cfg.JWTSecret, cfg)}-// provideContainerRegistryServiceInternal builds the registryDaemonGetter closure from-// the docker service. registryDaemonGetter is unexported, so wire can't name it.func provideContainerRegistryServiceInternal(db *database.DB, docker *services.DockerClientService, kv *services.KVService) *services.ContainerRegistryService {return services.NewContainerRegistryService(db, func(ctx context.Context) (services.RegistryDaemonClient, error) {return docker.GetClient(ctx)@@ -122,31 +69,22 @@ func provideProjectServiceInternal(db *database.DB, settings *services.SettingsSWithRegistryCredentialsProvider(environment.GetEnabledRegistryCredentials)}-// provideUpdaterServiceInternal passes *SystemUpgradeService for the unexported-// selfUpgradeService parameter so wire never sees the unexported type.func provideUpdaterServiceInternal(db *database.DB, settings *services.SettingsService, docker *services.DockerClientService, project *services.ProjectService, imageUpdate *services.ImageUpdateService, registry *services.ContainerRegistryService, event *services.EventService, image *services.ImageService, notification *services.NotificationService, systemUpgrade *services.SystemUpgradeService, activity *services.ActivityService) *services.UpdaterService {return services.NewUpdaterService(db, settings, docker, project, imageUpdate, registry, event, image, notification, systemUpgrade, activity)}-// provideUserServiceInternal applies the RoleService builder. The builder stays on the-// type for tests; wire calls this wrapper.func provideUserServiceInternal(db *database.DB, role *services.RoleService) *services.UserService {return services.NewUserService(db).WithRoleService(role)}-// provideApiKeyServiceInternal applies the RoleService builder.func provideApiKeyServiceInternal(db *database.DB, user *services.UserService, role *services.RoleService) *services.ApiKeyService {return services.NewApiKeyService(db, user).WithRoleService(role)}-// provideFederatedCredentialServiceInternal applies the RoleService builder.func provideFederatedCredentialServiceInternal(db *database.DB, auth *services.AuthService, user *services.UserService, settings *services.SettingsService, event *services.EventService, httpClient *http.Client, role *services.RoleService) *services.FederatedCredentialService {return services.NewFederatedCredentialService(db, auth, user, settings, event, httpClient).WithRoleService(role)}-// provideAuthMiddlewareInternal builds the shared Echo auth middleware. The builder-// methods take interfaces (ApiKeyValidator / EnvironmentAccessTokenResolver /-// PermissionResolver) that the concrete services already satisfy.func provideAuthMiddlewareInternal(auth *services.AuthService, apiKey *services.ApiKeyService, env *services.EnvironmentService, role *services.RoleService, cfg *config.Config) *middleware.AuthMiddleware {return middleware.NewAuthMiddleware(auth, cfg).WithApiKeyValidator(apiKey).@@ -154,32 +92,10 @@ func provideAuthMiddlewareInternal(auth *services.AuthService, apiKey *services.WithPermissionResolver(role)}-// Jobs aggregates every scheduler job. wire populates it via wire.Struct; the-// bootstrap then registers the constructed jobs with the scheduler and wires the-// settings-change callbacks — those are post-construction concerns wire does not handle.-type Jobs struct {- AutoUpdate *scheduler.AutoUpdateJob- ImageUpdateWatcher *scheduler.ImageUpdateWatcher- DockerClientRefresh *scheduler.DockerClientRefreshJob- Analytics *scheduler.AnalyticsJob- EventCleanup *scheduler.EventCleanupJob- PruningVolumeHelper *scheduler.PruningVolumeHelperJob- ExpiredSessionsCleanup *scheduler.ExpiredSessionsCleanupJob- ScheduledPrune *scheduler.ScheduledPruneJob- FilesystemWatcher *scheduler.FilesystemWatcherJob- VulnerabilityScan *scheduler.VulnerabilityScanJob- AutoHeal *scheduler.AutoHealJob-}--// provideAnalyticsJobInternal preserves the existing nil http.Client (the analytics job-// builds its own default client when none is supplied).func provideAnalyticsJobInternal(settings *services.SettingsService, kv *services.KVService, cfg *config.Config) *scheduler.AnalyticsJob {return scheduler.NewAnalyticsJob(settings, kv, nil, cfg)}-// provideFilesystemWatcherJobInternal supplies ctx + cfg.ProjectScanMaxDepth and keeps the-// watcher-setup failure non-fatal (logged; a nil job is tolerated downstream), matching-// the previous bootstrap behavior.func provideFilesystemWatcherJobInternal(ctx context.Context, project *services.ProjectService, template *services.TemplateService, settings *services.SettingsService, cfg *config.Config) *scheduler.FilesystemWatcherJob {job, err := scheduler.RegisterFilesystemWatcherJob(ctx, project, template, settings, cfg.ProjectScanMaxDepth)if err != nil {diff --git a/backend/internal/di/wire.go b/backend/internal/di/wire.godeleted file mode 100644index b0d345b78..000000000--- a/backend/internal/di/wire.go+++ /dev/null@@ -1,116 +0,0 @@-//go:build wireinject--// This file is consumed only by wire's code generator (build tag wireinject)-// and is excluded from normal builds. Run `go generate ./internal/di/` after-// changing the provider set to regenerate wire_gen.go.--package di--import (- "context"- "net/http"-- "github.com/google/wire"-- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/services"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"-)--// ServiceSet is the single, central provider set for the whole backend. Every-// service constructor (or the wrapper it requires) is listed here exactly once;-// wire derives the construction order from the dependency graph, so ordering is-// no longer maintained by hand. wire.Struct assembles the aggregate Services.-var ServiceSet = wire.NewSet(- // Infra providers that are not themselves services.- provideResourcesFSInternal,-- // Services wire constructs directly via their real constructors.- services.NewEventService,- services.NewActivityService,- services.NewSettingsService, // returns (*SettingsService, error); wire threads the error.- services.NewKVService,- services.NewJobService,- services.NewSettingsSearchService,- services.NewCustomizeSearchService,- services.NewApplicationImagesService,- services.NewDockerClientService,- services.NewRoleService,- services.NewSessionService,- services.NewEnvironmentService,- services.NewNotificationService,- services.NewVulnerabilityService,- services.NewImageUpdateService,- services.NewImageService,- services.NewBuildService,- services.NewBuildWorkspaceService,- services.NewLifecycleService,- provideProjectServiceInternal,- services.NewContainerService,- services.NewDashboardService,- services.NewNetworkService,- services.NewPortService,- services.NewSwarmService,- services.NewTemplateService,- services.NewOidcService,- services.NewSystemService,- services.NewSystemUpgradeService,- services.NewDiagnosticsService,- services.NewGitOpsSyncService,- services.NewWebhookService,- services.NewVariableService,-- // Services that require a wrapper (scalar config field, unexported parameter,- // or post-construction RoleService builder). See providers.go.- provideVersionServiceInternal,- provideGitRepositoryServiceInternal,- provideVolumeServiceInternal,- provideAuthServiceInternal,- provideContainerRegistryServiceInternal,- provideUpdaterServiceInternal,- provideUserServiceInternal,- provideApiKeyServiceInternal,- provideFederatedCredentialServiceInternal,-- // Shared Echo auth middleware (built from the auth-related services + config).- provideAuthMiddlewareInternal,-- // Assemble the aggregate container from everything above.- wire.Struct(new(Services), "*"),-)--// InitializeServices builds the full service graph. ctx, db, cfg, and httpClient-// are graph inputs supplied by the caller; every other value is constructed by-// ServiceSet. The generated implementation lives in wire_gen.go.-func InitializeServices(ctx context.Context, db *database.DB, cfg *config.Config, httpClient *http.Client) (*Services, error) {- panic(wire.Build(ServiceSet))-}--// JobSet builds every scheduler job from an already-constructed *Services (whose-// fields are exposed to the graph via wire.FieldsOf) plus the app context and config.-var JobSet = wire.NewSet(- wire.FieldsOf(new(*Services),- "Updater", "Settings", "ImageUpdate", "Environment", "Docker", "KV",- "Event", "Activity", "Session", "System", "Notification", "Project",- "Template", "Vulnerability", "Volume",- ),- scheduler.NewAutoUpdateJob,- scheduler.NewImageUpdateWatcher,- scheduler.NewDockerClientRefreshJob,- provideAnalyticsJobInternal,- scheduler.NewEventCleanupJob,- scheduler.NewPruningVolumeHelperJob,- scheduler.NewExpiredSessionsCleanupJob,- scheduler.NewScheduledPruneJob,- provideFilesystemWatcherJobInternal,- scheduler.NewVulnerabilityScanJob,- scheduler.NewAutoHealJob,- wire.Struct(new(Jobs), "*"),-)--// InitializeJobs constructs all scheduler jobs from the built services. The caller-// registers them with the scheduler and wires the settings-change callbacks.-func InitializeJobs(ctx context.Context, cfg *config.Config, svcs *Services) *Jobs {- panic(wire.Build(JobSet))-}diff --git a/backend/internal/di/wire_gen.go b/backend/internal/di/wire_gen.godeleted file mode 100644index 650b92cc9..000000000--- a/backend/internal/di/wire_gen.go+++ /dev/null@@ -1,193 +0,0 @@-// Code generated by Wire. DO NOT EDIT.--//go:generate go run -mod=mod github.com/google/wire/cmd/wire-//go:build !wireinject-// +build !wireinject--package di--import (- "context"- "github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/services"- "github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"- "github.com/google/wire"- "net/http"-)--// Injectors from wire.go:--// InitializeServices builds the full service graph. ctx, db, cfg, and httpClient-// are graph inputs supplied by the caller; every other value is constructed by-// ServiceSet. The generated implementation lives in wire_gen.go.-func InitializeServices(ctx context.Context, db *database.DB, cfg *config.Config, httpClient *http.Client) (*Services, error) {- fs := provideResourcesFSInternal()- settingsService, err := services.NewSettingsService(ctx, db)- if err != nil {- return nil, err- }- applicationImagesService := services.NewApplicationImagesService(fs, settingsService)- roleService := services.NewRoleService(db)- userService := provideUserServiceInternal(db, roleService)- eventService := services.NewEventService(db, cfg, httpClient)- dockerClientService := services.NewDockerClientService(ctx, db, cfg, settingsService)- kvService := services.NewKVService(db)- containerRegistryService := provideContainerRegistryServiceInternal(db, dockerClientService, kvService)- apiKeyService := provideApiKeyServiceInternal(db, userService, roleService)- environmentService := services.NewEnvironmentService(db, httpClient, dockerClientService, eventService, settingsService, apiKeyService)- notificationService := services.NewNotificationService(db, cfg, environmentService, eventService)- activityService := services.NewActivityService(db, settingsService)- imageUpdateService := services.NewImageUpdateService(db, settingsService, containerRegistryService, dockerClientService, eventService, notificationService, activityService)- vulnerabilityService := services.NewVulnerabilityService(db, dockerClientService, eventService, settingsService, notificationService, activityService, containerRegistryService)- imageService := services.NewImageService(db, dockerClientService, containerRegistryService, imageUpdateService, vulnerabilityService, eventService)- gitRepositoryService := provideGitRepositoryServiceInternal(db, cfg, eventService, settingsService)- buildService := services.NewBuildService(db, settingsService, dockerClientService, containerRegistryService, gitRepositoryService, eventService)- lifecycleService := services.NewLifecycleService(db, settingsService, eventService, dockerClientService)- projectService := provideProjectServiceInternal(db, settingsService, eventService, imageService, dockerClientService, buildService, lifecycleService, kvService, containerRegistryService, environmentService, cfg)- jobService := services.NewJobService(db, settingsService, cfg)- settingsSearchService := services.NewSettingsSearchService()- customizeSearchService := services.NewCustomizeSearchService()- containerService := services.NewContainerService(ctx, db, eventService, dockerClientService, imageService, settingsService, projectService)- buildWorkspaceService := services.NewBuildWorkspaceService(settingsService)- volumeService := provideVolumeServiceInternal(db, dockerClientService, eventService, settingsService, containerService, imageService, cfg)- networkService := services.NewNetworkService(db, dockerClientService, eventService)- portService := services.NewPortService(dockerClientService)- swarmService := services.NewSwarmService(dockerClientService, settingsService, kvService, containerRegistryService, environmentService)- sessionService := services.NewSessionService(db)- authService := provideAuthServiceInternal(userService, settingsService, eventService, sessionService, roleService, cfg)- oidcService := services.NewOidcService(authService, settingsService, cfg, httpClient)- templateService := services.NewTemplateService(ctx, db, httpClient, settingsService)- systemService := services.NewSystemService(db, dockerClientService, containerService, imageService, volumeService, networkService, settingsService, activityService)- versionService := provideVersionServiceInternal(httpClient, cfg, containerRegistryService, dockerClientService, imageUpdateService)- systemUpgradeService := services.NewSystemUpgradeService(db, dockerClientService, versionService, eventService, settingsService)- diagnosticsService := services.NewDiagnosticsService()- updaterService := provideUpdaterServiceInternal(db, settingsService, dockerClientService, projectService, imageUpdateService, containerRegistryService, eventService, imageService, notificationService, systemUpgradeService, activityService)- federatedCredentialService := provideFederatedCredentialServiceInternal(db, authService, userService, settingsService, eventService, httpClient, roleService)- gitOpsSyncService := services.NewGitOpsSyncService(db, gitRepositoryService, projectService, swarmService, eventService, settingsService)- webhookService := services.NewWebhookService(db, containerService, updaterService, projectService, gitOpsSyncService, eventService, environmentService)- dashboardService := services.NewDashboardService(db, dockerClientService, containerService, projectService, imageService, settingsService, vulnerabilityService, environmentService, versionService)- variableService := services.NewVariableService(db, environmentService, settingsService, kvService)- authMiddleware := provideAuthMiddlewareInternal(authService, apiKeyService, environmentService, roleService, cfg)- diServices := &Services{- AppImages: applicationImagesService,- User: userService,- Project: projectService,- Environment: environmentService,- Settings: settingsService,- KV: kvService,- JobSchedule: jobService,- SettingsSearch: settingsSearchService,- CustomizeSearch: customizeSearchService,- Container: containerService,- Image: imageService,- Build: buildService,- BuildWorkspace: buildWorkspaceService,- Lifecycle: lifecycleService,- Volume: volumeService,- Network: networkService,- Port: portService,- Swarm: swarmService,- ImageUpdate: imageUpdateService,- Session: sessionService,- Auth: authService,- Oidc: oidcService,- Docker: dockerClientService,- Template: templateService,- ContainerRegistry: containerRegistryService,- System: systemService,- SystemUpgrade: systemUpgradeService,- Diagnostics: diagnosticsService,- Updater: updaterService,- Event: eventService,- Activity: activityService,- Version: versionService,- Notification: notificationService,- ApiKey: apiKeyService,- Federated: federatedCredentialService,- GitRepository: gitRepositoryService,- GitOpsSync: gitOpsSyncService,- Webhook: webhookService,- Vulnerability: vulnerabilityService,- Dashboard: dashboardService,- Role: roleService,- Variable: variableService,- AuthMiddleware: authMiddleware,- }- return diServices, nil-}--// InitializeJobs constructs all scheduler jobs from the built services. The caller-// registers them with the scheduler and wires the settings-change callbacks.-func InitializeJobs(ctx context.Context, cfg *config.Config, svcs *Services) *Jobs {- updaterService := svcs.Updater- settingsService := svcs.Settings- autoUpdateJob := scheduler.NewAutoUpdateJob(updaterService, settingsService)- imageUpdateService := svcs.ImageUpdate- environmentService := svcs.Environment- dockerClientService := svcs.Docker- projectService := svcs.Project- imageUpdateWatcher := scheduler.NewImageUpdateWatcher(cfg, imageUpdateService, settingsService, environmentService, dockerClientService, projectService)- dockerClientRefreshJob := scheduler.NewDockerClientRefreshJob(dockerClientService, settingsService)- kvService := svcs.KV- analyticsJob := provideAnalyticsJobInternal(settingsService, kvService, cfg)- eventService := svcs.Event- activityService := svcs.Activity- eventCleanupJob := scheduler.NewEventCleanupJob(eventService, activityService, settingsService)- volumeService := svcs.Volume- pruningVolumeHelperJob := scheduler.NewPruningVolumeHelperJob(volumeService, settingsService)- sessionService := svcs.Session- expiredSessionsCleanupJob := scheduler.NewExpiredSessionsCleanupJob(sessionService, settingsService)- systemService := svcs.System- notificationService := svcs.Notification- scheduledPruneJob := scheduler.NewScheduledPruneJob(systemService, settingsService, notificationService)- templateService := svcs.Template- filesystemWatcherJob := provideFilesystemWatcherJobInternal(ctx, projectService, templateService, settingsService, cfg)- vulnerabilityService := svcs.Vulnerability- vulnerabilityScanJob := scheduler.NewVulnerabilityScanJob(vulnerabilityService, settingsService)- autoHealJob := scheduler.NewAutoHealJob(dockerClientService, settingsService, eventService, notificationService)- jobs := &Jobs{- AutoUpdate: autoUpdateJob,- ImageUpdateWatcher: imageUpdateWatcher,- DockerClientRefresh: dockerClientRefreshJob,- Analytics: analyticsJob,- EventCleanup: eventCleanupJob,- PruningVolumeHelper: pruningVolumeHelperJob,- ExpiredSessionsCleanup: expiredSessionsCleanupJob,- ScheduledPrune: scheduledPruneJob,- FilesystemWatcher: filesystemWatcherJob,- VulnerabilityScan: vulnerabilityScanJob,- AutoHeal: autoHealJob,- }- return jobs-}--// wire.go:--// ServiceSet is the single, central provider set for the whole backend. Every-// service constructor (or the wrapper it requires) is listed here exactly once;-// wire derives the construction order from the dependency graph, so ordering is-// no longer maintained by hand. wire.Struct assembles the aggregate Services.-var ServiceSet = wire.NewSet(-- provideResourcesFSInternal, services.NewEventService, services.NewActivityService, services.NewSettingsService, services.NewKVService, services.NewJobService, services.NewSettingsSearchService, services.NewCustomizeSearchService, services.NewApplicationImagesService, services.NewDockerClientService, services.NewRoleService, services.NewSessionService, services.NewEnvironmentService, services.NewNotificationService, services.NewVulnerabilityService, services.NewImageUpdateService, services.NewImageService, services.NewBuildService, services.NewBuildWorkspaceService, services.NewLifecycleService, provideProjectServiceInternal, services.NewContainerService, services.NewDashboardService, services.NewNetworkService, services.NewPortService, services.NewSwarmService, services.NewTemplateService, services.NewOidcService, services.NewSystemService, services.NewSystemUpgradeService, services.NewDiagnosticsService, services.NewGitOpsSyncService, services.NewWebhookService, services.NewVariableService, provideVersionServiceInternal,- provideGitRepositoryServiceInternal,- provideVolumeServiceInternal,- provideAuthServiceInternal,- provideContainerRegistryServiceInternal,- provideUpdaterServiceInternal,- provideUserServiceInternal,- provideApiKeyServiceInternal,- provideFederatedCredentialServiceInternal,-- provideAuthMiddlewareInternal, wire.Struct(new(Services), "*"),-)--// JobSet builds every scheduler job from an already-constructed *Services (whose-// fields are exposed to the graph via wire.FieldsOf) plus the app context and config.-var JobSet = wire.NewSet(wire.FieldsOf(new(*Services),- "Updater", "Settings", "ImageUpdate", "Environment", "Docker", "KV",- "Event", "Activity", "Session", "System", "Notification", "Project",- "Template", "Vulnerability", "Volume",-), scheduler.NewAutoUpdateJob, scheduler.NewImageUpdateWatcher, scheduler.NewDockerClientRefreshJob, provideAnalyticsJobInternal, scheduler.NewEventCleanupJob, scheduler.NewPruningVolumeHelperJob, scheduler.NewExpiredSessionsCleanupJob, scheduler.NewScheduledPruneJob, provideFilesystemWatcherJobInternal, scheduler.NewVulnerabilityScanJob, scheduler.NewAutoHealJob, wire.Struct(new(Jobs), "*"),-)diff --git a/backend/pkg/scheduler/scheduler.go b/backend/pkg/scheduler/scheduler.goindex 96d4356d5..8e829cb65 100644--- a/backend/pkg/scheduler/scheduler.go+++ b/backend/pkg/scheduler/scheduler.go@@ -196,15 +196,28 @@ func (js *JobScheduler) GetLocation() *time.Location {return js.location}-func (js *JobScheduler) Run(ctx context.Context) error {- js.StartScheduler()- <-ctx.Done()- // Running jobs may still own Docker or database resources. Wait for them here- // so Bootstrap cannot close shared services underneath them; the process-level- // signal handler owns the hard shutdown deadline for non-cooperative jobs.- <-js.cron.Stop().Done()- js.watcherWG.Wait()- return nil+// Stop stops the scheduler and waits for running jobs and bus watchers to finish.+// If ctx is canceled or reaches its deadline first, Stop returns ctx.Err().+func (js *JobScheduler) Stop(ctx context.Context) error {+ cronDone := js.cron.Stop().Done()+ watchersDone := make(chan struct{})+ go func() {+ js.watcherWG.Wait()+ close(watchersDone)+ }()++ select {+ case <-cronDone:+ case <-ctx.Done():+ return ctx.Err()+ }++ select {+ case <-watchersDone:+ return nil+ case <-ctx.Done():+ return ctx.Err()+ }}// upsertJobInternal records the job and (re)schedules it. A replacement expressiondiff --git a/backend/pkg/scheduler/scheduler_test.go b/backend/pkg/scheduler/scheduler_test.goindex 7ac71ba63..9059fea2e 100644--- a/backend/pkg/scheduler/scheduler_test.go+++ b/backend/pkg/scheduler/scheduler_test.go@@ -81,7 +81,7 @@ func TestJobScheduler_StartScheduler_SkipsDisabledConditionalJobs(t *testing.T)require.Empty(t, js.cron.Entries())}-func TestJobScheduler_RegisterBusWatcherUsesLifecycleAndWaitsForShutdown(t *testing.T) {+func TestJobScheduler_StopWaitsForBusWatchers(t *testing.T) {ctx, cancel := context.WithCancel(context.Background())js := NewJobScheduler(ctx, nil)watcher := &testBusWatcherInternal{@@ -92,6 +92,7 @@ func TestJobScheduler_RegisterBusWatcherUsesLifecycleAndWaitsForShutdown(t *test}js.RegisterBusWatcher(watcher, true)+ js.StartScheduler()select {case <-watcher.started:@@ -99,8 +100,8 @@ func TestJobScheduler_RegisterBusWatcherUsesLifecycleAndWaitsForShutdown(t *testt.Fatal("timed out waiting for bus watcher to start")}- runDone := make(chan error, 1)- go func() { runDone <- js.Run(ctx) }()+ stopDone := make(chan error, 1)+ go func() { stopDone <- js.Stop(context.Background()) }()cancel()select {@@ -108,7 +109,12 @@ func TestJobScheduler_RegisterBusWatcherUsesLifecycleAndWaitsForShutdown(t *testcase <-time.After(time.Second):t.Fatal("timed out waiting for bus watcher to stop")}- require.NoError(t, <-runDone)+ select {+ case err := <-stopDone:+ require.NoError(t, err)+ case <-time.After(time.Second):+ t.Fatal("scheduler did not stop after bus watcher finished")+ }}func TestJobScheduler_RegisterBusWatcherManualRunOption(t *testing.T) {@@ -340,7 +346,7 @@ func TestJobScheduler_AddJob_GenericJobWithoutShouldRunIsScheduled(t *testing.T)require.Len(t, js.cron.Entries(), 1)}-func TestJobScheduler_RunWaitsForCanceledJobToFinish(t *testing.T) {+func TestJobScheduler_StopWaitsForCanceledJobToFinish(t *testing.T) {lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())jobStarted := make(chan struct{}, 1)cancellationObserved := make(chan struct{}, 1)@@ -362,9 +368,7 @@ func TestJobScheduler_RunWaitsForCanceledJobToFinish(t *testing.T) {})},})-- runDone := make(chan error, 1)- go func() { runDone <- js.Run(lifecycleCtx) }()+ js.StartScheduler()t.Cleanup(func() {cancelLifecycle()select {@@ -386,9 +390,12 @@ func TestJobScheduler_RunWaitsForCanceledJobToFinish(t *testing.T) {t.Fatal("scheduled job did not observe lifecycle cancellation")}+ stopDone := make(chan error, 1)+ go func() { stopDone <- js.Stop(context.Background()) }()+select {- case err := <-runDone:- t.Fatalf("scheduler returned before the running job finished: %v", err)+ case err := <-stopDone:+ t.Fatalf("scheduler stopped before the running job finished: %v", err)case <-time.After(100 * time.Millisecond):}@@ -399,9 +406,9 @@ func TestJobScheduler_RunWaitsForCanceledJobToFinish(t *testing.T) {t.Fatal("scheduled job did not finish after release")}select {- case err := <-runDone:+ case err := <-stopDone:require.NoError(t, err)case <-time.After(time.Second):- t.Fatal("scheduler did not return after the running job finished")+ t.Fatal("scheduler did not stop after the running job finished")}}diff --git a/cli/go.mod b/cli/go.modindex a7a9713b0..d63ef0f51 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -10,7 +10,7 @@ require (charm.land/log/v2 v2.0.0github.com/charmbracelet/x/term v0.2.2github.com/fatih/color v1.19.0- github.com/getarcaneapp/arcane/types/v2 v2.4.0+ github.com/getarcaneapp/arcane/types/v2 v2.5.0github.com/go-viper/mapstructure/v2 v2.5.0github.com/mattn/go-runewidth v0.0.24github.com/spf13/cobra v1.10.2diff --git a/cli/go.sum b/cli/go.sumindex a657eed66..67b32ef28 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -61,8 +61,8 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkgithub.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=-github.com/getarcaneapp/arcane/types/v2 v2.4.0 h1:7OqHDsXVpJZlqvvUssFSY349Jd6SqsmbsHD4xIP6+NA=-github.com/getarcaneapp/arcane/types/v2 v2.4.0/go.mod h1:OVNW3xJ3bZNigfrnYJjalQILDGzP1NTalA+kwPUC/n8=+github.com/getarcaneapp/arcane/types/v2 v2.5.0 h1:JvnjF4fC5uhxyeLV75OHYbYLbWmLXrESCxooKNOtUcE=+github.com/getarcaneapp/arcane/types/v2 v2.5.0/go.mod h1:jjLII+bNg5vqP2edUt3tKg6uXAf1kxxdEILY+FXuZfE=github.com/go-logfmt/logfmt v0.6.1 h1:4hvbpePJKnIzH1B+8OR/JPbTx37NktoI9LE2QZBBkvE=github.com/go-logfmt/logfmt v0.6.1/go.mod h1:EV2pOAQoZaT1ZXZbqDl5hrymndi4SY9ED9/z6CO0XAk=github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=diff --git a/frontend/src/routes/(app)/settings/diagnostics/diagnostic-log-panel.svelte b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-log-panel.svelteindex 845c041e9..6dd54f248 100644--- a/frontend/src/routes/(app)/settings/diagnostics/diagnostic-log-panel.svelte+++ b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-log-panel.svelte@@ -2,7 +2,6 @@import { onMount, onDestroy } from 'svelte';import { m } from '$lib/paraglide/messages';import { createBackendLogsWebSocket, ReconnectingWebSocket } from '$lib/utils/ws';- import { diagnosticsService } from '$lib/services/diagnostics-service';import type { LogEntry } from '$lib/types/diagnostics';import { cn } from '$lib/utils';import { ArcaneButton } from '$lib/components/arcane-button/index.js';@@ -60,20 +59,13 @@return formatTime(t) || t;}- function logKey(entry: LogEntry): string {- return `${entry.time}-${entry.level}-${entry.message}-${attrsText(entry.attrs)}`;- }-onMount(async () => {- try {- const recent = await diagnosticsService.getRecentLogs();- logs = recent.slice(-maxLines);- } catch {- // initial backlog is best-effort; the live stream fills in- }ws = createBackendLogsWebSocket({onMessage: (e) => push(e),- onOpen: () => (connected = true),+ onOpen: () => {+ logs = [];+ connected = true;+ },onClose: () => (connected = false)});await ws.connect();@@ -135,7 +127,7 @@{#if filtered.length === 0}<div class="py-6 text-center text-muted-foreground">{m.diagnostics_logs_empty()}</div>{:else}- {#each filtered as entry (logKey(entry))}+ {#each filtered as entry (entry)}<div class="flex gap-2 rounded px-1 py-0.5 hover:bg-foreground/5"><span class="shrink-0 text-muted-foreground tabular-nums">{fmtTime(entry.time)}</span><span class={cn('w-12 shrink-0 font-semibold uppercase', levelClass(entry.level))}>{entry.level}</span>diff --git a/go.work.sum b/go.work.sumindex 06b3f41ea..8b094c739 100644--- a/go.work.sum+++ b/go.work.sum@@ -2081,16 +2081,12 @@ go.etcd.io/gofail v0.2.0 h1:p19drv16FKK345a09a1iubchlw/vmRuksmRzgBIGjcA=go.etcd.io/gofail v0.2.0/go.mod h1:nL3ILMGfkXTekKI3clMBNazKnjUZjYLKmBHzsVAnC1o=go.etcd.io/raft/v3 v3.6.0 h1:5NtvbDVYpnfZWcIHgGRk9DyzkBIXOi8j+DDp1IcnUWQ=go.etcd.io/raft/v3 v3.6.0/go.mod h1:nLvLevg6+xrVtHUmVaTcTz603gQPHfh7kUAwV6YpfGo=-go.getarcane.app/builds v0.2.0 h1:IXl78t2Lpr4FJ+HQhAGbTgENyPr2WLBxAmFebRu5kuU=-go.getarcane.app/builds v0.2.0/go.mod h1:korkB7gWCiWx00SbKtX0sTwxWYeL1pxeTKOYxohjJUA=-go.getarcane.app/streams v0.3.0 h1:UM4Y8E0lpi0GEKSJ5zUyeho9aJoBIi/Pr3dJnnhCkK4=-go.getarcane.app/streams v0.3.0/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=+go.getarcane.app/streams v0.3.1 h1:Exs9a9G3paM9PnB6DQc8YvIKNbfaUTB7q271SD30zL8=+go.getarcane.app/streams v0.3.1/go.mod h1:LHMKblQvsL1nqKh/Y+KgQbwFSMI2I7bs9u8ZwZqzjnQ=go.getarcane.app/updater v0.3.6 h1:+BqoycaRsHj+cLVSzcYQuqbHxUKbtmaozMNblz5bVSw=go.getarcane.app/updater v0.3.6/go.mod h1:2ENitZR/lA5MuBn60OZYR5wvU3ZCE+pAgfrebfOlRDA=go.getarcane.app/updater v0.3.7 h1:WqHsxudvt8gvCR7iSHdxdzwH0+hM0FAh64bSypBX9Mo=go.getarcane.app/updater v0.3.7/go.mod h1:9RZOKaBbpUJfVA4Q9/jvqtjvWBwCnVw0OkPeQCnqAAo=-go.getarcane.app/updater v0.6.0 h1:dwnCjQdYMCB7xuCmODs/FhT28BCOUT5Uxmn1XydHv2Q=-go.getarcane.app/updater v0.6.0/go.mod h1:8f0/0pi7J0yFqgwFTywiwk/NoUN/g6AfmprOuAUrI20=go.mongodb.org/mongo-driver v1.7.5 h1:ny3p0reEpgsR2cfA5cjgwFZg3Cv/ofFh/8jbhGtz9VI=go.mongodb.org/mongo-driver v1.7.5/go.mod h1:VXEWRZ6URJIkUq2SCAyapmhH0ZLRBP+FT4xhp5Zvxng=go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=