Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: generate services and jobs from google/wire (#2775)
Kyle Mendellaa5f76744633
diff --git a/Justfile b/Justfileindex 1baf3e884..993447d78 100644--- a/Justfile+++ b/Justfile@@ -443,35 +443,35 @@ deps action="update" target="all":# -----------------------------------------------------------------------------# Run go mod tidy in backend module-[group('go-modules')]+[group('gomod')]_gomod-tidy-backend:cd backend && go mod tidy# Run go mod tidy in CLI module-[group('go-modules')]+[group('gomod')]_gomod-tidy-cli:cd cli && go mod tidy# Run go mod tidy in types module-[group('go-modules')]+[group('gomod')]_gomod-tidy-types:cd types && go mod tidy# Run go mod tidy in all Go modules-[group('go-modules')]+[group('gomod')]_gomod-tidy-go: _gomod-tidy-backend _gomod-tidy-cli _gomod-tidy-types-[group('go-modules')]+[group('gomod')]_gomod-tidy-all:@just _gomod-tidy-gogo work sync-[group('go-modules')]+[group('gomod')]_gomod-sync-all:go work sync# Go module targets. Valid: "tidy [backend|cli|types|go|all]", "sync all".-[group('go-modules')]+[group('gomod')]gomod action="tidy" target="all":@just "_gomod-{{ action }}-{{ target }}"@@ -481,9 +481,19 @@ gomod action="tidy" target="all":# Generate edge tunnel protobuf/gRPC code.[group('codegen')]-proto-backend:+_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".+[group('codegen')]+generate target:+ @just "_generate-{{ target }}"+# Generate the docs config schema JSON.[group('docs')]_docs-config output="" source_root=".":diff --git a/backend/api/api.go b/backend/api/api.goindex 0be9a4a0d..c195f2403 100644--- a/backend/api/api.go+++ b/backend/api/api.go@@ -11,7 +11,7 @@ import ("github.com/getarcaneapp/arcane/backend/api/handlers""github.com/getarcaneapp/arcane/backend/api/middleware""github.com/getarcaneapp/arcane/backend/internal/config"- "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/backend/internal/di""github.com/labstack/echo/v4")@@ -137,51 +137,8 @@ func capitalizeFirst(s string) string {return strings.ToUpper(s[:1]) + s[1:]}-// Services holds all service dependencies needed by Huma handlers.-type Services struct {- AppContext context.Context- User *services.UserService- Auth *services.AuthService- Oidc *services.OidcService- ApiKey *services.ApiKeyService- Federated *services.FederatedCredentialService- AppImages *services.ApplicationImagesService- Project *services.ProjectService- Event *services.EventService- Activity *services.ActivityService- Version *services.VersionService- Environment *services.EnvironmentService- Settings *services.SettingsService- JobSchedule *services.JobService- SettingsSearch *services.SettingsSearchService- ContainerRegistry *services.ContainerRegistryService- Template *services.TemplateService- Docker *services.DockerClientService- Image *services.ImageService- ImageUpdate *services.ImageUpdateService- Build *services.BuildService- BuildWorkspace *services.BuildWorkspaceService- Volume *services.VolumeService- Container *services.ContainerService- Network *services.NetworkService- Port *services.PortService- Swarm *services.SwarmService- Notification *services.NotificationService- Updater *services.UpdaterService- CustomizeSearch *services.CustomizeSearchService- System *services.SystemService- SystemUpgrade *services.SystemUpgradeService- GitRepository *services.GitRepositoryService- GitOpsSync *services.GitOpsSyncService- Webhook *services.WebhookService- Vulnerability *services.VulnerabilityService- Dashboard *services.DashboardService- Role *services.RoleService- Config *config.Config-}-// SetupAPI creates and configures the Huma API attached to the Echo router.-func SetupAPI(e *echo.Echo, apiGroup *echo.Group, cfg *config.Config, svc *Services) huma.API {+func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlers.ActivityAppContext, cfg *config.Config, svc *di.Services) huma.API {humaConfig := huma.DefaultConfig("Arcane API", config.Version)humaConfig.Info.Description = "Modern Docker Management, Designed for Everyone"@@ -230,7 +187,7 @@ func SetupAPI(e *echo.Echo, apiGroup *echo.Group, cfg *config.Config, svc *Serviapi.UseMiddleware(middleware.NewAuthBridge(api, svc.Auth, svc.ApiKey, svc.Role, svc.Environment, cfg))// Register all Huma handlers- registerHandlers(api, svc)+ registerHandlersInternal(api, svc, appCtx, cfg)// Register Scalar API docs endpoint with dark moderegisterScalarDocs(apiGroup)@@ -306,128 +263,52 @@ func SetupAPIForSpec() huma.API {api := humaecho.NewWithGroup(e, apiGroup, humaConfig)// Register handlers with nil services (just for schema)- registerHandlers(api, nil)+ registerHandlersInternal(api, nil, 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 registerHandlers(api huma.API, svc *Services) {- var userSvc *services.UserService- var authSvc *services.AuthService- var oidcSvc *services.OidcService- var apiKeySvc *services.ApiKeyService- var federatedSvc *services.FederatedCredentialService- var appImagesSvc *services.ApplicationImagesService- var projectSvc *services.ProjectService- var eventSvc *services.EventService- var activitySvc *services.ActivityService- var versionSvc *services.VersionService- var environmentSvc *services.EnvironmentService- var settingsSvc *services.SettingsService- var jobScheduleSvc *services.JobService- var settingsSearchSvc *services.SettingsSearchService- var containerRegistrySvc *services.ContainerRegistryService- var templateSvc *services.TemplateService- var dockerSvc *services.DockerClientService- var imageSvc *services.ImageService- var imageUpdateSvc *services.ImageUpdateService- var buildSvc *services.BuildService- var buildWorkspaceSvc *services.BuildWorkspaceService- var volumeSvc *services.VolumeService- var containerSvc *services.ContainerService- var networkSvc *services.NetworkService- var portSvc *services.PortService- var swarmSvc *services.SwarmService- var notificationSvc *services.NotificationService- var updaterSvc *services.UpdaterService- var customizeSearchSvc *services.CustomizeSearchService- var systemSvc *services.SystemService- var systemUpgradeSvc *services.SystemUpgradeService- var gitRepositorySvc *services.GitRepositoryService- var gitOpsSyncSvc *services.GitOpsSyncService- var webhookSvc *services.WebhookService- var vulnerabilitySvc *services.VulnerabilityService- var dashboardSvc *services.DashboardService- var roleSvc *services.RoleService- var appCtx context.Context- var cfg *config.Config-- if svc != nil {- appCtx = svc.AppContext- userSvc = svc.User- authSvc = svc.Auth- oidcSvc = svc.Oidc- apiKeySvc = svc.ApiKey- federatedSvc = svc.Federated- appImagesSvc = svc.AppImages- projectSvc = svc.Project- eventSvc = svc.Event- activitySvc = svc.Activity- versionSvc = svc.Version- environmentSvc = svc.Environment- settingsSvc = svc.Settings- jobScheduleSvc = svc.JobSchedule- settingsSearchSvc = svc.SettingsSearch- containerRegistrySvc = svc.ContainerRegistry- templateSvc = svc.Template- dockerSvc = svc.Docker- imageSvc = svc.Image- imageUpdateSvc = svc.ImageUpdate- buildSvc = svc.Build- buildWorkspaceSvc = svc.BuildWorkspace- volumeSvc = svc.Volume- containerSvc = svc.Container- networkSvc = svc.Network- portSvc = svc.Port- swarmSvc = svc.Swarm- notificationSvc = svc.Notification- updaterSvc = svc.Updater- customizeSearchSvc = svc.CustomizeSearch- systemSvc = svc.System- systemUpgradeSvc = svc.SystemUpgrade- gitRepositorySvc = svc.GitRepository- gitOpsSyncSvc = svc.GitOpsSync- webhookSvc = svc.Webhook- vulnerabilitySvc = svc.Vulnerability- dashboardSvc = svc.Dashboard- roleSvc = svc.Role- cfg = svc.Config+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 keeps every field a true-nil pointer so handler nil-guards hold.+ if svc == nil {+ svc = &di.Services{}}- handlerAppCtx := handlers.NewActivityAppContext(appCtx)handlers.RegisterHealth(api)- handlers.RegisterAuth(api, userSvc, authSvc, oidcSvc)- handlers.RegisterApiKeys(api, apiKeySvc)- handlers.RegisterFederatedCredentials(api, federatedSvc)- handlers.RegisterRoles(api, roleSvc)- handlers.RegisterAppImages(api, appImagesSvc)- handlers.RegisterUsers(api, userSvc, authSvc)- handlers.RegisterProjects(api, projectSvc, activitySvc, handlerAppCtx)- handlers.RegisterVersion(api, versionSvc)- handlers.RegisterEvents(api, eventSvc, apiKeySvc)- handlers.RegisterActivities(api, activitySvc, environmentSvc)- handlers.RegisterOidc(api, authSvc, oidcSvc, roleSvc, userSvc, cfg)- handlers.RegisterEnvironments(api, environmentSvc, settingsSvc, apiKeySvc, eventSvc, cfg)- handlers.RegisterContainerRegistries(api, containerRegistrySvc, environmentSvc)- handlers.RegisterTemplates(api, templateSvc, environmentSvc)- handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc, buildSvc, activitySvc, handlerAppCtx)- handlers.RegisterBuildWorkspaces(api, buildWorkspaceSvc)- handlers.RegisterImageUpdates(api, imageUpdateSvc, imageSvc, handlerAppCtx)- handlers.RegisterSettings(api, settingsSvc, settingsSearchSvc, environmentSvc, cfg)- handlers.RegisterJobSchedules(api, jobScheduleSvc, environmentSvc)- handlers.RegisterVolumes(api, dockerSvc, volumeSvc, activitySvc, handlerAppCtx)- handlers.RegisterContainers(api, containerSvc, dockerSvc, settingsSvc, activitySvc, handlerAppCtx)- handlers.RegisterPorts(api, portSvc)- handlers.RegisterNetworks(api, networkSvc, dockerSvc, activitySvc, handlerAppCtx)- handlers.RegisterSwarm(api, swarmSvc, environmentSvc, eventSvc, cfg)- handlers.RegisterNotifications(api, notificationSvc, cfg)- handlers.RegisterUpdater(api, updaterSvc, handlerAppCtx)- handlers.RegisterCustomize(api, customizeSearchSvc)- handlers.RegisterSystem(api, dockerSvc, systemSvc, systemUpgradeSvc, cfg, activitySvc, handlerAppCtx)- handlers.RegisterGitRepositories(api, gitRepositorySvc)- handlers.RegisterGitOpsSyncs(api, gitOpsSyncSvc)- handlers.RegisterWebhooks(api, webhookSvc)- handlers.RegisterVulnerability(api, vulnerabilitySvc, handlerAppCtx)- handlers.RegisterDashboard(api, dashboardSvc)+ handlers.RegisterAuth(api, svc.User, svc.Auth, svc.Oidc)+ 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, svc.ApiKey)+ 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, svc.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, 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)}diff --git a/backend/api/diagnostics.go b/backend/api/diagnostics.godeleted file mode 100644index 6d9f2acbb..000000000--- a/backend/api/diagnostics.go+++ /dev/null@@ -1,44 +0,0 @@-package api--import (- "net/http"- "runtime"- "time"-- "github.com/getarcaneapp/arcane/backend/api/ws"- "github.com/getarcaneapp/arcane/backend/internal/middleware"- "github.com/getarcaneapp/arcane/backend/pkg/authz"- wshub "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"- "github.com/labstack/echo/v4"-)--type DiagnosticsHandler struct {- wsMetrics *ws.WebSocketMetrics-}--func RegisterDiagnosticsRoutes(group *echo.Group, authMiddleware *middleware.AuthMiddleware, wsMetrics *ws.WebSocketMetrics) {- h := &DiagnosticsHandler{wsMetrics: wsMetrics}-- diagnostics := group.Group("/diagnostics", authMiddleware.Add())- diagnostics.GET("/ws", h.WebSocketDiagnostics)-}--func (h *DiagnosticsHandler) WebSocketDiagnostics(c echo.Context) error {- ps, _ := c.Get("userPermissions").(*authz.PermissionSet)- if !ps.IsGlobalAdmin() {- return c.JSON(http.StatusForbidden, map[string]any{"error": "Admin access required"})- }-- metrics := h.wsMetrics.Snapshot()- connections := h.wsMetrics.Connections()-- return c.JSON(http.StatusOK, map[string]any{- "timestamp": time.Now().UTC().Format(time.RFC3339Nano),- "goroutines": runtime.NumGoroutine(),- "wsWorkerGoroutine": wshub.CountWorkerGoroutines(),- "gomaxprocs": runtime.GOMAXPROCS(0),- "goVersion": runtime.Version(),- "activeConnections": metrics,- "connections": connections,- })-}diff --git a/backend/api/handlers/diagnostics.go b/backend/api/handlers/diagnostics.gonew file mode 100644index 000000000..0b815eb51--- /dev/null+++ b/backend/api/handlers/diagnostics.go@@ -0,0 +1,73 @@+package handlers++import (+ "context"+ "net/http"++ "github.com/danielgtaylor/huma/v2"++ humamw "github.com/getarcaneapp/arcane/backend/api/middleware"+ "github.com/getarcaneapp/arcane/backend/api/ws"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/backend/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/logstream"+ "github.com/getarcaneapp/arcane/types/system"+)++// DiagnosticsHandler serves the REST diagnostics endpoints. The live WebSocket+// streams and pprof routes live in the api/ws package alongside the other+// streaming endpoints; the snapshot is assembled there too (ws.BuildDiagnostics).+type DiagnosticsHandler struct {+ diag *services.DiagnosticsService+}++type DiagnosticsInput struct{}++type GetDiagnosticsOutput struct {+ Body system.Diagnostics+}++type GetDiagnosticsLogsOutput struct {+ Body []system.LogEntry+}++// RegisterDiagnostics registers the Huma diagnostics REST endpoints.+func RegisterDiagnostics(api huma.API, diag *services.DiagnosticsService) {+ h := &DiagnosticsHandler{diag: diag}++ huma.Register(api, huma.Operation{+ OperationID: "get-diagnostics",+ Method: http.MethodGet,+ Path: "/diagnostics",+ Summary: "Get runtime diagnostics",+ Description: "Returns Go runtime, memory, garbage-collector, and WebSocket connection statistics.",+ Tags: []string{"Diagnostics"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ Middlewares: humamw.RequirePermission(api, authz.PermDiagnosticsRead),+ }, h.GetDiagnostics)++ huma.Register(api, huma.Operation{+ OperationID: "get-diagnostics-logs",+ Method: http.MethodGet,+ Path: "/diagnostics/logs",+ Summary: "Get recent backend logs",+ Description: "Returns the most recent buffered backend log entries (oldest first).",+ Tags: []string{"Diagnostics"},+ Security: []map[string][]string{+ {"BearerAuth": {}},+ {"ApiKeyAuth": {}},+ },+ Middlewares: humamw.RequirePermission(api, authz.PermDiagnosticsRead),+ }, h.GetRecentLogs)+}++func (h *DiagnosticsHandler) GetDiagnostics(_ context.Context, _ *DiagnosticsInput) (*GetDiagnosticsOutput, error) {+ return &GetDiagnosticsOutput{Body: ws.BuildDiagnostics(h.diag)}, nil+}++func (h *DiagnosticsHandler) GetRecentLogs(_ context.Context, _ *DiagnosticsInput) (*GetDiagnosticsLogsOutput, error) {+ return &GetDiagnosticsLogsOutput{Body: logstream.Default().Recent()}, nil+}diff --git a/backend/api/ws/diagnostics.go b/backend/api/ws/diagnostics.gonew file mode 100644index 000000000..9d74e04a1--- /dev/null+++ b/backend/api/ws/diagnostics.go@@ -0,0 +1,150 @@+package ws++import (+ "encoding/json"+ "net/http"+ "net/http/pprof"+ "time"++ "github.com/getarcaneapp/arcane/backend/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/backend/pkg/authz"+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/logstream"+ wshub "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"+ systemtypes "github.com/getarcaneapp/arcane/types/system"+ "github.com/gorilla/websocket"+ "github.com/labstack/echo/v4"+)++// diagnosticsStreamInterval is how often the live diagnostics stream pushes a snapshot.+const diagnosticsStreamInterval = 2 * time.Second++// BuildDiagnostics assembles a full diagnostics snapshot: runtime/memory/GC from+// the DiagnosticsService plus this package's WebSocket metrics and worker-goroutine+// count. Shared by the REST endpoint (via handlers) and the live WebSocket stream.+func BuildDiagnostics(diag *services.DiagnosticsService) systemtypes.Diagnostics {+ d := systemtypes.Diagnostics{Timestamp: time.Now().UTC()}+ if diag != nil {+ d.Runtime, d.Memory, d.GC = diag.Collect()+ }+ d.Runtime.WSWorkerGoroutines = wshub.CountWorkerGoroutines()+ d.WebSocket = systemtypes.WebSocketDiagnostics{+ Snapshot: defaultWebSocketMetrics.Snapshot(),+ Connections: defaultWebSocketMetrics.Connections(),+ }+ return d+}++// registerDiagnosticsRoutesInternal wires the global diagnostics WebSocket streams and the+// net/http/pprof debug endpoints. Streams require the diagnostics permission;+// pprof keeps the stricter admin-required gate. Called from NewWebSocketHandler.+func (h *WebSocketHandler) registerDiagnosticsRoutesInternal(group *echo.Group, authMiddleware *middleware.AuthMiddleware) {+ diag := group.Group("/diagnostics",+ authMiddleware.WithAdminNotRequired().Add(),+ middleware.RequirePermission(authz.PermDiagnosticsRead),+ )+ diag.GET("/stream", h.DiagnosticsStream)+ diag.GET("/logs/stream", h.ServerLogsStream)++ pprofGroup := group.Group("/debug/pprof", authMiddleware.WithAdminRequired().Add())+ pprofGroup.GET("", echo.WrapHandler(http.HandlerFunc(pprof.Index)))+ pprofGroup.GET("/", echo.WrapHandler(http.HandlerFunc(pprof.Index)))+ pprofGroup.GET("/cmdline", echo.WrapHandler(http.HandlerFunc(pprof.Cmdline)))+ pprofGroup.GET("/profile", echo.WrapHandler(http.HandlerFunc(pprof.Profile)))+ pprofGroup.POST("/symbol", echo.WrapHandler(http.HandlerFunc(pprof.Symbol)))+ pprofGroup.GET("/symbol", echo.WrapHandler(http.HandlerFunc(pprof.Symbol)))+ pprofGroup.GET("/trace", echo.WrapHandler(http.HandlerFunc(pprof.Trace)))+ pprofGroup.GET("/:name", echo.WrapHandler(http.HandlerFunc(pprof.Index)))+}++// DiagnosticsStream pushes a fresh diagnostics snapshot on connect and then every+// diagnosticsStreamInterval until the client disconnects.+func (h *WebSocketHandler) DiagnosticsStream(c echo.Context) error {+ conn, err := h.wsUpgrader.Upgrade(c.Response().Writer, c.Request(), nil)+ if err != nil {+ return nil+ }+ defer conn.Close()++ done := diagnosticsReadLoopInternal(conn)+ write := func() bool {+ b, marshalErr := json.Marshal(BuildDiagnostics(h.diagnosticsService))+ if marshalErr != nil {+ return true+ }+ return conn.WriteMessage(websocket.TextMessage, b) == nil+ }++ if !write() {+ return nil+ }+ ticker := time.NewTicker(diagnosticsStreamInterval)+ defer ticker.Stop()+ for {+ select {+ case <-done:+ return nil+ case <-ticker.C:+ if !write() {+ return nil+ }+ }+ }+}++// ServerLogsStream replays the recent backend log backlog then streams new entries live.+func (h *WebSocketHandler) ServerLogsStream(c echo.Context) error {+ conn, err := h.wsUpgrader.Upgrade(c.Response().Writer, c.Request(), nil)+ if err != nil {+ return nil+ }+ defer conn.Close()++ // Subscribe before replaying the backlog so no entry is missed in the gap; at+ // worst the newest backlog entry is delivered twice, which is harmless.+ ch, cancel := logstream.Default().Subscribe()+ defer cancel()++ done := diagnosticsReadLoopInternal(conn)+ write := func(e systemtypes.LogEntry) bool {+ b, marshalErr := json.Marshal(e)+ if marshalErr != nil {+ return true+ }+ return conn.WriteMessage(websocket.TextMessage, b) == nil+ }++ for _, e := range logstream.Default().Recent() {+ if !write(e) {+ return nil+ }+ }+ for {+ select {+ case <-done:+ return nil+ case e, ok := <-ch:+ if !ok {+ return nil+ }+ if !write(e) {+ return nil+ }+ }+ }+}++// diagnosticsReadLoopInternal drains incoming frames; the returned channel closes+// when the peer disconnects, signaling the writer loop to stop.+func diagnosticsReadLoopInternal(conn *websocket.Conn) <-chan struct{} {+ done := make(chan struct{})+ go func() {+ defer close(done)+ for {+ if _, _, err := conn.ReadMessage(); err != nil {+ return+ }+ }+ }()+ return done+}diff --git a/backend/api/ws/handler.go b/backend/api/ws/handler.goindex 8731d090c..25151255f 100644--- a/backend/api/ws/handler.go+++ b/backend/api/ws/handler.go@@ -134,11 +134,6 @@ func (m *WebSocketMetrics) applyDelta(kind string, delta int64) {var defaultWebSocketMetrics = NewWebSocketMetrics()-// DefaultWebSocketMetrics returns the package-level WebSocketMetrics singleton.-func DefaultWebSocketMetrics() *WebSocketMetrics {- return defaultWebSocketMetrics-}-// ============================================================================// WebSocket Handler// ============================================================================@@ -146,16 +141,17 @@ func DefaultWebSocketMetrics() *WebSocketMetrics {// WebSocketHandler consolidates all WebSocket and streaming endpoints.// REST endpoints are handled by Huma handlers.type WebSocketHandler struct {- projectService *services.ProjectService- containerService *services.ContainerService- swarmService *services.SwarmService- systemService *services.SystemService- wsUpgrader websocket.Upgrader- wsMetrics *WebSocketMetrics- activeConnections sync.Map- logStreamsMu sync.Mutex- logStreams map[string]*wsLogStream- cpuCache struct {+ projectService *services.ProjectService+ containerService *services.ContainerService+ swarmService *services.SwarmService+ systemService *services.SystemService+ diagnosticsService *services.DiagnosticsService+ wsUpgrader websocket.Upgrader+ wsMetrics *WebSocketMetrics+ activeConnections sync.Map+ logStreamsMu sync.Mutex+ logStreams map[string]*wsLogStream+ cpuCache struct {sync.RWMutexvalue float64@@ -321,18 +317,20 @@ func NewWebSocketHandler(containerService *services.ContainerService,swarmService *services.SwarmService,systemService *services.SystemService,+ diagnosticsService *services.DiagnosticsService,authMiddleware *middleware.AuthMiddleware,cfg *config.Config,) {handler := &WebSocketHandler{- projectService: projectService,- containerService: containerService,- swarmService: swarmService,- systemService: systemService,- wsMetrics: defaultWebSocketMetrics,- logStreams: make(map[string]*wsLogStream),- cgroupCache: system.NewCgroupCache(cgroupCacheTTL),- gpuMonitor: system.NewGPUMonitor(cfg.GPUMonitoringEnabled, cfg.GPUType),+ projectService: projectService,+ containerService: containerService,+ swarmService: swarmService,+ systemService: systemService,+ diagnosticsService: diagnosticsService,+ wsMetrics: defaultWebSocketMetrics,+ logStreams: make(map[string]*wsLogStream),+ cgroupCache: system.NewCgroupCache(cgroupCacheTTL),+ gpuMonitor: system.NewGPUMonitor(cfg.GPUMonitoringEnabled, cfg.GPUType),wsUpgrader: websocket.Upgrader{CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.GetAppURL()),ReadBufferSize: 32 * 1024,@@ -347,6 +345,7 @@ func NewWebSocketHandler(wsGroup.GET("/containers/:containerId/terminal", handler.ContainerExec, middleware.RequirePermission(authz.PermContainersExec))wsGroup.GET("/swarm/services/:serviceId/logs", handler.ServiceLogs, middleware.RequirePermission(authz.PermSwarmServicesLogs))wsGroup.GET("/system/stats", handler.SystemStats, middleware.RequirePermission(authz.PermSystemRead))+ handler.registerDiagnosticsRoutesInternal(group, authMiddleware)}// ============================================================================diff --git a/backend/go.mod b/backend/go.modindex 79dcfec12..d8dd91cb4 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -31,6 +31,7 @@ require (github.com/golang-jwt/jwt/v5 v5.3.1github.com/golang-migrate/migrate/v4 v4.19.1github.com/google/uuid v1.6.0+ github.com/google/wire v0.7.0github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674github.com/hashicorp/go-uuid v1.0.3github.com/jinzhu/copier v0.4.0@@ -128,6 +129,7 @@ require (github.com/google/go-github/v39 v39.2.0 // indirectgithub.com/google/go-querystring v1.2.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@@ -219,6 +221,7 @@ require (go.yaml.in/yaml/v4 v4.0.0-rc.4 // indirectgolang.org/x/sys v0.45.0 // indirectgolang.org/x/term v0.43.0 // indirect+ golang.org/x/tools v0.45.0 // indirectgoogle.golang.org/genproto/googleapis/api v0.0.0-20260511170946-3700d4141b60 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260511170946-3700d4141b60 // indirectgopkg.in/ini.v1 v1.67.2 // indirect@@ -231,3 +234,5 @@ require (modernc.org/sqlite v1.50.1 // indirecttags.cncf.io/container-device-interface v1.1.0 // indirect)++tool github.com/google/wire/cmd/wirediff --git a/backend/go.sum b/backend/go.sumindex 76af66d44..76b8e55ca 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -277,8 +277,12 @@ github.com/google/pprof v0.0.0-20260507013755-92041b743c96 h1:YDDnaZ9afWajDboPMtgithub.com/google/pprof v0.0.0-20260507013755-92041b743c96/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=@@ -558,7 +562,9 @@ go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.6go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.68.0 h1:cuXaPAfIoJKsYjBjPSb2nKZEmgM43zVr25l37IxhKME=go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.68.0/go.mod h1:BuzhPofpCzlDi/Q/Xjg54M4/3oWqqyDe2Zeq7A2I0QE=go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=+go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 h1:8UQVDcZxOJLtX6gxtDt3vY2WTgvZqMQRzjsqiIHQdkc=go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0/go.mod h1:2lmweYCiHYpEjQ/lSJBYhj9jP1zvCvQW4BqL9dnT7FQ=go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0 h1:w1K+pCJoPpQifuVpsKamUdn9U0zM3xUziVOqsGksUrY=@@ -570,10 +576,15 @@ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.43.0/go.mod hgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0 h1:3iZJKlCZufyRzPzlQhUIWVmfltrXuGyfjREgGP3UUjc=go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.43.0/go.mod h1:/G+nUPfhq2e+qiXMGxMwumDrP5jtzU+mWN7/sjT2rak=go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=+go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA=+go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=+go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=+go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=+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/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 62279c409..7a975d104 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -17,10 +17,12 @@ import ("github.com/moby/moby/client""github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/di""github.com/getarcaneapp/arcane/backend/internal/services"libcrypto "github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto""github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge"tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1"+ "github.com/getarcaneapp/arcane/backend/pkg/libarcane/logstream""github.com/getarcaneapp/arcane/backend/pkg/libarcane/startup""github.com/getarcaneapp/arcane/backend/pkg/scheduler""github.com/getarcaneapp/arcane/backend/pkg/utils"@@ -45,6 +47,9 @@ func Bootstrap(ctx context.Context) error {cfg.DockerConfig = runtimeIdentityCfg.DockerConfigSetupSlogLogger(cfg)+ // Tee all slog output into the in-memory ring buffer that powers the+ // diagnostics live log tail.+ slog.SetDefault(slog.New(logstream.NewSlogHandler(slog.Default().Handler(), logstream.Default())))ConfigureGormLogger(cfg)slog.InfoContext(ctx, "Arcane is starting...", "version", config.Version)slog.InfoContext(ctx, "Arcane Identity Configuration", "PUID", os.Getuid(), "PGID", os.Getgid())@@ -70,10 +75,11 @@ func Bootstrap(ctx context.Context) error {httpClient := newConfiguredHTTPClient(cfg)- appServices, dockerClientService, err := initializeServices(appCtx, db, cfg, httpClient)+ appServices, err := di.InitializeServices(appCtx, db, cfg, httpClient)if err != nil {return fmt.Errorf("failed to initialize services: %w", err)}+ dockerClientService := appServices.Dockerdefer dockerClientService.Close()defer func(ctx context.Context) {baseCtx := context.WithoutCancel(ctx)@@ -111,7 +117,7 @@ func newConfiguredHTTPClient(cfg *config.Config) *http.Client {return httputils.NewHTTPClient()}-func initializeStartupState(appCtx context.Context, cfg *config.Config, appServices *Services, dockerClientService *services.DockerClientService, httpClient *http.Client) {+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)}diff --git a/backend/internal/bootstrap/bootstrap_test.go b/backend/internal/bootstrap/bootstrap_test.goindex 330aac4fd..5924efc2d 100644--- a/backend/internal/bootstrap/bootstrap_test.go+++ b/backend/internal/bootstrap/bootstrap_test.go@@ -12,6 +12,8 @@ import ("time""github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/di"+ "github.com/getarcaneapp/arcane/backend/internal/middleware"libcrypto "github.com/getarcaneapp/arcane/backend/pkg/libarcane/crypto"tunnelpb "github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge/proto/tunnel/v1""github.com/stretchr/testify/assert"@@ -149,10 +151,13 @@ func TestConfigureHTTPProtocolsInternal(t *testing.T) {}func TestHTTP2APIResponsesDoNotUseAPIGzipInternal(t *testing.T) {- router, _ := setupRouter(context.Background(), &config.Config{+ cfg := &config.Config{AppUrl: "http://localhost:3552",Environment: config.AppEnvironmentTest,- }, &Services{})+ }+ router, _ := setupRouter(context.Background(), cfg, &di.Services{+ AuthMiddleware: middleware.NewAuthMiddleware(nil, cfg),+ })handler, protocols := configureHTTPProtocolsInternal(false, router)listener, err := net.Listen("tcp", "127.0.0.1:0")diff --git a/backend/internal/bootstrap/buildables_router_bootstrap.go b/backend/internal/bootstrap/buildables_router_bootstrap.goindex a1d338052..082c09165 100644--- a/backend/internal/bootstrap/buildables_router_bootstrap.go+++ b/backend/internal/bootstrap/buildables_router_bootstrap.go@@ -4,11 +4,12 @@ package bootstrapimport ("github.com/getarcaneapp/arcane/backend/api"+ "github.com/getarcaneapp/arcane/backend/internal/di""github.com/labstack/echo/v4")func init() {- registerBuildableRoutes = append(registerBuildableRoutes, func(apiGroup *echo.Group, svc *Services) {+ registerBuildableRoutes = append(registerBuildableRoutes, func(apiGroup *echo.Group, svc *di.Services) {api.SetupBuildablesRoutes(apiGroup, svc.Auth)})}diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.goindex 0df3cdca5..f8493cfa6 100644--- a/backend/internal/bootstrap/edge_bootstrap.go+++ b/backend/internal/bootstrap/edge_bootstrap.go@@ -8,6 +8,7 @@ import ("log/slog""github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/di""github.com/getarcaneapp/arcane/backend/internal/middleware""github.com/getarcaneapp/arcane/backend/internal/models""github.com/getarcaneapp/arcane/backend/internal/services"@@ -22,7 +23,7 @@ func registerEdgeTunnelRoutes(ctx context.Context,cfg *config.Config,apiGroup *echo.Group,- appServices *Services,+ appServices *di.Services,) *edge.TunnelServer {// Resolver that validates API key and returns the environment IDresolver := func(ctx context.Context, token string) (string, error) {diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex 68cafd63e..10b95a737 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -7,105 +7,84 @@ import ("net/http""github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/di""github.com/getarcaneapp/arcane/backend/pkg/libarcane"pkg_scheduler "github.com/getarcaneapp/arcane/backend/pkg/scheduler")-func registerJobs(appCtx context.Context, newScheduler *pkg_scheduler.JobScheduler, appServices *Services, appConfig *config.Config) {- autoUpdateJob := pkg_scheduler.NewAutoUpdateJob(appServices.Updater, appServices.Settings)- newScheduler.RegisterJob(autoUpdateJob)+func registerJobs(appCtx context.Context, newScheduler *pkg_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)- imagePollingJob := pkg_scheduler.NewImagePollingJob(appServices.ImageUpdate, appServices.Settings, appServices.Environment)- newScheduler.RegisterJob(imagePollingJob)-- environmentHealthJob := pkg_scheduler.NewEnvironmentHealthJob(appServices.Environment, appServices.Settings)+ newScheduler.RegisterJob(jobs.AutoUpdate)+ newScheduler.RegisterJob(jobs.ImagePolling)if !appConfig.AgentMode {- newScheduler.RegisterJob(environmentHealthJob)+ newScheduler.RegisterJob(jobs.EnvironmentHealth)}-- dockerClientRefreshJob := pkg_scheduler.NewDockerClientRefreshJob(appServices.Docker, appServices.Settings)- newScheduler.RegisterJob(dockerClientRefreshJob)-- analyticsJob := pkg_scheduler.NewAnalyticsJob(appServices.Settings, appServices.KV, nil, appConfig)- newScheduler.RegisterJob(analyticsJob)+ newScheduler.RegisterJob(jobs.DockerClientRefresh)+ newScheduler.RegisterJob(jobs.Analytics)// Send initial heartbeat on startup without blocking bootstrap.- go analyticsJob.Run(appCtx)-- eventCleanupJob := pkg_scheduler.NewEventCleanupJob(appServices.Event, appServices.Activity, appServices.Settings)- newScheduler.RegisterJob(eventCleanupJob)-- pruningVolumeHelperJob := pkg_scheduler.NewPruningVolumeHelperJob(appServices.Volume, appServices.Settings)- newScheduler.RegisterJob(pruningVolumeHelperJob)-- expiredSessionsCleanupJob := pkg_scheduler.NewExpiredSessionsCleanupJob(appServices.Session, appServices.Settings)- newScheduler.RegisterJob(expiredSessionsCleanupJob)-- scheduledPruneJob := pkg_scheduler.NewScheduledPruneJob(appServices.System, appServices.Settings, appServices.Notification)- newScheduler.RegisterJob(scheduledPruneJob)-- fsWatcherJob, err := pkg_scheduler.RegisterFilesystemWatcherJob(appCtx, appServices.Project, appServices.Template, appServices.Settings, appConfig.ProjectScanMaxDepth)- if err != nil {- slog.ErrorContext(appCtx, "Failed to register filesystem watcher job", "error", err)- }-- gitOpsSyncJob := pkg_scheduler.NewGitOpsSyncJob(appServices.GitOpsSync, appServices.Settings)- newScheduler.RegisterJob(gitOpsSyncJob)-- vulnerabilityScanJob := pkg_scheduler.NewVulnerabilityScanJob(appServices.Vulnerability, appServices.Settings)- newScheduler.RegisterJob(vulnerabilityScanJob)-- autoHealJob := pkg_scheduler.NewAutoHealJob(appServices.Docker, appServices.Settings, appServices.Event, appServices.Notification)- newScheduler.RegisterJob(autoHealJob)-- setupSettingsCallbacks(appCtx, appServices, appConfig, newScheduler, imagePollingJob, autoUpdateJob, environmentHealthJob, fsWatcherJob, scheduledPruneJob, vulnerabilityScanJob, autoHealJob)+ go jobs.Analytics.Run(appCtx)+ newScheduler.RegisterJob(jobs.EventCleanup)+ newScheduler.RegisterJob(jobs.PruningVolumeHelper)+ newScheduler.RegisterJob(jobs.ExpiredSessionsCleanup)+ newScheduler.RegisterJob(jobs.ScheduledPrune)+ // FilesystemWatcher is intentionally not scheduler-registered; it watches inline+ // and is only rebound on settings changes below.+ newScheduler.RegisterJob(jobs.GitOpsSync)+ newScheduler.RegisterJob(jobs.VulnerabilityScan)+ newScheduler.RegisterJob(jobs.AutoHeal)++ setupSettingsCallbacks(appCtx, appServices, appConfig, newScheduler, jobs)}-func setupSettingsCallbacks(lifecycleCtx context.Context, appServices *Services, appConfig *config.Config, newScheduler *pkg_scheduler.JobScheduler, imagePollingJob *pkg_scheduler.ImagePollingJob, autoUpdateJob *pkg_scheduler.AutoUpdateJob, environmentHealthJob *pkg_scheduler.EnvironmentHealthJob, fsWatcherJob *pkg_scheduler.FilesystemWatcherJob, scheduledPruneJob *pkg_scheduler.ScheduledPruneJob, vulnerabilityScanJob *pkg_scheduler.VulnerabilityScanJob, autoHealJob *pkg_scheduler.AutoHealJob) {+func setupSettingsCallbacks(lifecycleCtx context.Context, appServices *di.Services, appConfig *config.Config, newScheduler *pkg_scheduler.JobScheduler, jobs *di.Jobs) {appServices.Settings.OnImagePollingSettingsChanged = func(_ context.Context) {- if err := newScheduler.RescheduleJob(lifecycleCtx, imagePollingJob); err != nil {+ if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.ImagePolling); err != nil {slog.WarnContext(lifecycleCtx, "Failed to reschedule image-polling job", "error", err)}- if err := newScheduler.RescheduleJob(lifecycleCtx, autoUpdateJob); err != nil {+ if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.AutoUpdate); err != nil {slog.WarnContext(lifecycleCtx, "Failed to reschedule auto-update job", "error", err)}if !appConfig.AgentMode {- if err := newScheduler.RescheduleJob(lifecycleCtx, environmentHealthJob); err != nil {+ if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.EnvironmentHealth); err != nil {slog.WarnContext(lifecycleCtx, "Failed to reschedule environment-health 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, autoUpdateJob); err != nil {+ if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.AutoUpdate); err != nil {slog.WarnContext(lifecycleCtx, "Failed to reschedule auto-update job", "error", err)}}appServices.Settings.OnProjectsDirectoryChanged = func(_ context.Context) {- if fsWatcherJob != nil {- if err := fsWatcherJob.RestartProjectsWatcher(lifecycleCtx); err != nil {+ if jobs.FilesystemWatcher != nil {+ if err := jobs.FilesystemWatcher.RestartProjectsWatcher(lifecycleCtx); err != nil {slog.WarnContext(lifecycleCtx, "Failed to restart projects filesystem watcher", "error", err)}}}appServices.Settings.OnTemplatesDirectoryChanged = func(_ context.Context) {- if fsWatcherJob != nil {- if err := fsWatcherJob.RestartTemplatesWatcher(lifecycleCtx); err != nil {+ if jobs.FilesystemWatcher != nil {+ if err := jobs.FilesystemWatcher.RestartTemplatesWatcher(lifecycleCtx); err != nil {slog.WarnContext(lifecycleCtx, "Failed to restart templates filesystem watcher", "error", err)}}}appServices.Settings.OnScheduledPruneSettingsChanged = func(_ context.Context) {- if err := newScheduler.RescheduleJob(lifecycleCtx, scheduledPruneJob); err != nil {+ if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.ScheduledPrune); err != nil {slog.WarnContext(lifecycleCtx, "Failed to reschedule scheduled-prune job", "error", err)}}appServices.Settings.OnVulnerabilityScanSettingsChanged = func(_ context.Context) {- if err := newScheduler.RescheduleJob(lifecycleCtx, vulnerabilityScanJob); err != nil {+ if err := newScheduler.RescheduleJob(lifecycleCtx, jobs.VulnerabilityScan); err != nil {slog.WarnContext(lifecycleCtx, "Failed to reschedule vulnerability-scan job", "error", err)}}appServices.Settings.OnAutoHealSettingsChanged = func(ctx context.Context) {- if err := newScheduler.RescheduleJob(ctx, autoHealJob); err != nil {+ if err := newScheduler.RescheduleJob(ctx, jobs.AutoHeal); err != nil {slog.WarnContext(ctx, "Failed to reschedule auto-heal job", "error", err)}}@@ -119,7 +98,7 @@ func setupSettingsCallbacks(lifecycleCtx context.Context, appServices *Services,}// syncTimeoutSettingsToAgentsInternal syncs timeout settings to all connected remote environments-func syncTimeoutSettingsToAgentsInternal(ctx context.Context, appServices *Services, timeoutSettings []libarcane.SettingUpdate) {+func syncTimeoutSettingsToAgentsInternal(ctx context.Context, appServices *di.Services, timeoutSettings []libarcane.SettingUpdate) {envs, err := appServices.Environment.ListRemoteEnvironments(ctx)if err != nil {slog.WarnContext(ctx, "Failed to list remote environments for timeout sync", "error", err)diff --git a/backend/internal/bootstrap/playwright_router_bootstrap.go b/backend/internal/bootstrap/playwright_router_bootstrap.goindex 94d1cf410..a72ac5387 100644--- a/backend/internal/bootstrap/playwright_router_bootstrap.go+++ b/backend/internal/bootstrap/playwright_router_bootstrap.go@@ -6,13 +6,14 @@ import ("log/slog""github.com/getarcaneapp/arcane/backend/api"+ "github.com/getarcaneapp/arcane/backend/internal/di""github.com/getarcaneapp/arcane/backend/internal/services""github.com/labstack/echo/v4")func init() {- registerPlaywrightRoutes = []func(apiGroup *echo.Group, services *Services){- func(apiGroup *echo.Group, svc *Services) {+ registerPlaywrightRoutes = []func(apiGroup *echo.Group, services *di.Services){+ func(apiGroup *echo.Group, svc *di.Services) {playwrightService := services.NewPlaywrightService(svc.ApiKey, svc.User, svc.Federated)if playwrightService == nil {slog.Warn("Playwright service not available, skipping playwright routes")diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex ee9064a72..3f2fc05fe 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -4,8 +4,6 @@ import ("context""log/slog""net"- "net/http"- "net/http/pprof""path""strings"@@ -18,6 +16,7 @@ import ("github.com/getarcaneapp/arcane/backend/api/ws""github.com/getarcaneapp/arcane/backend/frontend""github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/di""github.com/getarcaneapp/arcane/backend/internal/middleware""github.com/getarcaneapp/arcane/backend/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"@@ -25,8 +24,8 @@ import ()var (- registerPlaywrightRoutes []func(apiGroup *echo.Group, services *Services)- registerBuildableRoutes []func(apiGroup *echo.Group, services *Services)+ registerPlaywrightRoutes []func(apiGroup *echo.Group, services *di.Services)+ registerBuildableRoutes []func(apiGroup *echo.Group, services *di.Services))var loggerSkipPatterns = []string{@@ -86,7 +85,7 @@ func requestLoggerMiddlewareInternal() echo.MiddlewareFunc {}}-func createAuthValidatorInternal(appServices *Services) middleware.AuthValidator {+func createAuthValidatorInternal(appServices *di.Services) middleware.AuthValidator {return func(ctx context.Context, c echo.Context) bool {req := c.Request()// Check for API key authentication@@ -120,7 +119,7 @@ func createAuthValidatorInternal(appServices *Services) middleware.AuthValidator}}-func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services) (*echo.Echo, *edge.TunnelServer) {+func setupRouter(ctx context.Context, cfg *config.Config, appServices *di.Services) (*echo.Echo, *edge.TunnelServer) {e := echo.New()e.HideBanner = truee.HidePort = true@@ -143,10 +142,7 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)e.Use(requestLoggerMiddlewareInternal()) //nolint:contextchecke.Use(secureCookieContextMiddlewareInternal(trustedProxyNets)) //nolint:contextcheck- authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).- WithApiKeyValidator(appServices.ApiKey).- WithEnvironmentAccessTokenResolver(appServices.Environment).- WithPermissionResolver(appServices.Role)+ authMiddleware := appServices.AuthMiddlewaree.Use(middleware.NewCORSMiddleware(cfg).Add())apiGroup := e.Group("/api")@@ -189,59 +185,14 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services))apiGroup.Use(envProxyMiddleware)- humaServices := &api.Services{- AppContext: ctx,- User: appServices.User,- Auth: appServices.Auth,- Oidc: appServices.Oidc,- ApiKey: appServices.ApiKey,- Federated: appServices.Federated,- AppImages: appServices.AppImages,- Project: appServices.Project,- Event: appServices.Event,- Activity: appServices.Activity,- Version: appServices.Version,- Environment: appServices.Environment,- Settings: appServices.Settings,- JobSchedule: appServices.JobSchedule,- SettingsSearch: appServices.SettingsSearch,- ContainerRegistry: appServices.ContainerRegistry,- Template: appServices.Template,- Docker: appServices.Docker,- Image: appServices.Image,- ImageUpdate: appServices.ImageUpdate,- Build: appServices.Build,- BuildWorkspace: appServices.BuildWorkspace,- Volume: appServices.Volume,- Container: appServices.Container,- Network: appServices.Network,- Port: appServices.Port,- Swarm: appServices.Swarm,- Notification: appServices.Notification,- Updater: appServices.Updater,- CustomizeSearch: appServices.CustomizeSearch,- System: appServices.System,- SystemUpgrade: appServices.SystemUpgrade,- GitRepository: appServices.GitRepository,- GitOpsSync: appServices.GitOpsSync,- Webhook: appServices.Webhook,- Vulnerability: appServices.Vulnerability,- Dashboard: appServices.Dashboard,- Role: appServices.Role,- Config: cfg,- }-- _ = api.SetupAPI(e, apiGroup, cfg, humaServices) //nolint:contextcheck // app lifecycle context is carried in humaServices for detached activity work.+ _ = api.SetupAPI(e, apiGroup, handlerAppCtx, cfg, appServices) //nolint:contextcheck // app lifecycle context is intentionally wrapped for detached activity work.for _, register := range registerBuildableRoutes {register(apiGroup, appServices)}- api.RegisterDiagnosticsRoutes(apiGroup, authMiddleware, ws.DefaultWebSocketMetrics()) //nolint:contextcheck- registerPprofRoutesInternal(apiGroup, authMiddleware) //nolint:contextcheck-// Remaining echo handlers (WebSocket/streaming)- ws.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.Swarm, appServices.System, authMiddleware, cfg) //nolint:contextcheck+ ws.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.Swarm, appServices.System, appServices.Diagnostics, authMiddleware, cfg) //nolint:contextcheck// Register edge tunnel endpoint for manager to accept agent connections// This is only registered when NOT in agent mode (i.e., running as manager)@@ -327,15 +278,3 @@ func remoteAddrInTrustedProxiesInternal(remoteAddr string, nets []*net.IPNet) bo}return false}--func registerPprofRoutesInternal(apiGroup *echo.Group, authMiddleware *middleware.AuthMiddleware) {- pprofGroup := apiGroup.Group("/debug/pprof", authMiddleware.WithAdminRequired().Add())- pprofGroup.GET("", echo.WrapHandler(http.HandlerFunc(pprof.Index)))- pprofGroup.GET("/", echo.WrapHandler(http.HandlerFunc(pprof.Index)))- pprofGroup.GET("/cmdline", echo.WrapHandler(http.HandlerFunc(pprof.Cmdline)))- pprofGroup.GET("/profile", echo.WrapHandler(http.HandlerFunc(pprof.Profile)))- pprofGroup.POST("/symbol", echo.WrapHandler(http.HandlerFunc(pprof.Symbol)))- pprofGroup.GET("/symbol", echo.WrapHandler(http.HandlerFunc(pprof.Symbol)))- pprofGroup.GET("/trace", echo.WrapHandler(http.HandlerFunc(pprof.Trace)))- pprofGroup.GET("/:name", echo.WrapHandler(http.HandlerFunc(pprof.Index)))-}diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.godeleted file mode 100644index 43b259633..000000000--- a/backend/internal/bootstrap/services_bootstrap.go+++ /dev/null@@ -1,116 +0,0 @@-package bootstrap--import (- "context"- "fmt"- "net/http"-- "github.com/getarcaneapp/arcane/backend/internal/config"- "github.com/getarcaneapp/arcane/backend/internal/database"- "github.com/getarcaneapp/arcane/backend/internal/services"- "github.com/getarcaneapp/arcane/backend/resources"-)--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- 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- 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-}--func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config, httpClient *http.Client) (svcs *Services, dockerSrvice *services.DockerClientService, err error) {- svcs = &Services{}-- svcs.Event = services.NewEventService(db, cfg, httpClient)- svcs.Activity = services.NewActivityService(db)- svcs.Settings, err = services.NewSettingsService(ctx, db)- if err != nil {- return nil, nil, fmt.Errorf("failed to settings service: %w", err)- }- svcs.KV = services.NewKVService(db)- svcs.JobSchedule = services.NewJobService(db, svcs.Settings, cfg)- svcs.SettingsSearch = services.NewSettingsSearchService()- svcs.CustomizeSearch = services.NewCustomizeSearchService()- svcs.AppImages = services.NewApplicationImagesService(resources.FS, svcs.Settings)- dockerClient := services.NewDockerClientService(ctx, db, cfg, svcs.Settings)- svcs.Docker = dockerClient- svcs.Role = services.NewRoleService(db)- svcs.User = services.NewUserService(db).WithRoleService(svcs.Role)- svcs.Session = services.NewSessionService(db)- svcs.ApiKey = services.NewApiKeyService(db, svcs.User).WithRoleService(svcs.Role)- svcs.ContainerRegistry = services.NewContainerRegistryService(db, func(ctx context.Context) (services.RegistryDaemonClient, error) {- return dockerClient.GetClient(ctx)- }, svcs.KV)- svcs.Environment = services.NewEnvironmentService(db, httpClient, svcs.Docker, svcs.Event, svcs.Settings, svcs.ApiKey)- svcs.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, svcs.ContainerRegistry, svcs.Docker)- svcs.Notification = services.NewNotificationService(db, cfg, svcs.Environment)- svcs.Vulnerability = services.NewVulnerabilityService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Notification, svcs.Activity, svcs.ContainerRegistry)- svcs.ImageUpdate = services.NewImageUpdateService(db, svcs.Settings, svcs.ContainerRegistry, svcs.Docker, svcs.Event, svcs.Notification, svcs.Activity)- svcs.Image = services.NewImageService(db, svcs.Docker, svcs.ContainerRegistry, svcs.ImageUpdate, svcs.Vulnerability, svcs.Event)- svcs.GitRepository = services.NewGitRepositoryService(db, cfg.GitWorkDir, svcs.Event, svcs.Settings)- svcs.Build = services.NewBuildService(db, svcs.Settings, svcs.Docker, svcs.ContainerRegistry, svcs.GitRepository, svcs.Event)- svcs.BuildWorkspace = services.NewBuildWorkspaceService(svcs.Settings)- svcs.Project = services.NewProjectService(db, svcs.Settings, svcs.Event, svcs.Image, svcs.Docker, svcs.Build, cfg)- svcs.Container = services.NewContainerService(ctx, db, svcs.Event, svcs.Docker, svcs.Image, svcs.Settings, svcs.Project)- svcs.Dashboard = services.NewDashboardService(- db,- svcs.Docker,- svcs.Container,- svcs.Project,- svcs.Image,- svcs.Settings,- svcs.Vulnerability,- svcs.Environment,- svcs.Version,- )- svcs.Volume = services.NewVolumeService(db, svcs.Docker, svcs.Event, svcs.Settings, svcs.Container, svcs.Image, cfg.BackupVolumeName)- svcs.Network = services.NewNetworkService(db, svcs.Docker, svcs.Event)- svcs.Port = services.NewPortService(svcs.Docker)- svcs.Swarm = services.NewSwarmService(svcs.Docker, svcs.Settings, svcs.KV, svcs.ContainerRegistry, svcs.Environment)- svcs.Template = services.NewTemplateService(ctx, db, httpClient, svcs.Settings)- svcs.Auth = services.NewAuthService(svcs.User, svcs.Settings, svcs.Event, svcs.Session, svcs.Role, cfg.JWTSecret, cfg)- svcs.Oidc = services.NewOidcService(svcs.Auth, svcs.Settings, cfg, httpClient)- svcs.Federated = services.NewFederatedCredentialService(db, svcs.Auth, svcs.User, svcs.Settings, svcs.Event, httpClient).WithRoleService(svcs.Role)- svcs.System = services.NewSystemService(db, svcs.Docker, svcs.Container, svcs.Image, svcs.Volume, svcs.Network, svcs.Settings, svcs.Activity)- svcs.SystemUpgrade = services.NewSystemUpgradeService(svcs.Docker, svcs.Version, svcs.Event, svcs.Settings)- svcs.Updater = services.NewUpdaterService(db, svcs.Settings, svcs.Docker, svcs.Project, svcs.ImageUpdate, svcs.ContainerRegistry, svcs.Event, svcs.Image, svcs.Notification, svcs.SystemUpgrade, svcs.Activity)- svcs.GitOpsSync = services.NewGitOpsSyncService(db, svcs.GitRepository, svcs.Project, svcs.Swarm, svcs.Event, svcs.Settings)- svcs.Webhook = services.NewWebhookService(db, svcs.Container, svcs.Updater, svcs.Project, svcs.GitOpsSync, svcs.Event)-- return svcs, dockerClient, nil-}diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.gonew file mode 100644index 000000000..755f3adec--- /dev/null+++ b/backend/internal/di/providers.go@@ -0,0 +1,183 @@+// 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 di++import (+ "context"+ "embed"+ "log/slog"+ "net/http"++ "github.com/getarcaneapp/arcane/backend/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/database"+ "github.com/getarcaneapp/arcane/backend/internal/middleware"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ pkg_scheduler "github.com/getarcaneapp/arcane/backend/pkg/scheduler"+ "github.com/getarcaneapp/arcane/backend/resources"+)++// 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+ 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+ // 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.++// 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) *services.VersionService {+ return services.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, registry, docker)+}++// 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)+}++// 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)+ }, kv)+}++// 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).+ WithEnvironmentAccessTokenResolver(env).+ 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 *pkg_scheduler.AutoUpdateJob+ ImagePolling *pkg_scheduler.ImagePollingJob+ EnvironmentHealth *pkg_scheduler.EnvironmentHealthJob+ DockerClientRefresh *pkg_scheduler.DockerClientRefreshJob+ Analytics *pkg_scheduler.AnalyticsJob+ EventCleanup *pkg_scheduler.EventCleanupJob+ PruningVolumeHelper *pkg_scheduler.PruningVolumeHelperJob+ ExpiredSessionsCleanup *pkg_scheduler.ExpiredSessionsCleanupJob+ ScheduledPrune *pkg_scheduler.ScheduledPruneJob+ FilesystemWatcher *pkg_scheduler.FilesystemWatcherJob+ GitOpsSync *pkg_scheduler.GitOpsSyncJob+ VulnerabilityScan *pkg_scheduler.VulnerabilityScanJob+ AutoHeal *pkg_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) *pkg_scheduler.AnalyticsJob {+ return pkg_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) *pkg_scheduler.FilesystemWatcherJob {+ job, err := pkg_scheduler.RegisterFilesystemWatcherJob(ctx, project, template, settings, cfg.ProjectScanMaxDepth)+ if err != nil {+ slog.ErrorContext(ctx, "Failed to register filesystem watcher job", "error", err)+ }+ return job+}diff --git a/backend/internal/di/wire.go b/backend/internal/di/wire.gonew file mode 100644index 000000000..301e47ea6--- /dev/null+++ b/backend/internal/di/wire.go@@ -0,0 +1,116 @@+//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/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/database"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ pkg_scheduler "github.com/getarcaneapp/arcane/backend/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.NewProjectService,+ 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 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", "GitOpsSync", "Vulnerability", "Volume",+ ),+ pkg_scheduler.NewAutoUpdateJob,+ pkg_scheduler.NewImagePollingJob,+ pkg_scheduler.NewEnvironmentHealthJob,+ pkg_scheduler.NewDockerClientRefreshJob,+ provideAnalyticsJobInternal,+ pkg_scheduler.NewEventCleanupJob,+ pkg_scheduler.NewPruningVolumeHelperJob,+ pkg_scheduler.NewExpiredSessionsCleanupJob,+ pkg_scheduler.NewScheduledPruneJob,+ provideFilesystemWatcherJobInternal,+ pkg_scheduler.NewGitOpsSyncJob,+ pkg_scheduler.NewVulnerabilityScanJob,+ pkg_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.gonew file mode 100644index 000000000..5dbcc0397--- /dev/null+++ b/backend/internal/di/wire_gen.go@@ -0,0 +1,194 @@+// 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/internal/config"+ "github.com/getarcaneapp/arcane/backend/internal/database"+ "github.com/getarcaneapp/arcane/backend/internal/services"+ "github.com/getarcaneapp/arcane/backend/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)+ activityService := services.NewActivityService(db)+ 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)+ projectService := services.NewProjectService(db, settingsService, eventService, imageService, dockerClientService, buildService, 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)+ systemUpgradeService := services.NewSystemUpgradeService(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)+ dashboardService := services.NewDashboardService(db, dockerClientService, containerService, projectService, imageService, settingsService, vulnerabilityService, environmentService, versionService)+ 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,+ 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,+ 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+ imagePollingJob := scheduler.NewImagePollingJob(imageUpdateService, settingsService, environmentService)+ environmentHealthJob := scheduler.NewEnvironmentHealthJob(environmentService, settingsService)+ dockerClientService := svcs.Docker+ 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)+ projectService := svcs.Project+ templateService := svcs.Template+ filesystemWatcherJob := provideFilesystemWatcherJobInternal(ctx, projectService, templateService, settingsService, cfg)+ gitOpsSyncService := svcs.GitOpsSync+ gitOpsSyncJob := scheduler.NewGitOpsSyncJob(gitOpsSyncService, settingsService)+ vulnerabilityService := svcs.Vulnerability+ vulnerabilityScanJob := scheduler.NewVulnerabilityScanJob(vulnerabilityService, settingsService)+ autoHealJob := scheduler.NewAutoHealJob(dockerClientService, settingsService, eventService, notificationService)+ jobs := &Jobs{+ AutoUpdate: autoUpdateJob,+ ImagePolling: imagePollingJob,+ EnvironmentHealth: environmentHealthJob,+ DockerClientRefresh: dockerClientRefreshJob,+ Analytics: analyticsJob,+ EventCleanup: eventCleanupJob,+ PruningVolumeHelper: pruningVolumeHelperJob,+ ExpiredSessionsCleanup: expiredSessionsCleanupJob,+ ScheduledPrune: scheduledPruneJob,+ FilesystemWatcher: filesystemWatcherJob,+ GitOpsSync: gitOpsSyncJob,+ 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.NewProjectService, services.NewContainerService, services.NewDashboardService, services.NewNetworkService, services.NewPortService, services.NewSwarmService, services.NewTemplateService, services.NewOidcService, services.NewSystemService, services.NewSystemUpgradeService, services.NewDiagnosticsService, services.NewGitOpsSyncService, services.NewWebhookService, 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", "GitOpsSync", "Vulnerability", "Volume",+), scheduler.NewAutoUpdateJob, scheduler.NewImagePollingJob, scheduler.NewEnvironmentHealthJob, scheduler.NewDockerClientRefreshJob, provideAnalyticsJobInternal, scheduler.NewEventCleanupJob, scheduler.NewPruningVolumeHelperJob, scheduler.NewExpiredSessionsCleanupJob, scheduler.NewScheduledPruneJob, provideFilesystemWatcherJobInternal, scheduler.NewGitOpsSyncJob, scheduler.NewVulnerabilityScanJob, scheduler.NewAutoHealJob, wire.Struct(new(Jobs), "*"),+)diff --git a/backend/internal/services/diagnostics_service.go b/backend/internal/services/diagnostics_service.gonew file mode 100644index 000000000..63a784f08--- /dev/null+++ b/backend/internal/services/diagnostics_service.go@@ -0,0 +1,85 @@+package services++import (+ "runtime"+ "runtime/debug"+ "time"++ "github.com/getarcaneapp/arcane/types/system"+)++// recentGCPauseSamples is the number of recent GC pause durations reported.+const recentGCPauseSamples = 16++// DiagnosticsService gathers Go runtime, memory, and garbage-collector+// statistics for the diagnostics endpoints. It holds no external dependencies;+// WebSocket metrics and worker-goroutine counts are merged in at the handler+// layer to avoid an import cycle with the api/ws package.+type DiagnosticsService struct {+ startedAt time.Time+}++// NewDiagnosticsService returns a DiagnosticsService. startedAt is captured at+// construction (≈ process start) and used to report uptime.+func NewDiagnosticsService() *DiagnosticsService {+ return &DiagnosticsService{startedAt: time.Now()}+}++// Collect samples the current runtime, memory, and GC state.+func (s *DiagnosticsService) Collect() (system.RuntimeInfo, system.MemoryInfo, system.GCInfo) {+ var mem runtime.MemStats+ runtime.ReadMemStats(&mem)++ var gc debug.GCStats+ debug.ReadGCStats(&gc)++ rt := system.RuntimeInfo{+ Goroutines: runtime.NumGoroutine(),+ GOMAXPROCS: runtime.GOMAXPROCS(0),+ NumCPU: runtime.NumCPU(),+ GoVersion: runtime.Version(),+ OS: runtime.GOOS,+ Arch: runtime.GOARCH,+ NumCgoCall: runtime.NumCgoCall(),+ UptimeSeconds: int64(time.Since(s.startedAt).Seconds()),+ }++ mi := system.MemoryInfo{+ Alloc: mem.Alloc,+ TotalAlloc: mem.TotalAlloc,+ Sys: mem.Sys,+ HeapAlloc: mem.HeapAlloc,+ HeapSys: mem.HeapSys,+ HeapInuse: mem.HeapInuse,+ HeapIdle: mem.HeapIdle,+ HeapReleased: mem.HeapReleased,+ HeapObjects: mem.HeapObjects,+ StackInuse: mem.StackInuse,+ StackSys: mem.StackSys,+ MSpanInuse: mem.MSpanInuse,+ MCacheInuse: mem.MCacheInuse,+ NextGC: mem.NextGC,+ NumGC: mem.NumGC,+ NumForcedGC: mem.NumForcedGC,+ GCCPUFraction: mem.GCCPUFraction,+ }++ // gc.Pause is ordered most-recent-first; cap the slice we expose.+ pauses := gc.Pause+ if len(pauses) > recentGCPauseSamples {+ pauses = pauses[:recentGCPauseSamples]+ }+ recent := make([]int64, len(pauses))+ for i, p := range pauses {+ recent[i] = p.Nanoseconds()+ }++ gi := system.GCInfo{+ LastGC: gc.LastGC,+ NumGC: gc.NumGC,+ PauseTotalNs: gc.PauseTotal.Nanoseconds(),+ RecentPausesNs: recent,+ }++ return rt, mi, gi+}diff --git a/backend/internal/services/diagnostics_service_test.go b/backend/internal/services/diagnostics_service_test.gonew file mode 100644index 000000000..370870209--- /dev/null+++ b/backend/internal/services/diagnostics_service_test.go@@ -0,0 +1,22 @@+package services++import "testing"++func TestDiagnosticsServiceCollect(t *testing.T) {+ s := NewDiagnosticsService()++ rt, mem, _ := s.Collect()++ if rt.Goroutines <= 0 {+ t.Errorf("expected a positive goroutine count, got %d", rt.Goroutines)+ }+ if rt.GoVersion == "" {+ t.Error("expected a non-empty Go version")+ }+ if rt.NumCPU <= 0 {+ t.Errorf("expected a positive CPU count, got %d", rt.NumCPU)+ }+ if mem.Sys == 0 {+ t.Error("expected non-zero Sys memory")+ }+}diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.goindex fd75a75f5..4cc340153 100644--- a/backend/pkg/authz/catalog.go+++ b/backend/pkg/authz/catalog.go@@ -92,6 +92,9 @@ var permissionCatalog = []PermissionCatalogResource{{"customize", "Customize", PermissionScopeGlobal, []PermissionCatalogAction{{"manage", PermCustomizeManage, "Manage", ""},}},+ {"diagnostics", "Diagnostics", PermissionScopeGlobal, []PermissionCatalogAction{+ {"read", PermDiagnosticsRead, "View", "View runtime diagnostics, pprof profiles, and backend logs"},+ }},{"containers", "Containers", PermissionScopeEnv, []PermissionCatalogAction{{"list", PermContainersList, "List", ""},{"read", PermContainersRead, "Read", ""},diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.goindex cd45b8c55..0e5c3b00a 100644--- a/backend/pkg/authz/permissions.go+++ b/backend/pkg/authz/permissions.go@@ -79,6 +79,11 @@ const (PermEventsRead = "events:read"PermCustomizeManage = "customize:manage"++ // PermDiagnosticsRead gates the admin-only runtime diagnostics surface+ // (runtime/memory/GC stats, WebSocket metrics, pprof profiles, and the live+ // backend log tail). Global-scoped; seeded only into the Admin role.+ PermDiagnosticsRead = "diagnostics:read")// Env-scoped permissions (resolved against the {id} env ID in the path).diff --git a/backend/pkg/libarcane/logstream/logstream.go b/backend/pkg/libarcane/logstream/logstream.gonew file mode 100644index 000000000..1487ec631--- /dev/null+++ b/backend/pkg/libarcane/logstream/logstream.go@@ -0,0 +1,152 @@+// Package logstream captures the application's own slog output into a bounded+// in-memory ring buffer and fans it out to live subscribers. It backs the+// diagnostics endpoints' "recent logs" backlog and the live backend-log+// WebSocket stream. It deliberately depends only on the shared types package so+// both bootstrap (which installs the slog handler) and the API handlers (which+// read it) can use it without an import cycle.+package logstream++import (+ "context"+ "log/slog"+ "sync"++ "github.com/getarcaneapp/arcane/types/system"+)++// defaultRingCapacity is the number of recent log entries retained in memory.+const defaultRingCapacity = 1000++// subscriberBuffer is the per-subscriber channel buffer. Slow consumers have+// entries dropped rather than blocking the logger.+const subscriberBuffer = 256++// Entry is a single captured log record.+type Entry = system.LogEntry++// Broadcaster keeps a bounded ring buffer of recent log entries and fans new+// entries out to any active subscribers. It is safe for concurrent use.+type Broadcaster struct {+ mu sync.Mutex+ buf []Entry+ start int+ size int+ capN int+ subs map[chan Entry]struct{}+}++// New returns a Broadcaster retaining up to capacity recent entries.+func New(capacity int) *Broadcaster {+ if capacity <= 0 {+ capacity = defaultRingCapacity+ }+ return &Broadcaster{+ buf: make([]Entry, capacity),+ capN: capacity,+ subs: make(map[chan Entry]struct{}),+ }+}++// Append records an entry in the ring buffer and delivers it to subscribers.+// Delivery is non-blocking; a subscriber whose buffer is full drops the entry.+func (b *Broadcaster) Append(e Entry) {+ b.mu.Lock()+ defer b.mu.Unlock()++ if b.size < b.capN {+ b.buf[(b.start+b.size)%b.capN] = e+ b.size+++ } else {+ b.buf[b.start] = e+ b.start = (b.start + 1) % b.capN+ }++ // Non-blocking sends under the lock: cancel() also takes the lock before+ // closing a subscriber channel, so we never send on a closed channel.+ for ch := range b.subs {+ select {+ case ch <- e:+ default:+ }+ }+}++// Recent returns the buffered entries in chronological order (oldest first).+func (b *Broadcaster) Recent() []Entry {+ b.mu.Lock()+ defer b.mu.Unlock()++ out := make([]Entry, b.size)+ for i := range b.size {+ out[i] = b.buf[(b.start+i)%b.capN]+ }+ return out+}++// Subscribe registers a new live subscriber. It returns a receive-only channel+// of subsequent entries and a cancel func that unsubscribes and closes the+// channel. cancel is idempotent.+func (b *Broadcaster) Subscribe() (<-chan Entry, func()) {+ ch := make(chan Entry, subscriberBuffer)+ b.mu.Lock()+ b.subs[ch] = struct{}{}+ b.mu.Unlock()++ var once sync.Once+ cancel := func() {+ once.Do(func() {+ b.mu.Lock()+ delete(b.subs, ch)+ close(ch)+ b.mu.Unlock()+ })+ }+ return ch, cancel+}++var defaultBroadcaster = New(defaultRingCapacity)++// Default returns the package-level Broadcaster singleton.+func Default() *Broadcaster { return defaultBroadcaster }++// slogHandler wraps a base slog.Handler, forwarding every record to it while+// also appending it to a Broadcaster.+type slogHandler struct {+ base slog.Handler+ b *Broadcaster+}++// NewSlogHandler returns a slog.Handler that tees records to base and to b.+func NewSlogHandler(base slog.Handler, b *Broadcaster) slog.Handler {+ return &slogHandler{base: base, b: b}+}++func (h *slogHandler) Enabled(ctx context.Context, level slog.Level) bool {+ return h.base.Enabled(ctx, level)+}++func (h *slogHandler) Handle(ctx context.Context, r slog.Record) error {+ var attrs map[string]any+ if r.NumAttrs() > 0 {+ attrs = make(map[string]any, r.NumAttrs())+ r.Attrs(func(a slog.Attr) bool {+ attrs[a.Key] = a.Value.Any()+ return true+ })+ }+ h.b.Append(Entry{+ Time: r.Time,+ Level: r.Level.String(),+ Message: r.Message,+ Attrs: attrs,+ })+ return h.base.Handle(ctx, r)+}++func (h *slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {+ return &slogHandler{base: h.base.WithAttrs(attrs), b: h.b}+}++func (h *slogHandler) WithGroup(name string) slog.Handler {+ return &slogHandler{base: h.base.WithGroup(name), b: h.b}+}diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 958d44b93..2b11fe281 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -3024,6 +3024,97 @@"rbac_migration_banner_title": "Welcome to RBAC","rbac_migration_banner_body": "Your access was migrated to Viewer on all environments. Admins can promote users from Settings → Users.","rbac_migration_banner_dismiss": "Dismiss",+ "_comment_diagnostics": "=== DIAGNOSTICS ===",+ "diagnostics_title": "Diagnostics",+ "diagnostics_description": "Live Go runtime, profiling, and backend logs.",+ "diagnostics_status_live": "Live",+ "diagnostics_status_paused": "Paused",+ "diagnostics_status_connecting": "Connecting…",+ "diagnostics_updated_ago": "updated {ago}",+ "diagnostics_just_now": "just now",+ "diagnostics_seconds_ago": "{seconds}s ago",+ "diagnostics_pause": "Pause",+ "diagnostics_resume": "Resume",+ "diagnostics_refresh": "Refresh",+ "diagnostics_loading": "Loading diagnostics…",+ "diagnostics_error_load": "Failed to load diagnostics",+ "diagnostics_error_download": "Download failed",+ "diagnostics_error_dump": "Failed to load dump",+ "diagnostics_stat_goroutines": "Goroutines",+ "diagnostics_stat_heap_alloc": "Heap Alloc",+ "diagnostics_stat_ws_conns": "WS Conns",+ "diagnostics_stat_gc_cycles": "GC Cycles",+ "diagnostics_stat_cpu_procs": "CPU / Procs",+ "diagnostics_stat_uptime": "Uptime",+ "diagnostics_section_runtime": "Runtime",+ "diagnostics_runtime_go_version": "Go version",+ "diagnostics_runtime_platform": "Platform",+ "diagnostics_runtime_gomaxprocs": "GOMAXPROCS",+ "diagnostics_runtime_num_cpu": "Logical CPUs",+ "diagnostics_runtime_goroutines": "Goroutines",+ "diagnostics_runtime_ws_workers": "WS worker goroutines",+ "diagnostics_runtime_cgo_calls": "Cgo calls",+ "diagnostics_runtime_uptime": "Uptime",+ "diagnostics_section_memory": "Memory / Heap",+ "diagnostics_mem_in_use": "In use",+ "diagnostics_mem_idle": "Idle",+ "diagnostics_mem_released": "Released",+ "diagnostics_mem_heap_alloc": "Heap alloc",+ "diagnostics_mem_heap_sys": "Heap sys",+ "diagnostics_mem_heap_objects": "Heap objects",+ "diagnostics_mem_stack_in_use": "Stack in use",+ "diagnostics_mem_total_alloc": "Total alloc (cumulative)",+ "diagnostics_mem_sys_total": "Sys (total)",+ "diagnostics_mem_next_gc": "Next GC target",+ "diagnostics_mem_gc_cpu_fraction": "GC CPU fraction",+ "diagnostics_section_gc": "Garbage Collector",+ "diagnostics_gc_total_cycles": "Total cycles",+ "diagnostics_gc_forced_cycles": "Forced cycles",+ "diagnostics_gc_total_pause": "Total pause",+ "diagnostics_gc_last": "Last GC",+ "diagnostics_gc_recent_pauses": "Recent pauses (newest left)",+ "diagnostics_section_websocket": "WebSocket Connections",+ "diagnostics_ws_project_logs": "Project logs",+ "diagnostics_ws_container_logs": "Container logs",+ "diagnostics_ws_container_stats": "Container stats",+ "diagnostics_ws_terminals": "Terminals",+ "diagnostics_ws_system_stats": "System stats",+ "diagnostics_ws_service_logs": "Service logs",+ "diagnostics_ws_kind_terminal": "Terminal",+ "diagnostics_section_connections": "Active Connections ({count})",+ "diagnostics_conn_kind": "Kind",+ "diagnostics_conn_resource": "Resource",+ "diagnostics_conn_client_ip": "Client IP",+ "diagnostics_conn_user": "User",+ "diagnostics_conn_since": "Since",+ "diagnostics_section_logs": "Live Backend Logs",+ "diagnostics_logs_streaming": "Streaming",+ "diagnostics_logs_disconnected": "Disconnected",+ "diagnostics_logs_count": "{count} lines",+ "diagnostics_logs_all_levels": "All levels",+ "diagnostics_logs_level_error": "Error",+ "diagnostics_logs_level_warn": "Warn",+ "diagnostics_logs_level_info": "Info",+ "diagnostics_logs_level_debug": "Debug",+ "diagnostics_logs_filter_placeholder": "Filter…",+ "diagnostics_logs_auto_scroll": "Auto-scroll",+ "diagnostics_logs_clear": "Clear",+ "diagnostics_logs_empty": "No log entries.",+ "diagnostics_section_dumps": "Inline Dumps",+ "diagnostics_dump_goroutine": "Goroutine stacks",+ "diagnostics_dump_heap": "Heap profile",+ "diagnostics_dump_loading": "Loading…",+ "diagnostics_dump_empty": "No data.",+ "diagnostics_section_profiles": "Download pprof Profiles",+ "diagnostics_profiles_hint": "Open the downloaded files with go tool pprof / go tool trace.",+ "diagnostics_profile_heap": "Heap",+ "diagnostics_profile_goroutine": "Goroutine",+ "diagnostics_profile_allocs": "Allocs",+ "diagnostics_profile_block": "Block",+ "diagnostics_profile_mutex": "Mutex",+ "diagnostics_profile_threadcreate": "Threads",+ "diagnostics_profile_cpu": "CPU (30s)",+ "diagnostics_profile_trace": "Trace (5s)","_comment_no_access": "=== NO ACCESS PAGE ===","no_access_page_title": "You don't have access to anything yet","no_access_page_body": "Your Arcane administrator hasn't assigned you any role permissions. Ask them to add a role to your account from Settings → Users."diff --git a/frontend/project.inlang/cache/plugins/2sy648wh9sugi b/frontend/project.inlang/cache/plugins/2sy648wh9sugiindex 1f9c4e487..3c313baea 100644--- a/frontend/project.inlang/cache/plugins/2sy648wh9sugi+++ b/frontend/project.inlang/cache/plugins/2sy648wh9sugi@@ -2008,28 +2008,34 @@ function parsePattern2(value) {continue;}if (char === "{") {- let variableName = "";- let closingIndex = -1;- for (let cursor = index + 1; cursor < value.length; cursor += 1) {- const current = value[cursor];- if (current === "}") {- closingIndex = cursor;- break;- }- variableName += current;- }+ const closingIndex = findPlaceholderClosingIndex(value, index);if (closingIndex === -1) {buffer += char;continue;}+ const placeholder = value.slice(index + 1, closingIndex);+ const markupNode = parseMarkupPlaceholder(placeholder);flushBuffer();+ if (markupNode) {+ for (const option of markupNode.options ?? []) {+ if (option.value.type === "variable-reference") {+ declarations.push({+ type: "input-variable",+ name: option.value.name+ });+ }+ }+ pattern.push(markupNode);+ index = closingIndex;+ continue;+ }declarations.push({type: "input-variable",- name: variableName+ name: placeholder});pattern.push({type: "expression",- arg: { type: "variable-reference", name: variableName }+ arg: { type: "variable-reference", name: placeholder }});index = closingIndex;continue;@@ -2042,6 +2048,176 @@ function parsePattern2(value) {pattern};}+function findPlaceholderClosingIndex(value, openingIndex) {+ let inQuotedLiteral = false;+ for (let cursor = openingIndex + 1; cursor < value.length; cursor += 1) {+ const current = value[cursor];+ if (inQuotedLiteral && current === "\\") {+ cursor += 1;+ continue;+ }+ if (current === "|") {+ inQuotedLiteral = !inQuotedLiteral;+ continue;+ }+ if (current === "}" && inQuotedLiteral === false) {+ return cursor;+ }+ }+ return -1;+}+function parseMarkupPlaceholder(placeholder) {+ if (placeholder.startsWith("#")) {+ const parsed = parseMarkupBody(placeholder.slice(1), true);+ if (!parsed) {+ throw new Error(`Invalid markup placeholder: {${placeholder}}`);+ }+ const { name, options, attributes, standalone } = parsed;+ return {+ type: standalone ? "markup-standalone" : "markup-start",+ name,+ ...options.length > 0 ? { options } : {},+ ...attributes.length > 0 ? { attributes } : {}+ };+ }+ if (placeholder.startsWith("/")) {+ const parsed = parseMarkupBody(placeholder.slice(1), false);+ if (!parsed) {+ throw new Error(`Invalid markup placeholder: {${placeholder}}`);+ }+ const { name, options, attributes } = parsed;+ return {+ type: "markup-end",+ name,+ ...options.length > 0 ? { options } : {},+ ...attributes.length > 0 ? { attributes } : {}+ };+ }+ return void 0;+}+function parseMarkupBody(body, allowStandalone) {+ let index = 0;+ const options = [];+ const attributes = [];+ let standalone = false;+ index = skipWhitespace(body, index);+ const nameToken = readNameToken(body, index);+ if (!nameToken) return void 0;+ const name = nameToken.value;+ index = nameToken.nextIndex;+ while (index < body.length) {+ index = skipWhitespace(body, index);+ if (index >= body.length) break;+ if (allowStandalone && body[index] === "/") {+ const trailing = body.slice(index + 1).trim();+ if (trailing.length > 0) return void 0;+ standalone = true;+ index = body.length;+ break;+ }+ if (body[index] === "@") {+ index += 1;+ const attributeName = readIdentifier(body, index);+ if (!attributeName) return void 0;+ index = attributeName.nextIndex;+ index = skipWhitespace(body, index);+ if (body[index] === "=") {+ index += 1;+ index = skipWhitespace(body, index);+ const attributeValue = parseMarkupValue(body, index);+ if (!attributeValue) return void 0;+ if (attributeValue.value.type === "variable-reference") {+ return void 0;+ }+ attributes.push({+ name: attributeName.value,+ value: attributeValue.value+ });+ index = attributeValue.nextIndex;+ } else {+ attributes.push({ name: attributeName.value, value: true });+ }+ continue;+ }+ const optionName = readIdentifier(body, index);+ if (!optionName) return void 0;+ index = optionName.nextIndex;+ index = skipWhitespace(body, index);+ if (body[index] !== "=") return void 0;+ index += 1;+ index = skipWhitespace(body, index);+ const optionValue = parseMarkupValue(body, index);+ if (!optionValue) return void 0;+ options.push({+ name: optionName.value,+ value: optionValue.value+ });+ index = optionValue.nextIndex;+ }+ return { name, options, attributes, standalone };+}+function skipWhitespace(value, index) {+ while (index < value.length && /\s/.test(value[index])) {+ index += 1;+ }+ return index;+}+function readNameToken(value, index) {+ return readIdentifier(value, index);+}+function readIdentifier(value, index) {+ let cursor = index;+ while (cursor < value.length && /\s/.test(value[cursor]) === false && value[cursor] !== "=" && value[cursor] !== "/" && value[cursor] !== "@") {+ cursor += 1;+ }+ const parsed = value.slice(index, cursor);+ if (parsed.length === 0) return void 0;+ return { value: parsed, nextIndex: cursor };+}+function parseMarkupValue(value, index) {+ if (index >= value.length) return void 0;+ if (value[index] === "|") {+ let cursor = index + 1;+ let literal2 = "";+ while (cursor < value.length) {+ const char = value[cursor];+ if (char === "\\") {+ const next = value[cursor + 1];+ if (next === "|" || next === "\\" || next === "}") {+ literal2 += next;+ cursor += 2;+ continue;+ }+ literal2 += char;+ cursor += 1;+ continue;+ }+ if (char === "|") {+ return {+ value: { type: "literal", value: literal2 },+ nextIndex: cursor + 1+ };+ }+ literal2 += char;+ cursor += 1;+ }+ return void 0;+ }+ if (value[index] === "$") {+ const variable = readIdentifier(value, index + 1);+ if (!variable) return void 0;+ return {+ value: { type: "variable-reference", name: variable.value },+ nextIndex: variable.nextIndex+ };+ }+ const literal = readIdentifier(value, index);+ if (!literal) return void 0;+ return {+ value: { type: "literal", value: literal.value },+ nextIndex: literal.nextIndex+ };+}function parseMatches(value) {const stripped = value.replace(" ", "");const matches = [];@@ -2083,13 +2259,26 @@ function parseDeclaration(value) {} else if (value.startsWith("local")) {const match = value.match(/local (\w+) = (\w+): (\w+)(.*)/);const [, name, ref, fn, optionsString] = match;- const options = optionsString?.trim().split(/\s+/).map((pair) => {- const [key, value2] = pair.split("=");- return key && value2 ? {- name: key,- value: { type: "literal", value: value2 }- } : null;- }).filter(Boolean);+ const options = [];+ for (const optionMatch of (optionsString ?? "").matchAll(+ /(\w+)\s*=\s*([^\s]+)/g+ )) {+ const optionName = optionMatch[1];+ const optionValue = optionMatch[2];+ if (!optionName || !optionValue) {+ continue;+ }+ options.push({+ name: optionName,+ value: optionValue.startsWith("$") && optionValue.length > 1 ? {+ type: "variable-reference",+ name: optionValue.slice(1)+ } : {+ type: "literal",+ value: optionValue+ }+ });+ }return {type: "local-variable",name: name.trim(),@@ -2219,12 +2408,45 @@ function serializeVariants(bundle, message, variants) {function serializePattern(pattern) {let result = "";for (const part of pattern) {- if (part.type === "text") {- result += escapePatternText(part.value);- } else if (part.arg.type === "variable-reference") {- result += `{${part.arg.name}}`;- } else {- throw new Error("Unsupported expression type");+ switch (part.type) {+ case "text":+ result += escapePatternText(part.value);+ break;+ case "expression":+ if (part.arg.type === "variable-reference") {+ result += `{${part.arg.name}}`;+ break;+ }+ throw new Error("Unsupported expression type");+ case "markup-start":+ result += serializeMarkup(+ "#",+ part.name,+ part.options,+ part.attributes,+ false+ );+ break;+ case "markup-end":+ result += serializeMarkup(+ "/",+ part.name,+ part.options,+ part.attributes,+ false+ );+ break;+ case "markup-standalone":+ result += serializeMarkup(+ "#",+ part.name,+ part.options,+ part.attributes,+ true+ );+ break;+ default:+ throw new Error("Unsupported pattern element type");}}return result;@@ -2232,6 +2454,31 @@ function serializePattern(pattern) {function escapePatternText(value) {return value.replace(/\\/g, "\\\\").replace(/{/g, "\\{").replace(/}/g, "\\}");}+function serializeMarkup(prefix, name, options, attributes, standalone) {+ const serializedOptions = (options ?? []).map((option) => {+ if (option.value.type === "variable-reference") {+ return `${option.name}=$${option.value.name}`;+ }+ return `${option.name}=|${escapeMarkupLiteral(option.value.value)}|`;+ });+ const serializedAttributes = (attributes ?? []).map((attribute) => {+ if (attribute.value === true) {+ return `@${attribute.name}`;+ }+ return `@${attribute.name}=|${escapeMarkupLiteral(attribute.value.value)}|`;+ });+ const metadata = [...serializedOptions, ...serializedAttributes].join(" ");+ if (metadata.length === 0) {+ return standalone ? `{${prefix}${name}/}` : `{${prefix}${name}}`;+ }+ if (standalone) {+ return `{${prefix}${name} ${metadata}/}`;+ }+ return `{${prefix}${name} ${metadata}}`;+}+function escapeMarkupLiteral(value) {+ return value.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/}/g, "\\}");+}function serializeMatcher(matches) {const parts = matches.sort((a, b) => a.key.localeCompare(b.key)).map((match) => match.type === "literal-match" ? `${match.key}=${match.value}` : `${match.key}=*`@@ -2253,10 +2500,15 @@ function serializeDeclaration(declaration) {}if (declaration.value.annotation?.options) {for (const option of declaration.value?.annotation?.options ?? []) {- if (option.value.type !== "literal") {- throw new Error("Unsupported option type");+ if (option.value.type === "literal") {+ result += ` ${option.name}=${option.value.value}`;+ continue;+ }+ if (option.value.type === "variable-reference") {+ result += ` ${option.name}=$${option.value.name}`;+ continue;}- result += ` ${option.name}=${option.value.value}`;+ throw new Error("Unsupported option type");}}return result;diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.tsindex f2bf2478a..7b9d8e620 100644--- a/frontend/src/lib/config/navigation-config.ts+++ b/frontend/src/lib/config/navigation-config.ts@@ -296,6 +296,13 @@ export const navigationItems: NavigationSections = {icon: ShieldAlertIcon,scope: 'global',requiredPermission: ['roles:read', 'roles:list']+ },+ {+ title: m.diagnostics_title(),+ url: '/settings/diagnostics',+ icon: ActivityIcon,+ scope: 'global',+ requiredPermission: 'diagnostics:read'}]}diff --git a/frontend/src/lib/services/diagnostics-service.ts b/frontend/src/lib/services/diagnostics-service.tsnew file mode 100644index 000000000..81f05306c--- /dev/null+++ b/frontend/src/lib/services/diagnostics-service.ts@@ -0,0 +1,57 @@+import BaseAPIService from './api-service';+import type { Diagnostics, LogEntry, PprofProfile } from '$lib/types/diagnostics';++export default class DiagnosticsAPIService extends BaseAPIService {+ /** One-shot runtime/memory/GC + WebSocket snapshot (used for initial paint). */+ async getDiagnostics(): Promise<Diagnostics> {+ const res = await this.api.get('/diagnostics');+ return res.data as Diagnostics;+ }++ /** Recent buffered backend log entries (oldest first). */+ async getRecentLogs(): Promise<LogEntry[]> {+ const res = await this.api.get('/diagnostics/logs');+ return (res.data ?? []) as LogEntry[];+ }++ /** Fetch a human-readable pprof dump (debug=2 text) for inline display. */+ async getDump(name: 'goroutine' | 'heap'): Promise<string> {+ const res = await this.api.get(`/debug/pprof/${name}`, {+ params: { debug: 2 },+ responseType: 'text'+ });+ return (res.data ?? '') as string;+ }++ /**+ * Download a raw pprof profile via the authed client (so bearer/API-key auth+ * is attached) and trigger a browser save. `profile` and `trace` are+ * time-sampled; pass an optional duration in seconds.+ */+ async downloadProfile(profile: PprofProfile, seconds?: number): Promise<void> {+ const params: Record<string, number> = {};+ if (profile === 'profile') params['seconds'] = seconds ?? 30;+ if (profile === 'trace') params['seconds'] = seconds ?? 5;++ const defaultSeconds = profile === 'trace' ? 5 : 30;+ const res = await this.api.get(`/debug/pprof/${profile}`, {+ params,+ responseType: 'blob',+ // Sampled profiles block for their full duration.+ timeout: profile === 'profile' || profile === 'trace' ? (seconds ?? defaultSeconds) * 1000 + 15000 : undefined+ });++ const blob = res.data as Blob;+ const url = URL.createObjectURL(blob);+ const ext = profile === 'trace' ? 'out' : 'pprof';+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = `${profile}.${ext}`;+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ URL.revokeObjectURL(url);+ }+}++export const diagnosticsService = new DiagnosticsAPIService();diff --git a/frontend/src/lib/types/diagnostics.ts b/frontend/src/lib/types/diagnostics.tsnew file mode 100644index 000000000..e7ba07f7e--- /dev/null+++ b/frontend/src/lib/types/diagnostics.ts@@ -0,0 +1,82 @@+// Mirrors backend/types/system/diagnostics.go (camelCase JSON keys).++export interface RuntimeInfo {+ goroutines: number;+ wsWorkerGoroutines: number;+ gomaxprocs: number;+ numCpu: number;+ goVersion: string;+ os: string;+ arch: string;+ numCgoCall: number;+ uptimeSeconds: number;+}++export interface MemoryInfo {+ alloc: number;+ totalAlloc: number;+ sys: number;+ heapAlloc: number;+ heapSys: number;+ heapInuse: number;+ heapIdle: number;+ heapReleased: number;+ heapObjects: number;+ stackInuse: number;+ stackSys: number;+ mspanInuse: number;+ mcacheInuse: number;+ nextGc: number;+ numGc: number;+ numForcedGc: number;+ gcCpuFraction: number;+}++export interface GCInfo {+ lastGc: string;+ numGc: number;+ pauseTotalNs: number;+ recentPausesNs: number[];+}++export interface WebSocketConnectionInfo {+ id: string;+ kind: string;+ envId?: string;+ resourceId?: string;+ clientIp?: string;+ userId?: string;+ userAgent?: string;+ startedAt: string;+}++export interface WebSocketMetricsSnapshot {+ projectLogsActive: number;+ containerLogsActive: number;+ containerStats: number;+ containerExec: number;+ systemStats: number;+ serviceLogsActive: number;+}++export interface WebSocketDiagnostics {+ snapshot: WebSocketMetricsSnapshot;+ connections: WebSocketConnectionInfo[];+}++export interface Diagnostics {+ timestamp: string;+ runtime: RuntimeInfo;+ memory: MemoryInfo;+ gc: GCInfo;+ websocket: WebSocketDiagnostics;+}++export interface LogEntry {+ time: string;+ level: string;+ message: string;+ attrs?: Record<string, unknown>;+}++export type PprofProfile = 'heap' | 'goroutine' | 'allocs' | 'block' | 'mutex' | 'threadcreate' | 'profile' | 'trace';diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.tsindex c6cef99f4..17937d5f5 100644--- a/frontend/src/lib/utils/ws.ts+++ b/frontend/src/lib/utils/ws.ts@@ -1,4 +1,5 @@import type { SystemStats } from '$lib/types/shared';+import type { Diagnostics, LogEntry } from '$lib/types/diagnostics';export interface ReconnectWSOptions<T> {buildUrl: () => string | Promise<string>;@@ -256,6 +257,52 @@ export function createContainerStatsWebSocket(opts: {});}+export function createDiagnosticsWebSocket(opts: {+ onMessage: (data: Diagnostics) => void;+ onOpen?: () => void;+ onClose?: () => void;+ onError?: (err: Event | Error) => void;+ maxBackoff?: number;+}) {+ const buildUrl = () => {+ const protocol = location.protocol === 'https:' ? 'wss' : 'ws';+ return `${protocol}://${location.host}/api/diagnostics/stream`;+ };++ return new ReconnectingWebSocket<Diagnostics>({+ buildUrl,+ parseMessage: (evt) => JSON.parse(evt.data as string) as Diagnostics,+ onMessage: opts.onMessage,+ onOpen: opts.onOpen,+ onClose: opts.onClose,+ onError: opts.onError,+ maxBackoff: opts.maxBackoff+ });+}++export function createBackendLogsWebSocket(opts: {+ onMessage: (data: LogEntry) => void;+ onOpen?: () => void;+ onClose?: () => void;+ onError?: (err: Event | Error) => void;+ maxBackoff?: number;+}) {+ const buildUrl = () => {+ const protocol = location.protocol === 'https:' ? 'wss' : 'ws';+ return `${protocol}://${location.host}/api/diagnostics/logs/stream`;+ };++ return new ReconnectingWebSocket<LogEntry>({+ buildUrl,+ parseMessage: (evt) => JSON.parse(evt.data as string) as LogEntry,+ onMessage: opts.onMessage,+ onOpen: opts.onOpen,+ onClose: opts.onClose,+ onError: opts.onError,+ maxBackoff: opts.maxBackoff+ });+}+// --- Debounce helper ---export function debounced<T extends (...args: any[]) => void>(func: T, delay: number) {diff --git a/frontend/src/routes/(app)/settings/diagnostics/+page.svelte b/frontend/src/routes/(app)/settings/diagnostics/+page.sveltenew file mode 100644index 000000000..4af8e0ab5--- /dev/null+++ b/frontend/src/routes/(app)/settings/diagnostics/+page.svelte@@ -0,0 +1,480 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { cn } from '$lib/utils';+ import { m } from '$lib/paraglide/messages';+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';+ import * as Collapsible from '$lib/components/ui/collapsible';+ import { createDiagnosticsWebSocket, ReconnectingWebSocket } from '$lib/utils/ws';+ import { diagnosticsService } from '$lib/services/diagnostics-service';+ import type { Diagnostics, PprofProfile } from '$lib/types/diagnostics';+ import {+ ActivityIcon,+ CpuIcon,+ MemoryStickIcon,+ ClockIcon,+ ConnectionIcon,+ RefreshIcon,+ DownloadIcon,+ ArrowDownIcon+ } from '$lib/icons';+ import DiagnosticStat from './diagnostic-stat.svelte';+ import DiagnosticLogPanel from './diagnostic-log-panel.svelte';++ let {}: PageProps = $props();++ let diag = $state<Diagnostics | null>(null);+ let connected = $state(false);+ let paused = $state(false);+ let lastUpdated = $state(0);+ let now = $state(Date.now());+ let error = $state<string | null>(null);++ let ws: ReconnectingWebSocket<Diagnostics> | null = null;+ let tick: ReturnType<typeof setInterval> | null = null;++ const wsKindLabels: Record<string, string> = {+ project_logs: m.diagnostics_ws_project_logs(),+ container_logs: m.diagnostics_ws_container_logs(),+ container_stats: m.diagnostics_ws_container_stats(),+ container_exec: m.diagnostics_ws_kind_terminal(),+ system_stats: m.diagnostics_ws_system_stats(),+ service_logs: m.diagnostics_ws_service_logs()+ };++ function fmtBytes(n: number): string {+ if (!n) return '0 B';+ if (n < 1024) return `${n} B`;+ const units = ['KB', 'MB', 'GB', 'TB'];+ let v = n;+ let i = -1;+ while (v >= 1024 && i < units.length - 1) {+ v /= 1024;+ i++;+ }+ return `${v.toFixed(1)} ${units[i]}`;+ }++ function fmtUptime(s: number): string {+ if (s < 60) return `${s}s`;+ const d = Math.floor(s / 86400);+ const h = Math.floor((s % 86400) / 3600);+ const mins = Math.floor((s % 3600) / 60);+ if (d > 0) return `${d}d ${h}h`;+ if (h > 0) return `${h}h ${mins}m`;+ return `${mins}m ${s % 60}s`;+ }++ function fmtNum(n: number): string {+ return n?.toLocaleString() ?? '0';+ }++ function fmtMs(ns: number): string {+ const ms = ns / 1e6;+ return ms < 1 ? `${(ns / 1e3).toFixed(0)}µs` : `${ms.toFixed(2)}ms`;+ }++ const agoText = $derived.by(() => {+ if (!lastUpdated) return '—';+ const s = Math.max(0, Math.round((now - lastUpdated) / 1000));+ return s <= 1 ? m.diagnostics_just_now() : m.diagnostics_seconds_ago({ seconds: s });+ });++ const totalConnections = $derived.by(() => {+ const s = diag?.websocket?.snapshot;+ if (!s) return 0;+ return s.projectLogsActive + s.containerLogsActive + s.containerStats + s.containerExec + s.systemStats + s.serviceLogsActive;+ });++ const heapBar = $derived.by(() => {+ const mem = diag?.memory;+ if (!mem || !mem.heapSys) return null;+ const released = mem.heapReleased;+ const idle = Math.max(0, mem.heapIdle - released);+ const inuse = mem.heapInuse;+ const total = mem.heapSys || inuse + idle + released || 1;+ return {+ inuse: (inuse / total) * 100,+ idle: (idle / total) * 100,+ released: (released / total) * 100+ };+ });++ const maxPause = $derived.by(() => {+ const p = diag?.gc?.recentPausesNs ?? [];+ return p.length ? Math.max(...p) : 0;+ });++ function applySnapshot(d: Diagnostics) {+ diag = d;+ lastUpdated = Date.now();+ error = null;+ }++ function openStream() {+ ws = createDiagnosticsWebSocket({+ onMessage: applySnapshot,+ onOpen: () => (connected = true),+ onClose: () => (connected = false)+ });+ ws.connect();+ }++ function closeStream() {+ ws?.close();+ ws = null;+ connected = false;+ }++ function togglePause() {+ paused = !paused;+ if (paused) closeStream();+ else openStream();+ }++ async function refresh() {+ try {+ applySnapshot(await diagnosticsService.getDiagnostics());+ } catch (e) {+ error = e instanceof Error ? e.message : m.diagnostics_error_load();+ }+ }++ // --- pprof dumps (inline) ---+ let dumpOpen = $state<{ goroutine: boolean; heap: boolean }>({ goroutine: false, heap: false });+ let dumpText = $state<{ goroutine: string; heap: string }>({ goroutine: '', heap: '' });+ let dumpLoading = $state<{ goroutine: boolean; heap: boolean }>({ goroutine: false, heap: false });++ async function loadDump(name: 'goroutine' | 'heap') {+ dumpLoading[name] = true;+ try {+ dumpText[name] = await diagnosticsService.getDump(name);+ } catch (e) {+ dumpText[name] = e instanceof Error ? e.message : m.diagnostics_error_dump();+ } finally {+ dumpLoading[name] = false;+ }+ }++ function onDumpToggle(name: 'goroutine' | 'heap', open: boolean) {+ dumpOpen[name] = open;+ if (open && !dumpText[name] && !dumpLoading[name]) loadDump(name);+ }++ // --- profile downloads ---+ const profiles: { id: PprofProfile; label: string }[] = [+ { id: 'heap', label: m.diagnostics_profile_heap() },+ { id: 'goroutine', label: m.diagnostics_profile_goroutine() },+ { id: 'allocs', label: m.diagnostics_profile_allocs() },+ { id: 'block', label: m.diagnostics_profile_block() },+ { id: 'mutex', label: m.diagnostics_profile_mutex() },+ { id: 'threadcreate', label: m.diagnostics_profile_threadcreate() },+ { id: 'profile', label: m.diagnostics_profile_cpu() },+ { id: 'trace', label: m.diagnostics_profile_trace() }+ ];+ let downloading = $state<string | null>(null);++ async function download(p: PprofProfile) {+ downloading = p;+ try {+ await diagnosticsService.downloadProfile(p);+ } catch (e) {+ error = e instanceof Error ? e.message : m.diagnostics_error_download();+ } finally {+ downloading = null;+ }+ }++ onMount(() => {+ refresh();+ openStream();+ tick = setInterval(() => (now = Date.now()), 1000);+ return () => {+ closeStream();+ if (tick) clearInterval(tick);+ };+ });+</script>++{#snippet row(label: string, value: string | number)}+ <div class="flex items-center justify-between gap-4 py-1.5">+ <span class="text-muted-foreground text-sm">{label}</span>+ <span class="text-sm font-medium tabular-nums">{value}</span>+ </div>+{/snippet}++{#snippet sectionHeader(title: string, Icon: typeof ActivityIcon)}+ <div class="mb-3 flex items-center gap-2">+ <Icon class="text-muted-foreground size-4" />+ <h2 class="text-sm font-semibold tracking-tight">{title}</h2>+ </div>+{/snippet}++<div class="px-2 py-4 sm:px-6 sm:py-6 lg:px-8">+ <!-- Header -->+ <div class="border-border/50 flex flex-wrap items-center justify-between gap-4 border-b pb-4 sm:pb-6">+ <div class="flex items-start gap-3 sm:gap-4">+ <div+ class="bg-primary/10 text-primary ring-primary/20 flex size-9 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10"+ >+ <ActivityIcon class="size-4 sm:size-5" />+ </div>+ <div>+ <h1 class="text-xl font-semibold tracking-tight sm:text-2xl">{m.diagnostics_title()}</h1>+ <p class="text-muted-foreground mt-1 text-sm">{m.diagnostics_description()}</p>+ </div>+ </div>++ <div class="flex items-center gap-3">+ <span class="flex items-center gap-1.5 text-xs font-medium">+ <span+ class={cn('size-2 rounded-full', paused ? 'bg-amber-500' : connected ? 'animate-pulse bg-emerald-500' : 'bg-zinc-500')}+ ></span>+ {paused ? m.diagnostics_status_paused() : connected ? m.diagnostics_status_live() : m.diagnostics_status_connecting()}+ </span>+ <span class="text-muted-foreground hidden text-xs tabular-nums sm:inline"+ >{m.diagnostics_updated_ago({ ago: agoText })}</span+ >+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ customLabel={paused ? m.diagnostics_resume() : m.diagnostics_pause()}+ onclick={togglePause}+ />+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ icon={RefreshIcon}+ customLabel={m.diagnostics_refresh()}+ onclick={refresh}+ />+ </div>+ </div>++ {#if error}+ <div class="border-destructive/40 bg-destructive/10 text-destructive mt-4 rounded-lg border px-3 py-2 text-sm">+ {error}+ </div>+ {/if}++ {#if diag}+ <!-- Metric tiles -->+ <div class="mt-6 grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">+ <DiagnosticStat+ label={m.diagnostics_stat_goroutines()}+ value={fmtNum(diag.runtime.goroutines)}+ icon={ActivityIcon}+ accent="text-sky-500"+ />+ <DiagnosticStat+ label={m.diagnostics_stat_heap_alloc()}+ value={fmtBytes(diag.memory.heapAlloc)}+ icon={MemoryStickIcon}+ accent="text-violet-500"+ />+ <DiagnosticStat+ label={m.diagnostics_stat_ws_conns()}+ value={fmtNum(totalConnections)}+ icon={ConnectionIcon}+ accent="text-emerald-500"+ />+ <DiagnosticStat+ label={m.diagnostics_stat_gc_cycles()}+ value={fmtNum(diag.memory.numGc)}+ icon={RefreshIcon}+ accent="text-amber-500"+ />+ <DiagnosticStat+ label={m.diagnostics_stat_cpu_procs()}+ value={`${diag.runtime.gomaxprocs}/${diag.runtime.numCpu}`}+ icon={CpuIcon}+ accent="text-rose-500"+ />+ <DiagnosticStat+ label={m.diagnostics_stat_uptime()}+ value={fmtUptime(diag.runtime.uptimeSeconds)}+ icon={ClockIcon}+ accent="text-teal-500"+ />+ </div>++ <div class="mt-8 grid gap-8 lg:grid-cols-2">+ <!-- Runtime -->+ <section>+ {@render sectionHeader(m.diagnostics_section_runtime(), CpuIcon)}+ <div class="divide-border/40 divide-y">+ {@render row(m.diagnostics_runtime_go_version(), diag.runtime.goVersion)}+ {@render row(m.diagnostics_runtime_platform(), `${diag.runtime.os}/${diag.runtime.arch}`)}+ {@render row(m.diagnostics_runtime_gomaxprocs(), diag.runtime.gomaxprocs)}+ {@render row(m.diagnostics_runtime_num_cpu(), diag.runtime.numCpu)}+ {@render row(m.diagnostics_runtime_goroutines(), fmtNum(diag.runtime.goroutines))}+ {@render row(m.diagnostics_runtime_ws_workers(), fmtNum(diag.runtime.wsWorkerGoroutines))}+ {@render row(m.diagnostics_runtime_cgo_calls(), fmtNum(diag.runtime.numCgoCall))}+ {@render row(m.diagnostics_runtime_uptime(), fmtUptime(diag.runtime.uptimeSeconds))}+ </div>+ </section>++ <!-- Memory -->+ <section>+ {@render sectionHeader(m.diagnostics_section_memory(), MemoryStickIcon)}+ {#if heapBar}+ <div class="bg-muted/40 mb-3 flex h-2.5 overflow-hidden rounded-full">+ <div class="bg-violet-500" style="width: {heapBar.inuse}%" title={m.diagnostics_mem_in_use()}></div>+ <div class="bg-violet-500/40" style="width: {heapBar.idle}%" title={m.diagnostics_mem_idle()}></div>+ <div class="bg-zinc-500/40" style="width: {heapBar.released}%" title={m.diagnostics_mem_released()}></div>+ </div>+ <div class="text-muted-foreground mb-2 flex flex-wrap gap-x-4 gap-y-1 text-[11px]">+ <span+ ><span class="mr-1 inline-block size-2 rounded-full bg-violet-500"></span>{m.diagnostics_mem_in_use()}+ {fmtBytes(diag.memory.heapInuse)}</span+ >+ <span+ ><span class="mr-1 inline-block size-2 rounded-full bg-violet-500/40"></span>{m.diagnostics_mem_idle()}+ {fmtBytes(diag.memory.heapIdle - diag.memory.heapReleased)}</span+ >+ <span+ ><span class="mr-1 inline-block size-2 rounded-full bg-zinc-500/40"></span>{m.diagnostics_mem_released()}+ {fmtBytes(diag.memory.heapReleased)}</span+ >+ </div>+ {/if}+ <div class="divide-border/40 divide-y">+ {@render row(m.diagnostics_mem_heap_alloc(), fmtBytes(diag.memory.heapAlloc))}+ {@render row(m.diagnostics_mem_heap_sys(), fmtBytes(diag.memory.heapSys))}+ {@render row(m.diagnostics_mem_heap_objects(), fmtNum(diag.memory.heapObjects))}+ {@render row(m.diagnostics_mem_stack_in_use(), fmtBytes(diag.memory.stackInuse))}+ {@render row(m.diagnostics_mem_total_alloc(), fmtBytes(diag.memory.totalAlloc))}+ {@render row(m.diagnostics_mem_sys_total(), fmtBytes(diag.memory.sys))}+ {@render row(m.diagnostics_mem_next_gc(), fmtBytes(diag.memory.nextGc))}+ {@render row(m.diagnostics_mem_gc_cpu_fraction(), `${(diag.memory.gcCpuFraction * 100).toFixed(3)}%`)}+ </div>+ </section>++ <!-- GC -->+ <section>+ {@render sectionHeader(m.diagnostics_section_gc(), RefreshIcon)}+ <div class="divide-border/40 divide-y">+ {@render row(m.diagnostics_gc_total_cycles(), fmtNum(diag.gc.numGc))}+ {@render row(m.diagnostics_gc_forced_cycles(), fmtNum(diag.memory.numForcedGc))}+ {@render row(m.diagnostics_gc_total_pause(), fmtMs(diag.gc.pauseTotalNs))}+ {@render row(m.diagnostics_gc_last(), diag.gc.lastGc ? new Date(diag.gc.lastGc).toLocaleTimeString() : '—')}+ </div>+ {#if diag.gc.recentPausesNs?.length}+ <div class="mt-3">+ <div class="text-muted-foreground mb-1 text-[11px]">{m.diagnostics_gc_recent_pauses()}</div>+ <div class="flex h-12 items-end gap-0.5">+ {#each diag.gc.recentPausesNs as p, i (i)}+ <div+ class="bg-amber-500/70 flex-1 rounded-sm"+ style="height: {maxPause ? Math.max(4, (p / maxPause) * 100) : 4}%"+ title={fmtMs(p)}+ ></div>+ {/each}+ </div>+ </div>+ {/if}+ </section>++ <!-- WebSocket -->+ <section>+ {@render sectionHeader(m.diagnostics_section_websocket(), ConnectionIcon)}+ <div class="divide-border/40 divide-y">+ {@render row(m.diagnostics_ws_project_logs(), fmtNum(diag.websocket.snapshot.projectLogsActive))}+ {@render row(m.diagnostics_ws_container_logs(), fmtNum(diag.websocket.snapshot.containerLogsActive))}+ {@render row(m.diagnostics_ws_container_stats(), fmtNum(diag.websocket.snapshot.containerStats))}+ {@render row(m.diagnostics_ws_terminals(), fmtNum(diag.websocket.snapshot.containerExec))}+ {@render row(m.diagnostics_ws_system_stats(), fmtNum(diag.websocket.snapshot.systemStats))}+ {@render row(m.diagnostics_ws_service_logs(), fmtNum(diag.websocket.snapshot.serviceLogsActive))}+ </div>+ </section>+ </div>++ <!-- Active connections table -->+ {#if diag.websocket.connections?.length}+ <section class="mt-8">+ {@render sectionHeader(m.diagnostics_section_connections({ count: diag.websocket.connections.length }), ConnectionIcon)}+ <div class="border-border/60 overflow-x-auto rounded-xl border">+ <table class="w-full text-left text-sm">+ <thead class="bg-muted/30 text-muted-foreground text-xs">+ <tr>+ <th class="px-3 py-2 font-medium">{m.diagnostics_conn_kind()}</th>+ <th class="px-3 py-2 font-medium">{m.diagnostics_conn_resource()}</th>+ <th class="px-3 py-2 font-medium">{m.diagnostics_conn_client_ip()}</th>+ <th class="px-3 py-2 font-medium">{m.diagnostics_conn_user()}</th>+ <th class="px-3 py-2 font-medium">{m.diagnostics_conn_since()}</th>+ </tr>+ </thead>+ <tbody class="divide-border/40 divide-y">+ {#each diag.websocket.connections as c (c.id)}+ <tr class="hover:bg-muted/20">+ <td class="px-3 py-2">{wsKindLabels[c.kind] ?? c.kind}</td>+ <td class="text-muted-foreground px-3 py-2 font-mono text-xs">{c.resourceId || '—'}</td>+ <td class="text-muted-foreground px-3 py-2 font-mono text-xs">{c.clientIp || '—'}</td>+ <td class="text-muted-foreground px-3 py-2 text-xs">{c.userId || '—'}</td>+ <td class="text-muted-foreground px-3 py-2 text-xs tabular-nums">+ {c.startedAt ? new Date(c.startedAt).toLocaleTimeString() : '—'}+ </td>+ </tr>+ {/each}+ </tbody>+ </table>+ </div>+ </section>+ {/if}++ <!-- Live logs -->+ <section class="mt-8">+ {@render sectionHeader(m.diagnostics_section_logs(), ActivityIcon)}+ <DiagnosticLogPanel />+ </section>++ <!-- Dumps -->+ <section class="mt-8">+ {@render sectionHeader(m.diagnostics_section_dumps(), CpuIcon)}+ <div class="space-y-2">+ {#each [{ id: 'goroutine', label: m.diagnostics_dump_goroutine() }, { id: 'heap', label: m.diagnostics_dump_heap() }] as d (d.id)}+ {@const name = d.id as 'goroutine' | 'heap'}+ <Collapsible.Root open={dumpOpen[name]} onOpenChange={(o: boolean) => onDumpToggle(name, o)}>+ <Collapsible.Trigger+ class="border-border/60 bg-card/40 hover:bg-muted/30 flex w-full items-center justify-between rounded-lg border px-3 py-2 text-sm font-medium"+ >+ {d.label}+ <ArrowDownIcon class={cn('size-4 transition-transform', dumpOpen[name] && '-rotate-180')} />+ </Collapsible.Trigger>+ <Collapsible.Content>+ <pre+ class="border-border/60 bg-background mt-1 max-h-96 overflow-auto rounded-lg border p-3 font-mono text-[11px] leading-relaxed">{dumpLoading[+ name+ ]+ ? m.diagnostics_dump_loading()+ : dumpText[name] || m.diagnostics_dump_empty()}</pre>+ </Collapsible.Content>+ </Collapsible.Root>+ {/each}+ </div>+ </section>++ <!-- Profiles -->+ <section class="mt-8 pb-8">+ {@render sectionHeader(m.diagnostics_section_profiles(), DownloadIcon)}+ <p class="text-muted-foreground mb-3 text-sm">{m.diagnostics_profiles_hint()}</p>+ <div class="flex flex-wrap gap-2">+ {#each profiles as p (p.id)}+ <ArcaneButton+ action="base"+ tone="outline"+ size="sm"+ icon={DownloadIcon}+ customLabel={p.label}+ loading={downloading === p.id}+ disabled={downloading !== null}+ onclick={() => download(p.id)}+ />+ {/each}+ </div>+ </section>+ {:else if !error}+ <div class="text-muted-foreground py-16 text-center text-sm">{m.diagnostics_loading()}</div>+ {/if}+</div>diff --git a/frontend/src/routes/(app)/settings/diagnostics/diagnostic-log-panel.svelte b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-log-panel.sveltenew file mode 100644index 000000000..25adda696--- /dev/null+++ b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-log-panel.svelte@@ -0,0 +1,162 @@+<script lang="ts">+ 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';+ import { TrashIcon } from '$lib/icons';++ interface Props {+ height?: string;+ maxLines?: number;+ }++ let { height = '360px', maxLines = 1000 }: Props = $props();++ let logs = $state<LogEntry[]>([]);+ let connected = $state(false);+ let autoScroll = $state(true);+ let filterText = $state('');+ let levelFilter = $state<'all' | 'error' | 'warn' | 'info' | 'debug'>('all');+ let viewport = $state<HTMLElement>();+ let ws: ReconnectingWebSocket<LogEntry> | null = null;++ const filtered = $derived(+ logs.filter((l) => {+ const lvl = l.level.toLowerCase();+ if (levelFilter !== 'all' && !lvl.startsWith(levelFilter)) return false;+ if (filterText && !l.message.toLowerCase().includes(filterText.toLowerCase())) return false;+ return true;+ })+ );++ function scrollToBottom() {+ if (autoScroll && viewport) {+ requestAnimationFrame(() => {+ if (viewport) viewport.scrollTop = viewport.scrollHeight;+ });+ }+ }++ function push(entry: LogEntry) {+ logs.push(entry);+ if (logs.length > maxLines) logs = logs.slice(logs.length - maxLines);+ scrollToBottom();+ }++ function levelClass(level: string): string {+ const l = level.toLowerCase();+ if (l.startsWith('error')) return 'text-red-400';+ if (l.startsWith('warn')) return 'text-amber-400';+ if (l.startsWith('debug')) return 'text-zinc-500';+ return 'text-emerald-400';+ }++ const timeFmt = new Intl.DateTimeFormat('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ hour12: false+ });+ function fmtTime(t: string): string {+ const d = new Date(t);+ return isNaN(d.getTime()) ? t : timeFmt.format(d);+ }++ function attrsText(attrs?: Record<string, unknown>): string {+ if (!attrs) return '';+ return Object.entries(attrs)+ .map(([k, v]) => `${k}=${String(v)}`)+ .join(' ');+ }++ 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),+ onClose: () => (connected = false)+ });+ await ws.connect();+ requestAnimationFrame(() => {+ if (viewport) viewport.scrollTop = viewport.scrollHeight;+ });+ });++ onDestroy(() => ws?.close());+</script>++<div class="border-border/60 overflow-hidden rounded-xl border">+ <div class="border-border/60 bg-muted/30 flex flex-wrap items-center gap-2 border-b px-3 py-2">+ <span class="flex items-center gap-1.5 text-xs font-medium">+ <span class={cn('size-2 rounded-full', connected ? 'bg-emerald-500' : 'bg-zinc-500')}></span>+ {connected ? m.diagnostics_logs_streaming() : m.diagnostics_logs_disconnected()}+ </span>+ <span class="text-muted-foreground text-xs tabular-nums">{m.diagnostics_logs_count({ count: filtered.length })}</span>++ <div class="ml-auto flex items-center gap-2">+ <select+ bind:value={levelFilter}+ class="border-border/60 bg-background h-7 rounded-md border px-2 text-xs"+ aria-label={m.diagnostics_logs_all_levels()}+ >+ <option value="all">{m.diagnostics_logs_all_levels()}</option>+ <option value="error">{m.diagnostics_logs_level_error()}</option>+ <option value="warn">{m.diagnostics_logs_level_warn()}</option>+ <option value="info">{m.diagnostics_logs_level_info()}</option>+ <option value="debug">{m.diagnostics_logs_level_debug()}</option>+ </select>+ <input+ bind:value={filterText}+ placeholder={m.diagnostics_logs_filter_placeholder()}+ class="border-border/60 bg-background h-7 w-32 rounded-md border px-2 text-xs"+ />+ <label class="text-muted-foreground flex items-center gap-1 text-xs">+ <input type="checkbox" bind:checked={autoScroll} class="size-3.5" />+ {m.diagnostics_logs_auto_scroll()}+ </label>+ <ArcaneButton+ action="base"+ tone="ghost"+ size="sm"+ icon={TrashIcon}+ customLabel={m.diagnostics_logs_clear()}+ onclick={() => (logs = [])}+ />+ </div>+ </div>++ <div+ bind:this={viewport}+ class="bg-background overflow-y-auto px-3 py-2 font-mono text-xs leading-relaxed"+ style="height: {height};"+ role="log"+ aria-live={connected ? 'polite' : 'off'}+ >+ {#if filtered.length === 0}+ <div class="text-muted-foreground py-6 text-center">{m.diagnostics_logs_empty()}</div>+ {:else}+ {#each filtered as entry (logKey(entry))}+ <div class="hover:bg-foreground/5 flex gap-2 rounded px-1 py-0.5">+ <span class="text-muted-foreground shrink-0 tabular-nums">{fmtTime(entry.time)}</span>+ <span class={cn('w-12 shrink-0 font-semibold uppercase', levelClass(entry.level))}>{entry.level}</span>+ <span class="min-w-0 break-words whitespace-pre-wrap">+ {entry.message}+ {#if entry.attrs}<span class="text-muted-foreground">{attrsText(entry.attrs)}</span>{/if}+ </span>+ </div>+ {/each}+ {/if}+ </div>+</div>diff --git a/frontend/src/routes/(app)/settings/diagnostics/diagnostic-stat.svelte b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-stat.sveltenew file mode 100644index 000000000..151f3846f--- /dev/null+++ b/frontend/src/routes/(app)/settings/diagnostics/diagnostic-stat.svelte@@ -0,0 +1,29 @@+<script lang="ts">+ import { cn } from '$lib/utils';+ import type { IconType } from '$lib/icons';++ interface Props {+ label: string;+ value: string | number;+ unit?: string;+ sub?: string;+ icon: IconType;+ accent?: string;+ }++ let { label, value, unit, sub, icon: Icon, accent = 'text-primary' }: Props = $props();+</script>++<div class="border-border/60 bg-card/40 flex items-center gap-3 rounded-lg border px-3.5 py-3">+ <div class={cn('bg-foreground/5 flex size-9 shrink-0 items-center justify-center rounded-md', accent)}>+ <Icon class="size-4" />+ </div>+ <div class="min-w-0">+ <div class="text-muted-foreground text-[11px] font-medium tracking-wide uppercase">{label}</div>+ <div class="flex items-baseline gap-1">+ <span class="text-lg leading-tight font-semibold tabular-nums">{value}</span>+ {#if unit}<span class="text-muted-foreground text-xs">{unit}</span>{/if}+ </div>+ {#if sub}<div class="text-muted-foreground truncate text-[11px]">{sub}</div>{/if}+ </div>+</div>diff --git a/types/system/diagnostics.go b/types/system/diagnostics.gonew file mode 100644index 000000000..e6dbce085--- /dev/null+++ b/types/system/diagnostics.go@@ -0,0 +1,102 @@+package system++import "time"++// Diagnostics is a point-in-time snapshot of the Go runtime, garbage collector,+// and active WebSocket connections. It is returned by the diagnostics REST+// endpoint and pushed over the live diagnostics WebSocket stream.+type Diagnostics struct {+ // Timestamp is when the snapshot was taken.+ //+ // Required: true+ Timestamp time.Time `json:"timestamp"`+ // Runtime holds Go runtime and scheduler counters.+ //+ // Required: true+ Runtime RuntimeInfo `json:"runtime"`+ // Memory holds a subset of runtime.MemStats.+ //+ // Required: true+ Memory MemoryInfo `json:"memory"`+ // GC holds garbage-collector statistics.+ //+ // Required: true+ GC GCInfo `json:"gc"`+ // WebSocket holds active WebSocket connection metrics.+ //+ // Required: true+ WebSocket WebSocketDiagnostics `json:"websocket"`+}++// RuntimeInfo describes the Go runtime, build, and scheduler state.+type RuntimeInfo struct {+ Goroutines int `json:"goroutines"`+ WSWorkerGoroutines int `json:"wsWorkerGoroutines"`+ GOMAXPROCS int `json:"gomaxprocs"`+ NumCPU int `json:"numCpu"`+ GoVersion string `json:"goVersion"`+ OS string `json:"os"`+ Arch string `json:"arch"`+ NumCgoCall int64 `json:"numCgoCall"`+ UptimeSeconds int64 `json:"uptimeSeconds"`+}++// MemoryInfo is the subset of runtime.MemStats surfaced in diagnostics. All+// byte counts are raw bytes.+type MemoryInfo struct {+ Alloc uint64 `json:"alloc"`+ TotalAlloc uint64 `json:"totalAlloc"`+ Sys uint64 `json:"sys"`+ HeapAlloc uint64 `json:"heapAlloc"`+ HeapSys uint64 `json:"heapSys"`+ HeapInuse uint64 `json:"heapInuse"`+ HeapIdle uint64 `json:"heapIdle"`+ HeapReleased uint64 `json:"heapReleased"`+ HeapObjects uint64 `json:"heapObjects"`+ StackInuse uint64 `json:"stackInuse"`+ StackSys uint64 `json:"stackSys"`+ MSpanInuse uint64 `json:"mspanInuse"`+ MCacheInuse uint64 `json:"mcacheInuse"`+ NextGC uint64 `json:"nextGc"`+ NumGC uint32 `json:"numGc"`+ NumForcedGC uint32 `json:"numForcedGc"`+ GCCPUFraction float64 `json:"gcCpuFraction"`+}++// GCInfo holds garbage-collector statistics from runtime/debug.ReadGCStats.+type GCInfo struct {+ // LastGC is the time of the most recent collection.+ LastGC time.Time `json:"lastGc"`+ // NumGC is the total number of completed GC cycles.+ NumGC int64 `json:"numGc"`+ // PauseTotalNs is the cumulative stop-the-world pause time in nanoseconds.+ PauseTotalNs int64 `json:"pauseTotalNs"`+ // RecentPausesNs lists the most recent GC pause durations (ns), newest first.+ RecentPausesNs []int64 `json:"recentPausesNs"`+}++// WebSocketDiagnostics aggregates the active WebSocket connection counts and the+// list of currently-tracked connections.+type WebSocketDiagnostics struct {+ Snapshot WebSocketMetricsSnapshot `json:"snapshot"`+ Connections []WebSocketConnectionInfo `json:"connections"`+}++// LogEntry is a single captured backend log record, exposed via the recent-logs+// endpoint and the live log WebSocket stream.+type LogEntry struct {+ // Time is when the record was emitted.+ //+ // Required: true+ Time time.Time `json:"time"`+ // Level is the slog level name (DEBUG, INFO, WARN, ERROR).+ //+ // Required: true+ Level string `json:"level"`+ // Message is the log message.+ //+ // Required: true+ Message string `json:"message"`+ // Attrs holds the record's structured attributes, if any.+ Attrs map[string]any `json:"attrs,omitempty"`+}