Skip to content

Modern Docker Management, Designed for Everyone

refactor: use huma to generate open api spec on top of gin (#1068)

Kyle Mendellf13d19c9e692
diff --git a/.arcane.json b/.arcane.json
index 8d33f4c1f..ce57c06fc 100644
--- a/.arcane.json
+++ b/.arcane.json
@@ -1,4 +1,4 @@
{
"version": "1.10.1",
- "revision": "f1e942ab"
+ "revision": "345b62c0"
}
diff --git a/.github/matchers/deadcode-matcher.json b/.github/matchers/deadcode-matcher.json
new file mode 100644
index 000000000..163d97807
--- /dev/null
+++ b/.github/matchers/deadcode-matcher.json
@@ -0,0 +1,17 @@
+{
+ "problemMatcher": [
+ {
+ "owner": "deadcode",
+ "pattern": [
+ {
+ "regexp": "^([^:]+):(\\d+):(\\d+):\\s+unreachable\\s+func:\\s+(.+)$",
+ "file": 1,
+ "line": 2,
+ "column": 3,
+ "message": 4
+ }
+ ],
+ "severity": "warning"
+ }
+ ]
+}
diff --git a/.github/svelte-check-matcher.json b/.github/matchers/svelte-check-matcher.json
similarity index 100%
rename from .github/svelte-check-matcher.json
rename to .github/matchers/svelte-check-matcher.json
diff --git a/.github/workflows/deadcode.yml b/.github/workflows/deadcode.yml
new file mode 100644
index 000000000..a724256ba
--- /dev/null
+++ b/.github/workflows/deadcode.yml
@@ -0,0 +1,97 @@
+name: Go Deadcode Check
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - "backend/**/*.go"
+ - "types/**/*.go"
+ - "cli/**/*.go"
+ - ".github/workflows/deadcode.yml"
+ - ".github/matchers/deadcode-matcher.json"
+ - "go.work"
+ - "backend/go.mod"
+ - "backend/go.sum"
+ pull_request:
+ branches: [main]
+ paths:
+ - "backend/**/*.go"
+ - "types/**/*.go"
+ - "cli/**/*.go"
+ - ".github/workflows/deadcode.yml"
+ - ".github/matchers/deadcode-matcher.json"
+ - "go.work"
+ - "backend/go.mod"
+ - "backend/go.sum"
+ workflow_dispatch:
+
+jobs:
+ deadcode:
+ name: Run GoLang Deadcode Analysis
+ runs-on: depot-ubuntu-latest
+ permissions:
+ contents: read
+ checks: write
+ pull-requests: write
+
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v6
+
+ - name: Setup Go
+ uses: actions/setup-go@v6
+ with:
+ go-version-file: backend/go.mod
+ cache-dependency-path: backend/go.sum
+
+ - name: Install deadcode
+ run: go install golang.org/x/tools/cmd/deadcode@latest
+
+ - name: Add deadcode problem matcher
+ run: echo "::add-matcher::.github/matchers/deadcode-matcher.json"
+
+ - name: Run deadcode analysis
+ id: deadcode
+ working-directory: backend
+ run: |
+ OUTPUT=$(deadcode ./... 2>&1 || true)
+ echo "$OUTPUT"
+ COUNT=$(echo "$OUTPUT" | grep -c "unreachable func" || echo "0")
+ echo "count=$COUNT" >> $GITHUB_OUTPUT
+ echo "output<<EOF" >> $GITHUB_OUTPUT
+ echo "$OUTPUT" >> $GITHUB_OUTPUT
+ echo "EOF" >> $GITHUB_OUTPUT
+
+ - name: Find Comment
+ if: github.event_name == 'pull_request'
+ uses: peter-evans/find-comment@v3
+ id: fc
+ with:
+ issue-number: ${{ github.event.pull_request.number }}
+ comment-author: "github-actions[bot]"
+ body-includes: "## 🔍 Deadcode Analysis"
+
+ - name: Comment deadcode results
+ if: github.event_name == 'pull_request'
+ uses: peter-evans/create-or-update-comment@v4
+ with:
+ comment-id: ${{ steps.fc.outputs.comment-id }}
+ issue-number: ${{ github.event.pull_request.number }}
+ body: |
+ ## 🔍 Deadcode Analysis
+
+ Found **${{ steps.deadcode.outputs.count }}** unreachable functions in the backend.
+
+ <details>
+ <summary>View details</summary>
+
+ ```
+ ${{ steps.deadcode.outputs.output }}
+ ```
+
+ Only remove deadcode that you know is 100% no longer used.
+
+ </details>
+
+ > Analysis from commit ${{ github.sha }}
+ edit-mode: replace
diff --git a/.github/workflows/svelte-check.yml b/.github/workflows/svelte-check.yml
index b6dfed1b8..501651956 100644
--- a/.github/workflows/svelte-check.yml
+++ b/.github/workflows/svelte-check.yml
@@ -49,7 +49,7 @@ jobs:
run: pnpm --filter arcane-frontend install --frozen-lockfile
- name: Add svelte-check problem matcher
- run: echo "::add-matcher::.github/svelte-check-matcher.json"
+ run: echo "::add-matcher::.github/matchers/svelte-check-matcher.json"
- name: Build frontend
run: pnpm --filter arcane-frontend build
diff --git a/backend/cli/openapi.go b/backend/cli/openapi.go
new file mode 100644
index 000000000..a86b37ffb
--- /dev/null
+++ b/backend/cli/openapi.go
@@ -0,0 +1,60 @@
+package cli
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/getarcaneapp/arcane/backend/internal/huma"
+ "github.com/spf13/cobra"
+)
+
+var openapiCmd = &cobra.Command{
+ Use: "openapi",
+ Short: "Export the OpenAPI specification",
+ Long: "Export the OpenAPI 3.1 specification in YAML or JSON format",
+ Run: func(cmd *cobra.Command, args []string) {
+ format, _ := cmd.Flags().GetString("format")
+ downgrade, _ := cmd.Flags().GetBool("downgrade")
+ outputFile, _ := cmd.Flags().GetString("output")
+
+ // Create Huma API for spec generation (no services needed)
+ api := huma.SetupAPIForSpec()
+
+ // Generate output
+ var output []byte
+ var err error
+
+ if format == "json" {
+ output, err = api.OpenAPI().MarshalJSON()
+ } else {
+ if downgrade {
+ output, err = api.OpenAPI().DowngradeYAML()
+ } else {
+ output, err = api.OpenAPI().YAML()
+ }
+ }
+
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error generating OpenAPI spec: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Write to file or stdout
+ if outputFile != "" {
+ if err := os.WriteFile(outputFile, output, 0600); err != nil {
+ fmt.Fprintf(os.Stderr, "Error writing file: %v\n", err)
+ os.Exit(1)
+ }
+ fmt.Fprintf(os.Stderr, "OpenAPI spec written to %s\n", outputFile)
+ } else {
+ fmt.Println(string(output))
+ }
+ },
+}
+
+func init() {
+ openapiCmd.Flags().StringP("format", "f", "yaml", "Output format: yaml or json")
+ openapiCmd.Flags().BoolP("downgrade", "d", false, "Downgrade to OpenAPI 3.0.3 for compatibility")
+ openapiCmd.Flags().StringP("output", "o", "", "Output file (default: stdout)")
+ rootCmd.AddCommand(openapiCmd)
+}
diff --git a/backend/go.mod b/backend/go.mod
index c5b522b9f..b61934dca 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -11,6 +11,7 @@ require (
github.com/cenkalti/backoff/v5 v5.0.3
github.com/compose-spec/compose-go/v2 v2.10.0
github.com/coreos/go-oidc/v3 v3.17.0
+ github.com/danielgtaylor/huma/v2 v2.34.1
github.com/docker/cli v28.5.2+incompatible
github.com/docker/compose/v5 v5.0.0
github.com/docker/distribution v2.8.3+incompatible
@@ -44,7 +45,6 @@ require (
golang.org/x/oauth2 v0.33.0
golang.org/x/sync v0.18.0
golang.org/x/text v0.31.0
- gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/postgres v1.6.0
gorm.io/gorm v1.31.1
)
diff --git a/backend/go.sum b/backend/go.sum
index 4d5088497..6d8a72077 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -94,6 +94,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
+github.com/danielgtaylor/huma/v2 v2.34.1 h1:EmOJAbzEGfy0wAq/QMQ1YKfEMBEfE94xdBRLPBP0gwQ=
+github.com/danielgtaylor/huma/v2 v2.34.1/go.mod h1:ynwJgLk8iGVgoaipi5tgwIQ5yoFNmiu+QdhU7CEEmhk=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
diff --git a/backend/internal/api/api_key_handler.go b/backend/internal/api/api_key_handler.go
deleted file mode 100644
index 2b42ce2b6..000000000
--- a/backend/internal/api/api_key_handler.go
+++ /dev/null
@@ -1,226 +0,0 @@
-package api
-
-import (
- "errors"
- "net/http"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/apikey"
-)
-
-type ApiKeyHandler struct {
- apiKeyService *services.ApiKeyService
-}
-
-func NewApiKeyHandler(group *gin.RouterGroup, apiKeyService *services.ApiKeyService, authMiddleware *middleware.AuthMiddleware) {
- handler := &ApiKeyHandler{apiKeyService: apiKeyService}
-
- apiGroup := group.Group("/api-keys")
- apiGroup.Use(authMiddleware.WithAdminRequired().Add())
- {
- apiGroup.GET("", handler.ListApiKeys)
- apiGroup.POST("", handler.CreateApiKey)
- apiGroup.GET("/:id", handler.GetApiKey)
- apiGroup.PUT("/:id", handler.UpdateApiKey)
- apiGroup.DELETE("/:id", handler.DeleteApiKey)
- }
-}
-
-// ListApiKeys godoc
-//
-// @Summary List API keys
-// @Description Get a paginated list of API keys
-// @Tags API Keys
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param search query string false "Search query for filtering by name or description"
-// @Param sort query string false "Column to sort by"
-// @Param order query string false "Sort direction (asc or desc)" default("asc")
-// @Param start query int false "Start index for pagination" default(0)
-// @Param limit query int false "Number of items per page" default(20)
-// @Success 200 {object} base.Paginated[apikey.ApiKey]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/api-keys [get]
-func (h *ApiKeyHandler) ListApiKeys(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- apiKeys, paginationResp, err := h.apiKeyService.ListApiKeys(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ApiKeyListError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": apiKeys,
- "pagination": paginationResp,
- })
-}
-
-// CreateApiKey godoc
-//
-// @Summary Create an API key
-// @Description Create a new API key for programmatic access
-// @Tags API Keys
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param request body apikey.Create true "API key creation request"
-// @Success 201 {object} base.ApiResponse[apikey.ApiKeyCreatedDto]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 401 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/api-keys [post]
-func (h *ApiKeyHandler) CreateApiKey(c *gin.Context) {
- user, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- var req apikey.Create
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- apiKey, err := h.apiKeyService.CreateApiKey(c.Request.Context(), user.ID, req)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ApiKeyCreationError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": apiKey,
- })
-}
-
-// GetApiKey godoc
-//
-// @Summary Get an API key
-// @Description Get details of a specific API key by ID
-// @Tags API Keys
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "API key ID"
-// @Success 200 {object} base.ApiResponse[apikey.ApiKey]
-// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/api-keys/{id} [get]
-func (h *ApiKeyHandler) GetApiKey(c *gin.Context) {
- id := c.Param("id")
-
- apiKey, err := h.apiKeyService.GetApiKey(c.Request.Context(), id)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ApiKeyNotFoundError{}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": apiKey,
- })
-}
-
-// UpdateApiKey godoc
-//
-// @Summary Update an API key
-// @Description Update an existing API key's details
-// @Tags API Keys
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param id path string true "API key ID"
-// @Param request body apikey.Update true "API key update request"
-// @Success 200 {object} base.ApiResponse[apikey.ApiKey]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/api-keys/{id} [put]
-func (h *ApiKeyHandler) UpdateApiKey(c *gin.Context) {
- id := c.Param("id")
-
- var req apikey.Update
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- apiKey, err := h.apiKeyService.UpdateApiKey(c.Request.Context(), id, req)
- if err != nil {
- if errors.Is(err, services.ErrApiKeyNotFound) {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ApiKeyNotFoundError{}).Error()},
- })
- return
- }
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ApiKeyUpdateError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": apiKey,
- })
-}
-
-// DeleteApiKey godoc
-//
-// @Summary Delete an API key
-// @Description Delete an API key by ID
-// @Tags API Keys
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "API key ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/api-keys/{id} [delete]
-func (h *ApiKeyHandler) DeleteApiKey(c *gin.Context) {
- id := c.Param("id")
-
- if err := h.apiKeyService.DeleteApiKey(c.Request.Context(), id); err != nil {
- if errors.Is(err, services.ErrApiKeyNotFound) {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ApiKeyNotFoundError{}).Error()},
- })
- return
- }
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ApiKeyDeletionError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "API key deleted successfully"},
- })
-}
diff --git a/backend/internal/api/app_images_handler.go b/backend/internal/api/app_images_handler.go
deleted file mode 100644
index 6da0ff3ea..000000000
--- a/backend/internal/api/app_images_handler.go
+++ /dev/null
@@ -1,81 +0,0 @@
-package api
-
-import (
- "net/http"
- "strconv"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- apphttp "github.com/getarcaneapp/arcane/backend/internal/utils/http"
- "github.com/gin-gonic/gin"
-)
-
-type ApplicationImagesHandler struct {
- appImagesService *services.ApplicationImagesService
-}
-
-func NewApplicationImagesHandler(group *gin.RouterGroup, appImagesService *services.ApplicationImagesService) {
- appImageHandler := &ApplicationImagesHandler{appImagesService: appImagesService}
-
- group.GET("/app-images/logo", appImageHandler.getLogo)
- group.GET("/app-images/favicon", appImageHandler.getFavicon)
- group.GET("/app-images/profile", appImageHandler.getDefaultProfile)
-}
-
-// getLogo godoc
-//
-// @Summary Get application logo
-// @Description Get the application logo image
-// @Tags Application Images
-// @Param full query bool false "Return full logo" default(false)
-// @Produce image/png,image/jpeg
-// @Success 200 {file} binary
-// @Router /api/app-images/logo [get]
-func (c *ApplicationImagesHandler) getLogo(ctx *gin.Context) {
- name := "logo"
-
- if fullParam := ctx.Query("full"); fullParam != "" {
- if full, err := strconv.ParseBool(fullParam); err == nil && full {
- name = "logo-full"
- }
- }
-
- c.getImage(ctx, name)
-}
-
-// getFavicon godoc
-//
-// @Summary Get application favicon
-// @Description Get the application favicon image
-// @Tags Application Images
-// @Produce image/png,image/jpeg
-// @Success 200 {file} binary
-// @Router /api/app-images/favicon [get]
-func (c *ApplicationImagesHandler) getFavicon(ctx *gin.Context) {
- c.getImage(ctx, "favicon")
-}
-
-// getDefaultProfile godoc
-//
-// @Summary Get default profile image
-// @Description Get the default user profile image
-// @Tags Application Images
-// @Produce image/png,image/jpeg
-// @Success 200 {file} binary
-// @Router /api/app-images/profile [get]
-func (c *ApplicationImagesHandler) getDefaultProfile(ctx *gin.Context) {
- c.getImage(ctx, "profile")
-}
-
-func (c *ApplicationImagesHandler) getImage(ctx *gin.Context, name string) {
- imageData, mimeType, err := c.appImagesService.GetImage(name)
- if err != nil {
- ctx.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.ImageRetrievalError{Err: err}).Error()}})
- return
- }
-
- ctx.Header("Content-Type", mimeType)
- apphttp.SetCacheControlHeader(ctx, 15*time.Minute, 24*time.Hour)
- ctx.Data(200, mimeType, imageData)
-}
diff --git a/backend/internal/api/auth_handler.go b/backend/internal/api/auth_handler.go
deleted file mode 100644
index 5c676f74d..000000000
--- a/backend/internal/api/auth_handler.go
+++ /dev/null
@@ -1,213 +0,0 @@
-package api
-
-import (
- "errors"
- "net/http"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/cookie"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/auth"
- "go.getarcane.app/types/user"
-)
-
-type AuthHandler struct {
- userService *services.UserService
- authService *services.AuthService
- oidcService *services.OidcService
-}
-
-func NewAuthHandler(group *gin.RouterGroup, userService *services.UserService, authService *services.AuthService, oidcService *services.OidcService, authMiddleware *middleware.AuthMiddleware) {
- ah := &AuthHandler{userService: userService, authService: authService, oidcService: oidcService}
-
- authApiGroup := group.Group("/auth")
- {
- authApiGroup.POST("/login", ah.Login)
- authApiGroup.POST("/logout", ah.Logout)
- authApiGroup.GET("/me", authMiddleware.WithAdminNotRequired().Add(), ah.GetCurrentUser)
- authApiGroup.POST("/refresh", ah.RefreshToken)
- authApiGroup.POST("/password", authMiddleware.WithAdminNotRequired().Add(), ah.ChangePassword)
- }
-}
-
-func (h *AuthHandler) Login(c *gin.Context) {
- var req auth.Login
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()}})
- return
- }
-
- localAuthEnabled, err := h.authService.IsLocalAuthEnabled(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.AuthSettingsCheckError{Err: err}).Error()}})
- return
- }
- if !localAuthEnabled {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.LocalAuthDisabledError{}).Error()}})
- return
- }
-
- userModel, tokenPair, err := h.authService.Login(c.Request.Context(), req.Username, req.Password)
- if err != nil {
- var statusCode int
- var errorMsg string
- switch {
- case errors.Is(err, services.ErrInvalidCredentials):
- statusCode = http.StatusUnauthorized
- errorMsg = (&common.InvalidCredentialsError{}).Error()
- case errors.Is(err, services.ErrLocalAuthDisabled):
- statusCode = http.StatusBadRequest
- errorMsg = (&common.LocalAuthDisabledError{}).Error()
- default:
- statusCode = http.StatusInternalServerError
- errorMsg = (&common.AuthFailedError{Err: err}).Error()
- }
- c.JSON(statusCode, gin.H{"success": false, "data": gin.H{"error": errorMsg}})
- return
- }
-
- c.SetSameSite(http.SameSiteLaxMode)
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
- // Add 60 seconds buffer to account for clock skew and network latency
- maxAge += 60
- cookie.CreateTokenCookie(c, maxAge, tokenPair.AccessToken)
-
- var out user.Response
- if mapErr := mapper.MapStruct(userModel, &out); mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.UserMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "token": tokenPair.AccessToken,
- "refreshToken": tokenPair.RefreshToken,
- "expiresAt": tokenPair.ExpiresAt,
- "user": out,
- },
- })
-}
-
-func (h *AuthHandler) Logout(c *gin.Context) {
- c.SetSameSite(http.SameSiteLaxMode)
- cookie.ClearTokenCookie(c)
- c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"message": "Logged out successfully"}})
-}
-
-// GetCurrentUser godoc
-//
-// @Summary Get current user
-// @Description Get the currently authenticated user's information
-// @Tags Auth
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Success 200 {object} base.ApiResponse[user.Response]
-// @Failure 401 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/auth/me [get]
-func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
- userID, exists := middleware.GetCurrentUserID(c)
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": gin.H{"error": (&common.NotAuthenticatedError{}).Error()}})
- return
- }
-
- userModel, err := h.userService.GetUser(c.Request.Context(), userID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.UserRetrievalError{Err: err}).Error()}})
- return
- }
-
- var out user.Response
- if mapErr := mapper.MapStruct(userModel, &out); mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.UserMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
-}
-
-func (h *AuthHandler) RefreshToken(c *gin.Context) {
- var req auth.Refresh
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()}})
- return
- }
-
- tokenPair, err := h.authService.RefreshToken(c.Request.Context(), req.RefreshToken)
- if err != nil {
- var statusCode int
- var errorMsg string
- switch {
- case errors.Is(err, services.ErrInvalidToken), errors.Is(err, services.ErrExpiredToken):
- statusCode = http.StatusUnauthorized
- errorMsg = (&common.InvalidTokenError{}).Error()
- default:
- statusCode = http.StatusInternalServerError
- errorMsg = (&common.TokenRefreshError{Err: err}).Error()
- }
- c.JSON(statusCode, gin.H{"success": false, "data": gin.H{"error": errorMsg}})
- return
- }
-
- c.SetSameSite(http.SameSiteLaxMode)
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
- // Add 60 seconds buffer to account for clock skew and network latency
- maxAge += 60
- cookie.CreateTokenCookie(c, maxAge, tokenPair.AccessToken)
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "token": tokenPair.AccessToken,
- "refreshToken": tokenPair.RefreshToken,
- "expiresAt": tokenPair.ExpiresAt,
- },
- })
-}
-
-func (h *AuthHandler) ChangePassword(c *gin.Context) {
- userModel, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- var req auth.PasswordChange
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()}})
- return
- }
-
- if req.CurrentPassword == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.PasswordRequiredError{}).Error()}})
- return
- }
-
- err := h.authService.ChangePassword(c.Request.Context(), userModel.ID, req.CurrentPassword, req.NewPassword)
- if err != nil {
- var statusCode int
- var errorMsg string
- switch {
- case errors.Is(err, services.ErrInvalidCredentials):
- statusCode = http.StatusUnauthorized
- errorMsg = (&common.IncorrectPasswordError{}).Error()
- default:
- statusCode = http.StatusInternalServerError
- errorMsg = (&common.PasswordChangeError{Err: err}).Error()
- }
- c.JSON(statusCode, gin.H{"success": false, "data": gin.H{"error": errorMsg}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"message": "Password changed successfully"}})
-}
diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.go
deleted file mode 100644
index 71cd87ba4..000000000
--- a/backend/internal/api/container_handler.go
+++ /dev/null
@@ -1,766 +0,0 @@
-package api
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "io"
- "log/slog"
- "net/http"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-
- "github.com/docker/docker/api/types/container"
- "github.com/docker/docker/api/types/network"
- "github.com/docker/go-connections/nat"
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- httputil "github.com/getarcaneapp/arcane/backend/internal/utils/http"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- ws "github.com/getarcaneapp/arcane/backend/internal/utils/ws"
- "github.com/gin-gonic/gin"
- "github.com/gorilla/websocket"
- containertypes "go.getarcane.app/types/container"
-)
-
-type ContainerHandler struct {
- containerService *services.ContainerService
- imageService *services.ImageService
- dockerService *services.DockerClientService
- statsStreams sync.Map
- containerWSUpgrader websocket.Upgrader
-}
-
-func NewContainerHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, containerService *services.ContainerService, imageService *services.ImageService, authMiddleware *middleware.AuthMiddleware, cfg *config.Config) {
- handler := &ContainerHandler{
- dockerService: dockerService,
- containerService: containerService,
- imageService: imageService,
- containerWSUpgrader: websocket.Upgrader{
- CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.AppUrl),
- ReadBufferSize: 32 * 1024,
- WriteBufferSize: 32 * 1024,
- EnableCompression: true,
- },
- }
-
- apiGroup := group.Group("/environments/:id/containers")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.GET("/counts", handler.GetContainerStatusCounts)
- apiGroup.GET("", handler.List)
- apiGroup.POST("", handler.Create)
- apiGroup.GET("/:containerId", handler.GetByID)
- apiGroup.GET("/:containerId/stats/ws", handler.GetStatsWS)
- apiGroup.POST("/:containerId/start", handler.Start)
- apiGroup.POST("/:containerId/stop", handler.Stop)
- apiGroup.POST("/:containerId/restart", handler.Restart)
- apiGroup.GET("/:containerId/logs/ws", handler.GetLogsWS)
- apiGroup.GET("/:containerId/exec/ws", handler.GetExecWS)
- apiGroup.DELETE("/:containerId", handler.Delete)
-
- }
-}
-
-type containerLogStream struct {
- hub *ws.Hub
- cancel context.CancelFunc
- format string
- seq atomic.Uint64
-}
-
-func (h *ContainerHandler) getOrStartContainerLogHub(containerID, format string, batched bool, follow bool, tail, since string, timestamps bool) *ws.Hub {
- // Create a new hub for each connection to ensure every client gets historical logs
- ls := &containerLogStream{
- hub: ws.NewHub(1024),
- format: format,
- }
-
- ctx, cancel := context.WithCancel(context.Background())
- ls.cancel = cancel
-
- ls.hub.SetOnEmpty(func() {
- slog.Debug("client disconnected, cleaning up log hub", "containerID", containerID, "format", format, "tail", tail)
- cancel()
- })
-
- go ls.hub.Run(ctx)
-
- slog.Debug("starting log stream pipeline", "containerID", containerID, "format", format, "batched", batched)
-
- lines := make(chan string, 256)
- go func() {
- defer func() {
- close(lines)
- slog.Debug("lines channel closed", "containerID", containerID)
- }()
-
- if err := h.containerService.StreamLogs(ctx, containerID, lines, follow, tail, since, timestamps); err != nil {
- slog.Error("StreamLogs failed", "containerID", containerID, "err", err)
- }
- }()
-
- if format == "json" {
- msgs := make(chan ws.LogMessage, 256)
- go func() {
- defer func() {
- close(msgs)
- slog.Debug("msgs channel closed", "containerID", containerID)
- }()
- lineCount := 0
- for line := range lines {
- lineCount++
- level, msg, ts := ws.NormalizeContainerLine(line)
- seq := ls.seq.Add(1)
- timestamp := ts
- if timestamp == "" {
- timestamp = ws.NowRFC3339()
- }
- msgs <- ws.LogMessage{
- Seq: seq,
- Level: level,
- Message: msg,
- Timestamp: timestamp,
- }
- }
- }()
- if batched {
- go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
- } else {
- go ws.ForwardLogJSON(ctx, ls.hub, msgs)
- }
- } else {
- cleanChan := make(chan string, 256)
- go func() {
- defer close(cleanChan)
- for line := range lines {
- _, msg, _ := ws.NormalizeContainerLine(line)
- cleanChan <- msg
- }
- }()
- go ws.ForwardLines(ctx, ls.hub, cleanChan)
- }
-
- return ls.hub
-}
-
-// GetLogsWS godoc
-//
-// @Summary Get container logs via WebSocket
-// @Description Stream container logs over WebSocket connection
-// @Tags Containers
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Param follow query bool false "Follow log output" default(true)
-// @Param tail query string false "Number of lines to show from the end" default(100)
-// @Param since query string false "Show logs since timestamp"
-// @Param timestamps query bool false "Show timestamps" default(true)
-// @Param format query string false "Output format (text or json)" default(text)
-// @Param batched query bool false "Batch log messages" default(false)
-// @Router /api/environments/{id}/containers/{containerId}/logs/ws [get]
-//
-// GET /api/containers/:id/logs/ws
-// /api/environments/:envId/containers/:containerId/logs/ws
-func (h *ContainerHandler) GetLogsWS(c *gin.Context) {
- containerID := c.Param("containerId")
- if containerID == "" {
- containerID = c.Param("id")
- }
- if strings.TrimSpace(containerID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.ContainerIDRequiredError{}).Error()}})
- return
- }
-
- follow := c.DefaultQuery("follow", "true") == "true"
- tail := c.DefaultQuery("tail", "100")
- since := c.Query("since")
- timestamps := c.DefaultQuery("timestamps", "true") == "true"
- format := c.DefaultQuery("format", "text")
- batched := c.DefaultQuery("batched", "false") == "true"
-
- conn, err := h.containerWSUpgrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- slog.Error("Failed to upgrade websocket connection", "err", err)
- return
- }
-
- slog.Debug("websocket connection upgraded", "containerID", containerID)
-
- hub := h.getOrStartContainerLogHub(containerID, format, batched, follow, tail, since, timestamps)
- ws.ServeClient(context.Background(), hub, conn)
- slog.Debug("websocket connection closed", "containerID", containerID)
-}
-
-// GetExecWS godoc
-//
-// @Summary Execute command in container via WebSocket
-// @Description Open an interactive shell session in a container over WebSocket
-// @Tags Containers
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Param shell query string false "Shell to use" default(/bin/sh)
-// @Router /api/environments/{id}/containers/{containerId}/exec/ws [get]
-//
-// GET /api/environments/:id/containers/:containerId/exec/ws
-func (h *ContainerHandler) GetExecWS(c *gin.Context) {
- containerID := c.Param("containerId")
- if strings.TrimSpace(containerID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.ContainerIDRequiredError{}).Error()}})
- return
- }
-
- shell := c.DefaultQuery("shell", "/bin/sh")
-
- conn, err := h.containerWSUpgrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.WebSocketUpgradeError{Err: err}).Error()}})
- return
- }
- defer conn.Close()
-
- ctx, cancel := context.WithCancel(c.Request.Context())
- defer cancel()
-
- execID, err := h.containerService.CreateExec(ctx, containerID, []string{shell})
- if err != nil {
- _ = conn.WriteMessage(websocket.TextMessage, []byte((&common.ExecCreationError{Err: err}).Error()+"\r\n"))
- return
- }
-
- stdin, stdout, err := h.containerService.AttachExec(ctx, execID)
- if err != nil {
- _ = conn.WriteMessage(websocket.TextMessage, []byte((&common.ExecAttachError{Err: err}).Error()+"\r\n"))
- return
- }
- defer func() {
- if closeErr := stdin.Close(); closeErr != nil {
- _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("Error closing stdin: %v\r\n", closeErr)))
- }
- }()
-
- done := make(chan struct{})
- readErr := make(chan error, 1)
- writeErr := make(chan error, 1)
-
- go h.execOutputPump(ctx, stdout, conn, done, writeErr)
- go h.execInputPump(stdin, conn, cancel, readErr, writeErr)
-
- h.waitForExecCompletion(conn, done, readErr, writeErr, ctx)
-}
-
-func (h *ContainerHandler) execOutputPump(ctx context.Context, stdout io.Reader, conn *websocket.Conn, done chan struct{}, writeErr chan error) {
- defer close(done)
- buf := make([]byte, 8192)
- for {
- select {
- case <-ctx.Done():
- return
- default:
- n, err := stdout.Read(buf)
- if n > 0 {
- if err := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); err != nil {
- select {
- case writeErr <- err:
- default:
- }
- return
- }
- }
- if err != nil {
- if err != io.EOF {
- select {
- case writeErr <- err:
- default:
- }
- }
- return
- }
- }
- }
-}
-
-func (h *ContainerHandler) execInputPump(stdin io.WriteCloser, conn *websocket.Conn, cancel context.CancelFunc, readErr, writeErr chan error) {
- for {
- messageType, data, err := conn.ReadMessage()
- if err != nil {
- if !websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
- select {
- case readErr <- fmt.Errorf("read message error: %w", err):
- default:
- }
- }
- cancel()
- return
- }
- if messageType == websocket.BinaryMessage || messageType == websocket.TextMessage {
- if _, err := stdin.Write(data); err != nil {
- select {
- case writeErr <- fmt.Errorf("stdin write error: %w", err):
- default:
- }
- return
- }
- }
- }
-}
-
-func (h *ContainerHandler) waitForExecCompletion(conn *websocket.Conn, done chan struct{}, readErr, writeErr chan error, ctx context.Context) {
- select {
- case <-done:
- case err := <-readErr:
- if err != nil {
- _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("\r\nRead error: %v\r\n", err)))
- }
- case err := <-writeErr:
- if err != nil {
- _ = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("\r\nWrite error: %v\r\n", err)))
- }
- case <-ctx.Done():
- }
-}
-
-// List godoc
-//
-// @Summary List containers
-// @Description Get a paginated list of Docker containers
-// @Tags Containers
-// @Param id path string true "Environment ID"
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[container.Summary]
-// @Router /api/environments/{id}/containers [get]
-func (h *ContainerHandler) List(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- if params.Limit == 0 {
- params.Limit = 20
- }
-
- includeAll := true
-
- containers, paginationResp, err := h.containerService.ListContainersPaginated(c.Request.Context(), params, includeAll)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerListError{Err: err}).Error()},
- })
- return
- }
-
- pagination.ApplyFilterResultsHeaders(&c.Writer, pagination.FilterResult[containertypes.Summary]{
- Items: containers,
- TotalCount: paginationResp.TotalItems,
- TotalAvailable: paginationResp.GrandTotalItems,
- })
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": containers,
- "pagination": paginationResp,
- })
-}
-
-// GetByID godoc
-//
-// @Summary Get container by ID
-// @Description Get detailed information about a Docker container
-// @Tags Containers
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Success 200 {object} base.ApiResponse[container.Details]
-// @Router /api/environments/{id}/containers/{containerId} [get]
-func (h *ContainerHandler) GetByID(c *gin.Context) {
- id := c.Param("containerId")
-
- container, err := h.containerService.GetContainerByID(c.Request.Context(), id)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerRetrievalError{Err: err}).Error()},
- })
- return
- }
-
- details := containertypes.NewDetails(container)
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": details,
- })
-}
-
-// Start godoc
-//
-// @Summary Start a container
-// @Description Start a stopped Docker container
-// @Tags Containers
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/containers/{containerId}/start [post]
-func (h *ContainerHandler) Start(c *gin.Context) {
- id := c.Param("containerId")
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
- if err := h.containerService.StartContainer(c.Request.Context(), id, *currentUser); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerStartError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Container started successfully"},
- })
-}
-
-// Stop godoc
-//
-// @Summary Stop a container
-// @Description Stop a running Docker container
-// @Tags Containers
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/containers/{containerId}/stop [post]
-func (h *ContainerHandler) Stop(c *gin.Context) {
- id := c.Param("containerId")
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
- if err := h.containerService.StopContainer(c.Request.Context(), id, *currentUser); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerStopError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Container stopped successfully"},
- })
-}
-
-// Restart godoc
-//
-// @Summary Restart a container
-// @Description Restart a Docker container
-// @Tags Containers
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/containers/{containerId}/restart [post]
-func (h *ContainerHandler) Restart(c *gin.Context) {
- id := c.Param("containerId")
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
- if err := h.containerService.RestartContainer(c.Request.Context(), id, *currentUser); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerRestartError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Container restarted successfully"},
- })
-}
-
-// Delete godoc
-//
-// @Summary Delete a container
-// @Description Delete a Docker container
-// @Tags Containers
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Param force query bool false "Force removal of running container"
-// @Param volumes query bool false "Remove associated volumes"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/containers/{containerId} [delete]
-func (h *ContainerHandler) Delete(c *gin.Context) {
- id := c.Param("containerId")
- force := c.Query("force") == "true"
- removeVolumes := c.Query("volumes") == "true"
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
- if err := h.containerService.DeleteContainer(c.Request.Context(), id, force, removeVolumes, *currentUser); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerDeleteError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Container deleted successfully"},
- })
-}
-
-// GetContainerStatusCounts godoc
-//
-// @Summary Get container status counts
-// @Description Get counts of running, stopped, and total containers
-// @Tags Containers
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[container.StatusCounts]
-// @Router /api/environments/{id}/containers/counts [get]
-func (h *ContainerHandler) GetContainerStatusCounts(c *gin.Context) {
- _, running, stopped, total, err := h.dockerService.GetAllContainers(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerStatusCountsError{Err: err}).Error()},
- })
- return
- }
-
- out := containertypes.StatusCounts{
- RunningContainers: running,
- StoppedContainers: stopped,
- TotalContainers: total,
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// Create godoc
-//
-// @Summary Create a container
-// @Description Create a new Docker container
-// @Tags Containers
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param container body container.Create true "Container creation data"
-// @Success 201 {object} base.ApiResponse[container.Created]
-// @Router /api/environments/{id}/containers [post]
-func (h *ContainerHandler) Create(c *gin.Context) {
- var req containertypes.Create
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- config := &container.Config{
- Image: req.Image,
- Cmd: req.Command,
- Entrypoint: req.Entrypoint,
- WorkingDir: req.WorkingDir,
- User: req.User,
- Env: req.Environment,
- ExposedPorts: make(nat.PortSet),
- Labels: map[string]string{
- "com.arcane.created": "true",
- },
- }
-
- portBindings := make(nat.PortMap)
- for containerPort, hostPort := range req.Ports {
- port, err := nat.NewPort("tcp", containerPort)
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidPortFormatError{Err: err}).Error()},
- })
- return
- }
- config.ExposedPorts[port] = struct{}{}
- portBindings[port] = []nat.PortBinding{
- {
- HostPort: hostPort,
- },
- }
- }
-
- hostConfig := &container.HostConfig{
- Binds: req.Volumes,
- PortBindings: portBindings,
- Privileged: req.Privileged,
- AutoRemove: req.AutoRemove,
- RestartPolicy: container.RestartPolicy{
- Name: container.RestartPolicyMode(req.RestartPolicy),
- },
- }
-
- if req.Memory > 0 {
- hostConfig.Memory = req.Memory
- }
- if req.CPUs > 0 {
- hostConfig.NanoCPUs = int64(req.CPUs * 1000000000)
- }
-
- var networkingConfig *network.NetworkingConfig
- if len(req.Networks) > 0 {
- networkingConfig = &network.NetworkingConfig{
- EndpointsConfig: make(map[string]*network.EndpointSettings),
- }
- for _, networkName := range req.Networks {
- networkingConfig.EndpointsConfig[networkName] = &network.EndpointSettings{}
- }
- }
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
- containerJSON, err := h.containerService.CreateContainer(
- c.Request.Context(),
- config,
- hostConfig,
- networkingConfig,
- req.Name,
- *currentUser,
- req.Credentials,
- )
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ContainerCreationError{Err: err}).Error()},
- })
- return
- }
-
- out := containertypes.Created{
- ID: containerJSON.ID,
- Name: containerJSON.Name,
- Image: containerJSON.Config.Image,
- Status: containerJSON.State.Status,
- Created: containerJSON.Created,
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-type containerStatsStream struct {
- hub *ws.Hub
- once sync.Once
- cancel context.CancelFunc
-}
-
-func (h *ContainerHandler) getOrStartContainerStatsHub(containerID string) *ws.Hub {
- key := fmt.Sprintf("%s::stats", containerID)
- v, _ := h.statsStreams.LoadOrStore(key, &containerStatsStream{
- hub: ws.NewHub(1024),
- })
- ss := v.(*containerStatsStream)
-
- ss.once.Do(func() {
- ctx, cancel := context.WithCancel(context.Background())
- ss.cancel = cancel
-
- ss.hub.SetOnEmpty(func() {
- slog.Debug("all clients disconnected, cleaning up stats hub", "containerID", containerID)
- cancel()
- h.statsStreams.Delete(key)
- })
-
- go ss.hub.Run(ctx)
-
- slog.Debug("starting stats stream pipeline", "containerID", containerID)
-
- statsChan := make(chan interface{}, 256)
- go func() {
- defer func() {
- close(statsChan)
- slog.Debug("stats channel closed", "containerID", containerID)
- }()
-
- if err := h.containerService.StreamStats(ctx, containerID, statsChan); err != nil {
- slog.Error("StreamStats failed", "containerID", containerID, "err", err)
- }
- }()
-
- go func() {
- for {
- select {
- case <-ctx.Done():
- return
- case stats, ok := <-statsChan:
- if !ok {
- return
- }
- if b, err := json.Marshal(stats); err == nil {
- ss.hub.Broadcast(b)
- }
- }
- }
- }()
- })
-
- return ss.hub
-}
-
-// GetStatsWS godoc
-//
-// @Summary Get container stats via WebSocket
-// @Description Stream container resource statistics over WebSocket connection
-// @Tags Containers
-// @Param id path string true "Environment ID"
-// @Param containerId path string true "Container ID"
-// @Router /api/environments/{id}/containers/{containerId}/stats/ws [get]
-func (h *ContainerHandler) GetStatsWS(c *gin.Context) {
- containerID := c.Param("containerId")
- if containerID == "" {
- containerID = c.Param("id")
- }
- if strings.TrimSpace(containerID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.ContainerIDRequiredError{}).Error()}})
- return
- }
-
- conn, err := h.containerWSUpgrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- slog.Error("Failed to upgrade websocket connection", "err", err)
- return
- }
-
- slog.Debug("websocket connection upgraded for stats", "containerID", containerID)
-
- hub := h.getOrStartContainerStatsHub(containerID)
- ws.ServeClient(context.Background(), hub, conn)
- slog.Debug("websocket connection closed for stats", "containerID", containerID)
-}
diff --git a/backend/internal/api/container_registry_handler.go b/backend/internal/api/container_registry_handler.go
deleted file mode 100644
index 8e33517d2..000000000
--- a/backend/internal/api/container_registry_handler.go
+++ /dev/null
@@ -1,340 +0,0 @@
-package api
-
-import (
- "context"
- "fmt"
- "net/http"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- registry "github.com/getarcaneapp/arcane/backend/internal/utils/registry"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/containerregistry"
-)
-
-type ContainerRegistryHandler struct {
- registryService *services.ContainerRegistryService
-}
-
-func NewContainerRegistryHandler(group *gin.RouterGroup, registryService *services.ContainerRegistryService, authMiddleware *middleware.AuthMiddleware) {
- handler := &ContainerRegistryHandler{registryService: registryService}
-
- apiGroup := group.Group("/container-registries")
-
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.GET("", handler.GetRegistries)
- apiGroup.POST("", handler.CreateRegistry)
- apiGroup.POST("/sync", handler.SyncRegistries)
- apiGroup.GET("/:id", handler.GetRegistry)
- apiGroup.PUT("/:id", handler.UpdateRegistry)
- apiGroup.DELETE("/:id", handler.DeleteRegistry)
- apiGroup.POST("/:id/test", handler.TestRegistry)
- }
-}
-
-// GetRegistries godoc
-//
-// @Summary List container registries
-// @Description Get a paginated list of container registries
-// @Tags Container Registries
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[containerregistry.Response]
-// @Router /api/container-registries [get]
-func (h *ContainerRegistryHandler) GetRegistries(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- registries, paginationResp, err := h.registryService.GetRegistriesPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryListError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": registries,
- "pagination": paginationResp,
- })
-}
-
-// GetRegistry godoc
-//
-// @Summary Get a container registry
-// @Description Get a container registry by ID
-// @Tags Container Registries
-// @Param id path string true "Registry ID"
-// @Success 200 {object} base.ApiResponse[containerregistry.Response]
-// @Router /api/container-registries/{id} [get]
-func (h *ContainerRegistryHandler) GetRegistry(c *gin.Context) {
- id := c.Param("id")
-
- registry, err := h.registryService.GetRegistryByID(c.Request.Context(), id)
- if err != nil {
- apiErr := models.ToAPIError(err)
- c.JSON(apiErr.HTTPStatus(), gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryRetrievalError{Err: err}).Error()},
- })
- return
- }
-
- out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.Response](registry)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryMappingError{Err: mapErr}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// CreateRegistry godoc
-//
-// @Summary Create a container registry
-// @Description Create a new container registry
-// @Tags Container Registries
-// @Accept json
-// @Produce json
-// @Param registry body models.CreateContainerRegistryRequest true "Registry creation data"
-// @Success 201 {object} base.ApiResponse[containerregistry.Response]
-// @Router /api/container-registries [post]
-func (h *ContainerRegistryHandler) CreateRegistry(c *gin.Context) {
- var req models.CreateContainerRegistryRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- registry, err := h.registryService.CreateRegistry(c.Request.Context(), req)
- if err != nil {
- apiErr := models.ToAPIError(err)
- c.JSON(apiErr.HTTPStatus(), gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryCreationError{Err: err}).Error()},
- })
- return
- }
-
- out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.Response](registry)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryMappingError{Err: mapErr}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// UpdateRegistry godoc
-//
-// @Summary Update a container registry
-// @Description Update an existing container registry
-// @Tags Container Registries
-// @Accept json
-// @Produce json
-// @Param id path string true "Registry ID"
-// @Param registry body models.UpdateContainerRegistryRequest true "Registry update data"
-// @Success 200 {object} base.ApiResponse[containerregistry.Response]
-// @Router /api/container-registries/{id} [put]
-func (h *ContainerRegistryHandler) UpdateRegistry(c *gin.Context) {
- id := c.Param("id")
-
- var req models.UpdateContainerRegistryRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- registry, err := h.registryService.UpdateRegistry(c.Request.Context(), id, req)
- if err != nil {
- apiErr := models.ToAPIError(err)
- c.JSON(apiErr.HTTPStatus(), gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryUpdateError{Err: err}).Error()},
- })
- return
- }
-
- out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.Response](registry)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryMappingError{Err: mapErr}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// DeleteRegistry godoc
-//
-// @Summary Delete a container registry
-// @Description Delete a container registry by ID
-// @Tags Container Registries
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Registry ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/container-registries/{id} [delete]
-func (h *ContainerRegistryHandler) DeleteRegistry(c *gin.Context) {
- id := c.Param("id")
-
- if err := h.registryService.DeleteRegistry(c.Request.Context(), id); err != nil {
- apiErr := models.ToAPIError(err)
- c.JSON(apiErr.HTTPStatus(), gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryDeletionError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Container registry deleted successfully"},
- })
-}
-
-// TestRegistry godoc
-//
-// @Summary Test a container registry
-// @Description Test connectivity and authentication to a container registry
-// @Tags Container Registries
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Registry ID"
-// @Success 200 {object} base.ApiResponse[containerregistry.TestResult]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/container-registries/{id}/test [post]
-func (h *ContainerRegistryHandler) TestRegistry(c *gin.Context) {
- id := c.Param("id")
-
- registry, err := h.registryService.GetRegistryByID(c.Request.Context(), id)
- if err != nil {
- apiErr := models.ToAPIError(err)
- c.JSON(apiErr.HTTPStatus(), gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryRetrievalError{Err: err}).Error()},
- })
- return
- }
-
- decryptedToken, err := utils.Decrypt(registry.Token)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TokenDecryptionError{Err: err}).Error()},
- })
- return
- }
-
- testResult, err := h.performRegistryTest(c.Request.Context(), registry, decryptedToken)
- if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": false,
- "data": gin.H{"message": (&common.RegistryTestError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": testResult,
- })
-}
-
-// SyncRegistries godoc
-//
-// @Summary Sync container registries
-// @Description Sync container registries from a remote source
-// @Tags Container Registries
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param request body containerregistry.SyncRequest true "Registries to sync"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/container-registries/sync [post]
-func (h *ContainerRegistryHandler) SyncRegistries(c *gin.Context) {
- var req containerregistry.SyncRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- if err := h.registryService.SyncRegistries(c.Request.Context(), req.Registries); err != nil {
- apiErr := models.ToAPIError(err)
- c.JSON(apiErr.HTTPStatus(), gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistrySyncError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Registries synced successfully"},
- })
-}
-
-func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, registryModel *models.ContainerRegistry, decryptedToken string) (map[string]interface{}, error) {
- var creds *registry.Credentials
- if registryModel.Username != "" && decryptedToken != "" {
- creds = &registry.Credentials{
- Username: registryModel.Username,
- Token: decryptedToken,
- }
- }
-
- testResult, err := registry.TestRegistryConnection(ctx, registryModel.URL, creds)
- if err != nil {
- return nil, err
- }
-
- if !testResult.AuthSuccess {
- if len(testResult.Errors) > 0 {
- return nil, fmt.Errorf("%s", testResult.Errors[0])
- }
- return nil, fmt.Errorf("invalid credentials")
- }
-
- return map[string]interface{}{
- "message": "Authentication succeeded",
- }, nil
-}
diff --git a/backend/internal/api/customize_handler.go b/backend/internal/api/customize_handler.go
deleted file mode 100644
index b8de80b6f..000000000
--- a/backend/internal/api/customize_handler.go
+++ /dev/null
@@ -1,75 +0,0 @@
-package api
-
-import (
- "net/http"
- "strings"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/search"
-)
-
-type CustomizeHandler struct {
- customizeSearchService *services.CustomizeSearchService
-}
-
-func NewCustomizeHandler(group *gin.RouterGroup, customizeSearchService *services.CustomizeSearchService, authMiddleware *middleware.AuthMiddleware) {
- handler := &CustomizeHandler{
- customizeSearchService: customizeSearchService,
- }
-
- // Expose customize search and categories endpoints under /api/customize
- apiGroup := group.Group("/customize")
- apiGroup.POST("/search", authMiddleware.WithAdminNotRequired().Add(), handler.Search)
- apiGroup.GET("/categories", authMiddleware.WithAdminNotRequired().Add(), handler.GetCategories)
-}
-
-// Search godoc
-//
-// @Summary Search customization options
-// @Description Search customization categories and options by query
-// @Tags Customize
-// @Accept json
-// @Produce json
-// @Param request body search.Request true "Search query"
-// @Success 200 {object} search.Response
-// @Router /api/customize/search [post]
-//
-// Search delegates to the customize search service and returns relevance-scored results
-func (h *CustomizeHandler) Search(c *gin.Context) {
- var req search.Request
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- if strings.TrimSpace(req.Query) == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.QueryParameterRequiredError{}).Error()},
- })
- return
- }
-
- results := h.customizeSearchService.Search(req.Query)
- c.JSON(http.StatusOK, results)
-}
-
-// GetCategories godoc
-//
-// @Summary Get customization categories
-// @Description Get all available customization categories with metadata
-// @Tags Customize
-// @Success 200 {array} search.Category
-// @Router /api/customize/categories [get]
-//
-// GetCategories returns all available customization categories with metadata
-func (h *CustomizeHandler) GetCategories(c *gin.Context) {
- categories := h.customizeSearchService.GetCustomizeCategories()
- c.JSON(http.StatusOK, categories)
-}
diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.go
deleted file mode 100644
index 4c8668116..000000000
--- a/backend/internal/api/environment_handler.go
+++ /dev/null
@@ -1,527 +0,0 @@
-package api
-
-import (
- "context"
- "log/slog"
- "net/http"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/environment"
-)
-
-const LOCAL_DOCKER_ENVIRONMENT_ID = "0"
-
-type EnvironmentHandler struct {
- environmentService *services.EnvironmentService
- settingsService *services.SettingsService
- cfg *config.Config
- httpClient *http.Client
-}
-
-func NewEnvironmentHandler(
- group *gin.RouterGroup,
- environmentService *services.EnvironmentService,
- settingsService *services.SettingsService,
- authMiddleware *middleware.AuthMiddleware,
- cfg *config.Config,
-) {
- h := &EnvironmentHandler{
- environmentService: environmentService,
- settingsService: settingsService,
- cfg: cfg,
- httpClient: &http.Client{
- Timeout: 30 * time.Second,
- },
- }
-
- apiGroup := group.Group("/environments")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.GET("", h.ListEnvironments)
- apiGroup.POST("", h.CreateEnvironment)
- apiGroup.GET("/:id", h.GetEnvironment)
- apiGroup.PUT("/:id", h.UpdateEnvironment)
- apiGroup.DELETE("/:id", h.DeleteEnvironment)
- apiGroup.POST("/:id/test", h.TestConnection)
- apiGroup.POST("/:id/heartbeat", h.UpdateHeartbeat)
- apiGroup.POST("/:id/agent/pair", h.PairAgent)
- apiGroup.POST("/:id/sync-registries", h.SyncRegistries)
- }
-}
-
-// PairAgent godoc
-//
-// @Summary Pair with local agent
-// @Description Generate or rotate the local agent pairing token
-// @Tags Environments
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID (must be 0 for local)"
-// @Param request body environment.AgentPairRequest false "Pair request with optional rotate flag"
-// @Success 200 {object} base.ApiResponse[environment.AgentPairResponse]
-// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/agent/pair [post]
-func (h *EnvironmentHandler) PairAgent(c *gin.Context) {
- if c.Param("id") != LOCAL_DOCKER_ENVIRONMENT_ID {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Not found"}})
- return
- }
- type pairReq struct {
- Rotate *bool `json:"rotate,omitempty"`
- }
- var req pairReq
- _ = c.ShouldBindJSON(&req)
-
- if h.cfg.AgentToken == "" || (req.Rotate != nil && *req.Rotate) {
- h.cfg.AgentToken = utils.GenerateRandomString(48)
- }
-
- // Persist token on the agent so it survives restarts
- if err := h.settingsService.SetStringSetting(c.Request.Context(), "agentToken", h.cfg.AgentToken); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.AgentTokenPersistenceError{Err: err}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "token": h.cfg.AgentToken,
- },
- })
-}
-
-// CreateEnvironment godoc
-//
-// @Summary Create an environment
-// @Description Create a new Docker environment
-// @Tags Environments
-// @Accept json
-// @Produce json
-// @Param environment body environment.Create true "Environment creation data"
-// @Success 201 {object} base.ApiResponse[environment.Response]
-// @Router /api/environments [post]
-//
-// Create
-func (h *EnvironmentHandler) CreateEnvironment(c *gin.Context) {
- var req environment.Create
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- env := &models.Environment{
- ApiUrl: req.ApiUrl,
- Enabled: true,
- }
- if req.Name != nil {
- env.Name = *req.Name
- }
- if req.Enabled != nil {
- env.Enabled = *req.Enabled
- }
-
- if (req.AccessToken == nil || *req.AccessToken == "") && req.BootstrapToken != nil && *req.BootstrapToken != "" {
- token, err := h.environmentService.PairAgentWithBootstrap(c.Request.Context(), req.ApiUrl, *req.BootstrapToken)
- if err != nil {
- slog.ErrorContext(c.Request.Context(), "Failed to pair with agent",
- "apiUrl", req.ApiUrl,
- "error", err.Error())
-
- c.JSON(http.StatusBadGateway, gin.H{
- "success": false,
- "data": gin.H{
- "error": (&common.AgentPairingError{Err: err}).Error(),
- "hint": "Ensure the agent is running and the bootstrap token matches AGENT_BOOTSTRAP_TOKEN",
- },
- })
- return
- }
- env.AccessToken = &token
- } else if req.AccessToken != nil && *req.AccessToken != "" {
- env.AccessToken = req.AccessToken
- }
-
- created, err := h.environmentService.CreateEnvironment(c.Request.Context(), env)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentCreationError{Err: err}).Error()}})
- return
- }
-
- // Sync registries to the new environment in the background
- if created.AccessToken != nil && *created.AccessToken != "" {
- go func() {
- ctx := context.Background()
- if err := h.environmentService.SyncRegistriesToEnvironment(ctx, created.ID); err != nil {
- slog.WarnContext(ctx, "Failed to sync registries to new environment",
- "environmentID", created.ID,
- "environmentName", created.Name,
- "error", err.Error())
- } else {
- slog.InfoContext(ctx, "Successfully synced registries to new environment",
- "environmentID", created.ID,
- "environmentName", created.Name)
- }
- }()
- }
-
- out, mapErr := mapper.MapOne[*models.Environment, environment.Response](created)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{"success": true, "data": out})
-}
-
-// ListEnvironments godoc
-//
-// @Summary List environments
-// @Description Get a paginated list of Docker environments
-// @Tags Environments
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[environment.Response]
-// @Router /api/environments [get]
-func (h *EnvironmentHandler) ListEnvironments(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- envs, paginationResp, err := h.environmentService.ListEnvironmentsPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentListError{Err: err}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": envs,
- "pagination": paginationResp,
- })
-}
-
-// GetEnvironment godoc
-//
-// @Summary Get an environment
-// @Description Get a Docker environment by ID
-// @Tags Environments
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[environment.Response]
-// @Router /api/environments/{id} [get]
-//
-// Get by ID
-func (h *EnvironmentHandler) GetEnvironment(c *gin.Context) {
- environmentID := c.Param("id")
-
- env, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentNotFoundError{}).Error()}})
- return
- }
-
- out, mapErr := mapper.MapOne[*models.Environment, environment.Response](env)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// UpdateEnvironment godoc
-//
-// @Summary Update an environment
-// @Description Update a Docker environment
-// @Tags Environments
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param environment body environment.Update true "Environment update data"
-// @Success 200 {object} base.ApiResponse[environment.Response]
-// @Router /api/environments/{id} [put]
-//
-// Update
-func (h *EnvironmentHandler) UpdateEnvironment(c *gin.Context) {
- environmentID := c.Param("id")
- isLocalEnv := environmentID == LOCAL_DOCKER_ENVIRONMENT_ID
-
- var req environment.Update
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- updates := h.buildUpdateMapInternal(&req, isLocalEnv)
-
- pairingSucceeded, err := h.handleEnvironmentPairingInternal(c.Request.Context(), environmentID, &req, updates, isLocalEnv)
- if err != nil {
- c.JSON(err.statusCode, gin.H{"success": false, "data": gin.H{"error": err.message}})
- return
- }
-
- updated, updateErr := h.environmentService.UpdateEnvironment(c.Request.Context(), environmentID, updates)
- if updateErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentUpdateError{Err: updateErr}).Error()}})
- return
- }
-
- h.triggerPostUpdateTasksInternal(environmentID, updated, pairingSucceeded, &req)
-
- out, mapErr := mapper.MapOne[*models.Environment, environment.Response](updated)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
-}
-
-func (h *EnvironmentHandler) buildUpdateMapInternal(req *environment.Update, isLocalEnv bool) map[string]any {
- updates := map[string]any{}
-
- // For local environment, only allow name
- if !isLocalEnv {
- if req.ApiUrl != nil {
- updates["api_url"] = *req.ApiUrl
- }
- if req.Enabled != nil {
- updates["enabled"] = *req.Enabled
- }
- }
-
- if req.Name != nil {
- updates["name"] = *req.Name
- }
-
- return updates
-}
-
-type updateError struct {
- statusCode int
- message string
-}
-
-func (h *EnvironmentHandler) handleEnvironmentPairingInternal(ctx context.Context, environmentID string, req *environment.Update, updates map[string]any, isLocalEnv bool) (bool, *updateError) {
- pairingSucceeded := false
-
- // Local environment cannot be paired or have access token updated
- if isLocalEnv {
- return pairingSucceeded, nil
- }
-
- // If caller asked to pair (bootstrapToken present) and no accessToken provided in the request,
- // resolve apiUrl (current or updated) and let the service pair and persist the token.
- if (req.AccessToken == nil) && req.BootstrapToken != nil && *req.BootstrapToken != "" {
- current, err := h.environmentService.GetEnvironmentByID(ctx, environmentID)
- if err != nil || current == nil {
- return false, &updateError{
- statusCode: http.StatusNotFound,
- message: "Environment not found",
- }
- }
-
- apiUrl := current.ApiUrl
- if req.ApiUrl != nil && *req.ApiUrl != "" {
- apiUrl = *req.ApiUrl
- }
-
- if _, err := h.environmentService.PairAndPersistAgentToken(ctx, environmentID, apiUrl, *req.BootstrapToken); err != nil {
- return false, &updateError{
- statusCode: http.StatusBadGateway,
- message: "Agent pairing failed: " + err.Error(),
- }
- }
- pairingSucceeded = true
- } else if req.AccessToken != nil {
- updates["access_token"] = *req.AccessToken
- }
-
- return pairingSucceeded, nil
-}
-
-func (h *EnvironmentHandler) triggerPostUpdateTasksInternal(environmentID string, updated *models.Environment, pairingSucceeded bool, req *environment.Update) {
- // Trigger health check after update to verify new configuration
- // This runs in background and doesn't block the response
- if updated.Enabled {
- go func() {
- ctx := context.Background()
- status, err := h.environmentService.TestConnection(ctx, environmentID, nil)
- if err != nil {
- slog.WarnContext(ctx, "Failed to test connection after environment update", "environment_id", environmentID, "environment_name", updated.Name, "status", status, "error", err)
- } else {
- slog.InfoContext(ctx, "Environment health check completed after update", "environment_id", environmentID, "environment_name", updated.Name, "status", status)
- }
- }()
- }
-
- // Sync registries if pairing succeeded or if access token was updated
- if pairingSucceeded || (req.AccessToken != nil && *req.AccessToken != "") {
- go func() {
- ctx := context.Background()
- if err := h.environmentService.SyncRegistriesToEnvironment(ctx, environmentID); err != nil {
- slog.WarnContext(ctx, "Failed to sync registries after environment update",
- "environmentID", environmentID,
- "environmentName", updated.Name,
- "error", err.Error())
- } else {
- slog.InfoContext(ctx, "Successfully synced registries after environment update",
- "environmentID", environmentID,
- "environmentName", updated.Name)
- }
- }()
- }
-}
-
-// DeleteEnvironment godoc
-//
-// @Summary Delete an environment
-// @Description Delete a Docker environment
-// @Tags Environments
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id} [delete]
-//
-// Delete
-func (h *EnvironmentHandler) DeleteEnvironment(c *gin.Context) {
- environmentID := c.Param("id")
-
- // Prevent deletion of local environment
- if environmentID == LOCAL_DOCKER_ENVIRONMENT_ID {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.LocalEnvironmentDeletionError{}).Error()}})
- return
- }
-
- err := h.environmentService.DeleteEnvironment(c.Request.Context(), environmentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.EnvironmentDeletionError{Err: err}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Environment deleted successfully"},
- })
-}
-
-// TestConnection godoc
-//
-// @Summary Test environment connection
-// @Description Test connectivity to a Docker environment
-// @Tags Environments
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param request body object false "Optional API URL to test"
-// @Success 200 {object} base.ApiResponse[environment.Test]
-// @Router /api/environments/{id}/test [post]
-//
-// TestConnection
-func (h *EnvironmentHandler) TestConnection(c *gin.Context) {
- environmentID := c.Param("id")
-
- // Allow optional apiUrl in request body to test without saving
- var req struct {
- ApiUrl *string `json:"apiUrl"`
- }
- _ = c.ShouldBindJSON(&req)
-
- status, err := h.environmentService.TestConnection(c.Request.Context(), environmentID, req.ApiUrl)
- resp := environment.Test{Status: status}
- if err != nil {
- msg := err.Error()
- resp.Message = &msg
- c.JSON(http.StatusServiceUnavailable, gin.H{
- "success": false,
- "data": resp,
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": resp,
- })
-}
-
-// UpdateHeartbeat godoc
-//
-// @Summary Update environment heartbeat
-// @Description Update the heartbeat timestamp for an environment
-// @Tags Environments
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/heartbeat [post]
-func (h *EnvironmentHandler) UpdateHeartbeat(c *gin.Context) {
- environmentID := c.Param("id")
-
- err := h.environmentService.UpdateEnvironmentHeartbeat(c.Request.Context(), environmentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.HeartbeatUpdateError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Heartbeat updated successfully",
- })
-}
-
-// SyncRegistries godoc
-//
-// @Summary Sync container registries
-// @Description Sync container registries to a remote environment
-// @Tags Environments
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/sync-registries [post]
-func (h *EnvironmentHandler) SyncRegistries(c *gin.Context) {
- environmentID := c.Param("id")
-
- err := h.environmentService.SyncRegistriesToEnvironment(c.Request.Context(), environmentID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistrySyncError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Registries synced successfully"},
- })
-}
diff --git a/backend/internal/api/event_handler.go b/backend/internal/api/event_handler.go
deleted file mode 100644
index 5f3fe418f..000000000
--- a/backend/internal/api/event_handler.go
+++ /dev/null
@@ -1,170 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/event"
-)
-
-type EventHandler struct {
- eventService *services.EventService
-}
-
-func NewEventHandler(group *gin.RouterGroup, eventService *services.EventService, authMiddleware *middleware.AuthMiddleware) {
- handler := &EventHandler{eventService: eventService}
-
- apiGroup := group.Group("/events")
- apiGroup.Use(authMiddleware.WithAdminRequired().Add())
- {
- apiGroup.GET("", handler.ListEvents)
- apiGroup.POST("", handler.CreateEvent)
- apiGroup.DELETE("/:eventId", handler.DeleteEvent)
- apiGroup.GET("/environment/:environmentId", handler.GetEventsByEnvironment)
- }
-}
-
-// ListEvents godoc
-//
-// @Summary List events
-// @Description Get a paginated list of system events
-// @Tags Events
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[event.Event]
-// @Router /api/events [get]
-func (h *EventHandler) ListEvents(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- events, paginationResp, err := h.eventService.ListEventsPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.EventListError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": events,
- "pagination": paginationResp,
- })
-}
-
-// GetEventsByEnvironment godoc
-//
-// @Summary Get events by environment
-// @Description Get a paginated list of events for a specific environment
-// @Tags Events
-// @Param environmentId path string true "Environment ID"
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[event.Event]
-// @Router /api/events/environment/{environmentId} [get]
-func (h *EventHandler) GetEventsByEnvironment(c *gin.Context) {
- environmentID := c.Param("environmentId")
- if environmentID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.EnvironmentIDRequiredError{}).Error()},
- })
- return
- }
-
- params := pagination.ExtractListModifiersQueryParams(c)
-
- events, paginationResp, err := h.eventService.GetEventsByEnvironmentPaginated(c.Request.Context(), environmentID, params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.EventListError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": events,
- "pagination": paginationResp,
- })
-}
-
-// CreateEvent godoc
-//
-// @Summary Create an event
-// @Description Create a new system event
-// @Tags Events
-// @Accept json
-// @Produce json
-// @Param event body event.Create true "Event creation data"
-// @Success 201 {object} base.ApiResponse[event.Event]
-// @Router /api/events [post]
-func (h *EventHandler) CreateEvent(c *gin.Context) {
- var req event.Create
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- event, err := h.eventService.CreateEventFromDto(c.Request.Context(), req)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.EventCreationError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": event,
- })
-}
-
-// DeleteEvent godoc
-//
-// @Summary Delete an event
-// @Description Delete a system event by ID
-// @Tags Events
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param eventId path string true "Event ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/events/{eventId} [delete]
-func (h *EventHandler) DeleteEvent(c *gin.Context) {
- eventID := c.Param("eventId")
- if eventID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.EventIDRequiredError{}).Error()},
- })
- return
- }
-
- if err := h.eventService.DeleteEvent(c.Request.Context(), eventID); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.EventDeletionError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Event deleted successfully"},
- })
-}
diff --git a/backend/internal/api/health_handler.go b/backend/internal/api/health_handler.go
deleted file mode 100644
index f4a9d948f..000000000
--- a/backend/internal/api/health_handler.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/gin-gonic/gin"
-)
-
-func NewHealthHandler(group *gin.RouterGroup) {
-
- group.GET("/health", func(c *gin.Context) {
- c.JSON(http.StatusOK, gin.H{"status": "UP"})
- })
-
- group.HEAD("/health", func(c *gin.Context) {
- c.Status(http.StatusOK)
- })
-}
diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.go
deleted file mode 100644
index 66b25c5d3..000000000
--- a/backend/internal/api/image_handler.go
+++ /dev/null
@@ -1,390 +0,0 @@
-package api
-
-import (
- "context"
- "errors"
- "fmt"
- "io"
- "log/slog"
- "mime/multipart"
- "net/http"
- "strings"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/image"
-)
-
-type ImageHandler struct {
- imageService *services.ImageService
- imageUpdateService *services.ImageUpdateService
- dockerService *services.DockerClientService
- settingsService *services.SettingsService
-}
-
-func NewImageHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, imageService *services.ImageService, imageUpdateService *services.ImageUpdateService, settingsService *services.SettingsService, authMiddleware *middleware.AuthMiddleware) {
- handler := &ImageHandler{dockerService: dockerService, imageService: imageService, imageUpdateService: imageUpdateService, settingsService: settingsService}
-
- apiGroup := group.Group("/environments/:id/images")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.GET("/counts", handler.GetImageUsageCounts)
- apiGroup.GET("", handler.List)
- apiGroup.GET("/:imageId", handler.GetByID)
- apiGroup.DELETE("/:imageId", handler.Remove)
- apiGroup.POST("/pull", handler.Pull)
- apiGroup.POST("/prune", handler.Prune)
- apiGroup.POST("/upload", handler.Upload)
- }
-}
-
-// List godoc
-//
-// @Summary List images
-// @Description Get a paginated list of Docker images
-// @Tags Images
-// @Param id path string true "Environment ID"
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[image.Summary]
-// @Router /api/environments/{id}/images [get]
-func (h *ImageHandler) List(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- if params.Limit == 0 {
- params.Limit = 20
- }
-
- images, paginationResp, err := h.imageService.ListImagesPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ImageListError{Err: err}).Error()},
- })
- return
- }
-
- pagination.ApplyFilterResultsHeaders(&c.Writer, pagination.FilterResult[image.Summary]{
- Items: images,
- TotalCount: paginationResp.TotalItems,
- TotalAvailable: paginationResp.GrandTotalItems,
- })
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": images,
- "pagination": paginationResp,
- })
-}
-
-// GetByID godoc
-//
-// @Summary Get image by ID
-// @Description Get a Docker image by its ID
-// @Tags Images
-// @Param id path string true "Environment ID"
-// @Param imageId path string true "Image ID"
-// @Success 200 {object} base.ApiResponse[image.DetailSummary]
-// @Router /api/environments/{id}/images/{imageId} [get]
-func (h *ImageHandler) GetByID(c *gin.Context) {
- id := c.Param("imageId")
-
- img, err := h.imageService.GetImageByID(c.Request.Context(), id)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": (&common.ImageNotFoundError{Err: err}).Error()}})
- return
- }
-
- out := image.NewDetailSummary(img)
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// Remove godoc
-//
-// @Summary Remove an image
-// @Description Remove a Docker image by ID
-// @Tags Images
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param imageId path string true "Image ID"
-// @Param force query bool false "Force removal"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/images/{imageId} [delete]
-func (h *ImageHandler) Remove(c *gin.Context) {
- id := c.Param("imageId")
- force := c.Query("force") == "true"
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
- if err := h.imageService.RemoveImage(c.Request.Context(), id, force, *currentUser); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ImageRemovalError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Image removed successfully"},
- })
-}
-
-// Pull godoc
-//
-// @Summary Pull an image
-// @Description Pull a Docker image from a registry
-// @Tags Images
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce application/x-json-stream
-// @Param id path string true "Environment ID"
-// @Param request body image.PullOptions true "Image pull request"
-// @Success 200 {string} string "Streaming JSON response"
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/images/pull [post]
-func (h *ImageHandler) Pull(c *gin.Context) {
- ctx := c.Request.Context()
- var req image.PullOptions
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
- c.Writer.Header().Set("Content-Type", "application/x-json-stream")
- c.Writer.Header().Set("Cache-Control", "no-cache")
- c.Writer.Header().Set("Connection", "keep-alive")
- c.Writer.Header().Set("X-Accel-Buffering", "no")
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- if err := h.imageService.PullImage(ctx, req.ImageName, c.Writer, *currentUser, req.Credentials); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ImagePullError{ImageName: req.ImageName, Err: err}).Error()},
- })
- return
- }
-
- slog.InfoContext(ctx, "Image pull stream completed",
- slog.String("imageName", req.ImageName))
-}
-
-// Prune godoc
-//
-// @Summary Prune unused images
-// @Description Remove unused Docker images
-// @Tags Images
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param dangling query bool false "Only remove dangling images"
-// @Success 200 {object} base.ApiResponse[image.PruneReport]
-// @Router /api/environments/{id}/images/prune [post]
-func (h *ImageHandler) Prune(c *gin.Context) {
- dangling := c.Query("dangling") == "true"
-
- var req struct {
- Dangling *bool `json:"dangling"`
- Filters map[string][]string `json:"filters"`
- }
- if err := c.ShouldBindJSON(&req); err == nil {
- if req.Dangling != nil {
- dangling = *req.Dangling
- } else if vals, ok := req.Filters["dangling"]; ok {
- for _, v := range vals {
- if v == "true" || v == "1" {
- dangling = true
- break
- }
- }
- }
- } else if c.Request.ContentLength > 0 {
- // Only return error if body was provided but invalid
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- slog.DebugContext(c.Request.Context(), "Image prune request", slog.Bool("dangling_only", dangling))
-
- report, err := h.imageService.PruneImages(c.Request.Context(), dangling)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ImagePruneError{Err: err}).Error()},
- })
- return
- }
-
- out := image.NewPruneReport(*report)
- c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
-}
-
-// GetImageUsageCounts godoc
-//
-// @Summary Get image usage counts
-// @Description Get counts of images in use, unused, total, and total size
-// @Tags Images
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[image.UsageCounts]
-// @Router /api/environments/{id}/images/counts [get]
-func (h *ImageHandler) GetImageUsageCounts(c *gin.Context) {
- ctx := c.Request.Context()
-
- var (
- inuse, unused, total int
- totalSize int64
- errs []error
- )
-
- _, iu, un, tot, err := h.dockerService.GetAllImages(ctx)
- if err != nil {
- errs = append(errs, fmt.Errorf("get images: %w", err))
- } else {
- inuse, unused, total = iu, un, tot
- }
-
- sz, err := h.imageService.GetTotalImageSize(ctx)
- if err != nil {
- errs = append(errs, fmt.Errorf("get total image size: %w", err))
- } else {
- totalSize = sz
- }
-
- if len(errs) > 0 {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ImageUsageCountsError{Err: errors.Join(errs...)}).Error()},
- })
- return
- }
-
- out := image.UsageCounts{
- Inuse: inuse,
- Unused: unused,
- Total: total,
- TotalSize: totalSize,
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// Upload godoc
-//
-// @Summary Upload an image
-// @Description Upload a Docker image from a tar archive
-// @Tags Images
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept multipart/form-data
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param file formData file true "Docker image tar archive"
-// @Success 200 {object} base.ApiResponse[image.LoadResult]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 413 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/images/upload [post]
-func (h *ImageHandler) Upload(c *gin.Context) {
- ctx := context.Background()
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- // Stream the uploaded file directly to the Docker daemon to avoid buffering large files in memory
- mr, err := c.Request.MultipartReader()
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidMultipartFormError{Err: err}).Error()},
- })
- return
- }
-
- var (
- part *multipart.Part
- fileName string
- found bool
- )
-
- for {
- p, err := mr.NextPart()
- if err != nil {
- if errors.Is(err, io.EOF) {
- break
- }
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.FileUploadReadError{Err: err}).Error()}})
- return
- }
- // Only consider file parts (have a filename)
- if p.FileName() != "" {
- part = p
- fileName = p.FileName()
- found = true
- break
- }
- // Discard and continue non-file parts
- _ = p.Close()
- }
-
- if !found || part == nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.NoFileUploadedError{}).Error()}})
- return
- }
- defer part.Close()
-
- maxSizeMB := h.settingsService.GetIntSetting(ctx, "maxImageUploadSize", 500)
- maxSizeBytes := int64(maxSizeMB) * 1024 * 1024
-
- // Validate that the file is a Docker image tar archive
- // We allow .tar, .tar.gz, .tgz, .tar.xz
- lowerName := strings.ToLower(fileName)
- if !strings.HasSuffix(lowerName, ".tar") && !strings.HasSuffix(lowerName, ".tar.gz") && !strings.HasSuffix(lowerName, ".tgz") && !strings.HasSuffix(lowerName, ".tar.xz") {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.InvalidFileFormatError{}).Error()}})
- return
- }
-
- result, err := h.imageService.LoadImageFromReader(ctx, part, fileName, *currentUser, maxSizeBytes)
- if err != nil {
- // Check if it's a size limit error
- if strings.Contains(err.Error(), "exceeds maximum allowed size") {
- c.JSON(http.StatusRequestEntityTooLarge, gin.H{"success": false, "data": gin.H{"error": err.Error()}})
- return
- }
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.ImageLoadError{Err: err}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": result,
- })
-}
diff --git a/backend/internal/api/image_update_handler.go b/backend/internal/api/image_update_handler.go
deleted file mode 100644
index ca2dae11f..000000000
--- a/backend/internal/api/image_update_handler.go
+++ /dev/null
@@ -1,211 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/imageupdate"
-)
-
-type ImageUpdateHandler struct {
- imageUpdateService *services.ImageUpdateService
-}
-
-func NewImageUpdateHandler(group *gin.RouterGroup, imageUpdateService *services.ImageUpdateService, authMiddleware *middleware.AuthMiddleware) {
- handler := &ImageUpdateHandler{imageUpdateService: imageUpdateService}
-
- apiGroup := group.Group("/environments/:id/image-updates")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.GET("/check", handler.CheckImageUpdate)
- apiGroup.GET("/check/:imageId", handler.CheckImageUpdateByID)
- apiGroup.POST("/check/:imageId", handler.CheckImageUpdateByID)
- apiGroup.POST("/check-batch", handler.CheckMultipleImages)
- apiGroup.POST("/check-all", handler.CheckAllImages)
- apiGroup.GET("/summary", handler.GetUpdateSummary)
- }
-}
-
-// CheckImageUpdate godoc
-//
-// @Summary Check image update by reference
-// @Description Check if an image has an update available by image reference
-// @Tags Image Updates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param imageRef query string true "Image reference (e.g., nginx:latest)"
-// @Success 200 {object} base.ApiResponse[imageupdate.Response]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/image-updates/check [get]
-func (h *ImageUpdateHandler) CheckImageUpdate(c *gin.Context) {
- imageRef := c.Query("imageRef")
- if imageRef == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.ImageRefRequiredError{}).Error(),
- })
- return
- }
-
- result, err := h.imageUpdateService.CheckImageUpdate(c.Request.Context(), imageRef)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ImageUpdateCheckError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": result,
- })
-}
-
-// CheckImageUpdateByID godoc
-//
-// @Summary Check image update by ID
-// @Description Check if an image has an update available by image ID
-// @Tags Image Updates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param imageId path string true "Image ID"
-// @Success 200 {object} base.ApiResponse[imageupdate.Response]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/image-updates/check/{imageId} [get]
-func (h *ImageUpdateHandler) CheckImageUpdateByID(c *gin.Context) {
- imageID := c.Param("imageId")
- if imageID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.ImageIDRequiredError{}).Error(),
- })
- return
- }
-
- result, err := h.imageUpdateService.CheckImageUpdateByID(c.Request.Context(), imageID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ImageUpdateCheckError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": result,
- })
-}
-
-// CheckMultipleImages godoc
-//
-// @Summary Check multiple images for updates
-// @Description Check multiple images for available updates
-// @Tags Image Updates
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param request body imageupdate.BatchImageUpdateRequest true "Batch image update request"
-// @Success 200 {object} base.ApiResponse[imageupdate.BatchResponse]
-// @Router /api/environments/{id}/image-updates/check-batch [post]
-func (h *ImageUpdateHandler) CheckMultipleImages(c *gin.Context) {
- var req imageupdate.BatchImageUpdateRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- if len(req.ImageRefs) == 0 {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.ImageRefListRequiredError{}).Error(),
- })
- return
- }
-
- results, err := h.imageUpdateService.CheckMultipleImages(c.Request.Context(), req.ImageRefs, req.Credentials)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.BatchImageUpdateCheckError{Err: err}).Error(),
- })
- return
- }
-
- response := imageupdate.BatchResponse(results)
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": response,
- })
-}
-
-// CheckAllImages godoc
-//
-// @Summary Check all images for updates
-// @Description Check all local images for available updates
-// @Tags Image Updates
-// @Accept json
-// @Produce json
-// @Param id path string false "Environment ID"
-// @Param request body imageupdate.BatchImageUpdateRequest false "Optional credentials"
-// @Success 200 {object} base.ApiResponse[imageupdate.BatchResponse]
-// @Router /api/environments/{id}/image-updates/check-all [post]
-func (h *ImageUpdateHandler) CheckAllImages(c *gin.Context) {
- var req imageupdate.BatchImageUpdateRequest
- _ = c.ShouldBindJSON(&req)
-
- results, err := h.imageUpdateService.CheckAllImages(c.Request.Context(), 0, req.Credentials)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.AllImageUpdateCheckError{Err: err}).Error(),
- })
- return
- }
-
- response := imageupdate.BatchResponse(results)
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": response,
- })
-}
-
-// GetUpdateSummary godoc
-//
-// @Summary Get image update summary
-// @Description Get a summary of images with available updates
-// @Tags Image Updates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[imageupdate.Summary]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/image-updates/summary [get]
-func (h *ImageUpdateHandler) GetUpdateSummary(c *gin.Context) {
- summary, err := h.imageUpdateService.GetUpdateSummary(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.UpdateSummaryError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": summary,
- })
-}
diff --git a/backend/internal/api/network_handler.go b/backend/internal/api/network_handler.go
deleted file mode 100644
index aafb17b76..000000000
--- a/backend/internal/api/network_handler.go
+++ /dev/null
@@ -1,253 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/docker/docker/api/types/network"
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- networktypes "go.getarcane.app/types/network"
-)
-
-type NetworkHandler struct {
- networkService *services.NetworkService
- dockerService *services.DockerClientService
-}
-
-func NewNetworkHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, networkService *services.NetworkService, authMiddleware *middleware.AuthMiddleware) {
- handler := &NetworkHandler{dockerService: dockerService, networkService: networkService}
-
- apiGroup := group.Group("/environments/:id/networks")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.GET("/counts", handler.GetNetworkUsageCounts)
- apiGroup.GET("", handler.List)
- apiGroup.GET("/:networkId", handler.GetByID)
- apiGroup.POST("", handler.Create)
- apiGroup.DELETE("/:networkId", handler.Remove)
- apiGroup.POST("/prune", handler.Prune)
- }
-}
-
-// List godoc
-//
-// @Summary List networks
-// @Description Get a paginated list of Docker networks
-// @Tags Networks
-// @Param id path string true "Environment ID"
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[network.Summary]
-// @Router /api/environments/{id}/networks [get]
-func (h *NetworkHandler) List(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- if params.Limit == 0 {
- params.Limit = 20
- }
-
- networks, paginationResp, err := h.networkService.ListNetworksPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.NetworkListError{Err: err}).Error()},
- })
- return
- }
-
- pagination.ApplyFilterResultsHeaders(&c.Writer, pagination.FilterResult[networktypes.Summary]{
- Items: networks,
- TotalCount: paginationResp.TotalItems,
- TotalAvailable: paginationResp.GrandTotalItems,
- })
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": networks,
- "pagination": paginationResp,
- })
-}
-
-// GetByID godoc
-//
-// @Summary Get network by ID
-// @Description Get a Docker network by its ID
-// @Tags Networks
-// @Param id path string true "Environment ID"
-// @Param networkId path string true "Network ID"
-// @Success 200 {object} base.ApiResponse[network.Inspect]
-// @Router /api/environments/{id}/networks/{networkId} [get]
-func (h *NetworkHandler) GetByID(c *gin.Context) {
- id := c.Param("networkId")
-
- networkInspect, err := h.networkService.GetNetworkByID(c.Request.Context(), id)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.NetworkNotFoundError{Err: err}).Error()},
- })
- return
- }
-
- out, mapErr := mapper.MapOne[network.Inspect, networktypes.Inspect](*networkInspect)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.NetworkMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// Create godoc
-//
-// @Summary Create a network
-// @Description Create a new Docker network
-// @Tags Networks
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param network body object true "Network creation data"
-// @Success 201 {object} base.ApiResponse[network.CreateResponse]
-// @Router /api/environments/{id}/networks [post]
-func (h *NetworkHandler) Create(c *gin.Context) {
- var req struct {
- Name string `json:"name" binding:"required"`
- Options network.CreateOptions `json:"options"`
- }
-
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- response, err := h.networkService.CreateNetwork(c.Request.Context(), req.Name, req.Options, *currentUser)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.NetworkCreationError{Err: err}).Error()},
- })
- return
- }
-
- out, mapErr := mapper.MapOne[network.CreateResponse, networktypes.CreateResponse](*response)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.NetworkMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// Remove godoc
-//
-// @Summary Remove a network
-// @Description Remove a Docker network by ID
-// @Tags Networks
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param networkId path string true "Network ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/networks/{networkId} [delete]
-func (h *NetworkHandler) Remove(c *gin.Context) {
- id := c.Param("networkId")
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- if err := h.networkService.RemoveNetwork(c.Request.Context(), id, *currentUser); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.NetworkRemovalError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Network removed successfully"},
- })
-}
-
-// GetNetworkUsageCounts godoc
-//
-// @Summary Get network usage counts
-// @Description Get counts of networks in use, unused, and total
-// @Tags Networks
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[network.UsageCounts]
-// @Router /api/environments/{id}/networks/counts [get]
-func (h *NetworkHandler) GetNetworkUsageCounts(c *gin.Context) {
- _, inuse, unused, total, err := h.dockerService.GetAllNetworks(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.NetworkUsageCountsError{Err: err}).Error()},
- })
- return
- }
-
- out := networktypes.UsageCounts{
- Inuse: inuse,
- Unused: unused,
- Total: total,
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// Prune godoc
-//
-// @Summary Prune unused networks
-// @Description Remove all unused Docker networks
-// @Tags Networks
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[network.PruneReport]
-// @Router /api/environments/{id}/networks/prune [post]
-func (h *NetworkHandler) Prune(c *gin.Context) {
- report, err := h.networkService.PruneNetworks(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.NetworkPruneError{Err: err}).Error()},
- })
- return
- }
-
- out, mapErr := mapper.MapOne[network.PruneReport, networktypes.PruneReport](*report)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.NetworkMappingError{Err: mapErr}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
diff --git a/backend/internal/api/notification_handler.go b/backend/internal/api/notification_handler.go
deleted file mode 100644
index 46e3aa6a7..000000000
--- a/backend/internal/api/notification_handler.go
+++ /dev/null
@@ -1,302 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/base"
- "go.getarcane.app/types/notification"
-)
-
-type NotificationHandler struct {
- notificationService *services.NotificationService
- appriseService *services.AppriseService
-}
-
-func NewNotificationHandler(group *gin.RouterGroup, notificationService *services.NotificationService, appriseService *services.AppriseService, authMiddleware *middleware.AuthMiddleware) {
- handler := &NotificationHandler{
- notificationService: notificationService,
- appriseService: appriseService,
- }
-
- notifications := group.Group("/environments/:id/notifications")
- notifications.Use(authMiddleware.WithAdminRequired().Add())
- {
- notifications.GET("/settings", handler.GetAllSettings)
- notifications.GET("/settings/:provider", handler.GetSettings)
- notifications.POST("/settings", handler.CreateOrUpdateSettings)
- notifications.DELETE("/settings/:provider", handler.DeleteSettings)
- notifications.POST("/test/:provider", handler.TestNotification)
-
- notifications.GET("/apprise", handler.GetAppriseSettings)
- notifications.POST("/apprise", handler.CreateOrUpdateAppriseSettings)
- notifications.POST("/apprise/test", handler.TestAppriseNotification)
- }
-}
-
-// GetAllSettings godoc
-//
-// @Summary Get all notification settings
-// @Description Get all notification provider settings
-// @Tags Notifications
-// @Param id path string true "Environment ID"
-// @Success 200 {array} notification.Response
-// @Router /api/environments/{id}/notifications/settings [get]
-func (h *NotificationHandler) GetAllSettings(c *gin.Context) {
- settings, err := h.notificationService.GetAllSettings(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.NotificationSettingsListError{Err: err}).Error()})
- return
- }
-
- // Map to DTOs
- responses := make([]notification.Response, len(settings))
- for i, setting := range settings {
- responses[i] = notification.Response{
- ID: setting.ID,
- Provider: notification.Provider(setting.Provider),
- Enabled: setting.Enabled,
- Config: base.JsonObject(setting.Config),
- }
- }
-
- c.JSON(http.StatusOK, responses)
-}
-
-// GetSettings godoc
-//
-// @Summary Get notification settings by provider
-// @Description Get notification settings for a specific provider
-// @Tags Notifications
-// @Param id path string true "Environment ID"
-// @Param provider path string true "Notification provider (discord, email)"
-// @Success 200 {object} notification.Response
-// @Router /api/environments/{id}/notifications/settings/{provider} [get]
-func (h *NotificationHandler) GetSettings(c *gin.Context) {
- providerStr := c.Param("provider")
- provider := models.NotificationProvider(providerStr)
-
- switch provider {
- case models.NotificationProviderDiscord, models.NotificationProviderEmail:
- default:
- c.JSON(http.StatusBadRequest, gin.H{"error": (&common.InvalidNotificationProviderError{}).Error()})
- return
- }
-
- settings, err := h.notificationService.GetSettingsByProvider(c.Request.Context(), provider)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"error": (&common.NotificationSettingsNotFoundError{}).Error()})
- return
- }
-
- response := notification.Response{
- ID: settings.ID,
- Provider: notification.Provider(settings.Provider),
- Enabled: settings.Enabled,
- Config: base.JsonObject(settings.Config),
- }
-
- c.JSON(http.StatusOK, response)
-}
-
-// CreateOrUpdateSettings godoc
-//
-// @Summary Create or update notification settings
-// @Description Create or update notification settings for a provider
-// @Tags Notifications
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param settings body notification.Update true "Notification settings"
-// @Success 200 {object} notification.Response
-// @Router /api/environments/{id}/notifications/settings [post]
-func (h *NotificationHandler) CreateOrUpdateSettings(c *gin.Context) {
- var req notification.Update
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
-
- settings, err := h.notificationService.CreateOrUpdateSettings(
- c.Request.Context(),
- models.NotificationProvider(req.Provider),
- req.Enabled,
- models.JSON(req.Config),
- )
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.NotificationSettingsUpdateError{Err: err}).Error()})
- return
- }
-
- response := notification.Response{
- ID: settings.ID,
- Provider: notification.Provider(settings.Provider),
- Enabled: settings.Enabled,
- Config: base.JsonObject(settings.Config),
- }
-
- c.JSON(http.StatusOK, response)
-}
-
-// DeleteSettings godoc
-//
-// @Summary Delete notification settings
-// @Description Delete notification settings for a provider
-// @Tags Notifications
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param provider path string true "Notification provider (discord, email)"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/notifications/settings/{provider} [delete]
-func (h *NotificationHandler) DeleteSettings(c *gin.Context) {
- providerStr := c.Param("provider")
- provider := models.NotificationProvider(providerStr)
-
- switch provider {
- case models.NotificationProviderDiscord, models.NotificationProviderEmail:
- default:
- c.JSON(http.StatusBadRequest, gin.H{"error": (&common.InvalidNotificationProviderError{}).Error()})
- return
- }
-
- if err := h.notificationService.DeleteSettings(c.Request.Context(), provider); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.NotificationSettingsDeletionError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"message": "Settings deleted successfully"})
-}
-
-// TestNotification godoc
-//
-// @Summary Test notification
-// @Description Send a test notification for a provider
-// @Tags Notifications
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param provider path string true "Notification provider (discord, email)"
-// @Param type query string false "Test type (simple or image-update)" default(simple)
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/notifications/test/{provider} [post]
-func (h *NotificationHandler) TestNotification(c *gin.Context) {
- providerStr := c.Param("provider")
- provider := models.NotificationProvider(providerStr)
-
- switch provider {
- case models.NotificationProviderDiscord, models.NotificationProviderEmail:
- default:
- c.JSON(http.StatusBadRequest, gin.H{"error": (&common.InvalidNotificationProviderError{}).Error()})
- return
- }
-
- testType := c.DefaultQuery("type", "simple") // "simple" or "image-update"
-
- if err := h.notificationService.TestNotification(c.Request.Context(), provider, testType); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.NotificationTestError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"message": "Test notification sent successfully"})
-}
-
-// GetAppriseSettings godoc
-//
-// @Summary Get Apprise settings
-// @Description Get Apprise notification settings
-// @Tags Notifications
-// @Param id path string true "Environment ID"
-// @Success 200 {object} notification.AppriseResponse
-// @Router /api/environments/{id}/notifications/apprise [get]
-func (h *NotificationHandler) GetAppriseSettings(c *gin.Context) {
- settings, err := h.appriseService.GetSettings(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"error": (&common.AppriseSettingsNotFoundError{}).Error()})
- return
- }
-
- response := notification.AppriseResponse{
- ID: settings.ID,
- APIURL: settings.APIURL,
- Enabled: settings.Enabled,
- ImageUpdateTag: settings.ImageUpdateTag,
- ContainerUpdateTag: settings.ContainerUpdateTag,
- }
-
- c.JSON(http.StatusOK, response)
-}
-
-// CreateOrUpdateAppriseSettings godoc
-//
-// @Summary Create or update Apprise settings
-// @Description Create or update Apprise notification settings
-// @Tags Notifications
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param settings body notification.AppriseUpdate true "Apprise settings"
-// @Success 200 {object} notification.AppriseResponse
-// @Router /api/environments/{id}/notifications/apprise [post]
-func (h *NotificationHandler) CreateOrUpdateAppriseSettings(c *gin.Context) {
- var req notification.AppriseUpdate
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
-
- if req.Enabled && req.APIURL == "" {
- c.JSON(http.StatusBadRequest, gin.H{"error": "API URL is required when Apprise is enabled"})
- return
- }
-
- settings, err := h.appriseService.CreateOrUpdateSettings(
- c.Request.Context(),
- req.APIURL,
- req.Enabled,
- req.ImageUpdateTag,
- req.ContainerUpdateTag,
- )
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.AppriseSettingsUpdateError{Err: err}).Error()})
- return
- }
-
- response := notification.AppriseResponse{
- ID: settings.ID,
- APIURL: settings.APIURL,
- Enabled: settings.Enabled,
- ImageUpdateTag: settings.ImageUpdateTag,
- ContainerUpdateTag: settings.ContainerUpdateTag,
- }
-
- c.JSON(http.StatusOK, response)
-}
-
-// TestAppriseNotification godoc
-//
-// @Summary Test Apprise notification
-// @Description Send a test notification via Apprise
-// @Tags Notifications
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/notifications/apprise/test [post]
-func (h *NotificationHandler) TestAppriseNotification(c *gin.Context) {
- if err := h.appriseService.TestNotification(c.Request.Context()); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.AppriseTestError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"message": "Test notification sent successfully"})
-}
diff --git a/backend/internal/api/oidc_handler.go b/backend/internal/api/oidc_handler.go
deleted file mode 100644
index 98f3a0213..000000000
--- a/backend/internal/api/oidc_handler.go
+++ /dev/null
@@ -1,152 +0,0 @@
-package api
-
-import (
- "net/http"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/cookie"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/auth"
- "go.getarcane.app/types/user"
-)
-
-type OidcHandler struct {
- authService *services.AuthService
- oidcService *services.OidcService
-}
-
-func NewOidcHandler(group *gin.RouterGroup, authService *services.AuthService, oidcService *services.OidcService) {
-
- handler := &OidcHandler{authService: authService, oidcService: oidcService}
-
- apiGroup := group.Group("/oidc")
- {
- apiGroup.POST("/url", handler.GetOidcAuthUrl)
- apiGroup.POST("/callback", handler.HandleOidcCallback)
- apiGroup.GET("/config", handler.GetOidcConfig)
- apiGroup.GET("/status", handler.GetOidcStatus)
- }
-}
-
-func (h *OidcHandler) GetOidcStatus(c *gin.Context) {
- status, err := h.authService.GetOidcConfigurationStatus(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.OidcStatusError{Err: err}).Error(),
- })
- return
- }
- c.JSON(http.StatusOK, status)
-}
-
-func (h *OidcHandler) GetOidcAuthUrl(c *gin.Context) {
- var req auth.OidcAuthUrlRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- enabled, err := h.authService.IsOidcEnabled(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": (&common.OidcStatusCheckError{}).Error()})
- return
- }
- if !enabled {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.OidcDisabledError{}).Error()})
- return
- }
-
- authUrl, stateCookieValue, err := h.oidcService.GenerateAuthURL(c.Request.Context(), req.RedirectUri)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": (&common.OidcAuthUrlGenerationError{Err: err}).Error()})
- return
- }
-
- cookie.CreateOidcStateCookie(c, stateCookieValue, 600)
-
- c.JSON(http.StatusOK, gin.H{
- "authUrl": authUrl,
- })
-}
-
-func (h *OidcHandler) HandleOidcCallback(c *gin.Context) {
- var req struct {
- Code string `json:"code" binding:"required"`
- State string `json:"state" binding:"required"`
- }
-
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
-
- encodedStateFromCookie, err := cookie.GetOidcStateCookie(c)
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.OidcStateCookieError{}).Error()})
- return
- }
- cookie.ClearOidcStateCookie(c)
-
- userInfo, tokenResp, err := h.oidcService.HandleCallback(c.Request.Context(), req.Code, req.State, encodedStateFromCookie)
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": (&common.OidcCallbackError{Err: err}).Error()})
- return
- }
-
- userModel, tokenPair, err := h.authService.OidcLogin(c.Request.Context(), *userInfo, tokenResp)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": (&common.AuthFailedError{Err: err}).Error()})
- return
- }
-
- c.SetSameSite(http.SameSiteLaxMode)
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
- // Add 60 seconds buffer to account for clock skew and network latency
- maxAge += 60
- cookie.CreateTokenCookie(c, maxAge, tokenPair.AccessToken)
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "token": tokenPair.AccessToken,
- "refreshToken": tokenPair.RefreshToken,
- "expiresAt": tokenPair.ExpiresAt,
- "user": user.Response{
- ID: userModel.ID,
- Username: userModel.Username,
- DisplayName: userModel.DisplayName,
- Email: userModel.Email,
- Roles: userModel.Roles,
- OidcSubjectId: userModel.OidcSubjectId,
- },
- })
-}
-
-func (h *OidcHandler) GetOidcConfig(c *gin.Context) {
- config, err := h.authService.GetOidcConfig(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.OidcConfigError{}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "clientId": config.ClientID,
- "redirectUri": h.oidcService.GetOidcRedirectURL(),
- "issuerUrl": config.IssuerURL,
- "authorizationEndpoint": config.AuthorizationEndpoint,
- "tokenEndpoint": config.TokenEndpoint,
- "userinfoEndpoint": config.UserinfoEndpoint,
- "scopes": config.Scopes,
- })
-}
diff --git a/backend/internal/api/project_handler.go b/backend/internal/api/project_handler.go
deleted file mode 100644
index 9303ed928..000000000
--- a/backend/internal/api/project_handler.go
+++ /dev/null
@@ -1,618 +0,0 @@
-package api
-
-import (
- "context"
- "errors"
- "fmt"
- "log/slog"
- "net/http"
- "strings"
- "sync/atomic"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
- httputil "github.com/getarcaneapp/arcane/backend/internal/utils/http"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- ws "github.com/getarcaneapp/arcane/backend/internal/utils/ws"
- "github.com/gin-gonic/gin"
- "github.com/gorilla/websocket"
- "go.getarcane.app/types/project"
-)
-
-type ProjectHandler struct {
- projectService *services.ProjectService
- wsUpgrader websocket.Upgrader
-}
-
-type projectLogStream struct {
- hub *ws.Hub
- cancel context.CancelFunc
- format string
- seq atomic.Uint64
-}
-
-func NewProjectHandler(group *gin.RouterGroup, projectService *services.ProjectService, authMiddleware *middleware.AuthMiddleware, cfg *config.Config) {
-
- handler := &ProjectHandler{
- projectService: projectService,
- wsUpgrader: websocket.Upgrader{
- CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.AppUrl),
- ReadBufferSize: 32 * 1024,
- WriteBufferSize: 32 * 1024,
- EnableCompression: true,
- },
- }
-
- apiGroup := group.Group("/environments/:id/projects")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
-
- apiGroup.GET("", handler.ListProjects)
- apiGroup.GET("/counts", handler.GetProjectStatusCounts)
- apiGroup.POST("/:projectId/up", handler.DeployProject)
- apiGroup.POST("/:projectId/down", handler.DownProject)
- apiGroup.POST("", handler.CreateProject)
- apiGroup.GET("/:projectId", handler.GetProject)
- apiGroup.POST("/:projectId/pull", handler.PullProjectImages)
- apiGroup.POST("/:projectId/redeploy", handler.RedeployProject)
- apiGroup.DELETE("/:projectId/destroy", handler.DestroyProject)
- apiGroup.PUT("/:projectId", handler.UpdateProject)
- apiGroup.PUT("/:projectId/includes", handler.UpdateProjectInclude)
- apiGroup.POST("/:projectId/restart", handler.RestartProject)
- apiGroup.GET("/:projectId/logs/ws", handler.GetProjectLogsWS)
-
- }
-}
-
-// ListProjects godoc
-//
-// @Summary List projects
-// @Description Get a paginated list of Docker Compose projects
-// @Tags Projects
-// @Param id path string true "Environment ID"
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[project.Details]
-// @Router /api/environments/{id}/projects [get]
-func (h *ProjectHandler) ListProjects(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- projectsResponse, paginationResp, err := h.projectService.ListProjects(c.Request.Context(), params)
- if err != nil {
- if errors.Is(err, context.Canceled) {
- c.JSON(http.StatusRequestTimeout, gin.H{
- "success": false,
- "error": "Request was canceled",
- })
- return
- }
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ProjectListError{Err: err}).Error(),
- })
- return
- }
- if projectsResponse == nil {
- projectsResponse = []project.Details{}
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": projectsResponse,
- "pagination": paginationResp,
- })
-}
-
-// DeployProject godoc
-//
-// @Summary Deploy a project
-// @Description Deploy a Docker Compose project (docker-compose up)
-// @Tags Projects
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/projects/{projectId}/up [post]
-func (h *ProjectHandler) DeployProject(c *gin.Context) {
- projectID := c.Param("projectId")
-
- if projectID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.ProjectIDRequiredError{}).Error(),
- })
- return
- }
-
- user, _ := middleware.GetCurrentUser(c)
- if err := h.projectService.DeployProject(c.Request.Context(), projectID, *user); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.ProjectDeploymentError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Project deployed successfully"},
- })
-}
-
-// DownProject godoc
-//
-// @Summary Bring down a project
-// @Description Bring down a Docker Compose project (docker-compose down)
-// @Tags Projects
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/projects/{projectId}/down [post]
-func (h *ProjectHandler) DownProject(c *gin.Context) {
- projectID := c.Param("projectId")
-
- user, _ := middleware.GetCurrentUser(c)
- if err := h.projectService.DownProject(c.Request.Context(), projectID, *user); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ProjectDownError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Project brought down successfully"},
- })
-}
-
-// CreateProject godoc
-//
-// @Summary Create a project
-// @Description Create a new Docker Compose project
-// @Tags Projects
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param project body project.Create true "Project creation data"
-// @Success 201 {object} base.ApiResponse[project.CreateReponse]
-// @Router /api/environments/{id}/projects [post]
-func (h *ProjectHandler) CreateProject(c *gin.Context) {
- var req project.Create
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
-
- user, _ := middleware.GetCurrentUser(c)
- proj, err := h.projectService.CreateProject(c.Request.Context(), req.Name, req.ComposeContent, req.EnvContent, *user)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": (&common.ProjectCreationError{Err: err}).Error()})
- return
- }
-
- var response project.CreateReponse
- if err := mapper.MapStruct(proj, &response); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "failed to map response"})
- return
- }
- response.Status = string(proj.Status)
- response.StatusReason = proj.StatusReason
- response.CreatedAt = proj.CreatedAt.Format(time.RFC3339)
- response.UpdatedAt = proj.UpdatedAt.Format(time.RFC3339)
- response.DirName = utils.DerefString(proj.DirName)
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": response,
- })
-}
-
-// GetProject godoc
-//
-// @Summary Get a project
-// @Description Get a Docker Compose project by ID
-// @Tags Projects
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Success 200 {object} base.ApiResponse[project.Details]
-// @Router /api/environments/{id}/projects/{projectId} [get]
-func (h *ProjectHandler) GetProject(c *gin.Context) {
- projectID := c.Param("projectId")
- if projectID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
- return
- }
-
- details, err := h.projectService.GetProjectDetails(c.Request.Context(), projectID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "error": (&common.ProjectDetailsError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": details,
- })
-}
-
-// RedeployProject godoc
-//
-// @Summary Redeploy a project
-// @Description Redeploy a Docker Compose project (down + up)
-// @Tags Projects
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/projects/{projectId}/redeploy [post]
-func (h *ProjectHandler) RedeployProject(c *gin.Context) {
- projectID := c.Param("projectId")
-
- if projectID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.ProjectIDRequiredError{}).Error(),
- })
- return
- }
-
- user, _ := middleware.GetCurrentUser(c)
- if err := h.projectService.RedeployProject(c.Request.Context(), projectID, *user); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.ProjectRedeploymentError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Project redeployed successfully"},
- })
-}
-
-// DestroyProject godoc
-//
-// @Summary Destroy a project
-// @Description Destroy a Docker Compose project and optionally remove files/volumes
-// @Tags Projects
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Param request body project.Destroy false "Destroy options"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/projects/{projectId}/destroy [delete]
-func (h *ProjectHandler) DestroyProject(c *gin.Context) {
- projectID := c.Param("projectId")
-
- var req project.Destroy
- if c.Request.ContentLength > 0 {
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
- }
-
- user, _ := middleware.GetCurrentUser(c)
- if err := h.projectService.DestroyProject(c.Request.Context(), projectID, req.RemoveFiles, req.RemoveVolumes, *user); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ProjectDestroyError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Project destroyed successfully"},
- })
-}
-
-// PullProjectImages godoc
-//
-// @Summary Pull project images
-// @Description Pull all images for a Docker Compose project
-// @Tags Projects
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce application/x-json-stream
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Param request body project.ImagePullRequest false "Pull options with optional credentials"
-// @Success 200 {string} string "Streaming JSON response"
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/projects/{projectId}/pull [post]
-func (h *ProjectHandler) PullProjectImages(c *gin.Context) {
- projectID := c.Param("projectId")
- if projectID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
- return
- }
-
- var req project.ImagePullRequest
- if c.Request.ContentLength > 0 {
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
- }
-
- c.Writer.Header().Set("Content-Type", "application/x-json-stream")
- c.Writer.Header().Set("Cache-Control", "no-cache")
- c.Writer.Header().Set("Connection", "keep-alive")
- c.Writer.Header().Set("X-Accel-Buffering", "no")
-
- _, _ = fmt.Fprintln(c.Writer, `{"status":"starting project image pull"}`)
-
- if err := h.projectService.PullProjectImages(c.Request.Context(), projectID, c.Writer, req.Credentials); err != nil {
- _, _ = fmt.Fprintf(c.Writer, `{"error":%q}`+"\n", err.Error())
- return
- }
-
- _, _ = fmt.Fprintln(c.Writer, `{"status":"complete"}`)
-}
-
-// UpdateProject godoc
-//
-// @Summary Update a project
-// @Description Update a Docker Compose project configuration
-// @Tags Projects
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Param project body project.Update true "Project update data"
-// @Success 200 {object} base.ApiResponse[project.Details]
-// @Router /api/environments/{id}/projects/{projectId} [put]
-func (h *ProjectHandler) UpdateProject(c *gin.Context) {
- projectID := c.Param("projectId")
- if projectID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
- return
- }
-
- var req project.Update
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
-
- if _, err := h.projectService.UpdateProject(c.Request.Context(), projectID, req.Name, req.ComposeContent, req.EnvContent); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectUpdateError{Err: err}).Error()})
- return
- }
-
- details, err := h.projectService.GetProjectDetails(c.Request.Context(), projectID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": (&common.ProjectDetailsError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": details,
- })
-}
-
-// UpdateProjectInclude godoc
-//
-// @Summary Update project include file
-// @Description Update an include file within a Docker Compose project
-// @Tags Projects
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Param include body project.UpdateIncludeFile true "Include file update data"
-// @Success 200 {object} base.ApiResponse[project.Details]
-// @Router /api/environments/{id}/projects/{projectId}/includes [put]
-func (h *ProjectHandler) UpdateProjectInclude(c *gin.Context) {
- projectID := c.Param("projectId")
- if projectID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
- return
- }
-
- var req project.UpdateIncludeFile
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.InvalidRequestFormatError{Err: err}).Error()})
- return
- }
-
- if err := h.projectService.UpdateProjectIncludeFile(c.Request.Context(), projectID, req.RelativePath, req.Content); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectUpdateError{Err: err}).Error()})
- return
- }
-
- details, err := h.projectService.GetProjectDetails(c.Request.Context(), projectID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": (&common.ProjectDetailsError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": details,
- })
-}
-
-// RestartProject godoc
-//
-// @Summary Restart a project
-// @Description Restart all containers in a Docker Compose project
-// @Tags Projects
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/projects/{projectId}/restart [post]
-func (h *ProjectHandler) RestartProject(c *gin.Context) {
- projectID := c.Param("projectId")
- if projectID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
- return
- }
-
- user, _ := middleware.GetCurrentUser(c)
- if err := h.projectService.RestartProject(c.Request.Context(), projectID, *user); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectRestartError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Project restarted successfully"},
- })
-}
-
-func (h *ProjectHandler) getOrStartProjectLogHub(projectID, format string, batched bool, follow bool, tail, since string, timestamps bool) *ws.Hub {
- // Create a new hub for each connection to ensure every client gets historical logs
- ls := &projectLogStream{
- hub: ws.NewHub(1024),
- format: format,
- }
-
- ctx, cancel := context.WithCancel(context.Background())
- ls.cancel = cancel
-
- ls.hub.SetOnEmpty(func() {
- slog.Debug("client disconnected, cleaning up project log hub", "projectID", projectID, "format", format, "tail", tail)
- cancel()
- })
-
- go ls.hub.Run(ctx)
-
- lines := make(chan string, 256)
- go func() {
- defer close(lines)
- _ = h.projectService.StreamProjectLogs(ctx, projectID, lines, follow, tail, since, timestamps)
- }()
-
- if format == "json" {
- msgs := make(chan ws.LogMessage, 256)
- go func() {
- defer close(msgs)
- for line := range lines {
- level, service, msg, ts := ws.NormalizeProjectLine(line)
- seq := ls.seq.Add(1)
- timestamp := ts
- if timestamp == "" {
- timestamp = ws.NowRFC3339()
- }
- msgs <- ws.LogMessage{
- Seq: seq,
- Level: level,
- Message: msg,
- Service: service,
- Timestamp: timestamp,
- }
- }
- }()
- if batched {
- go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
- } else {
- go ws.ForwardLogJSON(ctx, ls.hub, msgs)
- }
- } else {
- cleanChan := make(chan string, 256)
- go func() {
- defer close(cleanChan)
- for line := range lines {
- _, _, msg, _ := ws.NormalizeProjectLine(line)
- cleanChan <- msg
- }
- }()
- go ws.ForwardLines(ctx, ls.hub, cleanChan)
- }
-
- return ls.hub
-}
-
-// GetProjectLogsWS godoc
-//
-// @Summary Get project logs via WebSocket
-// @Description Stream project logs over WebSocket connection
-// @Tags Projects
-// @Param id path string true "Environment ID"
-// @Param projectId path string true "Project ID"
-// @Param follow query bool false "Follow log output" default(true)
-// @Param tail query string false "Number of lines to show from the end" default(100)
-// @Param since query string false "Show logs since timestamp"
-// @Param timestamps query bool false "Show timestamps" default(false)
-// @Param format query string false "Output format (text or json)" default(text)
-// @Param batched query bool false "Batch log messages" default(false)
-// @Router /api/environments/{id}/projects/{projectId}/logs/ws [get]
-func (h *ProjectHandler) GetProjectLogsWS(c *gin.Context) {
- projectID := c.Param("projectId")
- if strings.TrimSpace(projectID) == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
- return
- }
-
- follow := c.DefaultQuery("follow", "true") == "true"
- tail := c.DefaultQuery("tail", "100")
- since := c.Query("since")
- timestamps := c.DefaultQuery("timestamps", "false") == "true"
- format := c.DefaultQuery("format", "text")
- batched := c.DefaultQuery("batched", "false") == "true"
-
- conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- return
- }
- hub := h.getOrStartProjectLogHub(projectID, format, batched, follow, tail, since, timestamps)
- ws.ServeClient(context.Background(), hub, conn)
-}
-
-// GetProjectStatusCounts godoc
-//
-// @Summary Get project status counts
-// @Description Get counts of running, stopped, and total projects
-// @Tags Projects
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[project.StatusCounts]
-// @Router /api/environments/{id}/projects/counts [get]
-func (h *ProjectHandler) GetProjectStatusCounts(c *gin.Context) {
- _, running, stopped, total, err := h.projectService.GetProjectStatusCounts(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.ProjectStatusCountsError{Err: err}).Error()},
- })
- return
- }
-
- out := project.StatusCounts{
- RunningProjects: int(running),
- StoppedProjects: int(stopped),
- TotalProjects: int(total),
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
diff --git a/backend/internal/api/settings_handler.go b/backend/internal/api/settings_handler.go
deleted file mode 100644
index ff77b5459..000000000
--- a/backend/internal/api/settings_handler.go
+++ /dev/null
@@ -1,219 +0,0 @@
-package api
-
-import (
- "net/http"
- "strconv"
- "strings"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/search"
- "go.getarcane.app/types/settings"
-)
-
-type SettingsHandler struct {
- settingsService *services.SettingsService
- settingsSearchService *services.SettingsSearchService
-}
-
-func NewSettingsHandler(group *gin.RouterGroup, settingsService *services.SettingsService, settingsSearchService *services.SettingsSearchService, authMiddleware *middleware.AuthMiddleware) {
- handler := &SettingsHandler{
- settingsService: settingsService,
- settingsSearchService: settingsSearchService,
- }
-
- apiGroup := group.Group("/environments/:id/settings")
-
- apiGroup.GET("/public", handler.GetPublicSettings)
- apiGroup.GET("", authMiddleware.WithAdminNotRequired().Add(), handler.GetSettings)
- apiGroup.PUT("", authMiddleware.WithAdminRequired().Add(), handler.UpdateSettings)
-
- // Also expose top-level settings search and categories endpoints under /api/settings
- top := group.Group("/settings")
- top.POST("/search", authMiddleware.WithAdminNotRequired().Add(), handler.Search)
- top.GET("/categories", authMiddleware.WithAdminNotRequired().Add(), handler.GetCategories)
-}
-
-// Search godoc
-//
-// @Summary Search settings
-// @Description Search settings categories and individual settings by query
-// @Tags Settings
-// @Accept json
-// @Produce json
-// @Param request body search.Request true "Search query"
-// @Success 200 {object} search.Response
-// @Router /api/settings/search [post]
-//
-// Search delegates to the settings search service and returns relevance-scored results
-func (h *SettingsHandler) Search(c *gin.Context) {
- var req search.Request
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- if strings.TrimSpace(req.Query) == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.QueryParameterRequiredError{}).Error()},
- })
- return
- }
-
- results := h.settingsSearchService.Search(req.Query)
- c.JSON(http.StatusOK, results)
-}
-
-// GetCategories godoc
-//
-// @Summary Get settings categories
-// @Description Get all available settings categories with metadata
-// @Tags Settings
-// @Success 200 {array} settings.Category
-// @Router /api/settings/categories [get]
-//
-// GetCategories returns all available settings categories with metadata
-func (h *SettingsHandler) GetCategories(c *gin.Context) {
- categories := h.settingsSearchService.GetSettingsCategories()
- c.JSON(http.StatusOK, categories)
-}
-
-// GetSettings godoc
-//
-// @Summary Get settings
-// @Description Get all settings for an environment
-// @Tags Settings
-// @Param id path string true "Environment ID"
-// @Success 200 {array} settings.PublicSetting
-// @Router /api/environments/{id}/settings [get]
-func (h *SettingsHandler) GetSettings(c *gin.Context) {
- environmentID := c.Param("id")
-
- showAll := environmentID == "0"
- settingsList := h.settingsService.ListSettings(showAll)
-
- var settingsDto []settings.PublicSetting
- if err := mapper.MapStructList(settingsList, &settingsDto); err != nil {
- _ = c.Error(err)
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.SettingsMappingError{Err: err}).Error()},
- })
- return
- }
-
- settingsDto = append(settingsDto, settings.PublicSetting{
- Key: "uiConfigDisabled",
- Value: strconv.FormatBool(config.Load().UIConfigurationDisabled),
- Type: "boolean",
- })
-
- c.JSON(http.StatusOK, settingsDto)
-}
-
-// GetPublicSettings godoc
-//
-// @Summary Get public settings
-// @Description Get all public settings for an environment
-// @Tags Settings
-// @Param id path string true "Environment ID"
-// @Success 200 {array} settings.PublicSetting
-// @Router /api/environments/{id}/settings/public [get]
-func (h *SettingsHandler) GetPublicSettings(c *gin.Context) {
- settingsList := h.settingsService.ListSettings(false)
-
- var settingsDto []settings.PublicSetting
- if err := mapper.MapStructList(settingsList, &settingsDto); err != nil {
- _ = c.Error(err)
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.SettingsMappingError{Err: err}).Error()},
- })
- return
- }
-
- settingsDto = append(settingsDto, settings.PublicSetting{
- Key: "uiConfigDisabled",
- Value: strconv.FormatBool(config.Load().UIConfigurationDisabled),
- Type: "boolean",
- })
-
- c.JSON(http.StatusOK, settingsDto)
-}
-
-// UpdateSettings godoc
-//
-// @Summary Update settings
-// @Description Update settings for an environment
-// @Tags Settings
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param settings body settings.Update true "Settings update data"
-// @Success 200 {object} base.ApiResponse[[]settings.SettingDto]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 403 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/settings [put]
-func (h *SettingsHandler) UpdateSettings(c *gin.Context) {
- environmentID := c.Param("id")
-
- var req settings.Update
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- if environmentID != "0" {
- if req.AuthLocalEnabled != nil || req.OidcEnabled != nil ||
- req.AuthSessionTimeout != nil || req.AuthPasswordPolicy != nil ||
- req.AuthOidcConfig != nil || req.OidcClientId != nil ||
- req.OidcClientSecret != nil || req.OidcIssuerUrl != nil ||
- req.OidcScopes != nil || req.OidcAdminClaim != nil ||
- req.OidcAdminValue != nil || req.OidcMergeAccounts != nil {
- c.JSON(http.StatusForbidden, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.AuthSettingsUpdateError{}).Error()},
- })
- return
- }
- }
-
- updatedSettings, err := h.settingsService.UpdateSettings(c.Request.Context(), req)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.SettingsUpdateError{Err: err}).Error()},
- })
- return
- }
-
- settingDtos := make([]settings.SettingDto, 0, len(updatedSettings))
- for _, setting := range updatedSettings {
- settingDtos = append(settingDtos, settings.SettingDto{
- PublicSetting: settings.PublicSetting{
- Key: setting.Key,
- Type: "string",
- Value: setting.Value,
- },
- })
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "settings": settingDtos,
- })
-}
diff --git a/backend/internal/api/system_handler.go b/backend/internal/api/system_handler.go
deleted file mode 100644
index a5f36b61f..000000000
--- a/backend/internal/api/system_handler.go
+++ /dev/null
@@ -1,1021 +0,0 @@
-package api
-
-import (
- "bytes"
- "context"
- "encoding/csv"
- "encoding/json"
- "errors"
- "fmt"
- "log/slog"
- "net/http"
- "os/exec"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
- httputil "github.com/getarcaneapp/arcane/backend/internal/utils/http"
- "github.com/gin-gonic/gin"
- "github.com/gorilla/websocket"
- "github.com/shirou/gopsutil/v4/cpu"
- "github.com/shirou/gopsutil/v4/disk"
- "github.com/shirou/gopsutil/v4/host"
- "github.com/shirou/gopsutil/v4/mem"
- "go.getarcane.app/types/dockerinfo"
- "go.getarcane.app/types/system"
-)
-
-const (
- gpuCacheDuration = 30 * time.Second
-)
-
-// GPUStats represents statistics for a single GPU
-type GPUStats struct {
- Name string `json:"name"`
- Index int `json:"index"`
- MemoryUsed float64 `json:"memoryUsed"` // in bytes
- MemoryTotal float64 `json:"memoryTotal"` // in bytes
-}
-
-type SystemHandler struct {
- dockerService *services.DockerClientService
- systemService *services.SystemService
- upgradeService *services.SystemUpgradeService
- sysWsUpgrader websocket.Upgrader
- activeConnections sync.Map
- cpuCache struct {
- sync.RWMutex
- value float64
- timestamp time.Time
- }
- diskUsagePathCache struct {
- sync.RWMutex
- value string
- timestamp time.Time
- }
- gpuDetectionCache struct {
- sync.RWMutex
- detected bool
- timestamp time.Time
- gpuType string // "nvidia", "amd", "intel", or ""
- toolPath string
- }
- detectionDone bool
- detectionMutex sync.Mutex
- gpuMonitoringEnabled bool
- gpuType string
-}
-
-func NewSystemHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, authMiddleware *middleware.AuthMiddleware, cfg *config.Config) {
- handler := &SystemHandler{
- dockerService: dockerService,
- systemService: systemService,
- upgradeService: upgradeService,
- gpuMonitoringEnabled: cfg.GPUMonitoringEnabled,
- gpuType: cfg.GPUType,
- sysWsUpgrader: websocket.Upgrader{
- CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.AppUrl),
- },
- }
-
- apiGroup := group.Group("/environments/:id/system")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.HEAD("/health", handler.Health)
- apiGroup.GET("/stats/ws", handler.Stats)
- apiGroup.GET("/docker/info", handler.GetDockerInfo)
- apiGroup.POST("/prune", handler.PruneAll)
- apiGroup.POST("/containers/start-all", handler.StartAllContainers)
- apiGroup.POST("/containers/start-stopped", handler.StartAllStoppedContainers)
- apiGroup.POST("/containers/stop-all", handler.StopAllContainers)
- apiGroup.POST("/convert", handler.ConvertDockerRun)
-
- // Upgrade endpoints (admin required)
- apiGroup.GET("/upgrade/check", authMiddleware.WithAdminRequired().Add(), handler.CheckUpgradeAvailable)
- apiGroup.POST("/upgrade", authMiddleware.WithAdminRequired().Add(), handler.TriggerUpgrade)
- }
-}
-
-type SystemStats struct {
- CPUUsage float64 `json:"cpuUsage"`
- MemoryUsage uint64 `json:"memoryUsage"`
- MemoryTotal uint64 `json:"memoryTotal"`
- DiskUsage uint64 `json:"diskUsage,omitempty"`
- DiskTotal uint64 `json:"diskTotal,omitempty"`
- CPUCount int `json:"cpuCount"`
- Architecture string `json:"architecture"`
- Platform string `json:"platform"`
- Hostname string `json:"hostname,omitempty"`
- GPUCount int `json:"gpuCount"`
- GPUs []GPUStats `json:"gpus,omitempty"`
-}
-
-// Health godoc
-//
-// @Summary Check system health
-// @Description Check if the Docker daemon is responsive
-// @Tags System
-// @Param id path string true "Environment ID"
-// @Success 200
-// @Router /api/environments/{id}/system/health [head]
-func (h *SystemHandler) Health(c *gin.Context) {
- ctx := c.Request.Context()
-
- dockerClient, err := h.dockerService.GetClient()
- if err != nil {
- c.Status(http.StatusServiceUnavailable)
- return
- }
-
- // Try to ping Docker to ensure it's responsive
- _, err = dockerClient.Ping(ctx)
- if err != nil {
- c.Status(http.StatusServiceUnavailable)
- return
- }
-
- c.Status(http.StatusOK)
-}
-
-// GetDockerInfo godoc
-//
-// @Summary Get Docker info
-// @Description Get Docker daemon version and system information
-// @Tags System
-// @Param id path string true "Environment ID"
-// @Success 200 {object} dockerinfo.Info
-// @Router /api/environments/{id}/system/docker/info [get]
-func (h *SystemHandler) GetDockerInfo(c *gin.Context) {
- ctx := c.Request.Context()
-
- dockerClient, err := h.dockerService.GetClient()
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.DockerConnectionError{Err: err}).Error(),
- })
- return
- }
-
- version, err := dockerClient.ServerVersion(ctx)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.DockerVersionError{Err: err}).Error(),
- })
- return
- }
-
- info, err := dockerClient.Info(ctx)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.DockerInfoError{Err: err}).Error(),
- })
- return
- }
-
- cpuCount := info.NCPU
- memTotal := info.MemTotal
-
- // Check for cgroup limits (LXC, Docker, etc.)
- if cgroupLimits, err := utils.DetectCgroupLimits(); err == nil {
- // Use cgroup memory limit if available and smaller than host value
- if limit := cgroupLimits.MemoryLimit; limit > 0 {
- limitInt := int64(limit)
- if memTotal == 0 || limitInt < memTotal {
- memTotal = limitInt
- }
- }
-
- // Use cgroup CPU count if available
- if cgroupLimits.CPUCount > 0 && (cpuCount == 0 || cgroupLimits.CPUCount < cpuCount) {
- cpuCount = cgroupLimits.CPUCount
- }
- }
-
- // Update info with cgroup limits
- info.NCPU = cpuCount
- info.MemTotal = memTotal
-
- dockerInfo := dockerinfo.Info{
- Success: true,
- APIVersion: version.APIVersion,
- GitCommit: version.GitCommit,
- GoVersion: version.GoVersion,
- Os: version.Os,
- Arch: version.Arch,
- BuildTime: version.BuildTime,
- Info: info,
- }
-
- c.JSON(http.StatusOK, dockerInfo)
-}
-
-// PruneAll godoc
-//
-// @Summary Prune Docker resources
-// @Description Remove unused Docker resources (containers, images, volumes, networks)
-// @Tags System
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param request body system.PruneAllRequest true "Prune options"
-// @Success 200 {object} base.ApiResponse[system.PruneResult]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/system/prune [post]
-func (h *SystemHandler) PruneAll(c *gin.Context) {
- ctx := c.Request.Context()
- slog.InfoContext(ctx, "System prune operation initiated")
-
- var req system.PruneAllRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- slog.ErrorContext(ctx, "Failed to bind prune request JSON", "error", err, "client_ip", c.ClientIP())
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.InvalidRequestFormatError{Err: err}).Error(),
- })
- return
- }
-
- slog.InfoContext(ctx, "Prune request parsed successfully",
- "containers", req.Containers,
- "images", req.Images,
- "volumes", req.Volumes,
- "networks", req.Networks,
- "build_cache", req.BuildCache,
- "dangling", req.Dangling)
-
- result, err := h.systemService.PruneAll(ctx, req)
- if err != nil {
- slog.ErrorContext(ctx, "System prune operation failed", "error", err, "client_ip", c.ClientIP())
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.SystemPruneError{Err: err}).Error(),
- })
- return
- }
-
- slog.InfoContext(ctx, "System prune operation completed successfully",
- "containers_pruned", len(result.ContainersPruned),
- "images_deleted", len(result.ImagesDeleted),
- "volumes_deleted", len(result.VolumesDeleted),
- "networks_deleted", len(result.NetworksDeleted),
- "space_reclaimed", result.SpaceReclaimed,
- "success", result.Success,
- "error_count", len(result.Errors))
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Pruning completed",
- "data": result,
- })
-}
-
-// StartAllContainers godoc
-//
-// @Summary Start all containers
-// @Description Start all Docker containers
-// @Tags System
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[system.ContainerBulkActionResult]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/system/containers/start-all [post]
-func (h *SystemHandler) StartAllContainers(c *gin.Context) {
- result, err := h.systemService.StartAllContainers(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ContainerStartAllError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Container start operation completed",
- "data": result,
- })
-}
-
-// StartAllStoppedContainers godoc
-//
-// @Summary Start all stopped containers
-// @Description Start all stopped Docker containers
-// @Tags System
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[system.ContainerBulkActionResult]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/system/containers/start-stopped [post]
-func (h *SystemHandler) StartAllStoppedContainers(c *gin.Context) {
- result, err := h.systemService.StartAllStoppedContainers(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ContainerStartStoppedError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Stopped containers start operation completed",
- "data": result,
- })
-}
-
-func (h *SystemHandler) getDiskUsagePath(ctx context.Context) string {
- h.diskUsagePathCache.RLock()
- if h.diskUsagePathCache.value != "" && time.Since(h.diskUsagePathCache.timestamp) < 30*time.Second {
- path := h.diskUsagePathCache.value
- h.diskUsagePathCache.RUnlock()
- return path
- }
- h.diskUsagePathCache.RUnlock()
-
- diskUsagePath := h.systemService.GetDiskUsagePath(ctx)
- if diskUsagePath == "" {
- diskUsagePath = "/"
- }
-
- h.diskUsagePathCache.Lock()
- h.diskUsagePathCache.value = diskUsagePath
- h.diskUsagePathCache.timestamp = time.Now()
- h.diskUsagePathCache.Unlock()
-
- return diskUsagePath
-}
-
-// StopAllContainers godoc
-//
-// @Summary Stop all containers
-// @Description Stop all running Docker containers
-// @Tags System
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[system.ContainerBulkActionResult]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/system/containers/stop-all [post]
-func (h *SystemHandler) StopAllContainers(c *gin.Context) {
- result, err := h.systemService.StopAllContainers(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.ContainerStopAllError{Err: err}).Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Container stop operation completed",
- "data": result,
- })
-}
-
-// Stats godoc
-//
-// @Summary Get system stats via WebSocket
-// @Description Stream system resource statistics over WebSocket connection
-// @Tags System
-// @Param id path string true "Environment ID"
-// @Router /api/environments/{id}/system/stats/ws [get]
-//
-//nolint:gocognit
-func (h *SystemHandler) Stats(c *gin.Context) {
- clientIP := c.ClientIP()
-
- connCount, _ := h.activeConnections.LoadOrStore(clientIP, new(int32))
- count := connCount.(*int32)
-
- currentCount := atomic.AddInt32(count, 1)
- if currentCount > 5 {
- atomic.AddInt32(count, -1)
- c.JSON(http.StatusTooManyRequests, gin.H{
- "success": false,
- "error": "Too many concurrent stats connections from this IP",
- })
- return
- }
-
- defer func() {
- newCount := atomic.AddInt32(count, -1)
- if newCount <= 0 {
- h.activeConnections.Delete(clientIP)
- }
- }()
-
- conn, err := h.sysWsUpgrader.Upgrade(c.Writer, c.Request, nil)
- if err != nil {
- return
- }
- defer conn.Close()
-
- ticker := time.NewTicker(2 * time.Second)
- defer ticker.Stop()
-
- cpuUpdateTicker := time.NewTicker(1 * time.Second)
- defer cpuUpdateTicker.Stop()
-
- ctx, cancel := context.WithCancel(c.Request.Context())
- defer cancel()
-
- go func(ctx context.Context) {
- for {
- select {
- case <-ctx.Done():
- return
- case <-cpuUpdateTicker.C:
- if vals, err := cpu.Percent(0, false); err == nil && len(vals) > 0 {
- h.cpuCache.Lock()
- h.cpuCache.value = vals[0]
- h.cpuCache.timestamp = time.Now()
- h.cpuCache.Unlock()
- }
- }
- }
- }(ctx)
-
- send := func() error {
- h.cpuCache.RLock()
- cpuUsage := h.cpuCache.value
- h.cpuCache.RUnlock()
-
- cpuCount, err := cpu.Counts(true)
- if err != nil {
- cpuCount = runtime.NumCPU()
- }
-
- memInfo, _ := mem.VirtualMemory()
- var memUsed, memTotal uint64
- if memInfo != nil {
- memUsed = memInfo.Used
- memTotal = memInfo.Total
- }
-
- // Apply cgroup limits when running in a memory-limited container.
- // When a memory limit is set (e.g., deploy.resources.limits.memory in compose),
- // we must use BOTH the cgroup memory limit AND the cgroup memory usage.
- // Using host-wide memory usage against a container limit would show incorrect
- // percentages (e.g., 2GB host usage / 256MB limit = 825%).
- if cgroupLimits, err := utils.DetectCgroupLimits(); err == nil {
- // Use cgroup memory limit if available and smaller than host values
- if limit := cgroupLimits.MemoryLimit; limit > 0 {
- limitUint := uint64(limit)
- if memTotal == 0 || limitUint < memTotal {
- memTotal = limitUint
- // When we have a cgroup memory limit, we should also use cgroup memory usage
- // to ensure both values refer to the same scope (container, not host).
- // This fixes incorrect memory percentages when running with memory limits.
- if cgroupLimits.MemoryUsage > 0 {
- memUsed = uint64(cgroupLimits.MemoryUsage)
- }
- }
- }
-
- // Use cgroup CPU count if available
- if cgroupLimits.CPUCount > 0 && (cpuCount == 0 || cgroupLimits.CPUCount < cpuCount) {
- cpuCount = cgroupLimits.CPUCount
- }
- }
-
- diskUsagePath := h.getDiskUsagePath(ctx)
- diskInfo, err := disk.Usage(diskUsagePath)
- if err != nil || diskInfo == nil || diskInfo.Total == 0 {
- if diskUsagePath != "/" {
- diskInfo, _ = disk.Usage("/")
- }
- }
-
- var diskUsed, diskTotal uint64
- if diskInfo != nil {
- diskUsed = diskInfo.Used
- diskTotal = diskInfo.Total
- }
-
- hostInfo, _ := host.Info()
- var hostname string
- if hostInfo != nil {
- hostname = hostInfo.Hostname
- }
-
- var gpuStats []GPUStats
- var gpuCount int
- if h.gpuMonitoringEnabled {
- if gpuData, err := h.getGPUStats(ctx); err == nil {
- gpuStats = gpuData
- gpuCount = len(gpuData)
- }
- }
-
- stats := SystemStats{
- CPUUsage: cpuUsage,
- MemoryUsage: memUsed,
- MemoryTotal: memTotal,
- DiskUsage: diskUsed,
- DiskTotal: diskTotal,
- CPUCount: cpuCount,
- Architecture: runtime.GOARCH,
- Platform: runtime.GOOS,
- Hostname: hostname,
- GPUCount: gpuCount,
- GPUs: gpuStats,
- }
-
- _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
- return conn.WriteJSON(stats)
- }
-
- if vals, err := cpu.Percent(time.Second, false); err == nil && len(vals) > 0 {
- h.cpuCache.Lock()
- h.cpuCache.value = vals[0]
- h.cpuCache.timestamp = time.Now()
- h.cpuCache.Unlock()
- }
-
- if err := send(); err != nil {
- return
- }
-
- for {
- select {
- case <-c.Request.Context().Done():
- return
- case <-ticker.C:
- if err := send(); err != nil {
- return
- }
- }
- }
-}
-
-// ConvertDockerRun godoc
-//
-// @Summary Convert docker run command
-// @Description Convert a docker run command to docker-compose format
-// @Tags System
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param request body models.ConvertDockerRunRequest true "Docker run command"
-// @Success 200 {object} models.ConvertDockerRunResponse
-// @Router /api/environments/{id}/system/convert [post]
-func (h *SystemHandler) ConvertDockerRun(c *gin.Context) {
- var req models.ConvertDockerRunRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.InvalidRequestFormatError{Err: err}).Error(),
- })
- return
- }
-
- parsed, err := h.systemService.ParseDockerRunCommand(req.DockerRunCommand)
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": (&common.DockerRunParseError{Err: err}).Error(),
- "code": "BAD_REQUEST",
- })
- return
- }
-
- dockerCompose, envVars, serviceName, err := h.systemService.ConvertToDockerCompose(parsed)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": (&common.DockerComposeConversionError{Err: err}).Error(),
- "code": "CONVERSION_ERROR",
- })
- return
- }
-
- c.JSON(http.StatusOK, models.ConvertDockerRunResponse{
- Success: true,
- DockerCompose: dockerCompose,
- EnvVars: envVars,
- ServiceName: serviceName,
- })
-}
-
-// CheckUpgradeAvailable godoc
-//
-// @Summary Check for system upgrade
-// @Description Check if a system upgrade is available
-// @Tags System
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[system.UpgradeCheckResult]
-// @Router /api/environments/{id}/system/upgrade/check [get]
-//
-// CheckUpgradeAvailable checks if the local system can be upgraded
-// Remote environments are handled by the proxy middleware
-func (h *SystemHandler) CheckUpgradeAvailable(c *gin.Context) {
- canUpgrade, err := h.upgradeService.CanUpgrade(c.Request.Context())
-
- if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "canUpgrade": false,
- "error": true,
- "message": (&common.UpgradeCheckError{Err: err}).Error(),
- })
- slog.Debug("System upgrade check failed", "error", err)
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "canUpgrade": canUpgrade,
- "error": false,
- "message": "System can be upgraded",
- })
-}
-
-// TriggerUpgrade godoc
-//
-// @Summary Trigger system upgrade
-// @Description Trigger a system upgrade
-// @Tags System
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 202 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/system/upgrade [post]
-//
-// TriggerUpgrade triggers a system upgrade by spawning the upgrade CLI command
-// This runs the upgrade from outside the current container to avoid self-termination issues
-func (h *SystemHandler) TriggerUpgrade(c *gin.Context) {
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- slog.Info("System upgrade triggered", "user", currentUser.Username, "userId", currentUser.ID)
-
- err := h.upgradeService.TriggerUpgradeViaCLI(c.Request.Context(), *currentUser)
- if err != nil {
- slog.Error("System upgrade failed", "error", err, "user", currentUser.Username)
-
- statusCode := http.StatusInternalServerError
- if errors.Is(err, services.ErrUpgradeInProgress) {
- statusCode = http.StatusConflict
- }
-
- c.JSON(statusCode, gin.H{
- "error": (&common.UpgradeTriggerError{Err: err}).Error(),
- "message": "Failed to initiate upgrade",
- })
- return
- }
-
- c.JSON(http.StatusAccepted, gin.H{
- "message": "Upgrade initiated successfully. A new container is being created and will replace this one shortly.",
- "success": true,
- })
-}
-
-// getGPUStats collects and returns GPU statistics for all available GPUs
-func (h *SystemHandler) getGPUStats(ctx context.Context) ([]GPUStats, error) {
- // Check if we need to detect GPUs
- h.detectionMutex.Lock()
- done := h.detectionDone
- h.detectionMutex.Unlock()
-
- if !done {
- if err := h.detectGPUs(ctx); err != nil {
- return nil, err
- }
- }
-
- // Check cache
- h.gpuDetectionCache.RLock()
- if h.gpuDetectionCache.detected && time.Since(h.gpuDetectionCache.timestamp) < gpuCacheDuration {
- gpuType := h.gpuDetectionCache.gpuType
- h.gpuDetectionCache.RUnlock()
-
- // Collect stats based on GPU type
- switch gpuType {
- case "nvidia":
- return h.getNvidiaStats(ctx)
- case "amd":
- return h.getAMDStats(ctx)
- case "intel":
- return h.getIntelStats(ctx)
- }
- }
- h.gpuDetectionCache.RUnlock()
-
- // Re-detect if cache expired
- if err := h.detectGPUs(ctx); err != nil {
- return nil, err
- }
-
- // Try again after detection
- h.gpuDetectionCache.RLock()
- gpuType := h.gpuDetectionCache.gpuType
- h.gpuDetectionCache.RUnlock()
-
- switch gpuType {
- case "nvidia":
- return h.getNvidiaStats(ctx)
- case "amd":
- return h.getAMDStats(ctx)
- case "intel":
- return h.getIntelStats(ctx)
- default:
- return nil, fmt.Errorf("no supported GPU found")
- }
-}
-
-// detectGPUs detects available GPU management tools
-func (h *SystemHandler) detectGPUs(ctx context.Context) error {
- h.detectionMutex.Lock()
- defer h.detectionMutex.Unlock()
-
- // If GPU type is explicitly specified, skip detection and use that type
- if h.gpuType != "" && h.gpuType != "auto" {
- switch h.gpuType {
- case "nvidia":
- if path, err := exec.LookPath("nvidia-smi"); err == nil {
- h.gpuDetectionCache.Lock()
- h.gpuDetectionCache.detected = true
- h.gpuDetectionCache.gpuType = "nvidia"
- h.gpuDetectionCache.toolPath = path
- h.gpuDetectionCache.timestamp = time.Now()
- h.gpuDetectionCache.Unlock()
- h.detectionDone = true
- slog.InfoContext(ctx, "Using configured GPU type", slog.String("type", "nvidia"))
- return nil
- }
- return fmt.Errorf("nvidia-smi not found but GPU_TYPE set to nvidia")
-
- case "amd":
- if path, err := exec.LookPath("rocm-smi"); err == nil {
- h.gpuDetectionCache.Lock()
- h.gpuDetectionCache.detected = true
- h.gpuDetectionCache.gpuType = "amd"
- h.gpuDetectionCache.toolPath = path
- h.gpuDetectionCache.timestamp = time.Now()
- h.gpuDetectionCache.Unlock()
- h.detectionDone = true
- slog.InfoContext(ctx, "Using configured GPU type", slog.String("type", "amd"))
- return nil
- }
- return fmt.Errorf("rocm-smi not found but GPU_TYPE set to amd")
-
- case "intel":
- if path, err := exec.LookPath("intel_gpu_top"); err == nil {
- h.gpuDetectionCache.Lock()
- h.gpuDetectionCache.detected = true
- h.gpuDetectionCache.gpuType = "intel"
- h.gpuDetectionCache.toolPath = path
- h.gpuDetectionCache.timestamp = time.Now()
- h.gpuDetectionCache.Unlock()
- h.detectionDone = true
- slog.InfoContext(ctx, "Using configured GPU type", slog.String("type", "intel"))
- return nil
- }
- return fmt.Errorf("intel_gpu_top not found but GPU_TYPE set to intel")
-
- default:
- slog.WarnContext(ctx, "Invalid GPU_TYPE specified, falling back to auto-detection", slog.String("gpu_type", h.gpuType))
- // Fall through to auto-detection
- }
- }
-
- // Auto-detection: Check in order (nvidia → amd → intel)
- // Check for NVIDIA
- if path, err := exec.LookPath("nvidia-smi"); err == nil {
- h.gpuDetectionCache.Lock()
- h.gpuDetectionCache.detected = true
- h.gpuDetectionCache.gpuType = "nvidia"
- h.gpuDetectionCache.toolPath = path
- h.gpuDetectionCache.timestamp = time.Now()
- h.gpuDetectionCache.Unlock()
- h.detectionDone = true
- slog.InfoContext(ctx, "NVIDIA GPU detected", "tool", "nvidia-smi", "path", path)
- return nil
- }
-
- // Check for AMD ROCm
- if path, err := exec.LookPath("rocm-smi"); err == nil {
- h.gpuDetectionCache.Lock()
- h.gpuDetectionCache.detected = true
- h.gpuDetectionCache.gpuType = "amd"
- h.gpuDetectionCache.toolPath = path
- h.gpuDetectionCache.timestamp = time.Now()
- h.gpuDetectionCache.Unlock()
- h.detectionDone = true
- slog.InfoContext(ctx, "AMD GPU detected", "tool", "rocm-smi", "path", path)
- return nil
- }
-
- // Check for Intel GPU
- if path, err := exec.LookPath("intel_gpu_top"); err == nil {
- h.gpuDetectionCache.Lock()
- h.gpuDetectionCache.detected = true
- h.gpuDetectionCache.gpuType = "intel"
- h.gpuDetectionCache.toolPath = path
- h.gpuDetectionCache.timestamp = time.Now()
- h.gpuDetectionCache.Unlock()
- h.detectionDone = true
- slog.InfoContext(ctx, "Intel GPU detected", "tool", "intel_gpu_top", "path", path)
- return nil
- }
-
- h.detectionDone = true
- return fmt.Errorf("no supported GPU found")
-}
-
-// getNvidiaStats collects NVIDIA GPU statistics using nvidia-smi
-func (h *SystemHandler) getNvidiaStats(ctx context.Context) ([]GPUStats, error) {
- ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
- defer cancel()
-
- // Query: index, name, memory.used, memory.total
- cmd := exec.CommandContext(ctx, "nvidia-smi",
- "--query-gpu=index,name,memory.used,memory.total",
- "--format=csv,noheader,nounits")
-
- output, err := cmd.Output()
- if err != nil {
- slog.WarnContext(ctx, "Failed to execute nvidia-smi", "error", err)
- return nil, fmt.Errorf("nvidia-smi execution failed: %w", err)
- }
-
- return h.parseNvidiaOutput(ctx, output)
-}
-
-// parseNvidiaOutput parses CSV output from nvidia-smi
-func (h *SystemHandler) parseNvidiaOutput(ctx context.Context, output []byte) ([]GPUStats, error) {
- reader := csv.NewReader(bytes.NewReader(output))
- reader.TrimLeadingSpace = true
-
- records, err := reader.ReadAll()
- if err != nil {
- slog.WarnContext(ctx, "Failed to parse nvidia-smi CSV output", "error", err)
- return nil, fmt.Errorf("failed to parse nvidia-smi output: %w", err)
- }
-
- var stats []GPUStats
- for _, record := range records {
- if len(record) < 4 {
- continue
- }
-
- index, err := strconv.Atoi(strings.TrimSpace(record[0]))
- if err != nil {
- slog.WarnContext(ctx, "Failed to parse GPU index", "value", record[0])
- continue
- }
-
- name := strings.TrimSpace(record[1])
-
- memUsed, err := strconv.ParseFloat(strings.TrimSpace(record[2]), 64)
- if err != nil {
- slog.WarnContext(ctx, "Failed to parse memory used", "value", record[2])
- continue
- }
-
- memTotal, err := strconv.ParseFloat(strings.TrimSpace(record[3]), 64)
- if err != nil {
- slog.WarnContext(ctx, "Failed to parse memory total", "value", record[3])
- continue
- }
-
- // nvidia-smi returns MiB (mebibytes), convert to bytes (1 MiB = 1024*1024 bytes)
- stats = append(stats, GPUStats{
- Name: name,
- Index: index,
- MemoryUsed: memUsed * 1024 * 1024,
- MemoryTotal: memTotal * 1024 * 1024,
- })
- }
-
- if len(stats) == 0 {
- return nil, fmt.Errorf("no GPU data parsed from nvidia-smi")
- }
-
- slog.DebugContext(ctx, "Collected NVIDIA GPU stats", "gpu_count", len(stats))
- return stats, nil
-}
-
-// getAMDStats collects AMD GPU statistics using rocm-smi
-func (h *SystemHandler) getAMDStats(ctx context.Context) ([]GPUStats, error) {
- ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
- defer cancel()
-
- cmd := exec.CommandContext(ctx, "rocm-smi", "--showmeminfo", "vram", "--json")
- output, err := cmd.Output()
- if err != nil {
- slog.WarnContext(ctx, "Failed to execute rocm-smi", "error", err)
- return nil, fmt.Errorf("rocm-smi execution failed: %w", err)
- }
-
- return h.parseROCmOutput(ctx, output)
-}
-
-// ROCmSMIOutput represents the JSON structure from rocm-smi
-type ROCmSMIOutput map[string]ROCmGPUInfo
-
-type ROCmGPUInfo struct {
- VRAMUsed string `json:"VRAM Total Used Memory (B)"`
- VRAMTotal string `json:"VRAM Total Memory (B)"`
-}
-
-// parseROCmOutput parses JSON output from rocm-smi
-func (h *SystemHandler) parseROCmOutput(ctx context.Context, output []byte) ([]GPUStats, error) {
- var rocmData ROCmSMIOutput
- if err := json.Unmarshal(output, &rocmData); err != nil {
- slog.WarnContext(ctx, "Failed to parse rocm-smi JSON output", "error", err)
- return nil, fmt.Errorf("failed to parse rocm-smi output: %w", err)
- }
-
- var stats []GPUStats
- index := 0
- for gpuID, info := range rocmData {
- // Parse memory used (in bytes)
- memUsedBytes, err := strconv.ParseFloat(info.VRAMUsed, 64)
- if err != nil {
- slog.WarnContext(ctx, "Failed to parse AMD memory used", "gpu", gpuID, "value", info.VRAMUsed)
- continue
- }
-
- // Parse memory total (in bytes)
- memTotalBytes, err := strconv.ParseFloat(info.VRAMTotal, 64)
- if err != nil {
- slog.WarnContext(ctx, "Failed to parse AMD memory total", "gpu", gpuID, "value", info.VRAMTotal)
- continue
- }
-
- // ROCm already returns bytes, use directly
- stats = append(stats, GPUStats{
- Name: fmt.Sprintf("AMD GPU %s", gpuID),
- Index: index,
- MemoryUsed: memUsedBytes,
- MemoryTotal: memTotalBytes,
- })
- index++
- }
-
- if len(stats) == 0 {
- return nil, fmt.Errorf("no GPU data parsed from rocm-smi")
- }
-
- slog.DebugContext(ctx, "Collected AMD GPU stats", "gpu_count", len(stats))
- return stats, nil
-}
-
-// getIntelStats collects Intel GPU statistics using intel_gpu_top
-func (h *SystemHandler) getIntelStats(ctx context.Context) ([]GPUStats, error) {
- ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
- defer cancel()
-
- // intel_gpu_top requires running with -o - for single sample JSON output
- cmd := exec.CommandContext(ctx, "intel_gpu_top", "-J", "-o", "-")
- output, err := cmd.Output()
- if err != nil {
- slog.WarnContext(ctx, "Failed to execute intel_gpu_top", "error", err)
- return nil, fmt.Errorf("intel_gpu_top execution failed: %w", err)
- }
-
- return h.parseIntelOutput(ctx, output)
-}
-
-// parseIntelOutput parses JSON output from intel_gpu_top
-func (h *SystemHandler) parseIntelOutput(ctx context.Context, output []byte) ([]GPUStats, error) {
- // intel_gpu_top doesn't provide straightforward total memory info
- // This is a simplified implementation - for MVP we'll return basic info
-
- // For now, return a placeholder indicating Intel GPU detected
- // A more complete implementation would parse /sys/class/drm/card*/device/mem_info_vram_total
- stats := []GPUStats{
- {
- Name: "Intel GPU",
- Index: 0,
- MemoryUsed: 0,
- MemoryTotal: 0,
- },
- }
-
- slog.DebugContext(ctx, "Intel GPU detected but detailed stats not yet implemented")
- return stats, nil
-}
diff --git a/backend/internal/api/template_handler.go b/backend/internal/api/template_handler.go
deleted file mode 100644
index 15c7575e7..000000000
--- a/backend/internal/api/template_handler.go
+++ /dev/null
@@ -1,820 +0,0 @@
-package api
-
-import (
- "encoding/json"
- "net/http"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/env"
- "go.getarcane.app/types/template"
-)
-
-type TemplateHandler struct {
- templateService *services.TemplateService
-}
-
-func NewTemplateHandler(group *gin.RouterGroup, templateService *services.TemplateService, authMiddleware *middleware.AuthMiddleware) {
- handler := &TemplateHandler{templateService: templateService}
-
- apiGroup := group.Group("/templates")
-
- apiGroup.GET("/fetch", handler.FetchRegistry)
-
- apiGroup.GET("", authMiddleware.WithAdminNotRequired().WithSuccessOptional().Add(), handler.GetAllTemplatesPaginated)
- apiGroup.GET("/all", authMiddleware.WithAdminNotRequired().WithSuccessOptional().Add(), handler.GetAllTemplates)
- apiGroup.GET("/:id", authMiddleware.WithAdminNotRequired().WithSuccessOptional().Add(), handler.GetTemplate)
- apiGroup.GET("/:id/content", authMiddleware.WithAdminNotRequired().WithSuccessOptional().Add(), handler.GetTemplateContent)
-
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.POST("", handler.CreateTemplate)
- apiGroup.PUT("/:id", handler.UpdateTemplate)
- apiGroup.DELETE("/:id", handler.DeleteTemplate)
- apiGroup.POST("/:id/download", handler.DownloadTemplate)
- apiGroup.GET("/default", handler.GetDefaultTemplates)
- apiGroup.POST("/default", handler.SaveDefaultTemplates)
- apiGroup.GET("/registries", handler.GetRegistries)
- apiGroup.POST("/registries", handler.CreateRegistry)
- apiGroup.PUT("/registries/:id", handler.UpdateRegistry)
- apiGroup.DELETE("/registries/:id", handler.DeleteRegistry)
- apiGroup.GET("/variables", handler.GetGlobalVariables)
- apiGroup.PUT("/variables", handler.UpdateGlobalVariables)
- }
-}
-
-// GetAllTemplatesPaginated godoc
-//
-// @Summary List templates (paginated)
-// @Description Get a paginated list of compose templates
-// @Tags Templates
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[template.Template]
-// @Router /api/templates [get]
-func (h *TemplateHandler) GetAllTemplatesPaginated(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- if params.Limit == 0 {
- params.Limit = 20
- }
-
- templates, paginationResp, err := h.templateService.GetAllTemplatesPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateListError{Err: err}).Error()},
- })
- return
- }
-
- pagination.ApplyFilterResultsHeaders(&c.Writer, pagination.FilterResult[template.Template]{
- Items: templates,
- TotalCount: paginationResp.TotalItems,
- TotalAvailable: paginationResp.GrandTotalItems,
- })
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": templates,
- "pagination": paginationResp,
- })
-}
-
-// GetAllTemplates godoc
-//
-// @Summary List all templates
-// @Description Get all compose templates without pagination
-// @Tags Templates
-// @Success 200 {array} template.Template
-// @Router /api/templates/all [get]
-func (h *TemplateHandler) GetAllTemplates(c *gin.Context) {
- templates, err := h.templateService.GetAllTemplates(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateListError{Err: err}).Error()},
- })
- return
- }
-
- var out []template.Template
- if mapped, mapErr := mapper.MapSlice[models.ComposeTemplate, template.Template](templates); mapErr == nil {
- out = mapped
- } else {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateMappingError{Err: mapErr}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// GetTemplate godoc
-//
-// @Summary Get a template
-// @Description Get a compose template by ID
-// @Tags Templates
-// @Param id path string true "Template ID"
-// @Success 200 {object} base.ApiResponse[template.Template]
-// @Router /api/templates/{id} [get]
-func (h *TemplateHandler) GetTemplate(c *gin.Context) {
- id := c.Param("id")
- if id == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateIDRequiredError{}).Error()},
- })
- return
- }
-
- tmpl, err := h.templateService.GetTemplate(c.Request.Context(), id)
- if err != nil {
- status := http.StatusInternalServerError
- var msg string
- if err.Error() == "template not found" {
- status = http.StatusNotFound
- msg = (&common.TemplateNotFoundError{}).Error()
- } else {
- msg = (&common.TemplateRetrievalError{Err: err}).Error()
- }
- c.JSON(status, gin.H{
- "success": false,
- "data": gin.H{"error": msg},
- })
- return
- }
-
- var out template.Template
- if mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateMappingError{Err: mapErr}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// GetTemplateContent godoc
-//
-// @Summary Get template content
-// @Description Get the compose content for a template with parsed data
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Template ID"
-// @Success 200 {object} base.ApiResponse[template.Content]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/{id}/content [get]
-func (h *TemplateHandler) GetTemplateContent(c *gin.Context) {
- id := c.Param("id")
- if id == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateIDRequiredError{}).Error()},
- })
- return
- }
-
- contentData, err := h.templateService.GetTemplateContentWithParsedData(c.Request.Context(), id)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateContentError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": contentData,
- })
-}
-
-// CreateTemplate godoc
-//
-// @Summary Create a template
-// @Description Create a new compose template
-// @Tags Templates
-// @Accept json
-// @Produce json
-// @Param template body object true "Template creation data"
-// @Success 201 {object} base.ApiResponse[template.Template]
-// @Router /api/templates [post]
-func (h *TemplateHandler) CreateTemplate(c *gin.Context) {
- var req struct {
- Name string `json:"name" binding:"required"`
- Description string `json:"description"`
- Content string `json:"content" binding:"required"`
- EnvContent string `json:"envContent"`
- }
-
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- tmpl := &models.ComposeTemplate{
- Name: req.Name,
- Description: req.Description,
- Content: req.Content,
- IsCustom: true,
- IsRemote: false,
- }
- if req.EnvContent != "" {
- tmpl.EnvContent = &req.EnvContent
- }
-
- if err := h.templateService.CreateTemplate(c.Request.Context(), tmpl); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateCreationError{Err: err}).Error()},
- })
- return
- }
-
- var out template.Template
- if mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateMappingError{Err: mapErr}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// UpdateTemplate godoc
-//
-// @Summary Update a template
-// @Description Update an existing compose template
-// @Tags Templates
-// @Accept json
-// @Produce json
-// @Param id path string true "Template ID"
-// @Param template body object true "Template update data"
-// @Success 200 {object} base.ApiResponse[template.Template]
-// @Router /api/templates/{id} [put]
-func (h *TemplateHandler) UpdateTemplate(c *gin.Context) {
- id := c.Param("id")
- if id == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateIDRequiredError{}).Error()},
- })
- return
- }
-
- var req struct {
- Name string `json:"name" binding:"required"`
- Description string `json:"description"`
- Content string `json:"content" binding:"required"`
- EnvContent string `json:"envContent"`
- }
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- updates := &models.ComposeTemplate{
- Name: req.Name,
- Description: req.Description,
- Content: req.Content,
- }
- if req.EnvContent != "" {
- updates.EnvContent = &req.EnvContent
- } else {
- updates.EnvContent = nil
- }
-
- if err := h.templateService.UpdateTemplate(c.Request.Context(), id, updates); err != nil {
- status := http.StatusInternalServerError
- var msg string
- if err.Error() == "template not found" {
- status = http.StatusNotFound
- msg = (&common.TemplateNotFoundError{}).Error()
- } else {
- msg = (&common.TemplateUpdateError{Err: err}).Error()
- }
- c.JSON(status, gin.H{
- "success": false,
- "data": gin.H{"error": msg},
- })
- return
- }
-
- updated, err := h.templateService.GetTemplate(c.Request.Context(), id)
- if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Template updated successfully"},
- })
- return
- }
-
- var out template.Template
- if mapErr := mapper.MapStruct(updated, &out); mapErr != nil {
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Template updated successfully"},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// DeleteTemplate godoc
-//
-// @Summary Delete a template
-// @Description Delete a compose template
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Template ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/{id} [delete]
-func (h *TemplateHandler) DeleteTemplate(c *gin.Context) {
- id := c.Param("id")
- if id == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.TemplateIDRequiredError{}).Error()},
- })
- return
- }
-
- if err := h.templateService.DeleteTemplate(c.Request.Context(), id); err != nil {
- status := http.StatusInternalServerError
- var msg string
- if err.Error() == "template not found" {
- status = http.StatusNotFound
- msg = (&common.TemplateNotFoundError{}).Error()
- } else {
- msg = (&common.TemplateDeletionError{Err: err}).Error()
- }
- c.JSON(status, gin.H{
- "success": false,
- "data": gin.H{"error": msg},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Template deleted successfully"},
- })
-}
-
-// GetDefaultTemplates godoc
-//
-// @Summary Get default templates
-// @Description Get the default compose and env templates
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Success 200 {object} base.ApiResponse[template.DefaultTemplates]
-// @Router /api/templates/default [get]
-func (h *TemplateHandler) GetDefaultTemplates(c *gin.Context) {
- composeTemplate := h.templateService.GetComposeTemplate()
- envTemplate := h.templateService.GetEnvTemplate()
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "composeTemplate": composeTemplate,
- "envTemplate": envTemplate,
- },
- })
-}
-
-// SaveDefaultTemplates godoc
-//
-// @Summary Save default templates
-// @Description Save the default compose and env templates
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param templates body template.SaveDefault true "Default templates data"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/default [post]
-func (h *TemplateHandler) SaveDefaultTemplates(c *gin.Context) {
- var req struct {
- ComposeContent string `json:"composeContent" binding:"required"`
- EnvContent string `json:"envContent"`
- }
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- if err := h.templateService.SaveComposeTemplate(req.ComposeContent); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.DefaultTemplateSaveError{Err: err}).Error()},
- })
- return
- }
-
- if err := h.templateService.SaveEnvTemplate(req.EnvContent); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.DefaultTemplateSaveError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Default templates saved successfully"},
- })
-}
-
-// GetRegistries godoc
-//
-// @Summary List template registries
-// @Description Get all template registries
-// @Tags Templates
-// @Success 200 {array} template.Registry
-// @Router /api/templates/registries [get]
-func (h *TemplateHandler) GetRegistries(c *gin.Context) {
- registries, err := h.templateService.GetRegistries(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryFetchError{Err: err}).Error()},
- })
- return
- }
-
- out, mapErr := mapper.MapSlice[models.TemplateRegistry, template.Registry](registries)
- if mapErr != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryFetchError{Err: mapErr}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// CreateRegistry godoc
-//
-// @Summary Create a template registry
-// @Description Create a new template registry
-// @Tags Templates
-// @Accept json
-// @Produce json
-// @Param registry body object true "Registry creation data"
-// @Success 201 {object} base.ApiResponse[template.Registry]
-// @Router /api/templates/registries [post]
-func (h *TemplateHandler) CreateRegistry(c *gin.Context) {
- var req struct {
- Name string `json:"name" binding:"required"`
- URL string `json:"url" binding:"required"`
- Description string `json:"description"`
- Enabled bool `json:"enabled"`
- }
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- registry := &models.TemplateRegistry{
- Name: req.Name,
- URL: req.URL,
- Description: req.Description,
- Enabled: req.Enabled,
- }
- if err := h.templateService.CreateRegistry(c.Request.Context(), registry); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryCreationError{Err: err}).Error()},
- })
- return
- }
-
- var out template.Registry
- if mapErr := mapper.MapStruct(registry, &out); mapErr != nil {
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": gin.H{"message": "Registry created"},
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// UpdateRegistry godoc
-//
-// @Summary Update a template registry
-// @Description Update an existing template registry
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param id path string true "Registry ID"
-// @Param registry body template.UpdateRegistry true "Registry update data"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/registries/{id} [put]
-func (h *TemplateHandler) UpdateRegistry(c *gin.Context) {
- id := c.Param("id")
- if id == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryIDRequiredError{}).Error()},
- })
- return
- }
-
- var req struct {
- Name string `json:"name" binding:"required"`
- URL string `json:"url" binding:"required"`
- Description string `json:"description"`
- Enabled bool `json:"enabled"`
- }
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- updates := &models.TemplateRegistry{
- Name: req.Name,
- URL: req.URL,
- Description: req.Description,
- Enabled: req.Enabled,
- }
- if err := h.templateService.UpdateRegistry(c.Request.Context(), id, updates); err != nil {
- status := http.StatusInternalServerError
- var msg string
- if err.Error() == "registry not found" {
- status = http.StatusNotFound
- msg = (&common.RegistryNotFoundError{}).Error()
- } else {
- msg = (&common.RegistryUpdateError{Err: err}).Error()
- }
- c.JSON(status, gin.H{
- "success": false,
- "data": gin.H{"error": msg},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Registry updated successfully"},
- })
-}
-
-// DeleteRegistry godoc
-//
-// @Summary Delete a template registry
-// @Description Delete a template registry
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Registry ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 404 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/registries/{id} [delete]
-func (h *TemplateHandler) DeleteRegistry(c *gin.Context) {
- id := c.Param("id")
- if id == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.RegistryIDRequiredError{}).Error()},
- })
- return
- }
-
- if err := h.templateService.DeleteRegistry(c.Request.Context(), id); err != nil {
- status := http.StatusInternalServerError
- var msg string
- if err.Error() == "registry not found" {
- status = http.StatusNotFound
- msg = (&common.RegistryNotFoundError{}).Error()
- } else {
- msg = (&common.RegistryDeletionError{Err: err}).Error()
- }
- c.JSON(status, gin.H{
- "success": false,
- "data": gin.H{"error": msg},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Registry deleted successfully"},
- })
-}
-
-// FetchRegistry godoc
-//
-// @Summary Fetch remote registry
-// @Description Fetch templates from a remote registry URL
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param url query string true "Registry URL"
-// @Success 200 {object} map[string]any
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 502 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/fetch [get]
-func (h *TemplateHandler) FetchRegistry(c *gin.Context) {
- url := c.Query("url")
- if url == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.QueryParameterRequiredError{}).Error()},
- })
- return
- }
-
- body, err := h.templateService.FetchRaw(c.Request.Context(), url)
- if err != nil {
- c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": (&common.RegistryFetchError{Err: err}).Error()}})
- return
- }
-
- var registry interface{}
- if err := json.Unmarshal(body, &registry); err != nil {
- c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": (&common.InvalidJSONResponseError{Err: err}).Error()}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": registry,
- })
-}
-
-// DownloadTemplate godoc
-//
-// @Summary Download a template
-// @Description Download a remote template to local storage
-// @Tags Templates
-// @Param id path string true "Template ID"
-// @Success 200 {object} base.ApiResponse[template.Template]
-// @Router /api/templates/{id}/download [post]
-func (h *TemplateHandler) DownloadTemplate(c *gin.Context) {
- id := c.Param("id")
- if id == "" {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.TemplateIDRequiredError{}).Error()}})
- return
- }
-
- tmpl, err := h.templateService.GetTemplate(c.Request.Context(), id)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": (&common.TemplateNotFoundError{}).Error()}})
- return
- }
- if !tmpl.IsRemote {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": (&common.TemplateAlreadyLocalError{}).Error()}})
- return
- }
-
- localTemplate, err := h.templateService.DownloadTemplate(c.Request.Context(), tmpl)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": (&common.TemplateDownloadError{Err: err}).Error()}})
- return
- }
-
- var out template.Template
- if mapErr := mapper.MapStruct(localTemplate, &out); mapErr != nil {
- c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"message": "Template downloaded successfully"}})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// GetGlobalVariables godoc
-//
-// @Summary Get global variables
-// @Description Get global template variables
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Success 200 {object} base.ApiResponse[[]env.Variable]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/variables [get]
-func (h *TemplateHandler) GetGlobalVariables(c *gin.Context) {
- vars, err := h.templateService.GetGlobalVariables(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.GlobalVariablesRetrievalError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": vars,
- })
-}
-
-// UpdateGlobalVariables godoc
-//
-// @Summary Update global variables
-// @Description Update global template variables
-// @Tags Templates
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param variables body env.Summary true "Variables update data"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 400 {object} base.ApiResponse[base.ErrorResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/templates/variables [put]
-func (h *TemplateHandler) UpdateGlobalVariables(c *gin.Context) {
- var req env.Summary
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- if err := h.templateService.UpdateGlobalVariables(c.Request.Context(), req.Variables); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.GlobalVariablesUpdateError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "message": "Global variables updated successfully",
- },
- })
-}
diff --git a/backend/internal/api/updater_handler.go b/backend/internal/api/updater_handler.go
deleted file mode 100644
index 5024182f8..000000000
--- a/backend/internal/api/updater_handler.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package api
-
-import (
- "net/http"
- "strconv"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/updater"
-)
-
-type UpdaterHandler struct {
- updaterService *services.UpdaterService
-}
-
-func NewUpdaterHandler(group *gin.RouterGroup, updaterService *services.UpdaterService, authMiddleware *middleware.AuthMiddleware) {
- handler := &UpdaterHandler{updaterService: updaterService}
-
- apiGroup := group.Group("/environments/:id/updater")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.POST("/run", handler.Run)
- apiGroup.GET("/history", handler.History)
- apiGroup.GET("/status", handler.Status)
- }
-}
-
-// Run godoc
-//
-// @Summary Run updater
-// @Description Apply pending container updates
-// @Tags Updater
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param request body updater.Options false "Updater run options"
-// @Success 200 {object} base.ApiResponse[updater.Result]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/updater/run [post]
-func (h *UpdaterHandler) Run(c *gin.Context) {
- var req updater.Options
- _ = c.ShouldBindJSON(&req)
-
- out, err := h.updaterService.ApplyPending(c.Request.Context(), req.DryRun)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": (&common.UpdaterRunError{Err: err}).Error()})
- return
- }
-
- c.JSON(http.StatusOK, gin.H{"success": true, "data": out})
-}
-
-// Status godoc
-//
-// @Summary Get updater status
-// @Description Get the current status of the updater
-// @Tags Updater
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[updater.Status]
-// @Router /api/environments/{id}/updater/status [get]
-func (h *UpdaterHandler) Status(c *gin.Context) {
- status := h.updaterService.GetStatus()
- c.JSON(http.StatusOK, gin.H{"success": true, "data": status})
-}
-
-// History godoc
-//
-// @Summary Get updater history
-// @Description Get the history of update operations
-// @Tags Updater
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param limit query int false "Number of history entries to return" default(50)
-// @Success 200 {object} base.ApiResponse[[]updater.HistoryEntry]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/updater/history [get]
-func (h *UpdaterHandler) History(c *gin.Context) {
- limit := 50
- if ls := c.Query("limit"); ls != "" {
- if v, err := strconv.Atoi(ls); err == nil && v > 0 {
- limit = v
- }
- }
-
- history, err := h.updaterService.GetHistory(c.Request.Context(), limit)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": (&common.UpdaterHistoryError{Err: err}).Error()})
- return
- }
- c.JSON(http.StatusOK, gin.H{"success": true, "data": history})
-}
diff --git a/backend/internal/api/user_handler.go b/backend/internal/api/user_handler.go
deleted file mode 100644
index fd1b4ca9b..000000000
--- a/backend/internal/api/user_handler.go
+++ /dev/null
@@ -1,281 +0,0 @@
-package api
-
-import (
- "net/http"
- "time"
-
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- "go.getarcane.app/types/user"
-)
-
-type UserHandler struct {
- userService *services.UserService
-}
-
-func NewUserHandler(group *gin.RouterGroup, userService *services.UserService, authMiddleware *middleware.AuthMiddleware) {
-
- handler := &UserHandler{userService: userService}
-
- apiGroup := group.Group("/users")
- apiGroup.Use(authMiddleware.WithAdminRequired().Add())
- {
- apiGroup.GET("", handler.ListUsers)
- apiGroup.POST("", handler.CreateUser)
- apiGroup.GET("/:id", handler.GetUser)
- apiGroup.PUT("/:id", handler.UpdateUser)
- apiGroup.DELETE("/:id", handler.DeleteUser)
- }
-}
-
-// ListUsers godoc
-//
-// @Summary List users
-// @Description Get a paginated list of all users
-// @Tags Users
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[user.Response]
-// @Router /api/users [get]
-func (h *UserHandler) ListUsers(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- users, paginationResp, err := h.userService.ListUsersPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserListError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": users,
- "pagination": paginationResp,
- })
-}
-
-// CreateUser godoc
-//
-// @Summary Create a user
-// @Description Create a new user account
-// @Tags Users
-// @Accept json
-// @Produce json
-// @Param user body user.Create true "User creation data"
-// @Success 201 {object} base.ApiResponse[user.Response]
-// @Router /api/users [post]
-func (h *UserHandler) CreateUser(c *gin.Context) {
- var req user.Create
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- hashedPassword, err := h.userService.HashPassword(req.Password)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.PasswordHashError{Err: err}).Error()},
- })
- return
- }
-
- userModel := &models.User{
- Username: req.Username,
- PasswordHash: hashedPassword,
- DisplayName: req.DisplayName,
- Email: req.Email,
- Roles: req.Roles,
- Locale: req.Locale,
- BaseModel: models.BaseModel{
- CreatedAt: time.Now(),
- },
- }
-
- if userModel.Roles == nil {
- userModel.Roles = []string{"user"}
- }
-
- createdUser, err := h.userService.CreateUser(c.Request.Context(), userModel)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserCreationError{Err: err}).Error()},
- })
- return
- }
-
- out, err := mapper.MapOne[*models.User, user.Response](createdUser)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserMappingError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// GetUser godoc
-//
-// @Summary Get a user
-// @Description Get a user by ID
-// @Tags Users
-// @Param id path string true "User ID"
-// @Success 200 {object} base.ApiResponse[user.Response]
-// @Router /api/users/{id} [get]
-func (h *UserHandler) GetUser(c *gin.Context) {
- userID := c.Param("id")
-
- userModel, err := h.userService.GetUserByID(c.Request.Context(), userID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserNotFoundError{}).Error()},
- })
- return
- }
-
- out, err := mapper.MapOne[*models.User, user.Response](userModel)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserMappingError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// UpdateUser godoc
-//
-// @Summary Update a user
-// @Description Update an existing user's information
-// @Tags Users
-// @Accept json
-// @Produce json
-// @Param id path string true "User ID"
-// @Param user body user.Update true "User update data"
-// @Success 200 {object} base.ApiResponse[user.Response]
-// @Router /api/users/{id} [put]
-func (h *UserHandler) UpdateUser(c *gin.Context) {
- userID := c.Param("id")
-
- var req user.Update
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- userModel, err := h.userService.GetUserByID(c.Request.Context(), userID)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserNotFoundError{}).Error()},
- })
- return
- }
-
- if req.DisplayName != nil {
- userModel.DisplayName = req.DisplayName
- }
- if req.Email != nil {
- userModel.Email = req.Email
- }
- if req.Roles != nil {
- userModel.Roles = req.Roles
- }
- if req.Locale != nil {
- userModel.Locale = req.Locale
- }
-
- if req.Password != nil && *req.Password != "" {
- hashedPassword, err := h.userService.HashPassword(*req.Password)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.PasswordHashError{Err: err}).Error()},
- })
- return
- }
- userModel.PasswordHash = hashedPassword
- }
-
- now := time.Now()
- userModel.UpdatedAt = &now
-
- updatedUser, err := h.userService.UpdateUser(c.Request.Context(), userModel)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserUpdateError{Err: err}).Error()},
- })
- return
- }
-
- out, err := mapper.MapOne[*models.User, user.Response](updatedUser)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserMappingError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
-
-// DeleteUser godoc
-//
-// @Summary Delete a user
-// @Description Delete a user by ID
-// @Tags Users
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "User ID"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/users/{id} [delete]
-func (h *UserHandler) DeleteUser(c *gin.Context) {
- userID := c.Param("id")
-
- err := h.userService.DeleteUser(c.Request.Context(), userID)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.UserDeletionError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "User deleted successfully"},
- })
-}
diff --git a/backend/internal/api/version_handler.go b/backend/internal/api/version_handler.go
deleted file mode 100644
index 58ca16877..000000000
--- a/backend/internal/api/version_handler.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package api
-
-import (
- "log/slog"
- "net/http"
- "strings"
-
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/gin-gonic/gin"
-)
-
-type VersionHandler struct {
- version *services.VersionService
-}
-
-func NewVersionHandler(api *gin.RouterGroup, version *services.VersionService) *VersionHandler {
- h := &VersionHandler{version: version}
- api.GET("/version", h.Get)
- api.GET("/app-version", h.GetAppVersion)
- return h
-}
-
-// Get godoc
-//
-// @Summary Get version information
-// @Description Get application version information and check for updates
-// @Tags Version
-// @Param current query string false "Current version to compare against"
-// @Success 200 {object} version.Info
-// @Router /api/version [get]
-func (h *VersionHandler) Get(c *gin.Context) {
- current := strings.TrimSpace(c.Query("current"))
-
- info, err := h.version.GetVersionInformation(c.Request.Context(), current)
- if err != nil {
- slog.Warn("version information fetch error", "error", err)
- }
- c.JSON(http.StatusOK, info)
-}
-
-// GetAppVersion godoc
-//
-// @Summary Get app version
-// @Description Get the current application version
-// @Tags Version
-// @Success 200 {object} version.Info
-// @Router /api/app-version [get]
-func (h *VersionHandler) GetAppVersion(c *gin.Context) {
- info := h.version.GetAppVersionInfo(c.Request.Context())
- c.JSON(http.StatusOK, info)
-}
diff --git a/backend/internal/api/volume_handler.go b/backend/internal/api/volume_handler.go
deleted file mode 100644
index 6f639239d..000000000
--- a/backend/internal/api/volume_handler.go
+++ /dev/null
@@ -1,277 +0,0 @@
-package api
-
-import (
- "net/http"
-
- "github.com/docker/docker/api/types/volume"
- "github.com/getarcaneapp/arcane/backend/internal/common"
- "github.com/getarcaneapp/arcane/backend/internal/middleware"
- "github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
- "github.com/gin-gonic/gin"
- volumetypes "go.getarcane.app/types/volume"
-)
-
-type VolumeHandler struct {
- volumeService *services.VolumeService
- dockerService *services.DockerClientService
-}
-
-func NewVolumeHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, volumeService *services.VolumeService, authMiddleware *middleware.AuthMiddleware) {
- handler := &VolumeHandler{dockerService: dockerService, volumeService: volumeService}
-
- apiGroup := group.Group("/environments/:id/volumes")
- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())
- {
- apiGroup.GET("/counts", handler.GetVolumeUsageCounts)
- apiGroup.GET("", handler.List)
- apiGroup.GET("/:volumeName", handler.GetByName)
- apiGroup.POST("", handler.Create)
- apiGroup.DELETE("/:volumeName", handler.Remove)
- apiGroup.POST("/prune", handler.Prune)
- apiGroup.GET("/:volumeName/usage", handler.GetUsage)
- }
-}
-
-// List godoc
-//
-// @Summary List volumes
-// @Description Get a paginated list of Docker volumes
-// @Tags Volumes
-// @Param id path string true "Environment ID"
-// @Param pagination[page] query int false "Page number for pagination" default(1)
-// @Param pagination[limit] query int false "Number of items per page" default(20)
-// @Param sort[column] query string false "Column to sort by"
-// @Param sort[direction] query string false "Sort direction (asc or desc)" default("asc")
-// @Success 200 {object} base.Paginated[volume.Volume]
-// @Router /api/environments/{id}/volumes [get]
-func (h *VolumeHandler) List(c *gin.Context) {
- params := pagination.ExtractListModifiersQueryParams(c)
-
- if params.Limit == 0 {
- params.Limit = 20
- }
-
- volumes, paginationResp, counts, err := h.volumeService.ListVolumesPaginated(c.Request.Context(), params)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.VolumeListError{Err: err}).Error()},
- })
- return
- }
-
- pagination.ApplyFilterResultsHeaders(&c.Writer, pagination.FilterResult[volumetypes.Volume]{
- Items: volumes,
- TotalCount: paginationResp.TotalItems,
- TotalAvailable: paginationResp.GrandTotalItems,
- })
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": volumes,
- "counts": counts,
- "pagination": paginationResp,
- })
-}
-
-// GetByName godoc
-//
-// @Summary Get volume by name
-// @Description Get a Docker volume by its name
-// @Tags Volumes
-// @Param id path string true "Environment ID"
-// @Param volumeName path string true "Volume name"
-// @Success 200 {object} base.ApiResponse[volume.Volume]
-// @Router /api/environments/{id}/volumes/{volumeName} [get]
-func (h *VolumeHandler) GetByName(c *gin.Context) {
- name := c.Param("volumeName")
-
- vol, err := h.volumeService.GetVolumeByName(c.Request.Context(), name)
- if err != nil {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.VolumeNotFoundError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": vol,
- })
-}
-
-// Create godoc
-//
-// @Summary Create a volume
-// @Description Create a new Docker volume
-// @Tags Volumes
-// @Accept json
-// @Produce json
-// @Param id path string true "Environment ID"
-// @Param volume body volume.Create true "Volume creation data"
-// @Success 201 {object} base.ApiResponse[volume.Volume]
-// @Router /api/environments/{id}/volumes [post]
-func (h *VolumeHandler) Create(c *gin.Context) {
- var req volumetypes.Create
- if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.InvalidRequestFormatError{Err: err}).Error()},
- })
- return
- }
-
- options := volume.CreateOptions{
- Name: req.Name,
- Driver: req.Driver,
- Labels: req.Labels,
- DriverOpts: req.Options,
- }
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- response, err := h.volumeService.CreateVolume(c.Request.Context(), options, *currentUser)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.VolumeCreationError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusCreated, gin.H{
- "success": true,
- "data": response,
- })
-}
-
-// Remove godoc
-//
-// @Summary Remove a volume
-// @Description Remove a Docker volume by name
-// @Tags Volumes
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param volumeName path string true "Volume name"
-// @Param force query bool false "Force removal"
-// @Success 200 {object} base.ApiResponse[base.MessageResponse]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/volumes/{volumeName} [delete]
-func (h *VolumeHandler) Remove(c *gin.Context) {
- name := c.Param("volumeName")
- force := c.Query("force") == "true"
-
- currentUser, ok := middleware.RequireAuthentication(c)
- if !ok {
- return
- }
-
- if err := h.volumeService.DeleteVolume(c.Request.Context(), name, force, *currentUser); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.VolumeDeletionError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Volume removed successfully"},
- })
-}
-
-// Prune godoc
-//
-// @Summary Prune unused volumes
-// @Description Remove all unused Docker volumes
-// @Tags Volumes
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[volume.PruneReport]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/volumes/prune [post]
-func (h *VolumeHandler) Prune(c *gin.Context) {
- report, err := h.volumeService.PruneVolumes(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.VolumePruneError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": report,
- })
-}
-
-// GetUsage godoc
-//
-// @Summary Get volume usage
-// @Description Get containers using a specific volume
-// @Tags Volumes
-// @Security BearerAuth
-// @Security ApiKeyAuth
-// @Param id path string true "Environment ID"
-// @Param volumeName path string true "Volume name"
-// @Success 200 {object} base.ApiResponse[volume.Usage]
-// @Failure 500 {object} base.ApiResponse[base.ErrorResponse]
-// @Router /api/environments/{id}/volumes/{volumeName}/usage [get]
-func (h *VolumeHandler) GetUsage(c *gin.Context) {
- name := c.Param("volumeName")
-
- inUse, containers, err := h.volumeService.GetVolumeUsage(c.Request.Context(), name)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.VolumeUsageError{Err: err}).Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "inUse": inUse,
- "containers": containers,
- },
- })
-}
-
-// GetVolumeUsageCounts godoc
-//
-// @Summary Get volume usage counts
-// @Description Get counts of volumes in use, unused, and total
-// @Tags Volumes
-// @Param id path string true "Environment ID"
-// @Success 200 {object} base.ApiResponse[volume.UsageCounts]
-// @Router /api/environments/{id}/volumes/counts [get]
-func (h *VolumeHandler) GetVolumeUsageCounts(c *gin.Context) {
- _, running, stopped, total, err := h.dockerService.GetAllVolumes(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": (&common.VolumeCountsError{Err: err}).Error()},
- })
- return
- }
-
- out := volumetypes.UsageCounts{
- Inuse: running,
- Unused: stopped,
- Total: total,
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": out,
- })
-}
diff --git a/backend/internal/api/ws_handler.go b/backend/internal/api/ws_handler.go
new file mode 100644
index 000000000..d031e21a4
--- /dev/null
+++ b/backend/internal/api/ws_handler.go
@@ -0,0 +1,1002 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/csv"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "os/exec"
+ "runtime"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ httputil "github.com/getarcaneapp/arcane/backend/internal/utils/http"
+ ws "github.com/getarcaneapp/arcane/backend/internal/utils/ws"
+ "github.com/gin-gonic/gin"
+ "github.com/gorilla/websocket"
+ "github.com/shirou/gopsutil/v4/cpu"
+ "github.com/shirou/gopsutil/v4/disk"
+ "github.com/shirou/gopsutil/v4/host"
+ "github.com/shirou/gopsutil/v4/mem"
+)
+
+const (
+ gpuCacheDuration = 30 * time.Second
+)
+
+// GPUStats represents statistics for a single GPU
+type GPUStats struct {
+ Name string `json:"name"`
+ Index int `json:"index"`
+ MemoryUsed float64 `json:"memoryUsed"`
+ MemoryTotal float64 `json:"memoryTotal"`
+}
+
+// SystemStats represents system resource statistics for WebSocket streaming.
+type SystemStats struct {
+ CPUUsage float64 `json:"cpuUsage"`
+ MemoryUsage uint64 `json:"memoryUsage"`
+ MemoryTotal uint64 `json:"memoryTotal"`
+ DiskUsage uint64 `json:"diskUsage,omitempty"`
+ DiskTotal uint64 `json:"diskTotal,omitempty"`
+ CPUCount int `json:"cpuCount"`
+ Architecture string `json:"architecture"`
+ Platform string `json:"platform"`
+ Hostname string `json:"hostname,omitempty"`
+ GPUCount int `json:"gpuCount"`
+ GPUs []GPUStats `json:"gpus,omitempty"`
+}
+
+// ROCmSMIOutput represents the JSON structure from rocm-smi
+type ROCmSMIOutput map[string]ROCmGPUInfo
+
+// ROCmGPUInfo represents GPU info from rocm-smi
+type ROCmGPUInfo struct {
+ VRAMUsed string `json:"VRAM Total Used Memory (B)"`
+ VRAMTotal string `json:"VRAM Total Memory (B)"`
+}
+
+// WebSocketHandler consolidates all WebSocket and streaming endpoints.
+// REST endpoints are handled by Huma handlers.
+type WebSocketHandler struct {
+ projectService *services.ProjectService
+ containerService *services.ContainerService
+ systemService *services.SystemService
+ wsUpgrader websocket.Upgrader
+ activeConnections sync.Map
+ cpuCache struct {
+ sync.RWMutex
+ value float64
+ timestamp time.Time
+ }
+ diskUsagePathCache struct {
+ sync.RWMutex
+ value string
+ timestamp time.Time
+ }
+ gpuDetectionCache struct {
+ sync.RWMutex
+ detected bool
+ timestamp time.Time
+ gpuType string
+ toolPath string
+ }
+ detectionDone bool
+ detectionMutex sync.Mutex
+ gpuMonitoringEnabled bool
+ gpuType string
+}
+
+type wsLogStream struct {
+ hub *ws.Hub
+ cancel context.CancelFunc
+ format string
+ seq atomic.Uint64
+}
+
+func NewWebSocketHandler(
+ group *gin.RouterGroup,
+ projectService *services.ProjectService,
+ containerService *services.ContainerService,
+ systemService *services.SystemService,
+ authMiddleware *middleware.AuthMiddleware,
+ cfg *config.Config,
+) {
+ handler := &WebSocketHandler{
+ projectService: projectService,
+ containerService: containerService,
+ systemService: systemService,
+ gpuMonitoringEnabled: cfg.GPUMonitoringEnabled,
+ gpuType: cfg.GPUType,
+ wsUpgrader: websocket.Upgrader{
+ CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.AppUrl),
+ ReadBufferSize: 32 * 1024,
+ WriteBufferSize: 32 * 1024,
+ EnableCompression: true,
+ },
+ }
+
+ wsGroup := group.Group("/environments/:id/ws")
+ wsGroup.Use(authMiddleware.WithAdminNotRequired().Add())
+ {
+ // Project endpoints (pull moved to Huma handler)
+ wsGroup.GET("/projects/:projectId/logs", handler.ProjectLogs)
+
+ // Container endpoints
+ wsGroup.GET("/containers/:containerId/logs", handler.ContainerLogs)
+ wsGroup.GET("/containers/:containerId/stats", handler.ContainerStats)
+ wsGroup.GET("/containers/:containerId/exec", handler.ContainerExec)
+
+ // System endpoints
+ wsGroup.GET("/system/stats", handler.SystemStats)
+ }
+}
+
+// ============================================================================
+// Project WebSocket/Streaming Endpoints
+// ============================================================================
+
+// ProjectLogs streams project logs over WebSocket.
+//
+// @Summary Get project logs via WebSocket
+// @Description Stream project logs over WebSocket connection
+// @Tags WebSocket
+// @Param id path string true "Environment ID"
+// @Param projectId path string true "Project ID"
+// @Param follow query bool false "Follow log output" default(true)
+// @Param tail query string false "Number of lines to show from the end" default(100)
+// @Param since query string false "Show logs since timestamp"
+// @Param timestamps query bool false "Show timestamps" default(false)
+// @Param format query string false "Output format (text or json)" default(text)
+// @Param batched query bool false "Batch log messages" default(false)
+// @Router /api/environments/{id}/ws/projects/{projectId}/logs [get]
+func (h *WebSocketHandler) ProjectLogs(c *gin.Context) {
+ projectID := c.Param("projectId")
+ if strings.TrimSpace(projectID) == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
+ return
+ }
+
+ follow := c.DefaultQuery("follow", "true") == "true"
+ tail := c.DefaultQuery("tail", "100")
+ since := c.Query("since")
+ timestamps := c.DefaultQuery("timestamps", "false") == "true"
+ format := c.DefaultQuery("format", "text")
+ batched := c.DefaultQuery("batched", "false") == "true"
+
+ conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ if err != nil {
+ return
+ }
+
+ hub := h.startProjectLogHub(projectID, format, batched, follow, tail, since, timestamps)
+ ws.ServeClient(context.Background(), hub, conn)
+}
+
+func (h *WebSocketHandler) startProjectLogHub(projectID, format string, batched, follow bool, tail, since string, timestamps bool) *ws.Hub {
+ ls := &wsLogStream{
+ hub: ws.NewHub(1024),
+ format: format,
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ ls.cancel = cancel
+
+ ls.hub.SetOnEmpty(func() {
+ slog.Debug("client disconnected, cleaning up project log hub", "projectID", projectID)
+ cancel()
+ })
+
+ go ls.hub.Run(ctx)
+
+ lines := make(chan string, 256)
+ go func() {
+ defer close(lines)
+ _ = h.projectService.StreamProjectLogs(ctx, projectID, lines, follow, tail, since, timestamps)
+ }()
+
+ if format == "json" {
+ msgs := make(chan ws.LogMessage, 256)
+ go func() {
+ defer close(msgs)
+ for line := range lines {
+ level, service, msg, ts := ws.NormalizeProjectLine(line)
+ seq := ls.seq.Add(1)
+ timestamp := ts
+ if timestamp == "" {
+ timestamp = ws.NowRFC3339()
+ }
+ msgs <- ws.LogMessage{
+ Seq: seq,
+ Level: level,
+ Message: msg,
+ Service: service,
+ Timestamp: timestamp,
+ }
+ }
+ }()
+ if batched {
+ go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
+ } else {
+ go ws.ForwardLogJSON(ctx, ls.hub, msgs)
+ }
+ } else {
+ cleanChan := make(chan string, 256)
+ go func() {
+ defer close(cleanChan)
+ for line := range lines {
+ _, _, msg, _ := ws.NormalizeProjectLine(line)
+ cleanChan <- msg
+ }
+ }()
+ go ws.ForwardLines(ctx, ls.hub, cleanChan)
+ }
+
+ return ls.hub
+}
+
+// ============================================================================
+// Container WebSocket Endpoints
+// ============================================================================
+
+// ContainerLogs streams container logs over WebSocket.
+//
+// @Summary Get container logs via WebSocket
+// @Description Stream container logs over WebSocket connection
+// @Tags WebSocket
+// @Param id path string true "Environment ID"
+// @Param containerId path string true "Container ID"
+// @Param follow query bool false "Follow log output" default(true)
+// @Param tail query string false "Number of lines to show from the end" default(100)
+// @Param since query string false "Show logs since timestamp"
+// @Param timestamps query bool false "Show timestamps" default(false)
+// @Param format query string false "Output format (text or json)" default(text)
+// @Param batched query bool false "Batch log messages" default(false)
+// @Router /api/environments/{id}/ws/containers/{containerId}/logs [get]
+func (h *WebSocketHandler) ContainerLogs(c *gin.Context) {
+ containerID := c.Param("containerId")
+ if strings.TrimSpace(containerID) == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
+ return
+ }
+
+ follow := c.DefaultQuery("follow", "true") == "true"
+ tail := c.DefaultQuery("tail", "100")
+ since := c.Query("since")
+ timestamps := c.DefaultQuery("timestamps", "false") == "true"
+ format := c.DefaultQuery("format", "text")
+ batched := c.DefaultQuery("batched", "false") == "true"
+
+ conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ if err != nil {
+ return
+ }
+
+ hub := h.startContainerLogHub(containerID, format, batched, follow, tail, since, timestamps)
+ ws.ServeClient(context.Background(), hub, conn)
+}
+
+func (h *WebSocketHandler) startContainerLogHub(containerID, format string, batched, follow bool, tail, since string, timestamps bool) *ws.Hub {
+ ls := &wsLogStream{
+ hub: ws.NewHub(1024),
+ format: format,
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ ls.cancel = cancel
+
+ ls.hub.SetOnEmpty(func() {
+ slog.Debug("client disconnected, cleaning up container log hub", "containerID", containerID)
+ cancel()
+ })
+
+ go ls.hub.Run(ctx)
+
+ lines := make(chan string, 256)
+ go func() {
+ defer close(lines)
+ _ = h.containerService.StreamLogs(ctx, containerID, lines, follow, tail, since, timestamps)
+ }()
+
+ if format == "json" {
+ msgs := make(chan ws.LogMessage, 256)
+ go func() {
+ defer close(msgs)
+ for line := range lines {
+ level, msg, ts := ws.NormalizeContainerLine(line)
+ seq := ls.seq.Add(1)
+ timestamp := ts
+ if timestamp == "" {
+ timestamp = ws.NowRFC3339()
+ }
+ msgs <- ws.LogMessage{
+ Seq: seq,
+ Level: level,
+ Message: msg,
+ Timestamp: timestamp,
+ }
+ }
+ }()
+ if batched {
+ go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
+ } else {
+ go ws.ForwardLogJSON(ctx, ls.hub, msgs)
+ }
+ } else {
+ go ws.ForwardLines(ctx, ls.hub, lines)
+ }
+
+ return ls.hub
+}
+
+// ContainerStats streams container stats over WebSocket.
+//
+// @Summary Get container stats via WebSocket
+// @Description Stream container resource statistics over WebSocket connection
+// @Tags WebSocket
+// @Param id path string true "Environment ID"
+// @Param containerId path string true "Container ID"
+// @Router /api/environments/{id}/ws/containers/{containerId}/stats [get]
+func (h *WebSocketHandler) ContainerStats(c *gin.Context) {
+ containerID := c.Param("containerId")
+ if strings.TrimSpace(containerID) == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
+ return
+ }
+
+ conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ if err != nil {
+ return
+ }
+
+ hub := h.startContainerStatsHub(containerID)
+ ws.ServeClient(context.Background(), hub, conn)
+}
+
+func (h *WebSocketHandler) startContainerStatsHub(containerID string) *ws.Hub {
+ hub := ws.NewHub(64)
+
+ ctx, cancel := context.WithCancel(context.Background())
+
+ hub.SetOnEmpty(func() {
+ slog.Debug("client disconnected, cleaning up container stats hub", "containerID", containerID)
+ cancel()
+ })
+
+ go hub.Run(ctx)
+
+ statsChan := make(chan interface{}, 64)
+ go func() {
+ defer close(statsChan)
+ _ = h.containerService.StreamStats(ctx, containerID, statsChan)
+ }()
+
+ go func() {
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case stats, ok := <-statsChan:
+ if !ok {
+ return
+ }
+ if b, err := json.Marshal(stats); err == nil {
+ hub.Broadcast(b)
+ }
+ }
+ }
+ }()
+
+ return hub
+}
+
+// ContainerExec provides interactive terminal access to a container.
+//
+// @Summary Execute command in container via WebSocket
+// @Description Interactive terminal access to a container over WebSocket
+// @Tags WebSocket
+// @Param id path string true "Environment ID"
+// @Param containerId path string true "Container ID"
+// @Param cmd query string false "Command to execute" default(/bin/sh)
+// @Router /api/environments/{id}/ws/containers/{containerId}/exec [get]
+func (h *WebSocketHandler) ContainerExec(c *gin.Context) {
+ containerID := c.Param("containerId")
+ if strings.TrimSpace(containerID) == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
+ return
+ }
+
+ cmd := c.DefaultQuery("cmd", "/bin/sh")
+
+ conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+
+ ctx, cancel := context.WithCancel(c.Request.Context())
+ defer cancel()
+
+ // Create exec instance
+ execID, err := h.containerService.CreateExec(ctx, containerID, []string{cmd})
+ if err != nil {
+ _ = conn.WriteMessage(websocket.TextMessage, []byte((&common.ExecCreationError{Err: err}).Error()+"\r\n"))
+ return
+ }
+
+ // Attach to exec
+ stdin, stdout, err := h.containerService.AttachExec(ctx, execID)
+ if err != nil {
+ _ = conn.WriteMessage(websocket.TextMessage, []byte((&common.ExecAttachError{Err: err}).Error()+"\r\n"))
+ return
+ }
+ defer stdin.Close()
+
+ done := make(chan struct{})
+
+ // Read from container, write to websocket
+ go func() {
+ defer close(done)
+ buf := make([]byte, 4096)
+ for {
+ n, err := stdout.Read(buf)
+ if err != nil {
+ return
+ }
+ if n > 0 {
+ if err := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); err != nil {
+ return
+ }
+ }
+ }
+ }()
+
+ // Read from websocket, write to container
+ go func() {
+ for {
+ _, data, err := conn.ReadMessage()
+ if err != nil {
+ cancel()
+ return
+ }
+ if _, err := stdin.Write(data); err != nil {
+ return
+ }
+ }
+ }()
+
+ <-done
+}
+
+// ============================================================================
+// System WebSocket Endpoints
+// ============================================================================
+
+// checkRateLimit checks and applies rate limiting for WebSocket connections.
+// Returns the counter and whether the connection should be allowed.
+func (h *WebSocketHandler) checkRateLimit(clientIP string) (*int32, bool) {
+ connCount, _ := h.activeConnections.LoadOrStore(clientIP, new(int32))
+ count := connCount.(*int32)
+
+ currentCount := atomic.AddInt32(count, 1)
+ if currentCount > 5 {
+ atomic.AddInt32(count, -1)
+ return nil, false
+ }
+ return count, true
+}
+
+// releaseRateLimit decrements the connection counter and cleans up if needed.
+func (h *WebSocketHandler) releaseRateLimit(clientIP string, count *int32) {
+ newCount := atomic.AddInt32(count, -1)
+ if newCount <= 0 {
+ h.activeConnections.Delete(clientIP)
+ }
+}
+
+// startCPUSampler starts a background goroutine that samples CPU usage.
+func (h *WebSocketHandler) startCPUSampler(ctx context.Context, ticker *time.Ticker) {
+ go func(ctx context.Context) {
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if vals, err := cpu.Percent(0, false); err == nil && len(vals) > 0 {
+ h.cpuCache.Lock()
+ h.cpuCache.value = vals[0]
+ h.cpuCache.timestamp = time.Now()
+ h.cpuCache.Unlock()
+ }
+ }
+ }
+ }(ctx)
+}
+
+// collectSystemStats gathers all system statistics.
+func (h *WebSocketHandler) collectSystemStats(ctx context.Context) SystemStats {
+ h.cpuCache.RLock()
+ cpuUsage := h.cpuCache.value
+ h.cpuCache.RUnlock()
+
+ cpuCount := h.getCPUCount()
+ memUsed, memTotal := h.getMemoryInfo()
+ cpuCount, memUsed, memTotal = h.applyCgroupLimits(cpuCount, memUsed, memTotal)
+ diskUsed, diskTotal := h.getDiskInfo(ctx)
+ hostname := h.getHostname()
+ gpuStats, gpuCount := h.getGPUInfo(ctx)
+
+ return SystemStats{
+ CPUUsage: cpuUsage,
+ MemoryUsage: memUsed,
+ MemoryTotal: memTotal,
+ DiskUsage: diskUsed,
+ DiskTotal: diskTotal,
+ CPUCount: cpuCount,
+ Architecture: runtime.GOARCH,
+ Platform: runtime.GOOS,
+ Hostname: hostname,
+ GPUCount: gpuCount,
+ GPUs: gpuStats,
+ }
+}
+
+// getCPUCount returns the number of CPUs.
+func (h *WebSocketHandler) getCPUCount() int {
+ cpuCount, err := cpu.Counts(true)
+ if err != nil {
+ return runtime.NumCPU()
+ }
+ return cpuCount
+}
+
+// getMemoryInfo returns memory usage and total.
+func (h *WebSocketHandler) getMemoryInfo() (uint64, uint64) {
+ memInfo, _ := mem.VirtualMemory()
+ if memInfo == nil {
+ return 0, 0
+ }
+ return memInfo.Used, memInfo.Total
+}
+
+// applyCgroupLimits applies cgroup limits when running in a container.
+func (h *WebSocketHandler) applyCgroupLimits(cpuCount int, memUsed, memTotal uint64) (int, uint64, uint64) {
+ cgroupLimits, err := utils.DetectCgroupLimits()
+ if err != nil {
+ return cpuCount, memUsed, memTotal
+ }
+
+ if limit := cgroupLimits.MemoryLimit; limit > 0 {
+ limitUint := uint64(limit)
+ if memTotal == 0 || limitUint < memTotal {
+ memTotal = limitUint
+ if cgroupLimits.MemoryUsage > 0 {
+ memUsed = uint64(cgroupLimits.MemoryUsage)
+ }
+ }
+ }
+ if cgroupLimits.CPUCount > 0 && (cpuCount == 0 || cgroupLimits.CPUCount < cpuCount) {
+ cpuCount = cgroupLimits.CPUCount
+ }
+ return cpuCount, memUsed, memTotal
+}
+
+// getDiskInfo returns disk usage and total.
+func (h *WebSocketHandler) getDiskInfo(ctx context.Context) (uint64, uint64) {
+ diskUsagePath := h.getDiskUsagePath(ctx)
+ diskInfo, err := disk.Usage(diskUsagePath)
+ if err != nil || diskInfo == nil || diskInfo.Total == 0 {
+ if diskUsagePath != "/" {
+ diskInfo, _ = disk.Usage("/")
+ }
+ }
+ if diskInfo == nil {
+ return 0, 0
+ }
+ return diskInfo.Used, diskInfo.Total
+}
+
+// getHostname returns the system hostname.
+func (h *WebSocketHandler) getHostname() string {
+ hostInfo, _ := host.Info()
+ if hostInfo == nil {
+ return ""
+ }
+ return hostInfo.Hostname
+}
+
+// getGPUInfo returns GPU statistics if monitoring is enabled.
+func (h *WebSocketHandler) getGPUInfo(ctx context.Context) ([]GPUStats, int) {
+ if !h.gpuMonitoringEnabled {
+ return nil, 0
+ }
+ gpuData, err := h.getGPUStats(ctx)
+ if err != nil {
+ return nil, 0
+ }
+ return gpuData, len(gpuData)
+}
+
+// initializeCPUCache performs initial CPU sampling.
+func (h *WebSocketHandler) initializeCPUCache() {
+ if vals, err := cpu.Percent(time.Second, false); err == nil && len(vals) > 0 {
+ h.cpuCache.Lock()
+ h.cpuCache.value = vals[0]
+ h.cpuCache.timestamp = time.Now()
+ h.cpuCache.Unlock()
+ }
+}
+
+// SystemStats streams system stats over WebSocket.
+//
+// @Summary Get system stats via WebSocket
+// @Description Stream system resource statistics over WebSocket connection
+// @Tags WebSocket
+// @Param id path string true "Environment ID"
+// @Router /api/environments/{id}/ws/system/stats [get]
+func (h *WebSocketHandler) SystemStats(c *gin.Context) {
+ clientIP := c.ClientIP()
+
+ count, allowed := h.checkRateLimit(clientIP)
+ if !allowed {
+ c.JSON(http.StatusTooManyRequests, gin.H{
+ "success": false,
+ "error": "Too many concurrent stats connections from this IP",
+ })
+ return
+ }
+ defer h.releaseRateLimit(clientIP, count)
+
+ conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+
+ ticker := time.NewTicker(2 * time.Second)
+ defer ticker.Stop()
+
+ cpuUpdateTicker := time.NewTicker(1 * time.Second)
+ defer cpuUpdateTicker.Stop()
+
+ ctx, cancel := context.WithCancel(c.Request.Context())
+ defer cancel()
+
+ h.startCPUSampler(ctx, cpuUpdateTicker)
+
+ send := func() error {
+ stats := h.collectSystemStats(ctx)
+ _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
+ return conn.WriteJSON(stats)
+ }
+
+ h.initializeCPUCache()
+
+ if err := send(); err != nil {
+ return
+ }
+
+ for {
+ select {
+ case <-c.Request.Context().Done():
+ return
+ case <-ticker.C:
+ if err := send(); err != nil {
+ return
+ }
+ }
+ }
+}
+
+func (h *WebSocketHandler) getDiskUsagePath(ctx context.Context) string {
+ h.diskUsagePathCache.RLock()
+ if h.diskUsagePathCache.value != "" && time.Since(h.diskUsagePathCache.timestamp) < 5*time.Minute {
+ path := h.diskUsagePathCache.value
+ h.diskUsagePathCache.RUnlock()
+ return path
+ }
+ h.diskUsagePathCache.RUnlock()
+
+ // Default path
+ path := "/"
+
+ // Try to get Docker root from system service
+ if h.systemService != nil {
+ path = h.systemService.GetDiskUsagePath(ctx)
+ }
+
+ h.diskUsagePathCache.Lock()
+ h.diskUsagePathCache.value = path
+ h.diskUsagePathCache.timestamp = time.Now()
+ h.diskUsagePathCache.Unlock()
+
+ return path
+}
+
+// ============================================================================
+// GPU Monitoring
+// ============================================================================
+
+// getGPUStats collects and returns GPU statistics for all available GPUs
+func (h *WebSocketHandler) getGPUStats(ctx context.Context) ([]GPUStats, error) {
+ h.detectionMutex.Lock()
+ done := h.detectionDone
+ h.detectionMutex.Unlock()
+
+ if !done {
+ if err := h.detectGPUs(ctx); err != nil {
+ return nil, err
+ }
+ }
+
+ h.gpuDetectionCache.RLock()
+ if h.gpuDetectionCache.detected && time.Since(h.gpuDetectionCache.timestamp) < gpuCacheDuration {
+ gpuType := h.gpuDetectionCache.gpuType
+ h.gpuDetectionCache.RUnlock()
+
+ switch gpuType {
+ case "nvidia":
+ return h.getNvidiaStats(ctx)
+ case "amd":
+ return h.getAMDStats(ctx)
+ case "intel":
+ return h.getIntelStats(ctx)
+ }
+ }
+ h.gpuDetectionCache.RUnlock()
+
+ if err := h.detectGPUs(ctx); err != nil {
+ return nil, err
+ }
+
+ h.gpuDetectionCache.RLock()
+ gpuType := h.gpuDetectionCache.gpuType
+ h.gpuDetectionCache.RUnlock()
+
+ switch gpuType {
+ case "nvidia":
+ return h.getNvidiaStats(ctx)
+ case "amd":
+ return h.getAMDStats(ctx)
+ case "intel":
+ return h.getIntelStats(ctx)
+ default:
+ return nil, fmt.Errorf("no supported GPU found")
+ }
+}
+
+// detectGPUs detects available GPU management tools
+func (h *WebSocketHandler) detectGPUs(ctx context.Context) error {
+ h.detectionMutex.Lock()
+ defer h.detectionMutex.Unlock()
+
+ if h.gpuType != "" && h.gpuType != "auto" {
+ switch h.gpuType {
+ case "nvidia":
+ if path, err := exec.LookPath("nvidia-smi"); err == nil {
+ h.gpuDetectionCache.Lock()
+ h.gpuDetectionCache.detected = true
+ h.gpuDetectionCache.gpuType = "nvidia"
+ h.gpuDetectionCache.toolPath = path
+ h.gpuDetectionCache.timestamp = time.Now()
+ h.gpuDetectionCache.Unlock()
+ h.detectionDone = true
+ slog.InfoContext(ctx, "Using configured GPU type", slog.String("type", "nvidia"))
+ return nil
+ }
+ return fmt.Errorf("nvidia-smi not found but GPU_TYPE set to nvidia")
+
+ case "amd":
+ if path, err := exec.LookPath("rocm-smi"); err == nil {
+ h.gpuDetectionCache.Lock()
+ h.gpuDetectionCache.detected = true
+ h.gpuDetectionCache.gpuType = "amd"
+ h.gpuDetectionCache.toolPath = path
+ h.gpuDetectionCache.timestamp = time.Now()
+ h.gpuDetectionCache.Unlock()
+ h.detectionDone = true
+ slog.InfoContext(ctx, "Using configured GPU type", slog.String("type", "amd"))
+ return nil
+ }
+ return fmt.Errorf("rocm-smi not found but GPU_TYPE set to amd")
+
+ case "intel":
+ if path, err := exec.LookPath("intel_gpu_top"); err == nil {
+ h.gpuDetectionCache.Lock()
+ h.gpuDetectionCache.detected = true
+ h.gpuDetectionCache.gpuType = "intel"
+ h.gpuDetectionCache.toolPath = path
+ h.gpuDetectionCache.timestamp = time.Now()
+ h.gpuDetectionCache.Unlock()
+ h.detectionDone = true
+ slog.InfoContext(ctx, "Using configured GPU type", slog.String("type", "intel"))
+ return nil
+ }
+ return fmt.Errorf("intel_gpu_top not found but GPU_TYPE set to intel")
+
+ default:
+ slog.WarnContext(ctx, "Invalid GPU_TYPE specified, falling back to auto-detection", slog.String("gpu_type", h.gpuType))
+ }
+ }
+
+ if path, err := exec.LookPath("nvidia-smi"); err == nil {
+ h.gpuDetectionCache.Lock()
+ h.gpuDetectionCache.detected = true
+ h.gpuDetectionCache.gpuType = "nvidia"
+ h.gpuDetectionCache.toolPath = path
+ h.gpuDetectionCache.timestamp = time.Now()
+ h.gpuDetectionCache.Unlock()
+ h.detectionDone = true
+ slog.InfoContext(ctx, "NVIDIA GPU detected", "tool", "nvidia-smi", "path", path)
+ return nil
+ }
+
+ if path, err := exec.LookPath("rocm-smi"); err == nil {
+ h.gpuDetectionCache.Lock()
+ h.gpuDetectionCache.detected = true
+ h.gpuDetectionCache.gpuType = "amd"
+ h.gpuDetectionCache.toolPath = path
+ h.gpuDetectionCache.timestamp = time.Now()
+ h.gpuDetectionCache.Unlock()
+ h.detectionDone = true
+ slog.InfoContext(ctx, "AMD GPU detected", "tool", "rocm-smi", "path", path)
+ return nil
+ }
+
+ if path, err := exec.LookPath("intel_gpu_top"); err == nil {
+ h.gpuDetectionCache.Lock()
+ h.gpuDetectionCache.detected = true
+ h.gpuDetectionCache.gpuType = "intel"
+ h.gpuDetectionCache.toolPath = path
+ h.gpuDetectionCache.timestamp = time.Now()
+ h.gpuDetectionCache.Unlock()
+ h.detectionDone = true
+ slog.InfoContext(ctx, "Intel GPU detected", "tool", "intel_gpu_top", "path", path)
+ return nil
+ }
+
+ h.detectionDone = true
+ return fmt.Errorf("no supported GPU found")
+}
+
+// getNvidiaStats collects NVIDIA GPU statistics using nvidia-smi
+func (h *WebSocketHandler) getNvidiaStats(ctx context.Context) ([]GPUStats, error) {
+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, "nvidia-smi",
+ "--query-gpu=index,name,memory.used,memory.total",
+ "--format=csv,noheader,nounits")
+
+ output, err := cmd.Output()
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to execute nvidia-smi", "error", err)
+ return nil, fmt.Errorf("nvidia-smi execution failed: %w", err)
+ }
+
+ reader := csv.NewReader(bytes.NewReader(output))
+ reader.TrimLeadingSpace = true
+
+ records, err := reader.ReadAll()
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to parse nvidia-smi CSV output", "error", err)
+ return nil, fmt.Errorf("failed to parse nvidia-smi output: %w", err)
+ }
+
+ var stats []GPUStats
+ for _, record := range records {
+ if len(record) < 4 {
+ continue
+ }
+
+ index, err := strconv.Atoi(strings.TrimSpace(record[0]))
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to parse GPU index", "value", record[0])
+ continue
+ }
+
+ name := strings.TrimSpace(record[1])
+
+ memUsed, err := strconv.ParseFloat(strings.TrimSpace(record[2]), 64)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to parse memory used", "value", record[2])
+ continue
+ }
+
+ memTotal, err := strconv.ParseFloat(strings.TrimSpace(record[3]), 64)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to parse memory total", "value", record[3])
+ continue
+ }
+
+ stats = append(stats, GPUStats{
+ Name: name,
+ Index: index,
+ MemoryUsed: memUsed * 1024 * 1024,
+ MemoryTotal: memTotal * 1024 * 1024,
+ })
+ }
+
+ if len(stats) == 0 {
+ return nil, fmt.Errorf("no GPU data parsed from nvidia-smi")
+ }
+
+ slog.DebugContext(ctx, "Collected NVIDIA GPU stats", "gpu_count", len(stats))
+ return stats, nil
+}
+
+// getAMDStats collects AMD GPU statistics using rocm-smi
+func (h *WebSocketHandler) getAMDStats(ctx context.Context) ([]GPUStats, error) {
+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, "rocm-smi", "--showmeminfo", "vram", "--json")
+ output, err := cmd.Output()
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to execute rocm-smi", "error", err)
+ return nil, fmt.Errorf("rocm-smi execution failed: %w", err)
+ }
+
+ var rocmData ROCmSMIOutput
+ if err := json.Unmarshal(output, &rocmData); err != nil {
+ slog.WarnContext(ctx, "Failed to parse rocm-smi JSON output", "error", err)
+ return nil, fmt.Errorf("failed to parse rocm-smi output: %w", err)
+ }
+
+ var stats []GPUStats
+ index := 0
+ for gpuID, info := range rocmData {
+ memUsedBytes, err := strconv.ParseFloat(info.VRAMUsed, 64)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to parse AMD memory used", "gpu", gpuID, "value", info.VRAMUsed)
+ continue
+ }
+
+ memTotalBytes, err := strconv.ParseFloat(info.VRAMTotal, 64)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to parse AMD memory total", "gpu", gpuID, "value", info.VRAMTotal)
+ continue
+ }
+
+ stats = append(stats, GPUStats{
+ Name: fmt.Sprintf("AMD GPU %s", gpuID),
+ Index: index,
+ MemoryUsed: memUsedBytes,
+ MemoryTotal: memTotalBytes,
+ })
+ index++
+ }
+
+ if len(stats) == 0 {
+ return nil, fmt.Errorf("no GPU data parsed from rocm-smi")
+ }
+
+ slog.DebugContext(ctx, "Collected AMD GPU stats", "gpu_count", len(stats))
+ return stats, nil
+}
+
+// getIntelStats collects Intel GPU statistics using intel_gpu_top
+func (h *WebSocketHandler) getIntelStats(ctx context.Context) ([]GPUStats, error) {
+ stats := []GPUStats{
+ {
+ Name: "Intel GPU",
+ Index: 0,
+ MemoryUsed: 0,
+ MemoryTotal: 0,
+ },
+ }
+
+ slog.DebugContext(ctx, "Intel GPU detected but detailed stats not yet implemented")
+ return stats, nil
+}
diff --git a/backend/internal/bootstrap/logger_bootstrap.go b/backend/internal/bootstrap/logger_bootstrap.go
index a2be2eaeb..4793e9bab 100644
--- a/backend/internal/bootstrap/logger_bootstrap.go
+++ b/backend/internal/bootstrap/logger_bootstrap.go
@@ -1,6 +1,7 @@
package bootstrap
import (
+ "context"
"log/slog"
"os"
"strings"
@@ -14,6 +15,74 @@ import (
"gorm.io/gorm/logger"
)
+// timeFilterHandler wraps a slog.Handler and removes redundant time attributes
+// from grouped attributes (like request.time and response.time from slog-gin)
+type timeFilterHandler struct {
+ handler slog.Handler
+}
+
+func (h *timeFilterHandler) Enabled(ctx context.Context, level slog.Level) bool {
+ return h.handler.Enabled(ctx, level)
+}
+
+func (h *timeFilterHandler) Handle(ctx context.Context, r slog.Record) error {
+ // Filter out time attributes from groups
+ var filteredAttrs []slog.Attr
+ r.Attrs(func(a slog.Attr) bool {
+ if a.Value.Kind() == slog.KindGroup {
+ filtered := filterGroupTimeAttrs(a)
+ filteredAttrs = append(filteredAttrs, filtered)
+ } else {
+ filteredAttrs = append(filteredAttrs, a)
+ }
+ return true
+ })
+
+ // Create a new record without the original attrs
+ newRecord := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
+ newRecord.AddAttrs(filteredAttrs...)
+
+ return h.handler.Handle(ctx, newRecord)
+}
+
+func filterGroupTimeAttrs(a slog.Attr) slog.Attr {
+ if a.Value.Kind() != slog.KindGroup {
+ return a
+ }
+
+ var filtered []slog.Attr
+ for _, attr := range a.Value.Group() {
+ // Skip "time" attributes within groups (request.time, response.time)
+ if attr.Key == "time" {
+ continue
+ }
+ // Recursively filter nested groups
+ if attr.Value.Kind() == slog.KindGroup {
+ filtered = append(filtered, filterGroupTimeAttrs(attr))
+ } else {
+ filtered = append(filtered, attr)
+ }
+ }
+
+ return slog.Group(a.Key, anySlice(filtered)...)
+}
+
+func anySlice(attrs []slog.Attr) []any {
+ result := make([]any, len(attrs))
+ for i, a := range attrs {
+ result[i] = a
+ }
+ return result
+}
+
+func (h *timeFilterHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ return &timeFilterHandler{handler: h.handler.WithAttrs(attrs)}
+}
+
+func (h *timeFilterHandler) WithGroup(name string) slog.Handler {
+ return &timeFilterHandler{handler: h.handler.WithGroup(name)}
+}
+
func SetupGinLogger(cfg *config.Config) {
var lvl slog.Level
switch strings.ToLower(cfg.LogLevel) {
@@ -40,6 +109,9 @@ func SetupGinLogger(cfg *config.Config) {
})
}
+ // Wrap with timeFilterHandler to remove redundant time attributes from slog-gin
+ h = &timeFilterHandler{handler: h}
+
slog.SetDefault(slog.New(h))
}
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index 5ffa69434..57eb6141d 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -12,7 +12,9 @@ import (
"github.com/getarcaneapp/arcane/backend/frontend"
"github.com/getarcaneapp/arcane/backend/internal/api"
"github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/huma"
"github.com/getarcaneapp/arcane/backend/internal/middleware"
+ "go.getarcane.app/types"
)
var registerPlaywrightRoutes []func(apiGroup *gin.RouterGroup, services *Services)
@@ -28,11 +30,11 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {
router.Use(gin.Recovery())
loggerSkipPatterns := []string{
- "GET /api/environments/*/containers/*/logs/ws",
- "GET /api/environments/*/containers/*/stats/ws",
- "GET /api/environments/*/system/stats/ws",
- "GET /api/environments/*/projects/*/logs/ws",
- "GET /api/environments/*/containers/*/exec/ws",
+ "GET /api/environments/*/ws/containers/*/logs",
+ "GET /api/environments/*/ws/containers/*/stats",
+ "GET /api/environments/*/ws/containers/*/exec",
+ "GET /api/environments/*/ws/projects/*/logs",
+ "GET /api/environments/*/ws/system/stats",
"GET /_app/*",
"GET /img",
"GET /fonts",
@@ -72,19 +74,8 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {
apiGroup := router.Group("/api")
- api.NewApplicationImagesHandler(apiGroup, appServices.AppImages)
- api.NewUserHandler(apiGroup, appServices.User, authMiddleware)
- api.NewVersionHandler(apiGroup, appServices.Version)
- api.NewAuthHandler(apiGroup, appServices.User, appServices.Auth, appServices.Oidc, authMiddleware)
- api.NewEventHandler(apiGroup, appServices.Event, authMiddleware)
- api.NewOidcHandler(apiGroup, appServices.Auth, appServices.Oidc)
- api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Settings, authMiddleware, cfg)
- api.NewContainerRegistryHandler(apiGroup, appServices.ContainerRegistry, authMiddleware)
- api.NewTemplateHandler(apiGroup, appServices.Template, authMiddleware)
- api.NewApiKeyHandler(apiGroup, appServices.ApiKey, authMiddleware)
-
envMiddleware := middleware.NewEnvProxyMiddlewareWithParam(
- api.LOCAL_DOCKER_ENVIRONMENT_ID,
+ types.LOCAL_DOCKER_ENVIRONMENT_ID,
"id",
func(ctx context.Context, id string) (string, *string, bool, error) {
env, err := appServices.Environment.GetEnvironmentByID(ctx, id)
@@ -97,18 +88,37 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {
)
apiGroup.Use(envMiddleware)
- api.NewHealthHandler(apiGroup)
- api.NewContainerHandler(apiGroup, appServices.Docker, appServices.Container, appServices.Image, authMiddleware, cfg)
- api.NewImageHandler(apiGroup, appServices.Docker, appServices.Image, appServices.ImageUpdate, appServices.Settings, authMiddleware)
- api.NewImageUpdateHandler(apiGroup, appServices.ImageUpdate, authMiddleware)
- api.NewNetworkHandler(apiGroup, appServices.Docker, appServices.Network, authMiddleware)
- api.NewProjectHandler(apiGroup, appServices.Project, authMiddleware, cfg)
- api.NewSystemHandler(apiGroup, appServices.Docker, appServices.System, appServices.SystemUpgrade, authMiddleware, cfg)
- api.NewUpdaterHandler(apiGroup, appServices.Updater, authMiddleware)
- api.NewVolumeHandler(apiGroup, appServices.Docker, appServices.Volume, authMiddleware)
- api.NewNotificationHandler(apiGroup, appServices.Notification, appServices.Apprise, authMiddleware)
- api.NewSettingsHandler(apiGroup, appServices.Settings, appServices.SettingsSearch, authMiddleware)
- api.NewCustomizeHandler(apiGroup, appServices.CustomizeSearch, authMiddleware)
+ _ = huma.SetupAPI(router, apiGroup, cfg, &huma.Services{
+ User: appServices.User,
+ Auth: appServices.Auth,
+ Oidc: appServices.Oidc,
+ ApiKey: appServices.ApiKey,
+ AppImages: appServices.AppImages,
+ Project: appServices.Project,
+ Event: appServices.Event,
+ Version: appServices.Version,
+ Environment: appServices.Environment,
+ Settings: appServices.Settings,
+ SettingsSearch: appServices.SettingsSearch,
+ ContainerRegistry: appServices.ContainerRegistry,
+ Template: appServices.Template,
+ Docker: appServices.Docker,
+ Image: appServices.Image,
+ ImageUpdate: appServices.ImageUpdate,
+ Volume: appServices.Volume,
+ Container: appServices.Container,
+ Network: appServices.Network,
+ Notification: appServices.Notification,
+ Apprise: appServices.Apprise,
+ Updater: appServices.Updater,
+ CustomizeSearch: appServices.CustomizeSearch,
+ System: appServices.System,
+ SystemUpgrade: appServices.SystemUpgrade,
+ Config: cfg,
+ })
+
+ // Remaining Gin handlers (WebSocket/streaming)
+ api.NewWebSocketHandler(apiGroup, appServices.Project, appServices.Container, appServices.System, authMiddleware, cfg)
if cfg.Environment != "production" {
for _, registerFunc := range registerPlaywrightRoutes {
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index e111a4eb8..acfc5b0c9 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -2,17 +2,6 @@ package common
import "fmt"
-type InvalidRequestFormatError struct {
- Err error
-}
-
-func (e *InvalidRequestFormatError) Error() string {
- if e.Err != nil {
- return fmt.Sprintf("Invalid request format: %v", e.Err)
- }
- return "Invalid request format"
-}
-
type AuthSettingsCheckError struct {
Err error
}
@@ -111,14 +100,6 @@ func (e *ContainerIDRequiredError) Error() string {
return "Container ID is required"
}
-type WebSocketUpgradeError struct {
- Err error
-}
-
-func (e *WebSocketUpgradeError) Error() string {
- return fmt.Sprintf("Failed to upgrade connection: %v", e.Err)
-}
-
type ExecCreationError struct {
Err error
}
@@ -421,15 +402,6 @@ func (e *ImageRemovalError) Error() string {
return fmt.Sprintf("Failed to remove image: %v", e.Err)
}
-type ImagePullError struct {
- ImageName string
- Err error
-}
-
-func (e *ImagePullError) Error() string {
- return fmt.Sprintf("Failed to pull image '%s': %v", e.ImageName, e.Err)
-}
-
type ImagePruneError struct {
Err error
}
@@ -446,14 +418,6 @@ func (e *ImageUsageCountsError) Error() string {
return fmt.Sprintf("Failed to get image usage counts: %v", e.Err)
}
-type InvalidMultipartFormError struct {
- Err error
-}
-
-func (e *InvalidMultipartFormError) Error() string {
- return fmt.Sprintf("Invalid multipart form: %v", e.Err)
-}
-
type FileUploadReadError struct {
Err error
}
@@ -502,12 +466,6 @@ func (e *ImageIDRequiredError) Error() string {
return "imageId parameter is required"
}
-type ImageRefListRequiredError struct{}
-
-func (e *ImageRefListRequiredError) Error() string {
- return "At least one imageRef is required"
-}
-
type BatchImageUpdateCheckError struct {
Err error
}
@@ -858,22 +816,6 @@ func (e *DockerInfoError) Error() string {
return fmt.Sprintf("Failed to get Docker info: %v", e.Err)
}
-type DockerContainerListError struct {
- Err error
-}
-
-func (e *DockerContainerListError) Error() string {
- return fmt.Sprintf("Failed to list containers: %v", e.Err)
-}
-
-type DockerImageListError struct {
- Err error
-}
-
-func (e *DockerImageListError) Error() string {
- return fmt.Sprintf("Failed to list images: %v", e.Err)
-}
-
type SystemPruneError struct {
Err error
}
diff --git a/backend/internal/huma/handlers/apikeys.go b/backend/internal/huma/handlers/apikeys.go
new file mode 100644
index 000000000..64c0d3b3c
--- /dev/null
+++ b/backend/internal/huma/handlers/apikeys.go
@@ -0,0 +1,299 @@
+package handlers
+
+import (
+ "context"
+ "errors"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "go.getarcane.app/types/apikey"
+ "go.getarcane.app/types/base"
+)
+
+// ApiKeyHandler provides Huma-based API key management endpoints.
+type ApiKeyHandler struct {
+ apiKeyService *services.ApiKeyService
+}
+
+// --- Huma Input/Output Wrappers ---
+
+// ApiKeyPaginatedResponse is the paginated response for API keys.
+type ApiKeyPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []apikey.ApiKey `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListApiKeysInput struct {
+ Search string `query:"search" doc:"Search query for filtering by name or description"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`
+ Start int `query:"start" default:"0" doc:"Start index for pagination"`
+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`
+}
+
+type ListApiKeysOutput struct {
+ Body ApiKeyPaginatedResponse
+}
+
+type CreateApiKeyInput struct {
+ Body apikey.CreateApiKey
+}
+
+type CreateApiKeyOutput struct {
+ Body base.ApiResponse[apikey.ApiKeyCreatedDto]
+}
+
+type GetApiKeyInput struct {
+ ID string `path:"id" doc:"API key ID"`
+}
+
+type GetApiKeyOutput struct {
+ Body base.ApiResponse[apikey.ApiKey]
+}
+
+type UpdateApiKeyInput struct {
+ ID string `path:"id" doc:"API key ID"`
+ Body apikey.UpdateApiKey
+}
+
+type UpdateApiKeyOutput struct {
+ Body base.ApiResponse[apikey.ApiKey]
+}
+
+type DeleteApiKeyInput struct {
+ ID string `path:"id" doc:"API key ID"`
+}
+
+type DeleteApiKeyOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// RegisterApiKeys registers API key management routes using Huma.
+func RegisterApiKeys(api huma.API, apiKeyService *services.ApiKeyService) {
+ h := &ApiKeyHandler{
+ apiKeyService: apiKeyService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-api-keys",
+ Method: http.MethodGet,
+ Path: "/api-keys",
+ Summary: "List API keys",
+ Description: "Get a paginated list of API keys",
+ Tags: []string{"API Keys"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListApiKeys)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-api-key",
+ Method: http.MethodPost,
+ Path: "/api-keys",
+ Summary: "Create an API key",
+ Description: "Create a new API key for programmatic access",
+ Tags: []string{"API Keys"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateApiKey)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-api-key",
+ Method: http.MethodGet,
+ Path: "/api-keys/{id}",
+ Summary: "Get an API key",
+ Description: "Get details of a specific API key by ID",
+ Tags: []string{"API Keys"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetApiKey)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-api-key",
+ Method: http.MethodPut,
+ Path: "/api-keys/{id}",
+ Summary: "Update an API key",
+ Description: "Update an existing API key's details",
+ Tags: []string{"API Keys"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateApiKey)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-api-key",
+ Method: http.MethodDelete,
+ Path: "/api-keys/{id}",
+ Summary: "Delete an API key",
+ Description: "Delete an API key by ID",
+ Tags: []string{"API Keys"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteApiKey)
+}
+
+// ListApiKeys returns a paginated list of API keys.
+func (h *ApiKeyHandler) ListApiKeys(ctx context.Context, input *ListApiKeysInput) (*ListApiKeysOutput, error) {
+ if h.apiKeyService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ // Check admin access
+ if !humamw.IsAdminFromContext(ctx) {
+ return nil, huma.Error403Forbidden("admin access required")
+ }
+
+ params := pagination.QueryParams{
+ SearchQuery: pagination.SearchQuery{
+ Search: input.Search,
+ },
+ SortParams: pagination.SortParams{
+ Sort: input.Sort,
+ Order: pagination.SortOrder(input.Order),
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: input.Start,
+ Limit: input.Limit,
+ },
+ }
+
+ apiKeys, paginationResp, err := h.apiKeyService.ListApiKeys(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ApiKeyListError{Err: err}).Error())
+ }
+
+ return &ListApiKeysOutput{
+ Body: ApiKeyPaginatedResponse{
+ Success: true,
+ Data: apiKeys,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// CreateApiKey creates a new API key.
+func (h *ApiKeyHandler) CreateApiKey(ctx context.Context, input *CreateApiKeyInput) (*CreateApiKeyOutput, error) {
+ if h.apiKeyService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ // Check admin access
+ if !humamw.IsAdminFromContext(ctx) {
+ return nil, huma.Error403Forbidden("admin access required")
+ }
+
+ apiKey, err := h.apiKeyService.CreateApiKey(ctx, user.ID, input.Body)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ApiKeyCreationError{Err: err}).Error())
+ }
+
+ return &CreateApiKeyOutput{
+ Body: base.ApiResponse[apikey.ApiKeyCreatedDto]{
+ Success: true,
+ Data: *apiKey,
+ },
+ }, nil
+}
+
+// GetApiKey returns details of a specific API key.
+func (h *ApiKeyHandler) GetApiKey(ctx context.Context, input *GetApiKeyInput) (*GetApiKeyOutput, error) {
+ if h.apiKeyService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ // Check admin access
+ if !humamw.IsAdminFromContext(ctx) {
+ return nil, huma.Error403Forbidden("admin access required")
+ }
+
+ apiKey, err := h.apiKeyService.GetApiKey(ctx, input.ID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
+ }
+
+ return &GetApiKeyOutput{
+ Body: base.ApiResponse[apikey.ApiKey]{
+ Success: true,
+ Data: *apiKey,
+ },
+ }, nil
+}
+
+// UpdateApiKey updates an existing API key.
+func (h *ApiKeyHandler) UpdateApiKey(ctx context.Context, input *UpdateApiKeyInput) (*UpdateApiKeyOutput, error) {
+ if h.apiKeyService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ // Check admin access
+ if !humamw.IsAdminFromContext(ctx) {
+ return nil, huma.Error403Forbidden("admin access required")
+ }
+
+ apiKey, err := h.apiKeyService.UpdateApiKey(ctx, input.ID, input.Body)
+ if err != nil {
+ if errors.Is(err, services.ErrApiKeyNotFound) {
+ return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.ApiKeyUpdateError{Err: err}).Error())
+ }
+
+ return &UpdateApiKeyOutput{
+ Body: base.ApiResponse[apikey.ApiKey]{
+ Success: true,
+ Data: *apiKey,
+ },
+ }, nil
+}
+
+// DeleteApiKey deletes an API key.
+func (h *ApiKeyHandler) DeleteApiKey(ctx context.Context, input *DeleteApiKeyInput) (*DeleteApiKeyOutput, error) {
+ if h.apiKeyService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ // Check admin access
+ if !humamw.IsAdminFromContext(ctx) {
+ return nil, huma.Error403Forbidden("admin access required")
+ }
+
+ if err := h.apiKeyService.DeleteApiKey(ctx, input.ID); err != nil {
+ if errors.Is(err, services.ErrApiKeyNotFound) {
+ return nil, huma.Error404NotFound((&common.ApiKeyNotFoundError{}).Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.ApiKeyDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteApiKeyOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "API key deleted successfully",
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/appimages.go b/backend/internal/huma/handlers/appimages.go
new file mode 100644
index 000000000..9f88b87fd
--- /dev/null
+++ b/backend/internal/huma/handlers/appimages.go
@@ -0,0 +1,109 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+)
+
+// AppImagesHandler provides Huma-based application image endpoints.
+type AppImagesHandler struct {
+ appImagesService *services.ApplicationImagesService
+}
+
+// --- Huma Input/Output Wrappers ---
+
+type GetLogoInput struct {
+ Full bool `query:"full" default:"false" doc:"Return full logo instead of icon"`
+}
+
+type GetAppImageOutput struct {
+ ContentType string `header:"Content-Type"`
+ CacheControl string `header:"Cache-Control"`
+ Body []byte
+}
+
+// RegisterAppImages registers application image routes using Huma.
+func RegisterAppImages(api huma.API, appImagesService *services.ApplicationImagesService) {
+ h := &AppImagesHandler{
+ appImagesService: appImagesService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-logo",
+ Method: http.MethodGet,
+ Path: "/app-images/logo",
+ Summary: "Get application logo",
+ Description: "Get the application logo image",
+ Tags: []string{"Application Images"},
+ }, h.GetLogo)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-favicon",
+ Method: http.MethodGet,
+ Path: "/app-images/favicon",
+ Summary: "Get application favicon",
+ Description: "Get the application favicon image",
+ Tags: []string{"Application Images"},
+ }, h.GetFavicon)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-default-profile",
+ Method: http.MethodGet,
+ Path: "/app-images/profile",
+ Summary: "Get default profile image",
+ Description: "Get the default user profile image",
+ Tags: []string{"Application Images"},
+ }, h.GetDefaultProfile)
+}
+
+// GetLogo returns the application logo image.
+func (h *AppImagesHandler) GetLogo(ctx context.Context, input *GetLogoInput) (*GetAppImageOutput, error) {
+ if h.appImagesService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ name := "logo"
+ if input.Full {
+ name = "logo-full"
+ }
+
+ return h.getImage(name)
+}
+
+// GetFavicon returns the application favicon image.
+func (h *AppImagesHandler) GetFavicon(ctx context.Context, input *struct{}) (*GetAppImageOutput, error) {
+ if h.appImagesService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ return h.getImage("favicon")
+}
+
+// GetDefaultProfile returns the default user profile image.
+func (h *AppImagesHandler) GetDefaultProfile(ctx context.Context, input *struct{}) (*GetAppImageOutput, error) {
+ if h.appImagesService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ return h.getImage("profile")
+}
+
+func (h *AppImagesHandler) getImage(name string) (*GetAppImageOutput, error) {
+ imageData, mimeType, err := h.appImagesService.GetImage(name)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ImageRetrievalError{Err: err}).Error())
+ }
+
+ // Cache for 15 minutes, stale-while-revalidate for 24 hours
+ cacheControl := "public, max-age=900, stale-while-revalidate=86400"
+
+ return &GetAppImageOutput{
+ ContentType: mimeType,
+ CacheControl: cacheControl,
+ Body: imageData,
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/auth.go b/backend/internal/huma/handlers/auth.go
new file mode 100644
index 000000000..f25b1bab5
--- /dev/null
+++ b/backend/internal/huma/handlers/auth.go
@@ -0,0 +1,287 @@
+package handlers
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "time"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/cookie"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "go.getarcane.app/types/auth"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/user"
+)
+
+type AuthHandler struct {
+ userService *services.UserService
+ authService *services.AuthService
+ oidcService *services.OidcService
+}
+
+// --- Huma Input/Output Wrappers ---
+// These wrap the types from the types package for Huma's input/output handling.
+
+type LoginInput struct {
+ Body auth.Login
+}
+
+type LoginOutput struct {
+ SetCookie string `header:"Set-Cookie" doc:"Session cookie"`
+ Body base.ApiResponse[auth.LoginResponse]
+}
+
+type LogoutOutput struct {
+ SetCookie string `header:"Set-Cookie" doc:"Cleared session cookie"`
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type RefreshTokenInput struct {
+ Body auth.Refresh
+}
+
+type RefreshTokenOutput struct {
+ SetCookie string `header:"Set-Cookie" doc:"Updated session cookie"`
+ Body base.ApiResponse[auth.TokenRefreshResponse]
+}
+
+type ChangePasswordInput struct {
+ Body auth.PasswordChange
+}
+
+type ChangePasswordOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type GetCurrentUserOutput struct {
+ Body base.ApiResponse[user.User]
+}
+
+// RegisterAuth registers authentication routes using Huma.
+func RegisterAuth(api huma.API, userService *services.UserService, authService *services.AuthService, oidcService *services.OidcService) {
+ h := &AuthHandler{
+ userService: userService,
+ authService: authService,
+ oidcService: oidcService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "login",
+ Method: http.MethodPost,
+ Path: "/auth/login",
+ Summary: "Login",
+ Description: "Authenticate a user with username and password",
+ Tags: []string{"Auth"},
+ }, h.Login)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "logout",
+ Method: http.MethodPost,
+ Path: "/auth/logout",
+ Summary: "Logout",
+ Description: "Clear authentication session",
+ Tags: []string{"Auth"},
+ }, h.Logout)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-current-user",
+ Method: http.MethodGet,
+ Path: "/auth/me",
+ Summary: "Get current user",
+ Description: "Get the currently authenticated user's information",
+ Tags: []string{"Auth"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetCurrentUser)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "refresh-token",
+ Method: http.MethodPost,
+ Path: "/auth/refresh",
+ Summary: "Refresh token",
+ Description: "Obtain a new access token using a refresh token",
+ Tags: []string{"Auth"},
+ }, h.RefreshToken)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "change-password",
+ Method: http.MethodPost,
+ Path: "/auth/password",
+ Summary: "Change password",
+ Description: "Change the current user's password",
+ Tags: []string{"Auth"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ChangePassword)
+}
+
+// Login authenticates a user and returns tokens.
+func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutput, error) {
+ if h.authService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ localAuthEnabled, err := h.authService.IsLocalAuthEnabled(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.AuthSettingsCheckError{Err: err}).Error())
+ }
+ if !localAuthEnabled {
+ return nil, huma.Error400BadRequest((&common.LocalAuthDisabledError{}).Error())
+ }
+
+ userModel, tokenPair, err := h.authService.Login(ctx, input.Body.Username, input.Body.Password)
+ if err != nil {
+ switch {
+ case errors.Is(err, services.ErrInvalidCredentials):
+ return nil, huma.Error401Unauthorized((&common.InvalidCredentialsError{}).Error())
+ case errors.Is(err, services.ErrLocalAuthDisabled):
+ return nil, huma.Error400BadRequest((&common.LocalAuthDisabledError{}).Error())
+ default:
+ return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())
+ }
+ }
+
+ var userResp user.User
+ if mapErr := mapper.MapStruct(userModel, &userResp); mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: mapErr}).Error())
+ }
+
+ maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
+ if maxAge < 0 {
+ maxAge = 0
+ }
+ maxAge += 60
+
+ return &LoginOutput{
+ SetCookie: cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken),
+ Body: base.ApiResponse[auth.LoginResponse]{
+ Success: true,
+ Data: auth.LoginResponse{
+ Token: tokenPair.AccessToken,
+ RefreshToken: tokenPair.RefreshToken,
+ ExpiresAt: tokenPair.ExpiresAt,
+ User: userResp,
+ },
+ },
+ }, nil
+}
+
+// Logout clears the authentication session.
+func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutput, error) {
+ return &LogoutOutput{
+ SetCookie: cookie.BuildClearTokenCookieString(),
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Logged out successfully",
+ },
+ },
+ }, nil
+}
+
+// GetCurrentUser returns the currently authenticated user's information.
+func (h *AuthHandler) GetCurrentUser(ctx context.Context, input *struct{}) (*GetCurrentUserOutput, error) {
+ if h.userService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ userID, exists := humamw.GetUserIDFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ userModel, err := h.userService.GetUser(ctx, userID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserRetrievalError{Err: err}).Error())
+ }
+
+ var out user.User
+ if mapErr := mapper.MapStruct(userModel, &out); mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: mapErr}).Error())
+ }
+
+ return &GetCurrentUserOutput{
+ Body: base.ApiResponse[user.User]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// RefreshToken obtains a new access token using a refresh token.
+func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInput) (*RefreshTokenOutput, error) {
+ if h.authService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ tokenPair, err := h.authService.RefreshToken(ctx, input.Body.RefreshToken)
+ if err != nil {
+ switch {
+ case errors.Is(err, services.ErrInvalidToken), errors.Is(err, services.ErrExpiredToken):
+ return nil, huma.Error401Unauthorized((&common.InvalidTokenError{}).Error())
+ default:
+ return nil, huma.Error500InternalServerError((&common.TokenRefreshError{Err: err}).Error())
+ }
+ }
+
+ maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
+ if maxAge < 0 {
+ maxAge = 0
+ }
+ maxAge += 60
+
+ return &RefreshTokenOutput{
+ SetCookie: cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken),
+ Body: base.ApiResponse[auth.TokenRefreshResponse]{
+ Success: true,
+ Data: auth.TokenRefreshResponse{
+ Token: tokenPair.AccessToken,
+ RefreshToken: tokenPair.RefreshToken,
+ ExpiresAt: tokenPair.ExpiresAt,
+ },
+ },
+ }, nil
+}
+
+// ChangePassword changes the current user's password.
+func (h *AuthHandler) ChangePassword(ctx context.Context, input *ChangePasswordInput) (*ChangePasswordOutput, error) {
+ if h.authService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ userModel, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ if input.Body.CurrentPassword == "" {
+ return nil, huma.Error400BadRequest((&common.PasswordRequiredError{}).Error())
+ }
+
+ err := h.authService.ChangePassword(ctx, userModel.ID, input.Body.CurrentPassword, input.Body.NewPassword)
+ if err != nil {
+ switch {
+ case errors.Is(err, services.ErrInvalidCredentials):
+ return nil, huma.Error401Unauthorized((&common.IncorrectPasswordError{}).Error())
+ default:
+ return nil, huma.Error500InternalServerError((&common.PasswordChangeError{Err: err}).Error())
+ }
+ }
+
+ return &ChangePasswordOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Password changed successfully",
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/container_registries.go b/backend/internal/huma/handlers/container_registries.go
new file mode 100644
index 000000000..c94732f15
--- /dev/null
+++ b/backend/internal/huma/handlers/container_registries.go
@@ -0,0 +1,403 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/registry"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/containerregistry"
+)
+
+// ContainerRegistryHandler handles container registry management endpoints.
+type ContainerRegistryHandler struct {
+ registryService *services.ContainerRegistryService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+// ContainerRegistryPaginatedResponse is the paginated response for container registries.
+type ContainerRegistryPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []containerregistry.ContainerRegistry `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListContainerRegistriesInput struct {
+ Page int `query:"pagination[page]" default:"1" doc:"Page number"`
+ Limit int `query:"pagination[limit]" default:"20" doc:"Items per page"`
+ SortCol string `query:"sort[column]" doc:"Column to sort by"`
+ SortDir string `query:"sort[direction]" default:"asc" doc:"Sort direction"`
+}
+
+type ListContainerRegistriesOutput struct {
+ Body ContainerRegistryPaginatedResponse
+}
+
+type CreateContainerRegistryInput struct {
+ Body models.CreateContainerRegistryRequest
+}
+
+type CreateContainerRegistryOutput struct {
+ Body base.ApiResponse[containerregistry.ContainerRegistry]
+}
+
+type GetContainerRegistryInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+}
+
+type GetContainerRegistryOutput struct {
+ Body base.ApiResponse[containerregistry.ContainerRegistry]
+}
+
+type UpdateContainerRegistryInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+ Body models.UpdateContainerRegistryRequest
+}
+
+type UpdateContainerRegistryOutput struct {
+ Body base.ApiResponse[containerregistry.ContainerRegistry]
+}
+
+type DeleteContainerRegistryInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+}
+
+type DeleteContainerRegistryOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type TestContainerRegistryInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+}
+
+type TestContainerRegistryOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type SyncContainerRegistriesInput struct {
+ Body containerregistry.SyncRequest
+}
+
+type SyncContainerRegistriesOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterContainerRegistries registers all container registry endpoints.
+func RegisterContainerRegistries(api huma.API, registryService *services.ContainerRegistryService) {
+ h := &ContainerRegistryHandler{registryService: registryService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listContainerRegistries",
+ Method: "GET",
+ Path: "/container-registries",
+ Summary: "List container registries",
+ Description: "Get a paginated list of container registries",
+ Tags: []string{"Container Registries"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListRegistries)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "createContainerRegistry",
+ Method: "POST",
+ Path: "/container-registries",
+ Summary: "Create a container registry",
+ Description: "Create a new container registry",
+ Tags: []string{"Container Registries"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "syncContainerRegistries",
+ Method: "POST",
+ Path: "/container-registries/sync",
+ Summary: "Sync container registries",
+ Description: "Sync container registries from a remote source",
+ Tags: []string{"Container Registries"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.SyncRegistries)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getContainerRegistry",
+ Method: "GET",
+ Path: "/container-registries/{id}",
+ Summary: "Get a container registry",
+ Description: "Get a container registry by ID",
+ Tags: []string{"Container Registries"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateContainerRegistry",
+ Method: "PUT",
+ Path: "/container-registries/{id}",
+ Summary: "Update a container registry",
+ Description: "Update an existing container registry",
+ Tags: []string{"Container Registries"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteContainerRegistry",
+ Method: "DELETE",
+ Path: "/container-registries/{id}",
+ Summary: "Delete a container registry",
+ Description: "Delete a container registry by ID",
+ Tags: []string{"Container Registries"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "testContainerRegistry",
+ Method: "POST",
+ Path: "/container-registries/{id}/test",
+ Summary: "Test a container registry",
+ Description: "Test connectivity and authentication to a container registry",
+ Tags: []string{"Container Registries"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.TestRegistry)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// ListRegistries returns a paginated list of container registries.
+func (h *ContainerRegistryHandler) ListRegistries(ctx context.Context, input *ListContainerRegistriesInput) (*ListContainerRegistriesOutput, error) {
+ if h.registryService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Limit, input.SortCol, input.SortDir)
+
+ registries, paginationResp, err := h.registryService.GetRegistriesPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryListError{Err: err}).Error())
+ }
+
+ return &ListContainerRegistriesOutput{
+ Body: ContainerRegistryPaginatedResponse{
+ Success: true,
+ Data: registries,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// CreateRegistry creates a new container registry.
+func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *CreateContainerRegistryInput) (*CreateContainerRegistryOutput, error) {
+ if h.registryService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ reg, err := h.registryService.CreateRegistry(ctx, input.Body)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryCreationError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateContainerRegistryOutput{
+ Body: base.ApiResponse[containerregistry.ContainerRegistry]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetRegistry returns a container registry by ID.
+func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetContainerRegistryInput) (*GetContainerRegistryOutput, error) {
+ if h.registryService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ reg, err := h.registryService.GetRegistryByID(ctx, input.ID)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryRetrievalError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())
+ }
+
+ return &GetContainerRegistryOutput{
+ Body: base.ApiResponse[containerregistry.ContainerRegistry]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// UpdateRegistry updates a container registry.
+func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *UpdateContainerRegistryInput) (*UpdateContainerRegistryOutput, error) {
+ if h.registryService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ reg, err := h.registryService.UpdateRegistry(ctx, input.ID, input.Body)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryUpdateError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())
+ }
+
+ return &UpdateContainerRegistryOutput{
+ Body: base.ApiResponse[containerregistry.ContainerRegistry]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// DeleteRegistry deletes a container registry.
+func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *DeleteContainerRegistryInput) (*DeleteContainerRegistryOutput, error) {
+ if h.registryService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.registryService.DeleteRegistry(ctx, input.ID); err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteContainerRegistryOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Container registry deleted successfully",
+ },
+ },
+ }, nil
+}
+
+// TestRegistry tests connectivity to a container registry.
+func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *TestContainerRegistryInput) (*TestContainerRegistryOutput, error) {
+ if h.registryService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ reg, err := h.registryService.GetRegistryByID(ctx, input.ID)
+ if err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryRetrievalError{Err: err}).Error())
+ }
+
+ decryptedToken, err := utils.Decrypt(reg.Token)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.TokenDecryptionError{Err: err}).Error())
+ }
+
+ testResult, testErr := h.performRegistryTest(ctx, reg, decryptedToken)
+ if testErr != nil {
+ return nil, huma.Error400BadRequest((&common.RegistryTestError{Err: testErr}).Error())
+ }
+
+ return &TestContainerRegistryOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: testResult["message"].(string),
+ },
+ },
+ }, nil
+}
+
+// SyncRegistries syncs container registries from a remote source.
+func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *SyncContainerRegistriesInput) (*SyncContainerRegistriesOutput, error) {
+ if h.registryService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.registryService.SyncRegistries(ctx, input.Body.Registries); err != nil {
+ apiErr := models.ToAPIError(err)
+ return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistrySyncError{Err: err}).Error())
+ }
+
+ return &SyncContainerRegistriesOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Registries synced successfully",
+ },
+ },
+ }, nil
+}
+
+// ============================================================================
+// Helper Methods
+// ============================================================================
+
+func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, registryModel *models.ContainerRegistry, decryptedToken string) (map[string]interface{}, error) {
+ var creds *registry.Credentials
+ if registryModel.Username != "" && decryptedToken != "" {
+ creds = &registry.Credentials{
+ Username: registryModel.Username,
+ Token: decryptedToken,
+ }
+ }
+
+ testResult, err := registry.TestRegistryConnection(ctx, registryModel.URL, creds)
+ if err != nil {
+ return nil, err
+ }
+
+ if !testResult.AuthSuccess {
+ if len(testResult.Errors) > 0 {
+ return nil, fmt.Errorf("%s", testResult.Errors[0])
+ }
+ return nil, fmt.Errorf("invalid credentials")
+ }
+
+ return map[string]interface{}{
+ "message": "Authentication succeeded",
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/containers.go b/backend/internal/huma/handlers/containers.go
new file mode 100644
index 000000000..785dd36b6
--- /dev/null
+++ b/backend/internal/huma/handlers/containers.go
@@ -0,0 +1,442 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ dockercontainer "github.com/docker/docker/api/types/container"
+ "github.com/docker/docker/api/types/network"
+ "github.com/docker/go-connections/nat"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "go.getarcane.app/types/base"
+ containertypes "go.getarcane.app/types/container"
+)
+
+type ContainerHandler struct {
+ containerService *services.ContainerService
+ dockerService *services.DockerClientService
+}
+
+// Paginated response
+type ContainerPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []containertypes.Summary `json:"data"`
+ Counts containertypes.StatusCounts `json:"counts"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListContainersInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction"`
+ Start int `query:"start" default:"0" doc:"Start index"`
+ Limit int `query:"limit" default:"20" doc:"Limit"`
+}
+
+type ListContainersOutput struct {
+ Body ContainerPaginatedResponse
+}
+
+type GetContainerStatusCountsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+// ContainerStatusCountsResponse is a dedicated response type to avoid schema name collision
+type ContainerStatusCountsResponse struct {
+ Success bool `json:"success"`
+ Data containertypes.StatusCounts `json:"data"`
+}
+
+type GetContainerStatusCountsOutput struct {
+ Body ContainerStatusCountsResponse
+}
+
+type CreateContainerInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body containertypes.Create
+}
+
+// ContainerCreatedResponse is a dedicated response type
+type ContainerCreatedResponse struct {
+ Success bool `json:"success"`
+ Data containertypes.Created `json:"data"`
+}
+
+type CreateContainerOutput struct {
+ Body ContainerCreatedResponse
+}
+
+type GetContainerInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ContainerID string `path:"containerId" doc:"Container ID"`
+}
+
+// ContainerDetailsResponse is a dedicated response type
+type ContainerDetailsResponse struct {
+ Success bool `json:"success"`
+ Data containertypes.Details `json:"data"`
+}
+
+type GetContainerOutput struct {
+ Body ContainerDetailsResponse
+}
+
+type ContainerActionInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ContainerID string `path:"containerId" doc:"Container ID"`
+}
+
+// ContainerActionResponse is a dedicated response type
+type ContainerActionResponse struct {
+ Success bool `json:"success"`
+ Data base.MessageResponse `json:"data"`
+}
+
+type ContainerActionOutput struct {
+ Body ContainerActionResponse
+}
+
+type DeleteContainerInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ContainerID string `path:"containerId" doc:"Container ID"`
+ Force bool `query:"force" default:"false" doc:"Force delete running container"`
+ RemoveVolumes bool `query:"volumes" default:"false" doc:"Remove associated volumes"`
+}
+
+type DeleteContainerOutput struct {
+ Body ContainerActionResponse
+}
+
+// RegisterContainers registers container endpoints.
+func RegisterContainers(api huma.API, containerSvc *services.ContainerService, dockerSvc *services.DockerClientService) {
+ h := &ContainerHandler{
+ containerService: containerSvc,
+ dockerService: dockerSvc,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-containers",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/containers",
+ Summary: "List containers",
+ Description: "Paginated list of containers",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.ListContainers)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "container-status-counts",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/containers/counts",
+ Summary: "Container status counts",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetContainerStatusCounts)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-container",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/containers",
+ Summary: "Create container",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CreateContainer)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-container",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/containers/{containerId}",
+ Summary: "Get container",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetContainer)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "start-container",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/containers/{containerId}/start",
+ Summary: "Start container",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.StartContainer)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "stop-container",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/containers/{containerId}/stop",
+ Summary: "Stop container",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.StopContainer)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "restart-container",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/containers/{containerId}/restart",
+ Summary: "Restart container",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.RestartContainer)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-container",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/containers/{containerId}",
+ Summary: "Delete container",
+ Tags: []string{"Containers"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.DeleteContainer)
+}
+
+func (h *ContainerHandler) ListContainers(ctx context.Context, input *ListContainersInput) (*ListContainersOutput, error) {
+ if h.containerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := pagination.QueryParams{
+ SearchQuery: pagination.SearchQuery{Search: input.Search},
+ SortParams: pagination.SortParams{
+ Sort: input.Sort,
+ Order: pagination.SortOrder(input.Order),
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: input.Start,
+ Limit: input.Limit,
+ },
+ }
+
+ containers, paginationResp, counts, err := h.containerService.ListContainersPaginated(ctx, params, true)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerListError{Err: err}).Error())
+ }
+
+ return &ListContainersOutput{
+ Body: ContainerPaginatedResponse{
+ Success: true,
+ Data: containers,
+ Counts: counts,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+func (h *ContainerHandler) GetContainerStatusCounts(ctx context.Context, input *GetContainerStatusCountsInput) (*GetContainerStatusCountsOutput, error) {
+ if h.dockerService == nil {
+ return nil, huma.Error500InternalServerError("docker service not available")
+ }
+
+ _, running, stopped, total, err := h.dockerService.GetAllContainers(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerStatusCountsError{Err: err}).Error())
+ }
+
+ return &GetContainerStatusCountsOutput{
+ Body: ContainerStatusCountsResponse{
+ Success: true,
+ Data: containertypes.StatusCounts{
+ RunningContainers: int(running),
+ StoppedContainers: int(stopped),
+ TotalContainers: int(total),
+ },
+ },
+ }, nil
+}
+
+func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateContainerInput) (*CreateContainerOutput, error) {
+ if h.containerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("not authenticated")
+ }
+
+ // Build Docker config from input
+ config := &dockercontainer.Config{
+ Image: input.Body.Image,
+ Cmd: input.Body.Command,
+ Entrypoint: input.Body.Entrypoint,
+ WorkingDir: input.Body.WorkingDir,
+ User: input.Body.User,
+ Env: input.Body.Environment,
+ ExposedPorts: nat.PortSet{},
+ Labels: map[string]string{
+ "com.arcane.created": "true",
+ },
+ }
+
+ portBindings := nat.PortMap{}
+ for containerPort, hostPort := range input.Body.Ports {
+ port, err := nat.NewPort("tcp", containerPort)
+ if err != nil {
+ return nil, huma.Error400BadRequest((&common.InvalidPortFormatError{Err: err}).Error())
+ }
+ config.ExposedPorts[port] = struct{}{}
+ portBindings[port] = []nat.PortBinding{{HostPort: hostPort}}
+ }
+
+ hostConfig := &dockercontainer.HostConfig{
+ Binds: input.Body.Volumes,
+ PortBindings: portBindings,
+ Privileged: input.Body.Privileged,
+ AutoRemove: input.Body.AutoRemove,
+ RestartPolicy: dockercontainer.RestartPolicy{Name: dockercontainer.RestartPolicyMode(input.Body.RestartPolicy)},
+ }
+
+ if input.Body.Memory > 0 {
+ hostConfig.Memory = input.Body.Memory
+ }
+ if input.Body.CPUs > 0 {
+ hostConfig.NanoCPUs = int64(input.Body.CPUs * 1e9)
+ }
+
+ var networkingConfig *network.NetworkingConfig
+ if len(input.Body.Networks) > 0 {
+ networkingConfig = &network.NetworkingConfig{
+ EndpointsConfig: make(map[string]*network.EndpointSettings),
+ }
+ for _, net := range input.Body.Networks {
+ networkingConfig.EndpointsConfig[net] = &network.EndpointSettings{}
+ }
+ }
+
+ containerJSON, err := h.containerService.CreateContainer(ctx, config, hostConfig, networkingConfig, input.Body.Name, *user, input.Body.Credentials)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerCreationError{Err: err}).Error())
+ }
+
+ out := containertypes.Created{
+ ID: containerJSON.ID,
+ Name: containerJSON.Name,
+ Image: containerJSON.Config.Image,
+ Status: containerJSON.State.Status,
+ Created: containerJSON.Created,
+ }
+
+ return &CreateContainerOutput{
+ Body: ContainerCreatedResponse{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerInput) (*GetContainerOutput, error) {
+ if h.containerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ containerInspect, err := h.containerService.GetContainerByID(ctx, input.ContainerID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.ContainerRetrievalError{Err: err}).Error())
+ }
+
+ details := containertypes.NewDetails(containerInspect)
+
+ return &GetContainerOutput{
+ Body: ContainerDetailsResponse{
+ Success: true,
+ Data: details,
+ },
+ }, nil
+}
+
+func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+ if h.containerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("not authenticated")
+ }
+
+ if err := h.containerService.StartContainer(ctx, input.ContainerID, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerStartError{Err: err}).Error())
+ }
+
+ return &ContainerActionOutput{
+ Body: ContainerActionResponse{
+ Success: true,
+ Data: base.MessageResponse{Message: "Container started successfully"},
+ },
+ }, nil
+}
+
+func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+ if h.containerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("not authenticated")
+ }
+
+ if err := h.containerService.StopContainer(ctx, input.ContainerID, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerStopError{Err: err}).Error())
+ }
+
+ return &ContainerActionOutput{
+ Body: ContainerActionResponse{
+ Success: true,
+ Data: base.MessageResponse{Message: "Container stopped successfully"},
+ },
+ }, nil
+}
+
+func (h *ContainerHandler) RestartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {
+ if h.containerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("not authenticated")
+ }
+
+ if err := h.containerService.RestartContainer(ctx, input.ContainerID, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerRestartError{Err: err}).Error())
+ }
+
+ return &ContainerActionOutput{
+ Body: ContainerActionResponse{
+ Success: true,
+ Data: base.MessageResponse{Message: "Container restarted successfully"},
+ },
+ }, nil
+}
+
+func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteContainerInput) (*DeleteContainerOutput, error) {
+ if h.containerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("not authenticated")
+ }
+
+ if err := h.containerService.DeleteContainer(ctx, input.ContainerID, input.Force, input.RemoveVolumes, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerDeleteError{Err: err}).Error())
+ }
+
+ return &DeleteContainerOutput{
+ Body: ContainerActionResponse{
+ Success: true,
+ Data: base.MessageResponse{Message: "Container deleted successfully"},
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/customize.go b/backend/internal/huma/handlers/customize.go
new file mode 100644
index 000000000..a473d484b
--- /dev/null
+++ b/backend/internal/huma/handlers/customize.go
@@ -0,0 +1,97 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+ "strings"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "go.getarcane.app/types/category"
+ "go.getarcane.app/types/search"
+)
+
+// CustomizeHandler handles customization search endpoints.
+type CustomizeHandler struct {
+ customizeSearchService *services.CustomizeSearchService
+}
+
+// --- Input/Output Types ---
+
+type SearchCustomizeInput struct {
+ Body search.Request
+}
+
+type SearchCustomizeOutput struct {
+ Body search.Response
+}
+
+type GetCustomizeCategoriesInput struct{}
+
+type GetCustomizeCategoriesOutput struct {
+ Body []category.Category
+}
+
+// RegisterCustomize registers customization endpoints using Huma.
+func RegisterCustomize(api huma.API, customizeSearchService *services.CustomizeSearchService) {
+ h := &CustomizeHandler{
+ customizeSearchService: customizeSearchService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "search-customize",
+ Method: http.MethodPost,
+ Path: "/customize/search",
+ Summary: "Search customization options",
+ Description: "Search customization categories and options by query",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.Search)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-customize-categories",
+ Method: http.MethodGet,
+ Path: "/customize/categories",
+ Summary: "Get customization categories",
+ Description: "Get all available customization categories with metadata",
+ Tags: []string{"Customize"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetCategories)
+}
+
+// Search searches customization options by query.
+func (h *CustomizeHandler) Search(ctx context.Context, input *SearchCustomizeInput) (*SearchCustomizeOutput, error) {
+ if h.customizeSearchService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if strings.TrimSpace(input.Body.Query) == "" {
+ return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
+ }
+
+ results := h.customizeSearchService.Search(input.Body.Query)
+
+ return &SearchCustomizeOutput{
+ Body: results,
+ }, nil
+}
+
+// GetCategories returns all available customization categories.
+func (h *CustomizeHandler) GetCategories(ctx context.Context, input *GetCustomizeCategoriesInput) (*GetCustomizeCategoriesOutput, error) {
+ if h.customizeSearchService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ categories := h.customizeSearchService.GetCustomizeCategories()
+
+ return &GetCustomizeCategoriesOutput{
+ Body: categories,
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/environments.go b/backend/internal/huma/handlers/environments.go
new file mode 100644
index 000000000..646336ce2
--- /dev/null
+++ b/backend/internal/huma/handlers/environments.go
@@ -0,0 +1,585 @@
+package handlers
+
+import (
+ "context"
+ "log/slog"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/environment"
+)
+
+const localDockerEnvironmentID = "0"
+
+// EnvironmentHandler handles environment management endpoints.
+type EnvironmentHandler struct {
+ environmentService *services.EnvironmentService
+ settingsService *services.SettingsService
+ cfg *config.Config
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+// EnvironmentPaginatedResponse is the paginated response for environments.
+type EnvironmentPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []environment.Environment `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListEnvironmentsInput struct {
+ Page int `query:"pagination[page]" default:"1" doc:"Page number"`
+ Limit int `query:"pagination[limit]" default:"20" doc:"Items per page"`
+ SortCol string `query:"sort[column]" doc:"Column to sort by"`
+ SortDir string `query:"sort[direction]" default:"asc" doc:"Sort direction"`
+}
+
+type ListEnvironmentsOutput struct {
+ Body EnvironmentPaginatedResponse
+}
+
+type CreateEnvironmentInput struct {
+ Body environment.Create
+}
+
+type CreateEnvironmentOutput struct {
+ Body base.ApiResponse[environment.Environment]
+}
+
+type GetEnvironmentInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+}
+
+type GetEnvironmentOutput struct {
+ Body base.ApiResponse[environment.Environment]
+}
+
+type UpdateEnvironmentInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+ Body environment.Update
+}
+
+type UpdateEnvironmentOutput struct {
+ Body base.ApiResponse[environment.Environment]
+}
+
+type DeleteEnvironmentInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+}
+
+type DeleteEnvironmentOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type TestConnectionInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+ Body environment.TestConnectionRequest
+}
+
+type TestConnectionOutput struct {
+ Body base.ApiResponse[environment.Test]
+}
+
+type UpdateHeartbeatInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+}
+
+type UpdateHeartbeatOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type PairAgentInput struct {
+ ID string `path:"id" doc:"Environment ID (must be 0 for local)"`
+ Body environment.AgentPairRequest
+}
+
+type PairAgentOutput struct {
+ Body base.ApiResponse[environment.AgentPairResponse]
+}
+
+type SyncRegistriesInput struct {
+ ID string `path:"id" doc:"Environment ID"`
+}
+
+type SyncRegistriesOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterEnvironments registers all environment management endpoints.
+func RegisterEnvironments(api huma.API, environmentService *services.EnvironmentService, settingsService *services.SettingsService, cfg *config.Config) {
+ h := &EnvironmentHandler{
+ environmentService: environmentService,
+ settingsService: settingsService,
+ cfg: cfg,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listEnvironments",
+ Method: "GET",
+ Path: "/environments",
+ Summary: "List environments",
+ Description: "Get a paginated list of Docker environments",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListEnvironments)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "createEnvironment",
+ Method: "POST",
+ Path: "/environments",
+ Summary: "Create an environment",
+ Description: "Create a new Docker environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateEnvironment)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getEnvironment",
+ Method: "GET",
+ Path: "/environments/{id}",
+ Summary: "Get an environment",
+ Description: "Get a Docker environment by ID",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetEnvironment)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateEnvironment",
+ Method: "PUT",
+ Path: "/environments/{id}",
+ Summary: "Update an environment",
+ Description: "Update a Docker environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateEnvironment)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteEnvironment",
+ Method: "DELETE",
+ Path: "/environments/{id}",
+ Summary: "Delete an environment",
+ Description: "Delete a Docker environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteEnvironment)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "testConnection",
+ Method: "POST",
+ Path: "/environments/{id}/test",
+ Summary: "Test environment connection",
+ Description: "Test connectivity to a Docker environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.TestConnection)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateHeartbeat",
+ Method: "POST",
+ Path: "/environments/{id}/heartbeat",
+ Summary: "Update environment heartbeat",
+ Description: "Update the heartbeat timestamp for an environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateHeartbeat)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "pairAgent",
+ Method: "POST",
+ Path: "/environments/{id}/agent/pair",
+ Summary: "Pair with local agent",
+ Description: "Generate or rotate the local agent pairing token",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.PairAgent)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "syncEnvironmentRegistries",
+ Method: "POST",
+ Path: "/environments/{id}/sync-registries",
+ Summary: "Sync container registries",
+ Description: "Sync container registries to a remote environment",
+ Tags: []string{"Environments"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.SyncRegistries)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// ListEnvironments returns a paginated list of environments.
+func (h *EnvironmentHandler) ListEnvironments(ctx context.Context, input *ListEnvironmentsInput) (*ListEnvironmentsOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Limit, input.SortCol, input.SortDir)
+
+ envs, paginationResp, err := h.environmentService.ListEnvironmentsPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentListError{Err: err}).Error())
+ }
+
+ return &ListEnvironmentsOutput{
+ Body: EnvironmentPaginatedResponse{
+ Success: true,
+ Data: envs,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// CreateEnvironment creates a new environment.
+func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *CreateEnvironmentInput) (*CreateEnvironmentOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ env := &models.Environment{
+ ApiUrl: input.Body.ApiUrl,
+ Enabled: true,
+ }
+ if input.Body.Name != nil {
+ env.Name = *input.Body.Name
+ }
+ if input.Body.Enabled != nil {
+ env.Enabled = *input.Body.Enabled
+ }
+
+ if (input.Body.AccessToken == nil || *input.Body.AccessToken == "") && input.Body.BootstrapToken != nil && *input.Body.BootstrapToken != "" {
+ token, err := h.environmentService.PairAgentWithBootstrap(ctx, input.Body.ApiUrl, *input.Body.BootstrapToken)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to pair with agent", "apiUrl", input.Body.ApiUrl, "error", err.Error())
+ return nil, huma.Error502BadGateway((&common.AgentPairingError{Err: err}).Error())
+ }
+ env.AccessToken = &token
+ } else if input.Body.AccessToken != nil && *input.Body.AccessToken != "" {
+ env.AccessToken = input.Body.AccessToken
+ }
+
+ created, err := h.environmentService.CreateEnvironment(ctx, env)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentCreationError{Err: err}).Error())
+ }
+
+ // Sync registries in background (intentionally detached from request context)
+ if created.AccessToken != nil && *created.AccessToken != "" {
+ go func(envID string, envName string) { //nolint:contextcheck // intentional background context for async task
+ bgCtx := context.Background()
+ if err := h.environmentService.SyncRegistriesToEnvironment(bgCtx, envID); err != nil {
+ slog.WarnContext(bgCtx, "Failed to sync registries to new environment",
+ "environmentID", envID, "environmentName", envName, "error", err.Error())
+ }
+ }(created.ID, created.Name)
+ }
+
+ out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateEnvironmentOutput{
+ Body: base.ApiResponse[environment.Environment]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetEnvironment returns an environment by ID.
+func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvironmentInput) (*GetEnvironmentOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ env, err := h.environmentService.GetEnvironmentByID(ctx, input.ID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.EnvironmentNotFoundError{}).Error())
+ }
+
+ out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](env)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
+ }
+
+ return &GetEnvironmentOutput{
+ Body: base.ApiResponse[environment.Environment]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// UpdateEnvironment updates an environment.
+func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *UpdateEnvironmentInput) (*UpdateEnvironmentOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ isLocalEnv := input.ID == localDockerEnvironmentID
+ updates := h.buildUpdateMap(&input.Body, isLocalEnv)
+
+ pairingSucceeded, err := h.handleEnvironmentPairing(ctx, input.ID, &input.Body, updates, isLocalEnv)
+ if err != nil {
+ return nil, err
+ }
+
+ updated, updateErr := h.environmentService.UpdateEnvironment(ctx, input.ID, updates)
+ if updateErr != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentUpdateError{Err: updateErr}).Error())
+ }
+
+ h.triggerPostUpdateTasks(input.ID, updated, pairingSucceeded, &input.Body) //nolint:contextcheck // intentionally detached background tasks
+
+ out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](updated)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentMappingError{Err: mapErr}).Error())
+ }
+
+ return &UpdateEnvironmentOutput{
+ Body: base.ApiResponse[environment.Environment]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// DeleteEnvironment deletes an environment.
+func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *DeleteEnvironmentInput) (*DeleteEnvironmentOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == localDockerEnvironmentID {
+ return nil, huma.Error400BadRequest((&common.LocalEnvironmentDeletionError{}).Error())
+ }
+
+ if err := h.environmentService.DeleteEnvironment(ctx, input.ID); err != nil {
+ return nil, huma.Error500InternalServerError((&common.EnvironmentDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteEnvironmentOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Environment deleted successfully",
+ },
+ },
+ }, nil
+}
+
+// TestConnection tests connectivity to an environment.
+func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConnectionInput) (*TestConnectionOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ status, err := h.environmentService.TestConnection(ctx, input.ID, input.Body.ApiUrl)
+ resp := environment.Test{Status: status}
+ if err != nil {
+ msg := err.Error()
+ resp.Message = &msg
+ return &TestConnectionOutput{
+ Body: base.ApiResponse[environment.Test]{
+ Success: false,
+ Data: resp,
+ },
+ }, err
+ }
+
+ return &TestConnectionOutput{
+ Body: base.ApiResponse[environment.Test]{
+ Success: true,
+ Data: resp,
+ },
+ }, nil
+}
+
+// UpdateHeartbeat updates the heartbeat for an environment.
+func (h *EnvironmentHandler) UpdateHeartbeat(ctx context.Context, input *UpdateHeartbeatInput) (*UpdateHeartbeatOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.environmentService.UpdateEnvironmentHeartbeat(ctx, input.ID); err != nil {
+ return nil, huma.Error500InternalServerError((&common.HeartbeatUpdateError{Err: err}).Error())
+ }
+
+ return &UpdateHeartbeatOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Heartbeat updated successfully",
+ },
+ },
+ }, nil
+}
+
+// PairAgent generates or rotates the local agent pairing token.
+func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInput) (*PairAgentOutput, error) {
+ if h.environmentService == nil || h.settingsService == nil || h.cfg == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID != localDockerEnvironmentID {
+ return nil, huma.Error404NotFound("Not found")
+ }
+
+ if h.cfg.AgentToken == "" || (input.Body.Rotate != nil && *input.Body.Rotate) {
+ h.cfg.AgentToken = utils.GenerateRandomString(48)
+ }
+
+ if err := h.settingsService.SetStringSetting(ctx, "agentToken", h.cfg.AgentToken); err != nil {
+ return nil, huma.Error500InternalServerError((&common.AgentTokenPersistenceError{Err: err}).Error())
+ }
+
+ return &PairAgentOutput{
+ Body: base.ApiResponse[environment.AgentPairResponse]{
+ Success: true,
+ Data: environment.AgentPairResponse{
+ Token: h.cfg.AgentToken,
+ },
+ },
+ }, nil
+}
+
+// SyncRegistries syncs container registries to an environment.
+func (h *EnvironmentHandler) SyncRegistries(ctx context.Context, input *SyncRegistriesInput) (*SyncRegistriesOutput, error) {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.environmentService.SyncRegistriesToEnvironment(ctx, input.ID); err != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistrySyncError{Err: err}).Error())
+ }
+
+ return &SyncRegistriesOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Registries synced successfully",
+ },
+ },
+ }, nil
+}
+
+// ============================================================================
+// Helper Methods
+// ============================================================================
+
+func (h *EnvironmentHandler) buildUpdateMap(req *environment.Update, isLocalEnv bool) map[string]any {
+ updates := map[string]any{}
+
+ if !isLocalEnv {
+ if req.ApiUrl != nil {
+ updates["api_url"] = *req.ApiUrl
+ }
+ if req.Enabled != nil {
+ updates["enabled"] = *req.Enabled
+ }
+ }
+
+ if req.Name != nil {
+ updates["name"] = *req.Name
+ }
+
+ return updates
+}
+
+func (h *EnvironmentHandler) handleEnvironmentPairing(ctx context.Context, environmentID string, req *environment.Update, updates map[string]any, isLocalEnv bool) (bool, error) {
+ pairingSucceeded := false
+
+ if isLocalEnv {
+ return pairingSucceeded, nil
+ }
+
+ if req.AccessToken == nil && req.BootstrapToken != nil && *req.BootstrapToken != "" {
+ current, err := h.environmentService.GetEnvironmentByID(ctx, environmentID)
+ if err != nil || current == nil {
+ return false, huma.Error404NotFound("Environment not found")
+ }
+
+ apiUrl := current.ApiUrl
+ if req.ApiUrl != nil && *req.ApiUrl != "" {
+ apiUrl = *req.ApiUrl
+ }
+
+ if _, err := h.environmentService.PairAndPersistAgentToken(ctx, environmentID, apiUrl, *req.BootstrapToken); err != nil {
+ return false, huma.Error502BadGateway("Agent pairing failed: " + err.Error())
+ }
+ pairingSucceeded = true
+ } else if req.AccessToken != nil {
+ updates["access_token"] = *req.AccessToken
+ }
+
+ return pairingSucceeded, nil
+}
+
+func (h *EnvironmentHandler) triggerPostUpdateTasks(environmentID string, updated *models.Environment, pairingSucceeded bool, req *environment.Update) { //nolint:contextcheck // intentionally spawns background tasks
+ if updated.Enabled {
+ go func(envID string, envName string) {
+ ctx := context.Background()
+ status, err := h.environmentService.TestConnection(ctx, envID, nil)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to test connection after environment update",
+ "environment_id", envID, "environment_name", envName, "status", status, "error", err)
+ }
+ }(environmentID, updated.Name)
+ }
+
+ if pairingSucceeded || (req.AccessToken != nil && *req.AccessToken != "") {
+ go func(envID string, envName string) {
+ ctx := context.Background()
+ if err := h.environmentService.SyncRegistriesToEnvironment(ctx, envID); err != nil {
+ slog.WarnContext(ctx, "Failed to sync registries after environment update",
+ "environmentID", envID, "environmentName", envName, "error", err.Error())
+ }
+ }(environmentID, updated.Name)
+ }
+}
diff --git a/backend/internal/huma/handlers/events.go b/backend/internal/huma/handlers/events.go
new file mode 100644
index 000000000..a3dbb7d65
--- /dev/null
+++ b/backend/internal/huma/handlers/events.go
@@ -0,0 +1,234 @@
+package handlers
+
+import (
+ "context"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/event"
+)
+
+// EventHandler handles event management endpoints.
+type EventHandler struct {
+ eventService *services.EventService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+// EventPaginatedResponse is the paginated response for events.
+type EventPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []event.Event `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListEventsInput struct {
+ Page int `query:"pagination[page]" default:"1" doc:"Page number"`
+ Limit int `query:"pagination[limit]" default:"20" doc:"Items per page"`
+ SortCol string `query:"sort[column]" doc:"Column to sort by"`
+ SortDir string `query:"sort[direction]" default:"asc" doc:"Sort direction"`
+}
+
+type ListEventsOutput struct {
+ Body EventPaginatedResponse
+}
+
+type GetEventsByEnvironmentInput struct {
+ EnvironmentID string `path:"environmentId" doc:"Environment ID"`
+ Page int `query:"pagination[page]" default:"1" doc:"Page number"`
+ Limit int `query:"pagination[limit]" default:"20" doc:"Items per page"`
+ SortCol string `query:"sort[column]" doc:"Column to sort by"`
+ SortDir string `query:"sort[direction]" default:"asc" doc:"Sort direction"`
+}
+
+type GetEventsByEnvironmentOutput struct {
+ Body EventPaginatedResponse
+}
+
+type CreateEventInput struct {
+ Body event.CreateEvent
+}
+
+type CreateEventOutput struct {
+ Body base.ApiResponse[event.Event]
+}
+
+type DeleteEventInput struct {
+ EventID string `path:"eventId" doc:"Event ID"`
+}
+
+type DeleteEventOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterEvents registers all event management endpoints.
+func RegisterEvents(api huma.API, eventService *services.EventService) {
+ h := &EventHandler{eventService: eventService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listEvents",
+ Method: "GET",
+ Path: "/events",
+ Summary: "List events",
+ Description: "Get a paginated list of system events",
+ Tags: []string{"Events"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListEvents)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "createEvent",
+ Method: "POST",
+ Path: "/events",
+ Summary: "Create an event",
+ Description: "Create a new system event",
+ Tags: []string{"Events"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateEvent)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteEvent",
+ Method: "DELETE",
+ Path: "/events/{eventId}",
+ Summary: "Delete an event",
+ Description: "Delete a system event by ID",
+ Tags: []string{"Events"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteEvent)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getEventsByEnvironment",
+ Method: "GET",
+ Path: "/events/environment/{environmentId}",
+ Summary: "Get events by environment",
+ Description: "Get a paginated list of events for a specific environment",
+ Tags: []string{"Events"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetEventsByEnvironment)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// ListEvents returns a paginated list of events.
+func (h *EventHandler) ListEvents(ctx context.Context, input *ListEventsInput) (*ListEventsOutput, error) {
+ if h.eventService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Limit, input.SortCol, input.SortDir)
+
+ events, paginationResp, err := h.eventService.ListEventsPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.EventListError{Err: err}).Error())
+ }
+
+ return &ListEventsOutput{
+ Body: EventPaginatedResponse{
+ Success: true,
+ Data: events,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// GetEventsByEnvironment returns events for a specific environment.
+func (h *EventHandler) GetEventsByEnvironment(ctx context.Context, input *GetEventsByEnvironmentInput) (*GetEventsByEnvironmentOutput, error) {
+ if h.eventService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.EnvironmentID == "" {
+ return nil, huma.Error400BadRequest((&common.EnvironmentIDRequiredError{}).Error())
+ }
+
+ params := buildPaginationParams(input.Page, input.Limit, input.SortCol, input.SortDir)
+
+ events, paginationResp, err := h.eventService.GetEventsByEnvironmentPaginated(ctx, input.EnvironmentID, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.EventListError{Err: err}).Error())
+ }
+
+ return &GetEventsByEnvironmentOutput{
+ Body: EventPaginatedResponse{
+ Success: true,
+ Data: events,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// CreateEvent creates a new event.
+func (h *EventHandler) CreateEvent(ctx context.Context, input *CreateEventInput) (*CreateEventOutput, error) {
+ if h.eventService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ evt, err := h.eventService.CreateEventFromDto(ctx, input.Body)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.EventCreationError{Err: err}).Error())
+ }
+
+ return &CreateEventOutput{
+ Body: base.ApiResponse[event.Event]{
+ Success: true,
+ Data: *evt,
+ },
+ }, nil
+}
+
+// DeleteEvent deletes an event.
+func (h *EventHandler) DeleteEvent(ctx context.Context, input *DeleteEventInput) (*DeleteEventOutput, error) {
+ if h.eventService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.EventID == "" {
+ return nil, huma.Error400BadRequest((&common.EventIDRequiredError{}).Error())
+ }
+
+ if err := h.eventService.DeleteEvent(ctx, input.EventID); err != nil {
+ return nil, huma.Error500InternalServerError((&common.EventDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteEventOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Event deleted successfully",
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/health.go b/backend/internal/huma/handlers/health.go
new file mode 100644
index 000000000..8d418db3f
--- /dev/null
+++ b/backend/internal/huma/handlers/health.go
@@ -0,0 +1,43 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "go.getarcane.app/types/system"
+)
+
+// HealthOutput is the response for health check
+type HealthOutput struct {
+ Body system.HealthResponse
+}
+
+// RegisterHealth registers health check routes using Huma.
+func RegisterHealth(api huma.API) {
+ huma.Register(api, huma.Operation{
+ OperationID: "health-check",
+ Method: http.MethodGet,
+ Path: "/health",
+ Summary: "Health check",
+ Description: "Check if the API is healthy",
+ Tags: []string{"Health"},
+ }, func(ctx context.Context, input *struct{}) (*HealthOutput, error) {
+ return &HealthOutput{
+ Body: system.HealthResponse{
+ Status: "UP",
+ },
+ }, nil
+ })
+
+ huma.Register(api, huma.Operation{
+ OperationID: "health-check-head",
+ Method: http.MethodHead,
+ Path: "/health",
+ Summary: "Health check (HEAD)",
+ Description: "Check if the API is healthy (HEAD request)",
+ Tags: []string{"Health"},
+ }, func(ctx context.Context, input *struct{}) (*struct{}, error) {
+ return nil, nil
+ })
+}
diff --git a/backend/internal/huma/handlers/helpers.go b/backend/internal/huma/handlers/helpers.go
new file mode 100644
index 000000000..38b8b46ae
--- /dev/null
+++ b/backend/internal/huma/handlers/helpers.go
@@ -0,0 +1,29 @@
+package handlers
+
+import (
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+)
+
+// buildPaginationParams converts query parameters to pagination.QueryParams.
+func buildPaginationParams(page, limit int, sortCol, sortDir string) pagination.QueryParams {
+ if page < 1 {
+ page = 1
+ }
+ if limit < 1 {
+ limit = 20
+ }
+ // Convert page-based to offset-based
+ start := (page - 1) * limit
+ params := pagination.QueryParams{
+ SortParams: pagination.SortParams{
+ Sort: sortCol,
+ Order: pagination.SortOrder(sortDir),
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: start,
+ Limit: limit,
+ },
+ Filters: make(map[string]string),
+ }
+ return params
+}
diff --git a/backend/internal/huma/handlers/image_updates.go b/backend/internal/huma/handlers/image_updates.go
new file mode 100644
index 000000000..f47faa23b
--- /dev/null
+++ b/backend/internal/huma/handlers/image_updates.go
@@ -0,0 +1,207 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/imageupdate"
+)
+
+type ImageUpdateHandler struct {
+ imageUpdateService *services.ImageUpdateService
+}
+
+type CheckImageUpdateInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageRef string `query:"imageRef" doc:"Image reference"`
+}
+
+type CheckImageUpdateOutput struct {
+ Body base.ApiResponse[imageupdate.Response]
+}
+
+type CheckImageUpdateByIDInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageID string `path:"imageId" doc:"Image ID"`
+}
+
+type CheckImageUpdateByIDOutput struct {
+ Body base.ApiResponse[imageupdate.Response]
+}
+
+type CheckMultipleImagesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body imageupdate.BatchImageUpdateRequest
+}
+
+type CheckMultipleImagesOutput struct {
+ Body base.ApiResponse[imageupdate.BatchResponse]
+}
+
+type CheckAllImagesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body imageupdate.CheckAllImagesRequest
+}
+
+type CheckAllImagesOutput struct {
+ Body base.ApiResponse[imageupdate.BatchResponse]
+}
+
+type GetUpdateSummaryInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetUpdateSummaryOutput struct {
+ Body base.ApiResponse[imageupdate.Summary]
+}
+
+// RegisterImageUpdates registers image update endpoints.
+func RegisterImageUpdates(api huma.API, imageUpdateSvc *services.ImageUpdateService) {
+ h := &ImageUpdateHandler{imageUpdateService: imageUpdateSvc}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "check-image-update",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/image-updates/check",
+ Summary: "Check image update by reference",
+ Tags: []string{"Image Updates"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CheckImageUpdate)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "check-image-update-by-id",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/image-updates/check/{imageId}",
+ Summary: "Check image update by ID",
+ Tags: []string{"Image Updates"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CheckImageUpdateByID)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "check-image-update-by-id-post",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/image-updates/check/{imageId}",
+ Summary: "Check image update by ID (POST)",
+ Tags: []string{"Image Updates"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CheckImageUpdateByID)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "check-multiple-images",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/image-updates/check-batch",
+ Summary: "Check multiple images",
+ Tags: []string{"Image Updates"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CheckMultipleImages)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "check-all-images",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/image-updates/check-all",
+ Summary: "Check all images",
+ Tags: []string{"Image Updates"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CheckAllImages)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-update-summary",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/image-updates/summary",
+ Summary: "Get update summary",
+ Tags: []string{"Image Updates"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetUpdateSummary)
+}
+
+func (h *ImageUpdateHandler) CheckImageUpdate(ctx context.Context, input *CheckImageUpdateInput) (*CheckImageUpdateOutput, error) {
+ if input.ImageRef == "" {
+ return nil, huma.Error400BadRequest((&common.ImageRefRequiredError{}).Error())
+ }
+
+ result, err := h.imageUpdateService.CheckImageUpdate(ctx, input.ImageRef)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ImageUpdateCheckError{Err: err}).Error())
+ }
+
+ return &CheckImageUpdateOutput{
+ Body: base.ApiResponse[imageupdate.Response]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+func (h *ImageUpdateHandler) CheckImageUpdateByID(ctx context.Context, input *CheckImageUpdateByIDInput) (*CheckImageUpdateByIDOutput, error) {
+ if input.ImageID == "" {
+ return nil, huma.Error400BadRequest((&common.ImageIDRequiredError{}).Error())
+ }
+
+ result, err := h.imageUpdateService.CheckImageUpdateByID(ctx, input.ImageID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ImageUpdateCheckError{Err: err}).Error())
+ }
+
+ return &CheckImageUpdateByIDOutput{
+ Body: base.ApiResponse[imageupdate.Response]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+func (h *ImageUpdateHandler) CheckMultipleImages(ctx context.Context, input *CheckMultipleImagesInput) (*CheckMultipleImagesOutput, error) {
+ // Empty batch is valid - return empty results
+ if len(input.Body.ImageRefs) == 0 {
+ return &CheckMultipleImagesOutput{
+ Body: base.ApiResponse[imageupdate.BatchResponse]{
+ Success: true,
+ Data: imageupdate.BatchResponse{},
+ },
+ }, nil
+ }
+
+ results, err := h.imageUpdateService.CheckMultipleImages(ctx, input.Body.ImageRefs, input.Body.Credentials)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.BatchImageUpdateCheckError{Err: err}).Error())
+ }
+
+ return &CheckMultipleImagesOutput{
+ Body: base.ApiResponse[imageupdate.BatchResponse]{
+ Success: true,
+ Data: imageupdate.BatchResponse(results),
+ },
+ }, nil
+}
+
+func (h *ImageUpdateHandler) CheckAllImages(ctx context.Context, input *CheckAllImagesInput) (*CheckAllImagesOutput, error) {
+ results, err := h.imageUpdateService.CheckAllImages(ctx, 0, input.Body.Credentials)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.AllImageUpdateCheckError{Err: err}).Error())
+ }
+
+ return &CheckAllImagesOutput{
+ Body: base.ApiResponse[imageupdate.BatchResponse]{
+ Success: true,
+ Data: imageupdate.BatchResponse(results),
+ },
+ }, nil
+}
+
+func (h *ImageUpdateHandler) GetUpdateSummary(ctx context.Context, input *GetUpdateSummaryInput) (*GetUpdateSummaryOutput, error) {
+ summary, err := h.imageUpdateService.GetUpdateSummary(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UpdateSummaryError{Err: err}).Error())
+ }
+
+ return &GetUpdateSummaryOutput{
+ Body: base.ApiResponse[imageupdate.Summary]{
+ Success: true,
+ Data: *summary,
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/images.go b/backend/internal/huma/handlers/images.go
new file mode 100644
index 000000000..de7dcc5f4
--- /dev/null
+++ b/backend/internal/huma/handlers/images.go
@@ -0,0 +1,500 @@
+package handlers
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "mime/multipart"
+ "net/http"
+ "strings"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/image"
+)
+
+// ImageHandler provides Huma-based image management endpoints.
+type ImageHandler struct {
+ dockerService *services.DockerClientService
+ imageService *services.ImageService
+ imageUpdateService *services.ImageUpdateService
+ settingsService *services.SettingsService
+}
+
+// --- Huma Input/Output Wrappers ---
+
+// ImagePaginatedResponse is the paginated response for images.
+type ImagePaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []image.Summary `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListImagesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`
+ Start int `query:"start" default:"0" doc:"Start index for pagination"`
+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`
+ InUse string `query:"inUse" doc:"Filter by in-use status (true/false)"`
+ Updates string `query:"updates" doc:"Filter by update availability (true/false)"`
+}
+
+type ListImagesOutput struct {
+ Body ImagePaginatedResponse
+}
+
+type GetImageInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageID string `path:"imageId" doc:"Image ID"`
+}
+
+type GetImageOutput struct {
+ Body base.ApiResponse[image.DetailSummary]
+}
+
+type RemoveImageInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ImageID string `path:"imageId" doc:"Image ID"`
+ Force bool `query:"force" doc:"Force removal"`
+}
+
+type RemoveImageOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type PullImageInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body image.PullOptions
+}
+
+type PruneImagesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Dangling bool `query:"dangling" doc:"Only remove dangling images"`
+ Body *struct {
+ Dangling *bool `json:"dangling,omitempty"`
+ Filters map[string][]string `json:"filters,omitempty"`
+ }
+}
+
+type PruneImagesOutput struct {
+ Body base.ApiResponse[image.PruneReport]
+}
+
+type GetImageUsageCountsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type ImageUsageCountsResponse struct {
+ Success bool `json:"success"`
+ Data image.UsageCounts `json:"data"`
+}
+
+type GetImageUsageCountsOutput struct {
+ Body ImageUsageCountsResponse
+}
+
+type UploadImageInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ RawBody multipart.Form `contentType:"multipart/form-data"`
+}
+
+type UploadImageOutput struct {
+ Body base.ApiResponse[image.LoadResult]
+}
+
+// RegisterImages registers image management routes using Huma.
+func RegisterImages(api huma.API, dockerService *services.DockerClientService, imageService *services.ImageService, imageUpdateService *services.ImageUpdateService, settingsService *services.SettingsService) {
+ h := &ImageHandler{
+ dockerService: dockerService,
+ imageService: imageService,
+ imageUpdateService: imageUpdateService,
+ settingsService: settingsService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-images",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/images",
+ Summary: "List images",
+ Description: "Get a paginated list of Docker images",
+ Tags: []string{"Images"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListImages)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-image-usage-counts",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/images/counts",
+ Summary: "Get image usage counts",
+ Description: "Get counts of images in use, unused, total, and total size",
+ Tags: []string{"Images"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetImageUsageCounts)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-image",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/images/{imageId}",
+ Summary: "Get image by ID",
+ Description: "Get a Docker image by its ID",
+ Tags: []string{"Images"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetImage)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "remove-image",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/images/{imageId}",
+ Summary: "Remove an image",
+ Description: "Remove a Docker image by ID",
+ Tags: []string{"Images"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.RemoveImage)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "pull-image",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/images/pull",
+ Summary: "Pull an image",
+ Description: "Pull a Docker image from a registry with streaming progress output",
+ Tags: []string{"Images"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.PullImage)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "prune-images",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/images/prune",
+ Summary: "Prune unused images",
+ Description: "Remove unused Docker images",
+ Tags: []string{"Images"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.PruneImages)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "upload-image",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/images/upload",
+ Summary: "Upload an image",
+ Description: "Upload a Docker image from a tar archive",
+ Tags: []string{"Images"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ RequestBody: &huma.RequestBody{
+ Content: map[string]*huma.MediaType{
+ "multipart/form-data": {
+ Schema: &huma.Schema{
+ Type: "object",
+ Properties: map[string]*huma.Schema{
+ "file": {
+ Type: "string",
+ Format: "binary",
+ Description: "Docker image tar archive",
+ },
+ },
+ Required: []string{"file"},
+ },
+ },
+ },
+ },
+ }, h.UploadImage)
+}
+
+// ListImages returns a paginated list of images.
+func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (*ListImagesOutput, error) {
+ if h.imageService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ filters := make(map[string]string)
+ if input.InUse != "" {
+ filters["inUse"] = input.InUse
+ }
+ if input.Updates != "" {
+ filters["updates"] = input.Updates
+ }
+
+ params := pagination.QueryParams{
+ SearchQuery: pagination.SearchQuery{
+ Search: input.Search,
+ },
+ SortParams: pagination.SortParams{
+ Sort: input.Sort,
+ Order: pagination.SortOrder(input.Order),
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: input.Start,
+ Limit: input.Limit,
+ },
+ Filters: filters,
+ }
+
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+
+ images, paginationResp, err := h.imageService.ListImagesPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ImageListError{Err: err}).Error())
+ }
+
+ if images == nil {
+ images = []image.Summary{}
+ }
+
+ return &ListImagesOutput{
+ Body: ImagePaginatedResponse{
+ Success: true,
+ Data: images,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// GetImage returns an image by ID.
+func (h *ImageHandler) GetImage(ctx context.Context, input *GetImageInput) (*GetImageOutput, error) {
+ if h.imageService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ img, err := h.imageService.GetImageByID(ctx, input.ImageID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.ImageNotFoundError{Err: err}).Error())
+ }
+
+ out := image.NewDetailSummary(img)
+
+ return &GetImageOutput{
+ Body: base.ApiResponse[image.DetailSummary]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// RemoveImage removes a Docker image.
+func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput) (*RemoveImageOutput, error) {
+ if h.imageService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ if err := h.imageService.RemoveImage(ctx, input.ImageID, input.Force, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.ImageRemovalError{Err: err}).Error())
+ }
+
+ return &RemoveImageOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Image removed successfully",
+ },
+ },
+ }, nil
+}
+
+// PullImage pulls a Docker image with streaming progress.
+func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*huma.StreamResponse, error) {
+ if h.imageService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.Body.ImageName == "" {
+ return nil, huma.Error400BadRequest("image name is required")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ // Get full image name with tag and credentials
+ fullImageName := input.Body.GetFullImageName()
+ credentials := input.Body.GetCredentials()
+
+ return &huma.StreamResponse{
+ Body: func(humaCtx huma.Context) { //nolint:contextcheck // context is obtained from humaCtx.Context()
+ humaCtx.SetHeader("Content-Type", "application/x-json-stream")
+ humaCtx.SetHeader("Cache-Control", "no-cache")
+ humaCtx.SetHeader("Connection", "keep-alive")
+ humaCtx.SetHeader("X-Accel-Buffering", "no")
+
+ writer := humaCtx.BodyWriter()
+
+ if err := h.imageService.PullImage(humaCtx.Context(), fullImageName, writer, *user, credentials); err != nil {
+ _, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())
+ return
+ }
+ },
+ }, nil
+}
+
+// PruneImages removes unused Docker images.
+func (h *ImageHandler) PruneImages(ctx context.Context, input *PruneImagesInput) (*PruneImagesOutput, error) {
+ if h.imageService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ dangling := input.Dangling
+ if input.Body != nil {
+ if input.Body.Dangling != nil {
+ dangling = *input.Body.Dangling
+ } else if vals, ok := input.Body.Filters["dangling"]; ok {
+ for _, v := range vals {
+ if v == "true" || v == "1" {
+ dangling = true
+ break
+ }
+ }
+ }
+ }
+
+ report, err := h.imageService.PruneImages(ctx, dangling)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ImagePruneError{Err: err}).Error())
+ }
+
+ out := image.NewPruneReport(*report)
+
+ return &PruneImagesOutput{
+ Body: base.ApiResponse[image.PruneReport]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetImageUsageCounts returns counts of images by usage status.
+func (h *ImageHandler) GetImageUsageCounts(ctx context.Context, input *GetImageUsageCountsInput) (*GetImageUsageCountsOutput, error) {
+ if h.dockerService == nil || h.imageService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ var (
+ inuse, unused, total int
+ totalSize int64
+ errs []error
+ )
+
+ _, iu, un, tot, err := h.dockerService.GetAllImages(ctx)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("get images: %w", err))
+ } else {
+ inuse, unused, total = iu, un, tot
+ }
+
+ sz, err := h.imageService.GetTotalImageSize(ctx)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("get total image size: %w", err))
+ } else {
+ totalSize = sz
+ }
+
+ if len(errs) > 0 {
+ return nil, huma.Error500InternalServerError((&common.ImageUsageCountsError{Err: errors.Join(errs...)}).Error())
+ }
+
+ return &GetImageUsageCountsOutput{
+ Body: ImageUsageCountsResponse{
+ Success: true,
+ Data: image.UsageCounts{
+ Inuse: inuse,
+ Unused: unused,
+ Total: total,
+ TotalSize: totalSize,
+ },
+ },
+ }, nil
+}
+
+// UploadImage uploads a Docker image from a tar archive.
+func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput) (*UploadImageOutput, error) {
+ if h.imageService == nil || h.settingsService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ // Get file from multipart form
+ files := input.RawBody.File["file"]
+ if len(files) == 0 {
+ return nil, huma.Error400BadRequest((&common.NoFileUploadedError{}).Error())
+ }
+
+ fileHeader := files[0]
+ fileName := fileHeader.Filename
+
+ // Validate file extension
+ lowerName := strings.ToLower(fileName)
+ if !strings.HasSuffix(lowerName, ".tar") && !strings.HasSuffix(lowerName, ".tar.gz") && !strings.HasSuffix(lowerName, ".tgz") && !strings.HasSuffix(lowerName, ".tar.xz") {
+ return nil, huma.Error400BadRequest((&common.InvalidFileFormatError{}).Error())
+ }
+
+ // Get max upload size from settings
+ maxSizeMB := h.settingsService.GetIntSetting(ctx, "maxImageUploadSize", 500)
+ maxSizeBytes := int64(maxSizeMB) * 1024 * 1024
+
+ // Check file size
+ if fileHeader.Size > maxSizeBytes {
+ return nil, huma.NewError(http.StatusRequestEntityTooLarge, fmt.Sprintf("file size exceeds maximum allowed size of %d MB", maxSizeMB))
+ }
+
+ // Open the file
+ file, err := fileHeader.Open()
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.FileUploadReadError{Err: err}).Error())
+ }
+ defer file.Close()
+
+ // Load the image
+ result, err := h.imageService.LoadImageFromReader(ctx, file, fileName, *user, maxSizeBytes)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ImageLoadError{Err: err}).Error())
+ }
+
+ return &UploadImageOutput{
+ Body: base.ApiResponse[image.LoadResult]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/networks.go b/backend/internal/huma/handlers/networks.go
new file mode 100644
index 000000000..efae2a3a4
--- /dev/null
+++ b/backend/internal/huma/handlers/networks.go
@@ -0,0 +1,314 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ dockernetwork "github.com/docker/docker/api/types/network"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "go.getarcane.app/types/base"
+ networktypes "go.getarcane.app/types/network"
+)
+
+type NetworkHandler struct {
+ networkService *services.NetworkService
+ dockerService *services.DockerClientService
+}
+
+type NetworkPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []networktypes.Summary `json:"data"`
+ Counts networktypes.UsageCounts `json:"counts"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListNetworksInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Page int `query:"pagination[page]" default:"1"`
+ Limit int `query:"pagination[limit]" default:"20"`
+ SortCol string `query:"sort[column]"`
+ SortDir string `query:"sort[direction]" default:"asc"`
+ InUse string `query:"inUse" doc:"Filter by in-use status (true/false)"`
+}
+
+type ListNetworksOutput struct {
+ Body NetworkPaginatedResponse
+}
+
+type GetNetworkCountsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type NetworkCountsApiResponse struct {
+ Success bool `json:"success"`
+ Data networktypes.UsageCounts `json:"data"`
+}
+
+type GetNetworkCountsOutput struct {
+ Body NetworkCountsApiResponse
+}
+
+type NetworkCreatedApiResponse struct {
+ Success bool `json:"success"`
+ Data networktypes.CreateResponse `json:"data"`
+}
+
+type CreateNetworkInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body networktypes.CreateRequest
+}
+
+type CreateNetworkOutput struct {
+ Body NetworkCreatedApiResponse
+}
+
+// NetworkInspectApiResponse is a dedicated response type
+type NetworkInspectApiResponse struct {
+ Success bool `json:"success"`
+ Data networktypes.Inspect `json:"data"`
+}
+
+type GetNetworkInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ NetworkID string `path:"networkId" doc:"Network ID"`
+}
+
+type GetNetworkOutput struct {
+ Body NetworkInspectApiResponse
+}
+
+// NetworkMessageApiResponse is a dedicated response type
+type NetworkMessageApiResponse struct {
+ Success bool `json:"success"`
+ Data base.MessageResponse `json:"data"`
+}
+
+type DeleteNetworkInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ NetworkID string `path:"networkId" doc:"Network ID"`
+}
+
+type DeleteNetworkOutput struct {
+ Body NetworkMessageApiResponse
+}
+
+type PruneNetworksInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+// NetworkPruneResponse is a dedicated response type
+type NetworkPruneResponse struct {
+ Success bool `json:"success"`
+ Data networktypes.PruneReport `json:"data"`
+}
+
+type PruneNetworksOutput struct {
+ Body NetworkPruneResponse
+}
+
+// RegisterNetworks registers network endpoints.
+func RegisterNetworks(api huma.API, networkSvc *services.NetworkService, dockerSvc *services.DockerClientService) {
+ h := &NetworkHandler{
+ networkService: networkSvc,
+ dockerService: dockerSvc,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-networks",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/networks",
+ Summary: "List networks",
+ Tags: []string{"Networks"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.ListNetworks)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "network-counts",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/networks/counts",
+ Summary: "Network counts",
+ Tags: []string{"Networks"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetNetworkCounts)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-network",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/networks",
+ Summary: "Create network",
+ Tags: []string{"Networks"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CreateNetwork)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-network",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/networks/{networkId}",
+ Summary: "Get network",
+ Tags: []string{"Networks"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetNetwork)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-network",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/networks/{networkId}",
+ Summary: "Delete network",
+ Tags: []string{"Networks"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.DeleteNetwork)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "prune-networks",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/networks/prune",
+ Summary: "Prune networks",
+ Tags: []string{"Networks"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.PruneNetworks)
+}
+
+func (h *NetworkHandler) ListNetworks(ctx context.Context, input *ListNetworksInput) (*ListNetworksOutput, error) {
+ filters := make(map[string]string)
+ if input.InUse != "" {
+ filters["inUse"] = input.InUse
+ }
+
+ params := pagination.QueryParams{
+ SortParams: pagination.SortParams{
+ Sort: input.SortCol,
+ Order: pagination.SortOrder(input.SortDir),
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: (input.Page - 1) * input.Limit,
+ Limit: input.Limit,
+ },
+ Filters: filters,
+ }
+
+ networks, paginationResp, counts, err := h.networkService.ListNetworksPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkListError{Err: err}).Error())
+ }
+
+ return &ListNetworksOutput{
+ Body: NetworkPaginatedResponse{
+ Success: true,
+ Data: networks,
+ Counts: counts,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+func (h *NetworkHandler) GetNetworkCounts(ctx context.Context, input *GetNetworkCountsInput) (*GetNetworkCountsOutput, error) {
+ _, inuse, unused, total, err := h.dockerService.GetAllNetworks(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkUsageCountsError{Err: err}).Error())
+ }
+
+ return &GetNetworkCountsOutput{
+ Body: NetworkCountsApiResponse{
+ Success: true,
+ Data: networktypes.UsageCounts{
+ Inuse: inuse,
+ Unused: unused,
+ Total: total,
+ },
+ },
+ }, nil
+}
+
+func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkInput) (*CreateNetworkOutput, error) {
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("not authenticated")
+ }
+
+ // Convert to Docker SDK options
+ dockerOptions := input.Body.Options.ToDockerCreateOptions()
+
+ response, err := h.networkService.CreateNetwork(ctx, input.Body.Name, dockerOptions, *user)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkCreationError{Err: err}).Error())
+ }
+
+ out, err := mapper.MapOne[dockernetwork.CreateResponse, networktypes.CreateResponse](*response)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkMappingError{Err: err}).Error())
+ }
+
+ return &CreateNetworkOutput{
+ Body: NetworkCreatedApiResponse{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput) (*GetNetworkOutput, error) {
+ networkInspect, err := h.networkService.GetNetworkByID(ctx, input.NetworkID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.NetworkNotFoundError{Err: err}).Error())
+ }
+
+ out, err := mapper.MapOne[dockernetwork.Inspect, networktypes.Inspect](*networkInspect)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkMappingError{Err: err}).Error())
+ }
+
+ return &GetNetworkOutput{
+ Body: NetworkInspectApiResponse{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkInput) (*DeleteNetworkOutput, error) {
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized("not authenticated")
+ }
+
+ if err := h.networkService.RemoveNetwork(ctx, input.NetworkID, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkRemovalError{Err: err}).Error())
+ }
+
+ return &DeleteNetworkOutput{
+ Body: NetworkMessageApiResponse{
+ Success: true,
+ Data: base.MessageResponse{Message: "Network removed successfully"},
+ },
+ }, nil
+}
+
+func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksInput) (*PruneNetworksOutput, error) {
+ report, err := h.networkService.PruneNetworks(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkPruneError{Err: err}).Error())
+ }
+
+ out, err := mapper.MapOne[dockernetwork.PruneReport, networktypes.PruneReport](*report)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NetworkMappingError{Err: err}).Error())
+ }
+
+ return &PruneNetworksOutput{
+ Body: NetworkPruneResponse{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/notifications.go b/backend/internal/huma/handlers/notifications.go
new file mode 100644
index 000000000..b1ed25ba8
--- /dev/null
+++ b/backend/internal/huma/handlers/notifications.go
@@ -0,0 +1,318 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/notification"
+)
+
+type NotificationHandler struct {
+ notificationService *services.NotificationService
+ appriseService *services.AppriseService
+}
+
+type GetAllNotificationSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetAllNotificationSettingsOutput struct {
+ Body []notification.Response
+}
+
+type GetNotificationSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Provider string `path:"provider" doc:"Provider"`
+}
+
+type GetNotificationSettingsOutput struct {
+ Body notification.Response
+}
+
+type CreateOrUpdateNotificationSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body notification.Update
+}
+
+type CreateOrUpdateNotificationSettingsOutput struct {
+ Body notification.Response
+}
+
+type DeleteNotificationSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Provider string `path:"provider" doc:"Provider"`
+}
+
+type DeleteNotificationSettingsOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type TestNotificationInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Provider string `path:"provider" doc:"Provider"`
+ Type string `query:"type" default:"simple"`
+}
+
+type TestNotificationOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type GetAppriseSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetAppriseSettingsOutput struct {
+ Body notification.AppriseResponse
+}
+
+type CreateOrUpdateAppriseSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body notification.AppriseUpdate
+}
+
+type CreateOrUpdateAppriseSettingsOutput struct {
+ Body notification.AppriseResponse
+}
+
+type TestAppriseNotificationInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type TestAppriseNotificationOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// RegisterNotifications registers notification endpoints.
+func RegisterNotifications(api huma.API, notificationSvc *services.NotificationService, appriseSvc *services.AppriseService) {
+ h := &NotificationHandler{
+ notificationService: notificationSvc,
+ appriseService: appriseSvc,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-all-notification-settings",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/notifications/settings",
+ Summary: "Get all notification settings",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetAllNotificationSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-notification-settings",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/notifications/settings/{provider}",
+ Summary: "Get notification settings by provider",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetNotificationSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-or-update-notification-settings",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/notifications/settings",
+ Summary: "Create or update notification settings",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CreateOrUpdateNotificationSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-notification-settings",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/notifications/settings/{provider}",
+ Summary: "Delete notification settings",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.DeleteNotificationSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "test-notification",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/notifications/test/{provider}",
+ Summary: "Test notification",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.TestNotification)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-apprise-settings",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/notifications/apprise",
+ Summary: "Get Apprise settings",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.GetAppriseSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-or-update-apprise-settings",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/notifications/apprise",
+ Summary: "Create or update Apprise settings",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.CreateOrUpdateAppriseSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "test-apprise-notification",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/notifications/apprise/test",
+ Summary: "Test Apprise notification",
+ Tags: []string{"Notifications"},
+ Security: []map[string][]string{{"BearerAuth": {}}, {"ApiKeyAuth": {}}},
+ }, h.TestAppriseNotification)
+}
+
+func (h *NotificationHandler) GetAllNotificationSettings(ctx context.Context, input *GetAllNotificationSettingsInput) (*GetAllNotificationSettingsOutput, error) {
+ settings, err := h.notificationService.GetAllSettings(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NotificationSettingsListError{Err: err}).Error())
+ }
+
+ responses := make([]notification.Response, len(settings))
+ for i, setting := range settings {
+ responses[i] = notification.Response{
+ ID: setting.ID,
+ Provider: notification.Provider(setting.Provider),
+ Enabled: setting.Enabled,
+ Config: base.JsonObject(setting.Config),
+ }
+ }
+
+ return &GetAllNotificationSettingsOutput{Body: responses}, nil
+}
+
+func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, input *GetNotificationSettingsInput) (*GetNotificationSettingsOutput, error) {
+ provider := models.NotificationProvider(input.Provider)
+
+ settings, err := h.notificationService.GetSettingsByProvider(ctx, provider)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.NotificationSettingsNotFoundError{}).Error())
+ }
+
+ response := notification.Response{
+ ID: settings.ID,
+ Provider: notification.Provider(settings.Provider),
+ Enabled: settings.Enabled,
+ Config: base.JsonObject(settings.Config),
+ }
+
+ return &GetNotificationSettingsOutput{Body: response}, nil
+}
+
+func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Context, input *CreateOrUpdateNotificationSettingsInput) (*CreateOrUpdateNotificationSettingsOutput, error) {
+ provider := models.NotificationProvider(input.Body.Provider)
+ if provider != models.NotificationProviderDiscord && provider != models.NotificationProviderEmail {
+ return nil, huma.Error400BadRequest((&common.InvalidNotificationProviderError{}).Error())
+ }
+
+ settings, err := h.notificationService.CreateOrUpdateSettings(
+ ctx,
+ provider,
+ input.Body.Enabled,
+ models.JSON(input.Body.Config),
+ )
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.NotificationSettingsUpdateError{Err: err}).Error())
+ }
+
+ response := notification.Response{
+ ID: settings.ID,
+ Provider: notification.Provider(settings.Provider),
+ Enabled: settings.Enabled,
+ Config: base.JsonObject(settings.Config),
+ }
+
+ return &CreateOrUpdateNotificationSettingsOutput{Body: response}, nil
+}
+
+func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, input *DeleteNotificationSettingsInput) (*DeleteNotificationSettingsOutput, error) {
+ provider := models.NotificationProvider(input.Provider)
+
+ if err := h.notificationService.DeleteSettings(ctx, provider); err != nil {
+ return nil, huma.Error500InternalServerError((&common.NotificationSettingsDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteNotificationSettingsOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{Message: "Settings deleted successfully"},
+ },
+ }, nil
+}
+
+func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestNotificationInput) (*TestNotificationOutput, error) {
+ provider := models.NotificationProvider(input.Provider)
+
+ if err := h.notificationService.TestNotification(ctx, provider, input.Type); err != nil {
+ return nil, huma.Error500InternalServerError((&common.NotificationTestError{Err: err}).Error())
+ }
+
+ return &TestNotificationOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{Message: "Test notification sent successfully"},
+ },
+ }, nil
+}
+
+func (h *NotificationHandler) GetAppriseSettings(ctx context.Context, input *GetAppriseSettingsInput) (*GetAppriseSettingsOutput, error) {
+ settings, err := h.appriseService.GetSettings(ctx)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.AppriseSettingsNotFoundError{}).Error())
+ }
+
+ response := notification.AppriseResponse{
+ ID: settings.ID,
+ APIURL: settings.APIURL,
+ Enabled: settings.Enabled,
+ ImageUpdateTag: settings.ImageUpdateTag,
+ ContainerUpdateTag: settings.ContainerUpdateTag,
+ }
+
+ return &GetAppriseSettingsOutput{Body: response}, nil
+}
+
+func (h *NotificationHandler) CreateOrUpdateAppriseSettings(ctx context.Context, input *CreateOrUpdateAppriseSettingsInput) (*CreateOrUpdateAppriseSettingsOutput, error) {
+ if input.Body.Enabled && input.Body.APIURL == "" {
+ return nil, huma.Error400BadRequest("API URL is required when Apprise is enabled")
+ }
+
+ settings, err := h.appriseService.CreateOrUpdateSettings(
+ ctx,
+ input.Body.APIURL,
+ input.Body.Enabled,
+ input.Body.ImageUpdateTag,
+ input.Body.ContainerUpdateTag,
+ )
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.AppriseSettingsUpdateError{Err: err}).Error())
+ }
+
+ response := notification.AppriseResponse{
+ ID: settings.ID,
+ APIURL: settings.APIURL,
+ Enabled: settings.Enabled,
+ ImageUpdateTag: settings.ImageUpdateTag,
+ ContainerUpdateTag: settings.ContainerUpdateTag,
+ }
+
+ return &CreateOrUpdateAppriseSettingsOutput{Body: response}, nil
+}
+
+func (h *NotificationHandler) TestAppriseNotification(ctx context.Context, input *TestAppriseNotificationInput) (*TestAppriseNotificationOutput, error) {
+ if err := h.appriseService.TestNotification(ctx); err != nil {
+ return nil, huma.Error500InternalServerError((&common.AppriseTestError{Err: err}).Error())
+ }
+
+ return &TestAppriseNotificationOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{Message: "Test notification sent successfully"},
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/oidc.go b/backend/internal/huma/handlers/oidc.go
new file mode 100644
index 000000000..8121bb854
--- /dev/null
+++ b/backend/internal/huma/handlers/oidc.go
@@ -0,0 +1,227 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/cookie"
+ "go.getarcane.app/types/auth"
+ "go.getarcane.app/types/user"
+)
+
+// OidcHandler handles OIDC authentication endpoints.
+type OidcHandler struct {
+ authService *services.AuthService
+ oidcService *services.OidcService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+type GetOidcStatusInput struct{}
+
+type GetOidcStatusOutput struct {
+ Body auth.OidcStatusInfo
+}
+
+type GetOidcAuthUrlInput struct {
+ Body auth.OidcAuthUrlRequest
+}
+
+type GetOidcAuthUrlOutput struct {
+ SetCookie string `header:"Set-Cookie" doc:"OIDC state cookie"`
+ Body auth.OidcAuthUrlResponse
+}
+
+type HandleOidcCallbackInput struct {
+ OidcStateCookie string `cookie:"oidc_state" doc:"OIDC state cookie from auth URL request"`
+ Body auth.OidcCallbackRequest
+}
+
+type HandleOidcCallbackOutput struct {
+ SetCookie []string `header:"Set-Cookie" doc:"Session and clear state cookies"`
+ Body auth.OidcCallbackResponse
+}
+
+type GetOidcConfigInput struct{}
+
+type GetOidcConfigOutput struct {
+ Body auth.OidcConfigResponse
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterOidc registers all OIDC authentication endpoints using Huma.
+func RegisterOidc(api huma.API, authService *services.AuthService, oidcService *services.OidcService) {
+ h := &OidcHandler{authService: authService, oidcService: oidcService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-oidc-status",
+ Method: http.MethodGet,
+ Path: "/oidc/status",
+ Summary: "Get OIDC status",
+ Description: "Get the current OIDC configuration status",
+ Tags: []string{"OIDC"},
+ }, h.GetOidcStatus)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-oidc-config",
+ Method: http.MethodGet,
+ Path: "/oidc/config",
+ Summary: "Get OIDC config",
+ Description: "Get the OIDC client configuration",
+ Tags: []string{"OIDC"},
+ }, h.GetOidcConfig)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-oidc-auth-url",
+ Method: http.MethodPost,
+ Path: "/oidc/url",
+ Summary: "Get OIDC auth URL",
+ Description: "Generate an OIDC authorization URL for login",
+ Tags: []string{"OIDC"},
+ }, h.GetOidcAuthUrl)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "handle-oidc-callback",
+ Method: http.MethodPost,
+ Path: "/oidc/callback",
+ Summary: "Handle OIDC callback",
+ Description: "Process the OIDC callback and complete authentication",
+ Tags: []string{"OIDC"},
+ }, h.HandleOidcCallback)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// GetOidcStatus returns the OIDC configuration status.
+func (h *OidcHandler) GetOidcStatus(ctx context.Context, _ *GetOidcStatusInput) (*GetOidcStatusOutput, error) {
+ if h.authService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ status, err := h.authService.GetOidcConfigurationStatus(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.OidcStatusError{Err: err}).Error())
+ }
+
+ return &GetOidcStatusOutput{
+ Body: *status,
+ }, nil
+}
+
+// GetOidcConfig returns the OIDC client configuration.
+func (h *OidcHandler) GetOidcConfig(ctx context.Context, _ *GetOidcConfigInput) (*GetOidcConfigOutput, error) {
+ if h.authService == nil || h.oidcService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ config, err := h.authService.GetOidcConfig(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.OidcConfigError{}).Error())
+ }
+
+ return &GetOidcConfigOutput{
+ Body: auth.OidcConfigResponse{
+ ClientID: config.ClientID,
+ RedirectUri: h.oidcService.GetOidcRedirectURL(),
+ IssuerUrl: config.IssuerURL,
+ AuthorizationEndpoint: config.AuthorizationEndpoint,
+ TokenEndpoint: config.TokenEndpoint,
+ UserinfoEndpoint: config.UserinfoEndpoint,
+ Scopes: config.Scopes,
+ },
+ }, nil
+}
+
+// GetOidcAuthUrl generates an OIDC authorization URL and sets the state cookie.
+func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlInput) (*GetOidcAuthUrlOutput, error) {
+ if h.authService == nil || h.oidcService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ enabled, err := h.authService.IsOidcEnabled(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.OidcStatusCheckError{}).Error())
+ }
+ if !enabled {
+ return nil, huma.Error400BadRequest((&common.OidcDisabledError{}).Error())
+ }
+
+ authUrl, stateCookieValue, err := h.oidcService.GenerateAuthURL(ctx, input.Body.RedirectUri)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.OidcAuthUrlGenerationError{Err: err}).Error())
+ }
+
+ // Build state cookie (600 seconds = 10 minutes)
+ stateCookie := cookie.BuildOidcStateCookieString(stateCookieValue, 600, false)
+
+ return &GetOidcAuthUrlOutput{
+ SetCookie: stateCookie,
+ Body: auth.OidcAuthUrlResponse{
+ AuthUrl: authUrl,
+ },
+ }, nil
+}
+
+// HandleOidcCallback processes the OIDC callback and completes authentication.
+func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCallbackInput) (*HandleOidcCallbackOutput, error) {
+ if h.authService == nil || h.oidcService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ // Validate state cookie
+ if input.OidcStateCookie == "" {
+ return nil, huma.Error400BadRequest((&common.OidcStateCookieError{}).Error())
+ }
+
+ // Process OIDC callback
+ userInfo, tokenResp, err := h.oidcService.HandleCallback(ctx, input.Body.Code, input.Body.State, input.OidcStateCookie)
+ if err != nil {
+ return nil, huma.Error400BadRequest((&common.OidcCallbackError{Err: err}).Error())
+ }
+
+ // Complete login
+ userModel, tokenPair, err := h.authService.OidcLogin(ctx, *userInfo, tokenResp)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())
+ }
+
+ // Calculate cookie max age
+ maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
+ if maxAge < 0 {
+ maxAge = 0
+ }
+ maxAge += 60 // Add 60 seconds buffer for clock skew
+
+ // Build cookies: session token + clear state cookie
+ tokenCookie := cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken)
+ clearStateCookie := cookie.BuildClearOidcStateCookieString(false)
+
+ return &HandleOidcCallbackOutput{
+ SetCookie: []string{tokenCookie, clearStateCookie},
+ Body: auth.OidcCallbackResponse{
+ Success: true,
+ Token: tokenPair.AccessToken,
+ RefreshToken: tokenPair.RefreshToken,
+ ExpiresAt: tokenPair.ExpiresAt,
+ User: user.User{
+ ID: userModel.ID,
+ Username: userModel.Username,
+ DisplayName: userModel.DisplayName,
+ Email: userModel.Email,
+ Roles: userModel.Roles,
+ OidcSubjectId: userModel.OidcSubjectId,
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/projects.go b/backend/internal/huma/handlers/projects.go
new file mode 100644
index 000000000..b63ba3dfd
--- /dev/null
+++ b/backend/internal/huma/handlers/projects.go
@@ -0,0 +1,678 @@
+package handlers
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/project"
+)
+
+// ProjectHandler provides Huma-based project management endpoints.
+type ProjectHandler struct {
+ projectService *services.ProjectService
+}
+
+// --- Huma Input/Output Wrappers ---
+
+// ProjectPaginatedResponse is the paginated response for projects.
+type ProjectPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []project.Details `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListProjectsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`
+ Start int `query:"start" default:"0" doc:"Start index for pagination"`
+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`
+}
+
+type ListProjectsOutput struct {
+ Body ProjectPaginatedResponse
+}
+
+type GetProjectStatusCountsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetProjectStatusCountsOutput struct {
+ Body base.ApiResponse[project.StatusCounts]
+}
+
+type DeployProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+}
+
+type DeployProjectOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type DownProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+}
+
+type DownProjectOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type CreateProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body project.CreateProject
+}
+
+type CreateProjectOutput struct {
+ Body base.ApiResponse[project.CreateReponse]
+}
+
+type GetProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+}
+
+type GetProjectOutput struct {
+ Body base.ApiResponse[project.Details]
+}
+
+type RedeployProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+}
+
+type RedeployProjectOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type DestroyProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+ Body *project.Destroy
+}
+
+type DestroyProjectOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type UpdateProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+ Body project.UpdateProject
+}
+
+type UpdateProjectOutput struct {
+ Body base.ApiResponse[project.Details]
+}
+
+type UpdateProjectIncludeInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+ Body project.UpdateIncludeFile
+}
+
+type UpdateProjectIncludeOutput struct {
+ Body base.ApiResponse[project.Details]
+}
+
+type RestartProjectInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+}
+
+type RestartProjectOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type PullProjectImagesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ ProjectID string `path:"projectId" doc:"Project ID"`
+}
+
+// PullProgressEvent represents a Docker pull progress event
+type PullProgressEvent struct {
+ Status string `json:"status,omitempty"`
+ ID string `json:"id,omitempty"`
+ Progress string `json:"progress,omitempty"`
+ ProgressDetail struct {
+ Current int64 `json:"current,omitempty"`
+ Total int64 `json:"total,omitempty"`
+ } `json:"progressDetail,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// RegisterProjects registers project management routes using Huma.
+// Note: WebSocket and streaming endpoints remain as Gin handlers.
+func RegisterProjects(api huma.API, projectService *services.ProjectService) {
+ h := &ProjectHandler{
+ projectService: projectService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-projects",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/projects",
+ Summary: "List projects",
+ Description: "Get a paginated list of Docker Compose projects",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListProjects)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-project-status-counts",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/projects/counts",
+ Summary: "Get project status counts",
+ Description: "Get counts of running, stopped, and total projects",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetProjectStatusCounts)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deploy-project",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/projects/{projectId}/up",
+ Summary: "Deploy a project",
+ Description: "Deploy a Docker Compose project (docker-compose up)",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeployProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "down-project",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/projects/{projectId}/down",
+ Summary: "Bring down a project",
+ Description: "Bring down a Docker Compose project (docker-compose down)",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DownProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-project",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/projects",
+ Summary: "Create a project",
+ Description: "Create a new Docker Compose project",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-project",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/projects/{projectId}",
+ Summary: "Get a project",
+ Description: "Get a Docker Compose project by ID",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "redeploy-project",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/projects/{projectId}/redeploy",
+ Summary: "Redeploy a project",
+ Description: "Redeploy a Docker Compose project (down + up)",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.RedeployProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "destroy-project",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/projects/{projectId}/destroy",
+ Summary: "Destroy a project",
+ Description: "Destroy a Docker Compose project and optionally remove files/volumes",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DestroyProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-project",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/projects/{projectId}",
+ Summary: "Update a project",
+ Description: "Update a Docker Compose project configuration",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-project-include",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/projects/{projectId}/includes",
+ Summary: "Update project include file",
+ Description: "Update an include file within a Docker Compose project",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateProjectInclude)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "restart-project",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/projects/{projectId}/restart",
+ Summary: "Restart a project",
+ Description: "Restart all containers in a Docker Compose project",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.RestartProject)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "pull-project-images",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/projects/{projectId}/pull",
+ Summary: "Pull project images",
+ Description: "Pull all images for a Docker Compose project with streaming progress output",
+ Tags: []string{"Projects"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.PullProjectImages)
+}
+
+// ListProjects returns a paginated list of projects.
+func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsInput) (*ListProjectsOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := pagination.QueryParams{
+ SearchQuery: pagination.SearchQuery{
+ Search: input.Search,
+ },
+ SortParams: pagination.SortParams{
+ Sort: input.Sort,
+ Order: pagination.SortOrder(input.Order),
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: input.Start,
+ Limit: input.Limit,
+ },
+ }
+
+ projects, paginationResp, err := h.projectService.ListProjects(ctx, params)
+ if err != nil {
+ if errors.Is(err, context.Canceled) {
+ return nil, huma.Error500InternalServerError("Request was canceled")
+ }
+ return nil, huma.Error500InternalServerError((&common.ProjectListError{Err: err}).Error())
+ }
+
+ if projects == nil {
+ projects = []project.Details{}
+ }
+
+ return &ListProjectsOutput{
+ Body: ProjectPaginatedResponse{
+ Success: true,
+ Data: projects,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// GetProjectStatusCounts returns counts of projects by status.
+func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetProjectStatusCountsInput) (*GetProjectStatusCountsOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ _, running, stopped, total, err := h.projectService.GetProjectStatusCounts(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ProjectStatusCountsError{Err: err}).Error())
+ }
+
+ return &GetProjectStatusCountsOutput{
+ Body: base.ApiResponse[project.StatusCounts]{
+ Success: true,
+ Data: project.StatusCounts{
+ RunningProjects: int(running),
+ StoppedProjects: int(stopped),
+ TotalProjects: int(total),
+ },
+ },
+ }, nil
+}
+
+// DeployProject deploys a Docker Compose project.
+func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProjectInput) (*DeployProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ProjectID == "" {
+ return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ if err := h.projectService.DeployProject(ctx, input.ProjectID, *user); err != nil {
+ return nil, huma.Error400BadRequest((&common.ProjectDeploymentError{Err: err}).Error())
+ }
+
+ return &DeployProjectOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Project deployed successfully",
+ },
+ },
+ }, nil
+}
+
+// DownProject brings down a Docker Compose project.
+func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInput) (*DownProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ if err := h.projectService.DownProject(ctx, input.ProjectID, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.ProjectDownError{Err: err}).Error())
+ }
+
+ return &DownProjectOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Project brought down successfully",
+ },
+ },
+ }, nil
+}
+
+// CreateProject creates a new Docker Compose project.
+func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectInput) (*CreateProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ proj, err := h.projectService.CreateProject(ctx, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, *user)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ProjectCreationError{Err: err}).Error())
+ }
+
+ var response project.CreateReponse
+ if err := mapper.MapStruct(proj, &response); err != nil {
+ return nil, huma.Error500InternalServerError("failed to map response")
+ }
+ response.Status = string(proj.Status)
+ response.StatusReason = proj.StatusReason
+ response.CreatedAt = proj.CreatedAt.Format(time.RFC3339)
+ response.UpdatedAt = proj.UpdatedAt.Format(time.RFC3339)
+ response.DirName = utils.DerefString(proj.DirName)
+
+ return &CreateProjectOutput{
+ Body: base.ApiResponse[project.CreateReponse]{
+ Success: true,
+ Data: response,
+ },
+ }, nil
+}
+
+// GetProject returns a project by ID.
+func (h *ProjectHandler) GetProject(ctx context.Context, input *GetProjectInput) (*GetProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ProjectID == "" {
+ return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
+ }
+
+ details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.ProjectDetailsError{Err: err}).Error())
+ }
+
+ return &GetProjectOutput{
+ Body: base.ApiResponse[project.Details]{
+ Success: true,
+ Data: details,
+ },
+ }, nil
+}
+
+// RedeployProject redeploys a Docker Compose project.
+func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployProjectInput) (*RedeployProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ProjectID == "" {
+ return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ if err := h.projectService.RedeployProject(ctx, input.ProjectID, *user); err != nil {
+ return nil, huma.Error400BadRequest((&common.ProjectRedeploymentError{Err: err}).Error())
+ }
+
+ return &RedeployProjectOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Project redeployed successfully",
+ },
+ },
+ }, nil
+}
+
+// DestroyProject destroys a Docker Compose project.
+func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProjectInput) (*DestroyProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ removeFiles := false
+ removeVolumes := false
+ if input.Body != nil {
+ removeFiles = input.Body.RemoveFiles
+ removeVolumes = input.Body.RemoveVolumes
+ }
+
+ if err := h.projectService.DestroyProject(ctx, input.ProjectID, removeFiles, removeVolumes, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.ProjectDestroyError{Err: err}).Error())
+ }
+
+ return &DestroyProjectOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Project destroyed successfully",
+ },
+ },
+ }, nil
+}
+
+// UpdateProject updates a Docker Compose project.
+func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectInput) (*UpdateProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ProjectID == "" {
+ return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
+ }
+
+ if _, err := h.projectService.UpdateProject(ctx, input.ProjectID, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent); err != nil {
+ return nil, huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())
+ }
+
+ details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ProjectDetailsError{Err: err}).Error())
+ }
+
+ return &UpdateProjectOutput{
+ Body: base.ApiResponse[project.Details]{
+ Success: true,
+ Data: details,
+ },
+ }, nil
+}
+
+// UpdateProjectInclude updates an include file within a project.
+func (h *ProjectHandler) UpdateProjectInclude(ctx context.Context, input *UpdateProjectIncludeInput) (*UpdateProjectIncludeOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ProjectID == "" {
+ return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
+ }
+
+ if err := h.projectService.UpdateProjectIncludeFile(ctx, input.ProjectID, input.Body.RelativePath, input.Body.Content); err != nil {
+ return nil, huma.Error400BadRequest((&common.ProjectUpdateError{Err: err}).Error())
+ }
+
+ details, err := h.projectService.GetProjectDetails(ctx, input.ProjectID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ProjectDetailsError{Err: err}).Error())
+ }
+
+ return &UpdateProjectIncludeOutput{
+ Body: base.ApiResponse[project.Details]{
+ Success: true,
+ Data: details,
+ },
+ }, nil
+}
+
+// RestartProject restarts all containers in a project.
+func (h *ProjectHandler) RestartProject(ctx context.Context, input *RestartProjectInput) (*RestartProjectOutput, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ProjectID == "" {
+ return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ if err := h.projectService.RestartProject(ctx, input.ProjectID, *user); err != nil {
+ return nil, huma.Error400BadRequest((&common.ProjectRestartError{Err: err}).Error())
+ }
+
+ return &RestartProjectOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Project restarted successfully",
+ },
+ },
+ }, nil
+}
+
+// PullProjectImages pulls all images for a project with streaming progress.
+func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProjectImagesInput) (*huma.StreamResponse, error) {
+ if h.projectService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ProjectID == "" {
+ return nil, huma.Error400BadRequest((&common.ProjectIDRequiredError{}).Error())
+ }
+
+ return &huma.StreamResponse{
+ Body: func(humaCtx huma.Context) { //nolint:contextcheck // context is obtained from humaCtx.Context()
+ humaCtx.SetHeader("Content-Type", "application/x-json-stream")
+ humaCtx.SetHeader("Cache-Control", "no-cache")
+ humaCtx.SetHeader("Connection", "keep-alive")
+ humaCtx.SetHeader("X-Accel-Buffering", "no")
+
+ writer := humaCtx.BodyWriter()
+
+ _, _ = writer.Write([]byte(`{"status":"starting project image pull"}` + "\n"))
+ if f, ok := writer.(http.Flusher); ok {
+ f.Flush()
+ }
+
+ if err := h.projectService.PullProjectImages(humaCtx.Context(), input.ProjectID, writer, nil); err != nil {
+ _, _ = fmt.Fprintf(writer, `{"error":%q}`+"\n", err.Error())
+ return
+ }
+
+ _, _ = writer.Write([]byte(`{"status":"complete"}` + "\n"))
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/settings.go b/backend/internal/huma/handlers/settings.go
new file mode 100644
index 000000000..6f1afbc8a
--- /dev/null
+++ b/backend/internal/huma/handlers/settings.go
@@ -0,0 +1,258 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/category"
+ "go.getarcane.app/types/search"
+ "go.getarcane.app/types/settings"
+)
+
+// SettingsHandler provides Huma-based settings management endpoints.
+type SettingsHandler struct {
+ settingsService *services.SettingsService
+ settingsSearchService *services.SettingsSearchService
+ cfg *config.Config
+}
+
+// --- Huma Input/Output Wrappers ---
+
+type GetSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetSettingsOutput struct {
+ Body []settings.PublicSetting
+}
+
+type GetPublicSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetPublicSettingsOutput struct {
+ Body []settings.PublicSetting
+}
+
+type UpdateSettingsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body settings.Update `doc:"Settings update data"`
+}
+
+type UpdateSettingsOutput struct {
+ Body base.ApiResponse[[]settings.SettingDto]
+}
+
+type SearchSettingsInput struct {
+ Body search.Request `doc:"Search query"`
+}
+
+type SearchSettingsOutput struct {
+ Body search.Response
+}
+
+type GetCategoriesOutput struct {
+ Body []category.Category
+}
+
+// RegisterSettings registers settings management routes using Huma.
+func RegisterSettings(api huma.API, settingsService *services.SettingsService, settingsSearchService *services.SettingsSearchService, cfg *config.Config) {
+ h := &SettingsHandler{
+ settingsService: settingsService,
+ settingsSearchService: settingsSearchService,
+ cfg: cfg,
+ }
+
+ // Environment-scoped settings endpoints
+ huma.Register(api, huma.Operation{
+ OperationID: "get-public-settings",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/settings/public",
+ Summary: "Get public settings",
+ Description: "Get all public settings for an environment",
+ Tags: []string{"Settings"},
+ }, h.GetPublicSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-settings",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/settings",
+ Summary: "Get settings",
+ Description: "Get all settings for an environment",
+ Tags: []string{"Settings"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetSettings)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-settings",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/settings",
+ Summary: "Update settings",
+ Description: "Update settings for an environment",
+ Tags: []string{"Settings"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateSettings)
+
+ // Top-level settings endpoints (not environment-scoped)
+ huma.Register(api, huma.Operation{
+ OperationID: "search-settings",
+ Method: http.MethodPost,
+ Path: "/settings/search",
+ Summary: "Search settings",
+ Description: "Search settings categories and individual settings by query",
+ Tags: []string{"Settings"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.Search)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-settings-categories",
+ Method: http.MethodGet,
+ Path: "/settings/categories",
+ Summary: "Get settings categories",
+ Description: "Get all available settings categories with metadata",
+ Tags: []string{"Settings"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetCategories)
+}
+
+// GetPublicSettings returns public settings for an environment.
+func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublicSettingsInput) (*GetPublicSettingsOutput, error) {
+ if h.settingsService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ settingsList := h.settingsService.ListSettings(false)
+
+ var settingsDto []settings.PublicSetting
+ if err := mapper.MapStructList(settingsList, &settingsDto); err != nil {
+ return nil, huma.Error500InternalServerError((&common.SettingsMappingError{Err: err}).Error())
+ }
+
+ // Add UI config disabled setting
+ uiConfigDisabled := false
+ if h.cfg != nil {
+ uiConfigDisabled = h.cfg.UIConfigurationDisabled
+ }
+ settingsDto = append(settingsDto, settings.PublicSetting{
+ Key: "uiConfigDisabled",
+ Value: strconv.FormatBool(uiConfigDisabled),
+ Type: "boolean",
+ })
+
+ return &GetPublicSettingsOutput{Body: settingsDto}, nil
+}
+
+// GetSettings returns all settings for an environment.
+func (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInput) (*GetSettingsOutput, error) {
+ if h.settingsService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ showAll := input.EnvironmentID == "0"
+ settingsList := h.settingsService.ListSettings(showAll)
+
+ var settingsDto []settings.PublicSetting
+ if err := mapper.MapStructList(settingsList, &settingsDto); err != nil {
+ return nil, huma.Error500InternalServerError((&common.SettingsMappingError{Err: err}).Error())
+ }
+
+ // Add UI config disabled setting
+ uiConfigDisabled := false
+ if h.cfg != nil {
+ uiConfigDisabled = h.cfg.UIConfigurationDisabled
+ }
+ settingsDto = append(settingsDto, settings.PublicSetting{
+ Key: "uiConfigDisabled",
+ Value: strconv.FormatBool(uiConfigDisabled),
+ Type: "boolean",
+ })
+
+ return &GetSettingsOutput{Body: settingsDto}, nil
+}
+
+// UpdateSettings updates settings for an environment.
+func (h *SettingsHandler) UpdateSettings(ctx context.Context, input *UpdateSettingsInput) (*UpdateSettingsOutput, error) {
+ if h.settingsService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ // Check if trying to update auth settings on non-local environment
+ if input.EnvironmentID != "0" {
+ req := input.Body
+ if req.AuthLocalEnabled != nil || req.OidcEnabled != nil ||
+ req.AuthSessionTimeout != nil || req.AuthPasswordPolicy != nil ||
+ req.AuthOidcConfig != nil || req.OidcClientId != nil ||
+ req.OidcClientSecret != nil || req.OidcIssuerUrl != nil ||
+ req.OidcScopes != nil || req.OidcAdminClaim != nil ||
+ req.OidcAdminValue != nil || req.OidcMergeAccounts != nil {
+ return nil, huma.Error403Forbidden((&common.AuthSettingsUpdateError{}).Error())
+ }
+ }
+
+ updatedSettings, err := h.settingsService.UpdateSettings(ctx, input.Body)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.SettingsUpdateError{Err: err}).Error())
+ }
+
+ settingDtos := make([]settings.SettingDto, 0, len(updatedSettings))
+ for _, setting := range updatedSettings {
+ settingDtos = append(settingDtos, settings.SettingDto{
+ PublicSetting: settings.PublicSetting{
+ Key: setting.Key,
+ Type: "string",
+ Value: setting.Value,
+ },
+ })
+ }
+
+ return &UpdateSettingsOutput{
+ Body: base.ApiResponse[[]settings.SettingDto]{
+ Success: true,
+ Data: settingDtos,
+ },
+ }, nil
+}
+
+// Search searches settings by query.
+func (h *SettingsHandler) Search(ctx context.Context, input *SearchSettingsInput) (*SearchSettingsOutput, error) {
+ if h.settingsSearchService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if strings.TrimSpace(input.Body.Query) == "" {
+ return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
+ }
+
+ results := h.settingsSearchService.Search(input.Body.Query)
+ return &SearchSettingsOutput{Body: results}, nil
+}
+
+// GetCategories returns all available settings categories.
+func (h *SettingsHandler) GetCategories(ctx context.Context, input *struct{}) (*GetCategoriesOutput, error) {
+ if h.settingsSearchService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ categories := h.settingsSearchService.GetSettingsCategories()
+ return &GetCategoriesOutput{Body: categories}, nil
+}
diff --git a/backend/internal/huma/handlers/system.go b/backend/internal/huma/handlers/system.go
new file mode 100644
index 000000000..6d6b9d410
--- /dev/null
+++ b/backend/internal/huma/handlers/system.go
@@ -0,0 +1,493 @@
+package handlers
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "go.getarcane.app/types/base"
+ containertypes "go.getarcane.app/types/container"
+ "go.getarcane.app/types/dockerinfo"
+ "go.getarcane.app/types/system"
+)
+
+// SystemHandler handles system management endpoints.
+type SystemHandler struct {
+ dockerService *services.DockerClientService
+ systemService *services.SystemService
+ upgradeService *services.SystemUpgradeService
+ cfg *config.Config
+}
+
+// --- Input/Output Types ---
+
+type SystemHealthInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type SystemHealthOutput struct {
+ Status int `status:"200"`
+}
+
+type GetDockerInfoInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetDockerInfoOutput struct {
+ Body dockerinfo.Info
+}
+
+type PruneAllInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body system.PruneAllRequest `doc:"Prune options"`
+}
+
+type PruneAllOutput struct {
+ Body base.ApiResponse[system.PruneAllResult]
+}
+
+type StartAllContainersInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type StartAllContainersOutput struct {
+ Body base.ApiResponse[containertypes.ActionResult]
+}
+
+type StartAllStoppedContainersInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type StartAllStoppedContainersOutput struct {
+ Body base.ApiResponse[containertypes.ActionResult]
+}
+
+type StopAllContainersInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type StopAllContainersOutput struct {
+ Body base.ApiResponse[containertypes.ActionResult]
+}
+
+type ConvertDockerRunInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body models.ConvertDockerRunRequest `doc:"Docker run command"`
+}
+
+type ConvertDockerRunOutput struct {
+ Body models.ConvertDockerRunResponse
+}
+
+type CheckUpgradeInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+// UpgradeCheckResultData is the response for upgrade check.
+type UpgradeCheckResultData struct {
+ CanUpgrade bool `json:"canUpgrade"`
+ Error bool `json:"error"`
+ Message string `json:"message"`
+}
+
+type CheckUpgradeOutput struct {
+ Body UpgradeCheckResultData
+}
+
+type TriggerUpgradeInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type TriggerUpgradeOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// RegisterSystem registers system management endpoints using Huma.
+// Note: WebSocket endpoints (stats) remain in the Gin handler.
+func RegisterSystem(api huma.API, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, cfg *config.Config) {
+ h := &SystemHandler{
+ dockerService: dockerService,
+ systemService: systemService,
+ upgradeService: upgradeService,
+ cfg: cfg,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "system-health",
+ Method: http.MethodHead,
+ Path: "/environments/{id}/system/health",
+ Summary: "Check system health",
+ Description: "Check if the Docker daemon is responsive",
+ Tags: []string{"System"},
+ DefaultStatus: http.StatusOK,
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.Health)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-docker-info",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/system/docker/info",
+ Summary: "Get Docker info",
+ Description: "Get Docker daemon version and system information",
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetDockerInfo)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "prune-all",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/system/prune",
+ Summary: "Prune Docker resources",
+ Description: "Remove unused Docker resources (containers, images, volumes, networks)",
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.PruneAll)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "start-all-containers",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/system/containers/start-all",
+ Summary: "Start all containers",
+ Description: "Start all Docker containers",
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.StartAllContainers)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "start-all-stopped-containers",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/system/containers/start-stopped",
+ Summary: "Start all stopped containers",
+ Description: "Start all stopped Docker containers",
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.StartAllStoppedContainers)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "stop-all-containers",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/system/containers/stop-all",
+ Summary: "Stop all containers",
+ Description: "Stop all running Docker containers",
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.StopAllContainers)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "convert-docker-run",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/system/convert",
+ Summary: "Convert docker run command",
+ Description: "Convert a docker run command to docker-compose format",
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ConvertDockerRun)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "check-upgrade",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/system/upgrade/check",
+ Summary: "Check for system upgrade",
+ Description: "Check if a system upgrade is available",
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CheckUpgradeAvailable)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "trigger-upgrade",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/system/upgrade",
+ Summary: "Trigger system upgrade",
+ Description: "Trigger a system upgrade",
+ DefaultStatus: http.StatusAccepted,
+ Tags: []string{"System"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.TriggerUpgrade)
+}
+
+// Health checks if the Docker daemon is responsive.
+func (h *SystemHandler) Health(ctx context.Context, input *SystemHealthInput) (*SystemHealthOutput, error) {
+ if h.dockerService == nil {
+ return nil, huma.Error503ServiceUnavailable("docker service not available")
+ }
+
+ dockerClient, err := h.dockerService.GetClient()
+ if err != nil {
+ return nil, huma.Error503ServiceUnavailable((&common.DockerConnectionError{Err: err}).Error())
+ }
+
+ _, err = dockerClient.Ping(ctx)
+ if err != nil {
+ return nil, huma.Error503ServiceUnavailable((&common.DockerPingError{Err: err}).Error())
+ }
+
+ return &SystemHealthOutput{}, nil
+}
+
+// GetDockerInfo returns Docker daemon version and system information.
+func (h *SystemHandler) GetDockerInfo(ctx context.Context, input *GetDockerInfoInput) (*GetDockerInfoOutput, error) {
+ if h.dockerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ dockerClient, err := h.dockerService.GetClient()
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.DockerConnectionError{Err: err}).Error())
+ }
+
+ version, err := dockerClient.ServerVersion(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.DockerVersionError{Err: err}).Error())
+ }
+
+ info, err := dockerClient.Info(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.DockerInfoError{Err: err}).Error())
+ }
+
+ cpuCount := info.NCPU
+ memTotal := info.MemTotal
+
+ // Check for cgroup limits (LXC, Docker, etc.)
+ if cgroupLimits, err := utils.DetectCgroupLimits(); err == nil {
+ if limit := cgroupLimits.MemoryLimit; limit > 0 {
+ limitInt := int64(limit)
+ if memTotal == 0 || limitInt < memTotal {
+ memTotal = limitInt
+ }
+ }
+ if cgroupLimits.CPUCount > 0 && (cpuCount == 0 || cgroupLimits.CPUCount < cpuCount) {
+ cpuCount = cgroupLimits.CPUCount
+ }
+ }
+
+ info.NCPU = cpuCount
+ info.MemTotal = memTotal
+
+ return &GetDockerInfoOutput{
+ Body: dockerinfo.Info{
+ Success: true,
+ APIVersion: version.APIVersion,
+ GitCommit: version.GitCommit,
+ GoVersion: version.GoVersion,
+ Os: version.Os,
+ Arch: version.Arch,
+ BuildTime: version.BuildTime,
+ Info: info,
+ },
+ }, nil
+}
+
+// PruneAll removes unused Docker resources.
+func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*PruneAllOutput, error) {
+ if h.systemService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ slog.InfoContext(ctx, "System prune operation initiated",
+ "containers", input.Body.Containers,
+ "images", input.Body.Images,
+ "volumes", input.Body.Volumes,
+ "networks", input.Body.Networks,
+ "build_cache", input.Body.BuildCache,
+ "dangling", input.Body.Dangling)
+
+ result, err := h.systemService.PruneAll(ctx, input.Body)
+ if err != nil {
+ slog.ErrorContext(ctx, "System prune operation failed", "error", err)
+ return nil, huma.Error500InternalServerError((&common.SystemPruneError{Err: err}).Error())
+ }
+
+ slog.InfoContext(ctx, "System prune operation completed successfully",
+ "containers_pruned", len(result.ContainersPruned),
+ "images_deleted", len(result.ImagesDeleted),
+ "volumes_deleted", len(result.VolumesDeleted),
+ "networks_deleted", len(result.NetworksDeleted),
+ "space_reclaimed", result.SpaceReclaimed)
+
+ return &PruneAllOutput{
+ Body: base.ApiResponse[system.PruneAllResult]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+// StartAllContainers starts all Docker containers.
+func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllContainersInput) (*StartAllContainersOutput, error) {
+ if h.systemService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ result, err := h.systemService.StartAllContainers(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerStartAllError{Err: err}).Error())
+ }
+
+ return &StartAllContainersOutput{
+ Body: base.ApiResponse[containertypes.ActionResult]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+// StartAllStoppedContainers starts all stopped Docker containers.
+func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *StartAllStoppedContainersInput) (*StartAllStoppedContainersOutput, error) {
+ if h.systemService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ result, err := h.systemService.StartAllStoppedContainers(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerStartStoppedError{Err: err}).Error())
+ }
+
+ return &StartAllStoppedContainersOutput{
+ Body: base.ApiResponse[containertypes.ActionResult]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+// StopAllContainers stops all running Docker containers.
+func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllContainersInput) (*StopAllContainersOutput, error) {
+ if h.systemService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ result, err := h.systemService.StopAllContainers(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.ContainerStopAllError{Err: err}).Error())
+ }
+
+ return &StopAllContainersOutput{
+ Body: base.ApiResponse[containertypes.ActionResult]{
+ Success: true,
+ Data: *result,
+ },
+ }, nil
+}
+
+// ConvertDockerRun converts a docker run command to docker-compose format.
+func (h *SystemHandler) ConvertDockerRun(ctx context.Context, input *ConvertDockerRunInput) (*ConvertDockerRunOutput, error) {
+ if h.systemService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ parsed, err := h.systemService.ParseDockerRunCommand(input.Body.DockerRunCommand)
+ if err != nil {
+ return nil, huma.Error400BadRequest((&common.DockerRunParseError{Err: err}).Error())
+ }
+
+ dockerCompose, envVars, serviceName, err := h.systemService.ConvertToDockerCompose(parsed)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.DockerComposeConversionError{Err: err}).Error())
+ }
+
+ return &ConvertDockerRunOutput{
+ Body: models.ConvertDockerRunResponse{
+ Success: true,
+ DockerCompose: dockerCompose,
+ EnvVars: envVars,
+ ServiceName: serviceName,
+ },
+ }, nil
+}
+
+// CheckUpgradeAvailable checks if a system upgrade is available.
+func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckUpgradeInput) (*CheckUpgradeOutput, error) {
+ if h.upgradeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ canUpgrade, err := h.upgradeService.CanUpgrade(ctx)
+ if err != nil {
+ slog.Debug("System upgrade check failed", "error", err)
+ return &CheckUpgradeOutput{
+ Body: UpgradeCheckResultData{
+ CanUpgrade: false,
+ Error: true,
+ Message: (&common.UpgradeCheckError{Err: err}).Error(),
+ },
+ }, nil
+ }
+
+ return &CheckUpgradeOutput{
+ Body: UpgradeCheckResultData{
+ CanUpgrade: canUpgrade,
+ Error: false,
+ Message: "System can be upgraded",
+ },
+ }, nil
+}
+
+// TriggerUpgrade triggers a system upgrade.
+func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradeInput) (*TriggerUpgradeOutput, error) {
+ if h.upgradeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ slog.Info("System upgrade triggered", "user", user.Username, "userId", user.ID)
+
+ err := h.upgradeService.TriggerUpgradeViaCLI(ctx, *user)
+ if err != nil {
+ slog.Error("System upgrade failed", "error", err, "user", user.Username)
+
+ if errors.Is(err, services.ErrUpgradeInProgress) {
+ return nil, huma.Error409Conflict((&common.UpgradeTriggerError{Err: err}).Error())
+ }
+
+ return nil, huma.Error500InternalServerError((&common.UpgradeTriggerError{Err: err}).Error())
+ }
+
+ return &TriggerUpgradeOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Upgrade initiated successfully. A new container is being created and will replace this one shortly.",
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/templates.go b/backend/internal/huma/handlers/templates.go
new file mode 100644
index 000000000..ef7a3bde3
--- /dev/null
+++ b/backend/internal/huma/handlers/templates.go
@@ -0,0 +1,856 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/env"
+ "go.getarcane.app/types/template"
+)
+
+// TemplateHandler handles template management endpoints.
+type TemplateHandler struct {
+ templateService *services.TemplateService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+// TemplatePaginatedResponse is the paginated response for templates.
+type TemplatePaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []template.Template `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListTemplatesInput struct {
+ Page int `query:"pagination[page]" default:"1" doc:"Page number"`
+ Limit int `query:"pagination[limit]" default:"20" doc:"Items per page"`
+ SortCol string `query:"sort[column]" doc:"Column to sort by"`
+ SortDir string `query:"sort[direction]" default:"asc" doc:"Sort direction"`
+}
+
+type ListTemplatesOutput struct {
+ Body TemplatePaginatedResponse
+}
+
+type GetAllTemplatesInput struct{}
+
+type GetAllTemplatesOutput struct {
+ Body base.ApiResponse[[]template.Template]
+}
+
+type GetTemplateInput struct {
+ ID string `path:"id" doc:"Template ID"`
+}
+
+type GetTemplateOutput struct {
+ Body base.ApiResponse[template.Template]
+}
+
+type GetTemplateContentInput struct {
+ ID string `path:"id" doc:"Template ID"`
+}
+
+type GetTemplateContentOutput struct {
+ Body base.ApiResponse[template.TemplateContent]
+}
+
+type CreateTemplateInput struct {
+ Body template.CreateRequest
+}
+
+type CreateTemplateOutput struct {
+ Body base.ApiResponse[template.Template]
+}
+
+type UpdateTemplateInput struct {
+ ID string `path:"id" doc:"Template ID"`
+ Body template.UpdateRequest
+}
+
+type UpdateTemplateOutput struct {
+ Body base.ApiResponse[template.Template]
+}
+
+type DeleteTemplateInput struct {
+ ID string `path:"id" doc:"Template ID"`
+}
+
+type DeleteTemplateOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type DownloadTemplateInput struct {
+ ID string `path:"id" doc:"Template ID"`
+}
+
+type DownloadTemplateOutput struct {
+ Body base.ApiResponse[template.Template]
+}
+
+type GetDefaultTemplatesInput struct{}
+
+type GetDefaultTemplatesOutput struct {
+ Body base.ApiResponse[template.DefaultTemplatesResponse]
+}
+
+type SaveDefaultTemplatesInput struct {
+ Body template.SaveDefaultTemplatesRequest
+}
+
+type SaveDefaultTemplatesOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type GetTemplateRegistriesInput struct{}
+
+type GetTemplateRegistriesOutput struct {
+ Body base.ApiResponse[[]template.TemplateRegistry]
+}
+
+type CreateTemplateRegistryInput struct {
+ Body template.CreateRegistryRequest
+}
+
+type CreateTemplateRegistryOutput struct {
+ Body base.ApiResponse[template.TemplateRegistry]
+}
+
+type UpdateTemplateRegistryInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+ Body template.UpdateRegistryRequest
+}
+
+type UpdateTemplateRegistryOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type DeleteTemplateRegistryInput struct {
+ ID string `path:"id" doc:"Registry ID"`
+}
+
+type DeleteTemplateRegistryOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type FetchTemplateRegistryInput struct {
+ URL string `query:"url" required:"true" doc:"Registry URL"`
+}
+
+type FetchTemplateRegistryOutput struct {
+ Body base.ApiResponse[template.RemoteRegistry]
+}
+
+type GetGlobalVariablesInput struct{}
+
+type GetGlobalVariablesOutput struct {
+ Body base.ApiResponse[[]env.Variable]
+}
+
+type UpdateGlobalVariablesInput struct {
+ Body env.Summary
+}
+
+type UpdateGlobalVariablesOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterTemplates registers all template management endpoints.
+func RegisterTemplates(api huma.API, templateService *services.TemplateService) {
+ h := &TemplateHandler{templateService: templateService}
+
+ // Public endpoints (no auth required in original)
+ huma.Register(api, huma.Operation{
+ OperationID: "fetchTemplateRegistry",
+ Method: "GET",
+ Path: "/templates/fetch",
+ Summary: "Fetch remote registry",
+ Description: "Fetch templates from a remote registry URL",
+ Tags: []string{"Templates"},
+ }, h.FetchRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listTemplatesPaginated",
+ Method: "GET",
+ Path: "/templates",
+ Summary: "List templates (paginated)",
+ Description: "Get a paginated list of compose templates",
+ Tags: []string{"Templates"},
+ }, h.ListTemplates)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getAllTemplates",
+ Method: "GET",
+ Path: "/templates/all",
+ Summary: "List all templates",
+ Description: "Get all compose templates without pagination",
+ Tags: []string{"Templates"},
+ }, h.GetAllTemplates)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getTemplate",
+ Method: "GET",
+ Path: "/templates/{id}",
+ Summary: "Get a template",
+ Description: "Get a compose template by ID",
+ Tags: []string{"Templates"},
+ }, h.GetTemplate)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getTemplateContent",
+ Method: "GET",
+ Path: "/templates/{id}/content",
+ Summary: "Get template content",
+ Description: "Get the compose content for a template with parsed data",
+ Tags: []string{"Templates"},
+ }, h.GetTemplateContent)
+
+ // Protected endpoints
+ huma.Register(api, huma.Operation{
+ OperationID: "createTemplate",
+ Method: "POST",
+ Path: "/templates",
+ Summary: "Create a template",
+ Description: "Create a new compose template",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateTemplate)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateTemplate",
+ Method: "PUT",
+ Path: "/templates/{id}",
+ Summary: "Update a template",
+ Description: "Update an existing compose template",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateTemplate)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteTemplate",
+ Method: "DELETE",
+ Path: "/templates/{id}",
+ Summary: "Delete a template",
+ Description: "Delete a compose template",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteTemplate)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "downloadTemplate",
+ Method: "POST",
+ Path: "/templates/{id}/download",
+ Summary: "Download a template",
+ Description: "Download a remote template to local storage",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DownloadTemplate)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getDefaultTemplates",
+ Method: "GET",
+ Path: "/templates/default",
+ Summary: "Get default templates",
+ Description: "Get the default compose and env templates",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetDefaultTemplates)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "saveDefaultTemplates",
+ Method: "POST",
+ Path: "/templates/default",
+ Summary: "Save default templates",
+ Description: "Save the default compose and env templates",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.SaveDefaultTemplates)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getTemplateRegistries",
+ Method: "GET",
+ Path: "/templates/registries",
+ Summary: "List template registries",
+ Description: "Get all template registries",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetRegistries)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "createTemplateRegistry",
+ Method: "POST",
+ Path: "/templates/registries",
+ Summary: "Create a template registry",
+ Description: "Create a new template registry",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateTemplateRegistry",
+ Method: "PUT",
+ Path: "/templates/registries/{id}",
+ Summary: "Update a template registry",
+ Description: "Update an existing template registry",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteTemplateRegistry",
+ Method: "DELETE",
+ Path: "/templates/registries/{id}",
+ Summary: "Delete a template registry",
+ Description: "Delete a template registry",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteRegistry)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getGlobalVariables",
+ Method: "GET",
+ Path: "/templates/variables",
+ Summary: "Get global variables",
+ Description: "Get global template variables",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetGlobalVariables)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateGlobalVariables",
+ Method: "PUT",
+ Path: "/templates/variables",
+ Summary: "Update global variables",
+ Description: "Update global template variables",
+ Tags: []string{"Templates"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateGlobalVariables)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// ListTemplates returns a paginated list of templates.
+func (h *TemplateHandler) ListTemplates(ctx context.Context, input *ListTemplatesInput) (*ListTemplatesOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Limit, input.SortCol, input.SortDir)
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+
+ templates, paginationResp, err := h.templateService.GetAllTemplatesPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateListError{Err: err}).Error())
+ }
+
+ return &ListTemplatesOutput{
+ Body: TemplatePaginatedResponse{
+ Success: true,
+ Data: templates,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// GetAllTemplates returns all templates without pagination.
+func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatesInput) (*GetAllTemplatesOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ templates, err := h.templateService.GetAllTemplates(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateListError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapSlice[models.ComposeTemplate, template.Template](templates)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())
+ }
+
+ return &GetAllTemplatesOutput{
+ Body: base.ApiResponse[[]template.Template]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetTemplate returns a template by ID.
+func (h *TemplateHandler) GetTemplate(ctx context.Context, input *GetTemplateInput) (*GetTemplateOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == "" {
+ return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
+ }
+
+ tmpl, err := h.templateService.GetTemplate(ctx, input.ID)
+ if err != nil {
+ if err.Error() == "template not found" {
+ return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.TemplateRetrievalError{Err: err}).Error())
+ }
+
+ var out template.Template
+ if mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())
+ }
+
+ return &GetTemplateOutput{
+ Body: base.ApiResponse[template.Template]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetTemplateContent returns template content with parsed data.
+func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemplateContentInput) (*GetTemplateContentOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == "" {
+ return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
+ }
+
+ contentData, err := h.templateService.GetTemplateContentWithParsedData(ctx, input.ID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateContentError{Err: err}).Error())
+ }
+
+ return &GetTemplateContentOutput{
+ Body: base.ApiResponse[template.TemplateContent]{
+ Success: true,
+ Data: *contentData,
+ },
+ }, nil
+}
+
+// CreateTemplate creates a new template.
+func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTemplateInput) (*CreateTemplateOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ tmpl := &models.ComposeTemplate{
+ Name: input.Body.Name,
+ Description: input.Body.Description,
+ Content: input.Body.Content,
+ IsCustom: true,
+ IsRemote: false,
+ }
+ if input.Body.EnvContent != "" {
+ tmpl.EnvContent = &input.Body.EnvContent
+ }
+
+ if err := h.templateService.CreateTemplate(ctx, tmpl); err != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateCreationError{Err: err}).Error())
+ }
+
+ var out template.Template
+ if mapErr := mapper.MapStruct(tmpl, &out); mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateTemplateOutput{
+ Body: base.ApiResponse[template.Template]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// UpdateTemplate updates a template.
+func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTemplateInput) (*UpdateTemplateOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == "" {
+ return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
+ }
+
+ updates := &models.ComposeTemplate{
+ Name: input.Body.Name,
+ Description: input.Body.Description,
+ Content: input.Body.Content,
+ }
+ if input.Body.EnvContent != "" {
+ updates.EnvContent = &input.Body.EnvContent
+ } else {
+ updates.EnvContent = nil
+ }
+
+ if err := h.templateService.UpdateTemplate(ctx, input.ID, updates); err != nil {
+ if err.Error() == "template not found" {
+ return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.TemplateUpdateError{Err: err}).Error())
+ }
+
+ updated, err := h.templateService.GetTemplate(ctx, input.ID)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateRetrievalError{Err: err}).Error())
+ }
+
+ var out template.Template
+ if mapErr := mapper.MapStruct(updated, &out); mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())
+ }
+
+ return &UpdateTemplateOutput{
+ Body: base.ApiResponse[template.Template]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// DeleteTemplate deletes a template.
+func (h *TemplateHandler) DeleteTemplate(ctx context.Context, input *DeleteTemplateInput) (*DeleteTemplateOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == "" {
+ return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
+ }
+
+ if err := h.templateService.DeleteTemplate(ctx, input.ID); err != nil {
+ if err.Error() == "template not found" {
+ return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.TemplateDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteTemplateOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Template deleted successfully",
+ },
+ },
+ }, nil
+}
+
+// DownloadTemplate downloads a remote template to local storage.
+func (h *TemplateHandler) DownloadTemplate(ctx context.Context, input *DownloadTemplateInput) (*DownloadTemplateOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == "" {
+ return nil, huma.Error400BadRequest((&common.TemplateIDRequiredError{}).Error())
+ }
+
+ tmpl, err := h.templateService.GetTemplate(ctx, input.ID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.TemplateNotFoundError{}).Error())
+ }
+ if !tmpl.IsRemote {
+ return nil, huma.Error400BadRequest((&common.TemplateAlreadyLocalError{}).Error())
+ }
+
+ localTemplate, err := h.templateService.DownloadTemplate(ctx, tmpl)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateDownloadError{Err: err}).Error())
+ }
+
+ var out template.Template
+ if mapErr := mapper.MapStruct(localTemplate, &out); mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.TemplateMappingError{Err: mapErr}).Error())
+ }
+
+ return &DownloadTemplateOutput{
+ Body: base.ApiResponse[template.Template]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetDefaultTemplates returns the default compose and env templates.
+func (h *TemplateHandler) GetDefaultTemplates(ctx context.Context, _ *GetDefaultTemplatesInput) (*GetDefaultTemplatesOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ composeTemplate := h.templateService.GetComposeTemplate()
+ envTemplate := h.templateService.GetEnvTemplate()
+
+ return &GetDefaultTemplatesOutput{
+ Body: base.ApiResponse[template.DefaultTemplatesResponse]{
+ Success: true,
+ Data: template.DefaultTemplatesResponse{
+ ComposeTemplate: composeTemplate,
+ EnvTemplate: envTemplate,
+ },
+ },
+ }, nil
+}
+
+// SaveDefaultTemplates saves the default compose and env templates.
+func (h *TemplateHandler) SaveDefaultTemplates(ctx context.Context, input *SaveDefaultTemplatesInput) (*SaveDefaultTemplatesOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.templateService.SaveComposeTemplate(input.Body.ComposeContent); err != nil {
+ return nil, huma.Error500InternalServerError((&common.DefaultTemplateSaveError{Err: err}).Error())
+ }
+
+ if err := h.templateService.SaveEnvTemplate(input.Body.EnvContent); err != nil {
+ return nil, huma.Error500InternalServerError((&common.DefaultTemplateSaveError{Err: err}).Error())
+ }
+
+ return &SaveDefaultTemplatesOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Default templates saved successfully",
+ },
+ },
+ }, nil
+}
+
+// GetRegistries returns all template registries.
+func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegistriesInput) (*GetTemplateRegistriesOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ registries, err := h.templateService.GetRegistries(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryFetchError{Err: err}).Error())
+ }
+
+ out, mapErr := mapper.MapSlice[models.TemplateRegistry, template.TemplateRegistry](registries)
+ if mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryFetchError{Err: mapErr}).Error())
+ }
+
+ return &GetTemplateRegistriesOutput{
+ Body: base.ApiResponse[[]template.TemplateRegistry]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// CreateRegistry creates a new template registry.
+func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTemplateRegistryInput) (*CreateTemplateRegistryOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ registry := &models.TemplateRegistry{
+ Name: input.Body.Name,
+ URL: input.Body.URL,
+ Description: input.Body.Description,
+ Enabled: input.Body.Enabled,
+ }
+ if err := h.templateService.CreateRegistry(ctx, registry); err != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryCreationError{Err: err}).Error())
+ }
+
+ var out template.TemplateRegistry
+ if mapErr := mapper.MapStruct(registry, &out); mapErr != nil {
+ return nil, huma.Error500InternalServerError((&common.RegistryMappingError{Err: mapErr}).Error())
+ }
+
+ return &CreateTemplateRegistryOutput{
+ Body: base.ApiResponse[template.TemplateRegistry]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// UpdateRegistry updates a template registry.
+func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplateRegistryInput) (*UpdateTemplateRegistryOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == "" {
+ return nil, huma.Error400BadRequest((&common.RegistryIDRequiredError{}).Error())
+ }
+
+ updates := &models.TemplateRegistry{
+ Name: input.Body.Name,
+ URL: input.Body.URL,
+ Description: input.Body.Description,
+ Enabled: input.Body.Enabled,
+ }
+ if err := h.templateService.UpdateRegistry(ctx, input.ID, updates); err != nil {
+ if err.Error() == "registry not found" {
+ return nil, huma.Error404NotFound((&common.RegistryNotFoundError{}).Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.RegistryUpdateError{Err: err}).Error())
+ }
+
+ return &UpdateTemplateRegistryOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Registry updated successfully",
+ },
+ },
+ }, nil
+}
+
+// DeleteRegistry deletes a template registry.
+func (h *TemplateHandler) DeleteRegistry(ctx context.Context, input *DeleteTemplateRegistryInput) (*DeleteTemplateRegistryOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.ID == "" {
+ return nil, huma.Error400BadRequest((&common.RegistryIDRequiredError{}).Error())
+ }
+
+ if err := h.templateService.DeleteRegistry(ctx, input.ID); err != nil {
+ if err.Error() == "registry not found" {
+ return nil, huma.Error404NotFound((&common.RegistryNotFoundError{}).Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.RegistryDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteTemplateRegistryOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Registry deleted successfully",
+ },
+ },
+ }, nil
+}
+
+// FetchRegistry fetches templates from a remote registry URL.
+func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplateRegistryInput) (*FetchTemplateRegistryOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.URL == "" {
+ return nil, huma.Error400BadRequest((&common.QueryParameterRequiredError{}).Error())
+ }
+
+ body, err := h.templateService.FetchRaw(ctx, input.URL)
+ if err != nil {
+ return nil, huma.Error502BadGateway((&common.RegistryFetchError{Err: err}).Error())
+ }
+
+ var registry template.RemoteRegistry
+ if err := json.Unmarshal(body, &registry); err != nil {
+ return nil, huma.Error502BadGateway((&common.InvalidJSONResponseError{Err: err}).Error())
+ }
+
+ return &FetchTemplateRegistryOutput{
+ Body: base.ApiResponse[template.RemoteRegistry]{
+ Success: true,
+ Data: registry,
+ },
+ }, nil
+}
+
+// GetGlobalVariables returns global template variables.
+func (h *TemplateHandler) GetGlobalVariables(ctx context.Context, _ *GetGlobalVariablesInput) (*GetGlobalVariablesOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ vars, err := h.templateService.GetGlobalVariables(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.GlobalVariablesRetrievalError{Err: err}).Error())
+ }
+
+ return &GetGlobalVariablesOutput{
+ Body: base.ApiResponse[[]env.Variable]{
+ Success: true,
+ Data: vars,
+ },
+ }, nil
+}
+
+// UpdateGlobalVariables updates global template variables.
+func (h *TemplateHandler) UpdateGlobalVariables(ctx context.Context, input *UpdateGlobalVariablesInput) (*UpdateGlobalVariablesOutput, error) {
+ if h.templateService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.templateService.UpdateGlobalVariables(ctx, input.Body.Variables); err != nil {
+ return nil, huma.Error500InternalServerError((&common.GlobalVariablesUpdateError{Err: err}).Error())
+ }
+
+ return &UpdateGlobalVariablesOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Global variables updated successfully",
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/updater.go b/backend/internal/huma/handlers/updater.go
new file mode 100644
index 000000000..e0f878675
--- /dev/null
+++ b/backend/internal/huma/handlers/updater.go
@@ -0,0 +1,156 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/updater"
+)
+
+// UpdaterHandler provides Huma-based updater management endpoints.
+type UpdaterHandler struct {
+ updaterService *services.UpdaterService
+}
+
+// --- Huma Input/Output Wrappers ---
+
+type RunUpdaterInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body *updater.Options `doc:"Updater run options"`
+}
+
+type RunUpdaterOutput struct {
+ Body base.ApiResponse[*updater.Result]
+}
+
+type GetUpdaterStatusInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetUpdaterStatusOutput struct {
+ Body base.ApiResponse[updater.Status]
+}
+
+type GetUpdaterHistoryInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Limit int `query:"limit" default:"50" doc:"Number of history entries to return"`
+}
+
+type GetUpdaterHistoryOutput struct {
+ Body base.ApiResponse[[]models.AutoUpdateRecord]
+}
+
+// RegisterUpdater registers updater management routes using Huma.
+func RegisterUpdater(api huma.API, updaterService *services.UpdaterService) {
+ h := &UpdaterHandler{
+ updaterService: updaterService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "run-updater",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/updater/run",
+ Summary: "Run updater",
+ Description: "Apply pending container updates",
+ Tags: []string{"Updater"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.RunUpdater)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-updater-status",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/updater/status",
+ Summary: "Get updater status",
+ Description: "Get the current status of the updater",
+ Tags: []string{"Updater"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetUpdaterStatus)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-updater-history",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/updater/history",
+ Summary: "Get updater history",
+ Description: "Get the history of update operations",
+ Tags: []string{"Updater"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetUpdaterHistory)
+}
+
+// RunUpdater applies pending container updates.
+func (h *UpdaterHandler) RunUpdater(ctx context.Context, input *RunUpdaterInput) (*RunUpdaterOutput, error) {
+ if h.updaterService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ dryRun := false
+ if input.Body != nil {
+ dryRun = input.Body.DryRun
+ }
+
+ out, err := h.updaterService.ApplyPending(ctx, dryRun)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UpdaterRunError{Err: err}).Error())
+ }
+
+ return &RunUpdaterOutput{
+ Body: base.ApiResponse[*updater.Result]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetUpdaterStatus returns the current status of the updater.
+func (h *UpdaterHandler) GetUpdaterStatus(ctx context.Context, input *GetUpdaterStatusInput) (*GetUpdaterStatusOutput, error) {
+ if h.updaterService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ status := h.updaterService.GetStatus()
+
+ return &GetUpdaterStatusOutput{
+ Body: base.ApiResponse[updater.Status]{
+ Success: true,
+ Data: status,
+ },
+ }, nil
+}
+
+// GetUpdaterHistory returns the history of update operations.
+func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdaterHistoryInput) (*GetUpdaterHistoryOutput, error) {
+ if h.updaterService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ limit := input.Limit
+ if limit <= 0 {
+ limit = 50
+ }
+
+ history, err := h.updaterService.GetHistory(ctx, limit)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UpdaterHistoryError{Err: err}).Error())
+ }
+
+ return &GetUpdaterHistoryOutput{
+ Body: base.ApiResponse[[]models.AutoUpdateRecord]{
+ Success: true,
+ Data: history,
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/users.go b/backend/internal/huma/handlers/users.go
new file mode 100644
index 000000000..aedd81f04
--- /dev/null
+++ b/backend/internal/huma/handlers/users.go
@@ -0,0 +1,322 @@
+package handlers
+
+import (
+ "context"
+ "time"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
+ "go.getarcane.app/types/base"
+ "go.getarcane.app/types/user"
+)
+
+// UserHandler handles user management endpoints.
+type UserHandler struct {
+ userService *services.UserService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+// UserPaginatedResponse is the paginated response for users.
+type UserPaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []user.User `json:"data"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListUsersInput struct {
+ Page int `query:"pagination[page]" default:"1" doc:"Page number"`
+ Limit int `query:"pagination[limit]" default:"20" doc:"Items per page"`
+ SortCol string `query:"sort[column]" doc:"Column to sort by"`
+ SortDir string `query:"sort[direction]" default:"asc" doc:"Sort direction"`
+}
+
+type ListUsersOutput struct {
+ Body UserPaginatedResponse
+}
+
+type CreateUserInput struct {
+ Body user.CreateUser
+}
+
+type CreateUserOutput struct {
+ Body base.ApiResponse[user.User]
+}
+
+type GetUserInput struct {
+ UserID string `path:"userId" doc:"User ID"`
+}
+
+type GetUserOutput struct {
+ Body base.ApiResponse[user.User]
+}
+
+type UpdateUserInput struct {
+ UserID string `path:"userId" doc:"User ID"`
+ Body user.UpdateUser
+}
+
+type UpdateUserOutput struct {
+ Body base.ApiResponse[user.User]
+}
+
+type DeleteUserInput struct {
+ UserID string `path:"userId" doc:"User ID"`
+}
+
+type DeleteUserOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterUsers registers all user management endpoints.
+func RegisterUsers(api huma.API, userService *services.UserService) {
+ h := &UserHandler{userService: userService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "listUsers",
+ Method: "GET",
+ Path: "/users",
+ Summary: "List users",
+ Description: "Get a paginated list of all users",
+ Tags: []string{"Users"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListUsers)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "createUser",
+ Method: "POST",
+ Path: "/users",
+ Summary: "Create a user",
+ Description: "Create a new user account",
+ Tags: []string{"Users"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateUser)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getUser",
+ Method: "GET",
+ Path: "/users/{userId}",
+ Summary: "Get a user",
+ Description: "Get a user by ID",
+ Tags: []string{"Users"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetUser)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "updateUser",
+ Method: "PUT",
+ Path: "/users/{userId}",
+ Summary: "Update a user",
+ Description: "Update an existing user's information",
+ Tags: []string{"Users"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.UpdateUser)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "deleteUser",
+ Method: "DELETE",
+ Path: "/users/{userId}",
+ Summary: "Delete a user",
+ Description: "Delete a user by ID",
+ Tags: []string{"Users"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.DeleteUser)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// ListUsers returns a paginated list of users.
+func (h *UserHandler) ListUsers(ctx context.Context, input *ListUsersInput) (*ListUsersOutput, error) {
+ if h.userService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ params := buildPaginationParams(input.Page, input.Limit, input.SortCol, input.SortDir)
+
+ users, paginationResp, err := h.userService.ListUsersPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserListError{Err: err}).Error())
+ }
+
+ return &ListUsersOutput{
+ Body: UserPaginatedResponse{
+ Success: true,
+ Data: users,
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// CreateUser creates a new user.
+func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*CreateUserOutput, error) {
+ if h.userService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ hashedPassword, err := h.userService.HashPassword(input.Body.Password)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.PasswordHashError{Err: err}).Error())
+ }
+
+ userModel := &models.User{
+ Username: input.Body.Username,
+ PasswordHash: hashedPassword,
+ DisplayName: input.Body.DisplayName,
+ Email: input.Body.Email,
+ Roles: input.Body.Roles,
+ Locale: input.Body.Locale,
+ BaseModel: models.BaseModel{
+ CreatedAt: time.Now(),
+ },
+ }
+
+ if userModel.Roles == nil {
+ userModel.Roles = []string{"user"}
+ }
+
+ createdUser, err := h.userService.CreateUser(ctx, userModel)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserCreationError{Err: err}).Error())
+ }
+
+ out, err := mapper.MapOne[*models.User, user.User](createdUser)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())
+ }
+
+ return &CreateUserOutput{
+ Body: base.ApiResponse[user.User]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// GetUser returns a user by ID.
+func (h *UserHandler) GetUser(ctx context.Context, input *GetUserInput) (*GetUserOutput, error) {
+ if h.userService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ userModel, err := h.userService.GetUserByID(ctx, input.UserID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())
+ }
+
+ out, err := mapper.MapOne[*models.User, user.User](userModel)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())
+ }
+
+ return &GetUserOutput{
+ Body: base.ApiResponse[user.User]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// UpdateUser updates a user.
+func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*UpdateUserOutput, error) {
+ if h.userService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ userModel, err := h.userService.GetUserByID(ctx, input.UserID)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.UserNotFoundError{}).Error())
+ }
+
+ if input.Body.DisplayName != nil {
+ userModel.DisplayName = input.Body.DisplayName
+ }
+ if input.Body.Email != nil {
+ userModel.Email = input.Body.Email
+ }
+ if input.Body.Roles != nil {
+ userModel.Roles = input.Body.Roles
+ }
+ if input.Body.Locale != nil {
+ userModel.Locale = input.Body.Locale
+ }
+
+ if input.Body.Password != nil && *input.Body.Password != "" {
+ hashedPassword, err := h.userService.HashPassword(*input.Body.Password)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.PasswordHashError{Err: err}).Error())
+ }
+ userModel.PasswordHash = hashedPassword
+ }
+
+ now := time.Now()
+ userModel.UpdatedAt = &now
+
+ updatedUser, err := h.userService.UpdateUser(ctx, userModel)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserUpdateError{Err: err}).Error())
+ }
+
+ out, err := mapper.MapOne[*models.User, user.User](updatedUser)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: err}).Error())
+ }
+
+ return &UpdateUserOutput{
+ Body: base.ApiResponse[user.User]{
+ Success: true,
+ Data: out,
+ },
+ }, nil
+}
+
+// DeleteUser deletes a user.
+func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*DeleteUserOutput, error) {
+ if h.userService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.userService.DeleteUser(ctx, input.UserID); err != nil {
+ return nil, huma.Error500InternalServerError((&common.UserDeletionError{Err: err}).Error())
+ }
+
+ return &DeleteUserOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "User deleted successfully",
+ },
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/version.go b/backend/internal/huma/handlers/version.go
new file mode 100644
index 000000000..ed7678081
--- /dev/null
+++ b/backend/internal/huma/handlers/version.go
@@ -0,0 +1,96 @@
+package handlers
+
+import (
+ "context"
+ "strings"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "go.getarcane.app/types/version"
+)
+
+// VersionHandler handles version information endpoints.
+type VersionHandler struct {
+ versionService *services.VersionService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+type GetVersionInput struct {
+ Current string `query:"current" doc:"Current version to compare against"`
+}
+
+type GetVersionOutput struct {
+ Body version.Check
+}
+
+type GetAppVersionInput struct{}
+
+type GetAppVersionOutput struct {
+ Body version.Info
+}
+
+// ============================================================================
+// Registration
+// ============================================================================
+
+// RegisterVersion registers version endpoints.
+func RegisterVersion(api huma.API, versionService *services.VersionService) {
+ h := &VersionHandler{versionService: versionService}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getVersion",
+ Method: "GET",
+ Path: "/version",
+ Summary: "Get version information",
+ Description: "Get application version information and check for updates",
+ Tags: []string{"Version"},
+ }, h.GetVersion)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "getAppVersion",
+ Method: "GET",
+ Path: "/app-version",
+ Summary: "Get app version",
+ Description: "Get the current application version",
+ Tags: []string{"Version"},
+ }, h.GetAppVersion)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+// GetVersion returns version information with optional update check.
+func (h *VersionHandler) GetVersion(ctx context.Context, input *GetVersionInput) (*GetVersionOutput, error) {
+ if h.versionService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ current := strings.TrimSpace(input.Current)
+ info, _ := h.versionService.GetVersionInformation(ctx, current)
+
+ return &GetVersionOutput{
+ Body: version.Check{
+ CurrentVersion: info.CurrentVersion,
+ NewestVersion: info.NewestVersion,
+ UpdateAvailable: info.UpdateAvailable,
+ ReleaseURL: info.ReleaseURL,
+ },
+ }, nil
+}
+
+// GetAppVersion returns the current application version.
+func (h *VersionHandler) GetAppVersion(ctx context.Context, _ *GetAppVersionInput) (*GetAppVersionOutput, error) {
+ if h.versionService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ info := h.versionService.GetAppVersionInfo(ctx)
+
+ return &GetAppVersionOutput{
+ Body: *info,
+ }, nil
+}
diff --git a/backend/internal/huma/handlers/volumes.go b/backend/internal/huma/handlers/volumes.go
new file mode 100644
index 000000000..1943c5880
--- /dev/null
+++ b/backend/internal/huma/handlers/volumes.go
@@ -0,0 +1,476 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/docker/docker/api/types/volume"
+ "github.com/getarcaneapp/arcane/backend/internal/common"
+ humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "go.getarcane.app/types/base"
+ volumetypes "go.getarcane.app/types/volume"
+)
+
+// VolumeHandler provides Huma-based volume management endpoints.
+type VolumeHandler struct {
+ volumeService *services.VolumeService
+ dockerService *services.DockerClientService
+}
+
+// --- Huma Input/Output Wrappers ---
+
+// VolumeUsageCountsData represents the counts of volumes by usage status.
+// This is a local type to avoid schema naming conflicts with image.UsageCounts.
+type VolumeUsageCountsData struct {
+ Inuse int `json:"inuse"`
+ Unused int `json:"unused"`
+ Total int `json:"total"`
+}
+
+// VolumePaginatedResponse is the paginated response for volumes.
+type VolumePaginatedResponse struct {
+ Success bool `json:"success"`
+ Data []volumetypes.Volume `json:"data"`
+ Counts VolumeUsageCountsData `json:"counts"`
+ Pagination base.PaginationResponse `json:"pagination"`
+}
+
+type ListVolumesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Search string `query:"search" doc:"Search query"`
+ Sort string `query:"sort" doc:"Column to sort by"`
+ Order string `query:"order" default:"asc" doc:"Sort direction (asc or desc)"`
+ Start int `query:"start" default:"0" doc:"Start index for pagination"`
+ Limit int `query:"limit" default:"20" doc:"Number of items per page"`
+ InUse string `query:"inUse" doc:"Filter by in-use status (true/false)"`
+}
+
+type ListVolumesOutput struct {
+ Body VolumePaginatedResponse
+}
+
+type GetVolumeInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ VolumeName string `path:"volumeName" doc:"Volume name"`
+}
+
+type GetVolumeOutput struct {
+ Body base.ApiResponse[*volumetypes.Volume]
+}
+
+type CreateVolumeInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body volumetypes.Create `doc:"Volume creation data"`
+}
+
+type CreateVolumeOutput struct {
+ Body base.ApiResponse[*volumetypes.Volume]
+}
+
+type RemoveVolumeInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ VolumeName string `path:"volumeName" doc:"Volume name"`
+ Force bool `query:"force" doc:"Force removal"`
+}
+
+type RemoveVolumeOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+type PruneVolumesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+// VolumePruneReportData represents the result of a volume prune operation.
+// This is a local type to avoid schema naming conflicts with image.PruneReport.
+type VolumePruneReportData struct {
+ VolumesDeleted []string `json:"volumesDeleted,omitempty"`
+ SpaceReclaimed uint64 `json:"spaceReclaimed"`
+}
+
+type PruneVolumesOutput struct {
+ Body base.ApiResponse[VolumePruneReportData]
+}
+
+type GetVolumeUsageInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ VolumeName string `path:"volumeName" doc:"Volume name"`
+}
+
+// VolumeUsageResponse represents volume usage information.
+type VolumeUsageResponse struct {
+ InUse bool `json:"inUse"`
+ Containers []string `json:"containers"`
+}
+
+type GetVolumeUsageOutput struct {
+ Body base.ApiResponse[VolumeUsageResponse]
+}
+
+type GetVolumeUsageCountsInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetVolumeUsageCountsOutput struct {
+ Body base.ApiResponse[VolumeUsageCountsData]
+}
+
+type GetVolumeSizesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+// VolumeSizeInfo represents size information for a single volume.
+type VolumeSizeInfo struct {
+ Name string `json:"name"`
+ Size int64 `json:"size"`
+ RefCount int64 `json:"refCount"`
+}
+
+type GetVolumeSizesOutput struct {
+ Body base.ApiResponse[[]VolumeSizeInfo]
+}
+
+// RegisterVolumes registers volume management routes using Huma.
+func RegisterVolumes(api huma.API, dockerService *services.DockerClientService, volumeService *services.VolumeService) {
+ h := &VolumeHandler{
+ volumeService: volumeService,
+ dockerService: dockerService,
+ }
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-volume-usage-counts",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/volumes/counts",
+ Summary: "Get volume usage counts",
+ Description: "Get counts of volumes in use, unused, and total",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetVolumeUsageCounts)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "list-volumes",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/volumes",
+ Summary: "List volumes",
+ Description: "Get a paginated list of Docker volumes",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.ListVolumes)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-volume",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/volumes/{volumeName}",
+ Summary: "Get volume by name",
+ Description: "Get a Docker volume by its name",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetVolume)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-volume",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/volumes",
+ Summary: "Create a volume",
+ Description: "Create a new Docker volume",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.CreateVolume)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "remove-volume",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/volumes/{volumeName}",
+ Summary: "Remove a volume",
+ Description: "Remove a Docker volume by name",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.RemoveVolume)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "prune-volumes",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/volumes/prune",
+ Summary: "Prune unused volumes",
+ Description: "Remove all unused Docker volumes",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.PruneVolumes)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-volume-usage",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/volumes/{volumeName}/usage",
+ Summary: "Get volume usage",
+ Description: "Get containers using a specific volume",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetVolumeUsage)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-volume-sizes",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/volumes/sizes",
+ Summary: "Get volume sizes",
+ Description: "Get disk usage sizes for all volumes (slow operation)",
+ Tags: []string{"Volumes"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.GetVolumeSizes)
+}
+
+// ListVolumes returns a paginated list of volumes.
+func (h *VolumeHandler) ListVolumes(ctx context.Context, input *ListVolumesInput) (*ListVolumesOutput, error) {
+ if h.volumeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ filters := make(map[string]string)
+ if input.InUse != "" {
+ filters["inUse"] = input.InUse
+ }
+
+ params := pagination.QueryParams{
+ SearchQuery: pagination.SearchQuery{
+ Search: input.Search,
+ },
+ SortParams: pagination.SortParams{
+ Sort: input.Sort,
+ Order: pagination.SortOrder(input.Order),
+ },
+ PaginationParams: pagination.PaginationParams{
+ Start: input.Start,
+ Limit: input.Limit,
+ },
+ Filters: filters,
+ }
+
+ if params.Limit == 0 {
+ params.Limit = 20
+ }
+
+ volumes, paginationResp, counts, err := h.volumeService.ListVolumesPaginated(ctx, params)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VolumeListError{Err: err}).Error())
+ }
+
+ if volumes == nil {
+ volumes = []volumetypes.Volume{}
+ }
+
+ return &ListVolumesOutput{
+ Body: VolumePaginatedResponse{
+ Success: true,
+ Data: volumes,
+ Counts: VolumeUsageCountsData{
+ Inuse: counts.Inuse,
+ Unused: counts.Unused,
+ Total: counts.Total,
+ },
+ Pagination: base.PaginationResponse{
+ TotalPages: paginationResp.TotalPages,
+ TotalItems: paginationResp.TotalItems,
+ CurrentPage: paginationResp.CurrentPage,
+ ItemsPerPage: paginationResp.ItemsPerPage,
+ GrandTotalItems: paginationResp.GrandTotalItems,
+ },
+ },
+ }, nil
+}
+
+// GetVolume returns a volume by name.
+func (h *VolumeHandler) GetVolume(ctx context.Context, input *GetVolumeInput) (*GetVolumeOutput, error) {
+ if h.volumeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ vol, err := h.volumeService.GetVolumeByName(ctx, input.VolumeName)
+ if err != nil {
+ return nil, huma.Error404NotFound((&common.VolumeNotFoundError{Err: err}).Error())
+ }
+
+ return &GetVolumeOutput{
+ Body: base.ApiResponse[*volumetypes.Volume]{
+ Success: true,
+ Data: vol,
+ },
+ }, nil
+}
+
+// CreateVolume creates a new Docker volume.
+func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInput) (*CreateVolumeOutput, error) {
+ if h.volumeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ options := volume.CreateOptions{
+ Name: input.Body.Name,
+ Driver: input.Body.Driver,
+ Labels: input.Body.Labels,
+ DriverOpts: input.Body.DriverOpts,
+ }
+
+ response, err := h.volumeService.CreateVolume(ctx, options, *user)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VolumeCreationError{Err: err}).Error())
+ }
+
+ return &CreateVolumeOutput{
+ Body: base.ApiResponse[*volumetypes.Volume]{
+ Success: true,
+ Data: response,
+ },
+ }, nil
+}
+
+// RemoveVolume removes a Docker volume.
+func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInput) (*RemoveVolumeOutput, error) {
+ if h.volumeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ user, exists := humamw.GetCurrentUserFromContext(ctx)
+ if !exists {
+ return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
+ }
+
+ if err := h.volumeService.DeleteVolume(ctx, input.VolumeName, input.Force, *user); err != nil {
+ return nil, huma.Error500InternalServerError((&common.VolumeDeletionError{Err: err}).Error())
+ }
+
+ return &RemoveVolumeOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Volume removed successfully",
+ },
+ },
+ }, nil
+}
+
+// PruneVolumes removes all unused Docker volumes.
+func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInput) (*PruneVolumesOutput, error) {
+ if h.volumeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ report, err := h.volumeService.PruneVolumes(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VolumePruneError{Err: err}).Error())
+ }
+
+ return &PruneVolumesOutput{
+ Body: base.ApiResponse[VolumePruneReportData]{
+ Success: true,
+ Data: VolumePruneReportData{
+ VolumesDeleted: report.VolumesDeleted,
+ SpaceReclaimed: report.SpaceReclaimed,
+ },
+ },
+ }, nil
+}
+
+// GetVolumeUsage returns containers using a specific volume.
+func (h *VolumeHandler) GetVolumeUsage(ctx context.Context, input *GetVolumeUsageInput) (*GetVolumeUsageOutput, error) {
+ if h.volumeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ inUse, containers, err := h.volumeService.GetVolumeUsage(ctx, input.VolumeName)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VolumeUsageError{Err: err}).Error())
+ }
+
+ return &GetVolumeUsageOutput{
+ Body: base.ApiResponse[VolumeUsageResponse]{
+ Success: true,
+ Data: VolumeUsageResponse{
+ InUse: inUse,
+ Containers: containers,
+ },
+ },
+ }, nil
+}
+
+// GetVolumeUsageCounts returns counts of volumes by usage status.
+func (h *VolumeHandler) GetVolumeUsageCounts(ctx context.Context, input *GetVolumeUsageCountsInput) (*GetVolumeUsageCountsOutput, error) {
+ if h.dockerService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ _, inuse, unused, total, err := h.dockerService.GetAllVolumes(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.VolumeCountsError{Err: err}).Error())
+ }
+
+ return &GetVolumeUsageCountsOutput{
+ Body: base.ApiResponse[VolumeUsageCountsData]{
+ Success: true,
+ Data: VolumeUsageCountsData{
+ Inuse: inuse,
+ Unused: unused,
+ Total: total,
+ },
+ },
+ }, nil
+}
+
+// GetVolumeSizes returns disk usage sizes for all volumes.
+// This is a slow operation as it requires calculating disk usage.
+func (h *VolumeHandler) GetVolumeSizes(ctx context.Context, input *GetVolumeSizesInput) (*GetVolumeSizesOutput, error) {
+ if h.volumeService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ sizes, err := h.volumeService.GetVolumeSizes(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+
+ result := make([]VolumeSizeInfo, 0, len(sizes))
+ for name, info := range sizes {
+ result = append(result, VolumeSizeInfo{
+ Name: name,
+ Size: info.Size,
+ RefCount: info.RefCount,
+ })
+ }
+
+ return &GetVolumeSizesOutput{
+ Body: base.ApiResponse[[]VolumeSizeInfo]{
+ Success: true,
+ Data: result,
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
new file mode 100644
index 000000000..644cad235
--- /dev/null
+++ b/backend/internal/huma/huma.go
@@ -0,0 +1,348 @@
+package huma
+
+import (
+ "reflect"
+ "strings"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/danielgtaylor/huma/v2/adapters/humagin"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/huma/handlers"
+ "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/gin-gonic/gin"
+)
+
+// customSchemaNamer creates unique schema names using package prefix for types
+// from go.getarcane.app/types to avoid conflicts between packages that have
+// types with the same name (e.g., image.Summary vs env.Summary).
+func customSchemaNamer(t reflect.Type, hint string) string {
+ name := huma.DefaultSchemaNamer(t, hint)
+
+ // Get the package path - for non-pointer types this gives the full import path
+ pkgPath := t.PkgPath()
+
+ // For pointer types, get the element's package path
+ if pkgPath == "" && t.Kind() == reflect.Ptr {
+ pkgPath = t.Elem().PkgPath()
+ }
+
+ // Use type string representation for package identification
+ // Format: "pkgname.TypeName" - we extract the pkgname part
+ typeStr := t.String()
+ var shortPkg string
+ if dotIdx := strings.Index(typeStr, "."); dotIdx != -1 {
+ shortPkg = typeStr[:dotIdx]
+ }
+
+ // For types from our types package, prefix with the package name
+ if strings.HasPrefix(pkgPath, "go.getarcane.app/types/") {
+ // Extract package name (e.g., "image" from "go.getarcane.app/types/image")
+ parts := strings.Split(pkgPath, "/")
+ if len(parts) > 0 {
+ pkgName := parts[len(parts)-1]
+ // Capitalize the package name and prefix it
+ pkgName = strings.ToUpper(pkgName[:1]) + pkgName[1:]
+ return pkgName + name
+ }
+ }
+
+ // Handle Docker SDK types that have name conflicts
+ // Docker has many packages with overlapping type names:
+ // types.ServiceConfig vs registry.ServiceConfig
+ // types.GenericResource vs swarm.GenericResource
+ // etc.
+ // We prefix ALL Docker types with their package name
+ dockerPackages := map[string]string{
+ "types": "DockerTypes",
+ "registry": "DockerRegistry",
+ "system": "DockerSystem",
+ "container": "DockerContainer",
+ "network": "DockerNetwork",
+ "volume": "DockerVolume",
+ "swarm": "DockerSwarm",
+ "mount": "DockerMount",
+ "filters": "DockerFilters",
+ "blkiodev": "DockerBlkiodev",
+ "strslice": "DockerStrslice",
+ "events": "DockerEvents",
+ "image": "DockerImage",
+ }
+
+ // Check if this is a Docker type based on pkgPath
+ if strings.Contains(pkgPath, "github.com/docker/docker") {
+ // Extract the last part of the package path
+ parts := strings.Split(pkgPath, "/")
+ lastPart := parts[len(parts)-1]
+ if prefix, ok := dockerPackages[lastPart]; ok {
+ return prefix + name
+ }
+ }
+
+ // Also check short package name from type string for nested/embedded types
+ if prefix, ok := dockerPackages[shortPkg]; ok {
+ return prefix + name
+ }
+
+ // Handle generic types like base.ApiResponse[T] where T is from go.getarcane.app/types
+ // The name will be something like "BaseApiResponseUsageCounts" and we need to
+ // differentiate based on the inner type's package
+ if strings.HasPrefix(pkgPath, "go.getarcane.app/types/base") {
+ // Check if this is a generic type by looking at string representation
+ typeName := t.String()
+ // For generics, Go's String() returns something like:
+ // "base.ApiResponse[go.getarcane.app/types/volume.UsageCounts]"
+ if strings.Contains(typeName, "[") && strings.Contains(typeName, "go.getarcane.app/types/") {
+ // Extract the inner package name
+ start := strings.Index(typeName, "go.getarcane.app/types/")
+ if start != -1 {
+ rest := typeName[start+len("go.getarcane.app/types/"):]
+ end := strings.Index(rest, ".")
+ if end != -1 {
+ innerPkg := rest[:end]
+ innerPkg = strings.ToUpper(innerPkg[:1]) + innerPkg[1:]
+ // Insert the package name into the schema name
+ // BaseApiResponseUsageCounts -> BaseApiResponseVolumeUsageCounts
+ return strings.Replace(name, "UsageCounts", innerPkg+"UsageCounts", 1)
+ }
+ }
+ }
+ }
+
+ return name
+}
+
+// Services holds all service dependencies needed by Huma handlers.
+type Services struct {
+ User *services.UserService
+ Auth *services.AuthService
+ Oidc *services.OidcService
+ ApiKey *services.ApiKeyService
+ AppImages *services.ApplicationImagesService
+ Project *services.ProjectService
+ Event *services.EventService
+ Version *services.VersionService
+ Environment *services.EnvironmentService
+ Settings *services.SettingsService
+ SettingsSearch *services.SettingsSearchService
+ ContainerRegistry *services.ContainerRegistryService
+ Template *services.TemplateService
+ Docker *services.DockerClientService
+ Image *services.ImageService
+ ImageUpdate *services.ImageUpdateService
+ Volume *services.VolumeService
+ Container *services.ContainerService
+ Network *services.NetworkService
+ Notification *services.NotificationService
+ Apprise *services.AppriseService
+ Updater *services.UpdaterService
+ CustomizeSearch *services.CustomizeSearchService
+ System *services.SystemService
+ SystemUpgrade *services.SystemUpgradeService
+ Config *config.Config
+}
+
+// SetupAPI creates and configures the Huma API alongside the existing Gin router.
+func SetupAPI(router *gin.Engine, apiGroup *gin.RouterGroup, cfg *config.Config, svc *Services) huma.API {
+ humaConfig := huma.DefaultConfig("Arcane API", config.Version)
+ humaConfig.Info.Description = "Modern Docker Management, Designed for Everyone"
+
+ // Disable default docs path - we'll use Scalar instead
+ humaConfig.DocsPath = ""
+
+ // Configure servers for OpenAPI spec
+ if cfg.AppUrl != "" {
+ humaConfig.Servers = []*huma.Server{
+ {URL: cfg.AppUrl + "/api"},
+ }
+ } else {
+ humaConfig.Servers = []*huma.Server{
+ {URL: "/api"},
+ }
+ }
+
+ // Configure security schemes
+ humaConfig.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
+ "BearerAuth": {
+ Type: "http",
+ Scheme: "bearer",
+ BearerFormat: "JWT",
+ Description: "JWT Bearer token authentication",
+ },
+ "ApiKeyAuth": {
+ Type: "apiKey",
+ In: "header",
+ Name: "X-API-Key",
+ Description: "API Key authentication",
+ },
+ }
+
+ // Use custom schema namer to avoid conflicts between types with same name
+ // from different packages (e.g., image.Summary vs env.Summary)
+ humaConfig.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", customSchemaNamer)
+
+ // Create Huma API wrapping the Gin router group
+ api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+
+ // Add authentication middleware
+ api.UseMiddleware(middleware.NewAuthBridge(svc.Auth, cfg))
+
+ // Register all Huma handlers
+ registerHandlers(api, svc)
+
+ // Register Scalar API docs endpoint with dark mode
+ registerScalarDocs(apiGroup)
+
+ return api
+}
+
+// scalarDocsHTML returns the HTML template for Scalar API documentation.
+const scalarDocsHTML = `<!doctype html>
+<html>
+ <head>
+ <title>Arcane API Reference</title>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ </head>
+ <body>
+ <script
+ id="api-reference"
+ data-url="/api/openapi.json"
+ data-configuration='{
+ "theme": "purple",
+ "darkMode": true,
+ "layout": "modern",
+ "hiddenClients": ["unirest"],
+ "defaultHttpClient": { "targetKey": "shell", "clientKey": "curl" }
+ }'></script>
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
+ </body>
+</html>`
+
+// registerScalarDocs adds the Scalar API documentation endpoint.
+func registerScalarDocs(apiGroup *gin.RouterGroup) {
+ apiGroup.GET("/docs", func(c *gin.Context) {
+ c.Header("Content-Type", "text/html")
+ c.String(200, scalarDocsHTML)
+ })
+}
+
+// SetupAPIForSpec creates a Huma API instance for OpenAPI spec generation only.
+// No services are required - this is purely for schema generation.
+func SetupAPIForSpec() huma.API {
+ gin.SetMode(gin.ReleaseMode)
+ router := gin.New()
+ apiGroup := router.Group("/api")
+
+ humaConfig := huma.DefaultConfig("Arcane API", config.Version)
+ humaConfig.Info.Description = "Modern Docker Management, Designed for Everyone"
+ humaConfig.Servers = []*huma.Server{
+ {URL: "/api"},
+ }
+ humaConfig.Components.SecuritySchemes = map[string]*huma.SecurityScheme{
+ "BearerAuth": {
+ Type: "http",
+ Scheme: "bearer",
+ BearerFormat: "JWT",
+ Description: "JWT Bearer token authentication",
+ },
+ "ApiKeyAuth": {
+ Type: "apiKey",
+ In: "header",
+ Name: "X-API-Key",
+ Description: "API Key authentication",
+ },
+ }
+
+ // Use custom schema namer to avoid conflicts between types with same name
+ humaConfig.Components.Schemas = huma.NewMapRegistry("#/components/schemas/", customSchemaNamer)
+
+ api := humagin.NewWithGroup(router, apiGroup, humaConfig)
+
+ // Register handlers with nil services (just for schema)
+ registerHandlers(api, 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 appImagesSvc *services.ApplicationImagesService
+ var projectSvc *services.ProjectService
+ var eventSvc *services.EventService
+ var versionSvc *services.VersionService
+ var environmentSvc *services.EnvironmentService
+ var settingsSvc *services.SettingsService
+ 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 volumeSvc *services.VolumeService
+ var containerSvc *services.ContainerService
+ var networkSvc *services.NetworkService
+ var notificationSvc *services.NotificationService
+ var appriseSvc *services.AppriseService
+ var updaterSvc *services.UpdaterService
+ var customizeSearchSvc *services.CustomizeSearchService
+ var systemSvc *services.SystemService
+ var systemUpgradeSvc *services.SystemUpgradeService
+ var cfg *config.Config
+
+ if svc != nil {
+ userSvc = svc.User
+ authSvc = svc.Auth
+ oidcSvc = svc.Oidc
+ apiKeySvc = svc.ApiKey
+ appImagesSvc = svc.AppImages
+ projectSvc = svc.Project
+ eventSvc = svc.Event
+ versionSvc = svc.Version
+ environmentSvc = svc.Environment
+ settingsSvc = svc.Settings
+ settingsSearchSvc = svc.SettingsSearch
+ containerRegistrySvc = svc.ContainerRegistry
+ templateSvc = svc.Template
+ dockerSvc = svc.Docker
+ imageSvc = svc.Image
+ imageUpdateSvc = svc.ImageUpdate
+ volumeSvc = svc.Volume
+ containerSvc = svc.Container
+ networkSvc = svc.Network
+ notificationSvc = svc.Notification
+ appriseSvc = svc.Apprise
+ updaterSvc = svc.Updater
+ customizeSearchSvc = svc.CustomizeSearch
+ systemSvc = svc.System
+ systemUpgradeSvc = svc.SystemUpgrade
+ cfg = svc.Config
+ }
+ handlers.RegisterHealth(api)
+ handlers.RegisterAuth(api, userSvc, authSvc, oidcSvc)
+ handlers.RegisterApiKeys(api, apiKeySvc)
+ handlers.RegisterAppImages(api, appImagesSvc)
+ handlers.RegisterProjects(api, projectSvc)
+ handlers.RegisterUsers(api, userSvc)
+ handlers.RegisterVersion(api, versionSvc)
+ handlers.RegisterEvents(api, eventSvc)
+ handlers.RegisterOidc(api, authSvc, oidcSvc)
+ handlers.RegisterEnvironments(api, environmentSvc, settingsSvc, cfg)
+ handlers.RegisterContainerRegistries(api, containerRegistrySvc)
+ handlers.RegisterTemplates(api, templateSvc)
+ handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc)
+ handlers.RegisterImageUpdates(api, imageUpdateSvc)
+ handlers.RegisterSettings(api, settingsSvc, settingsSearchSvc, cfg)
+ handlers.RegisterVolumes(api, dockerSvc, volumeSvc)
+ handlers.RegisterContainers(api, containerSvc, dockerSvc)
+ handlers.RegisterNetworks(api, networkSvc, dockerSvc)
+ handlers.RegisterNotifications(api, notificationSvc, appriseSvc)
+ handlers.RegisterUpdater(api, updaterSvc)
+ handlers.RegisterCustomize(api, customizeSearchSvc)
+ handlers.RegisterSystem(api, dockerSvc, systemSvc, systemUpgradeSvc, cfg)
+}
diff --git a/backend/internal/huma/middleware/auth.go b/backend/internal/huma/middleware/auth.go
new file mode 100644
index 000000000..ba1855349
--- /dev/null
+++ b/backend/internal/huma/middleware/auth.go
@@ -0,0 +1,222 @@
+package middleware
+
+import (
+ "context"
+ "net/http"
+ "strings"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+)
+
+const (
+ headerAgentBootstrap = "X-Arcane-Agent-Bootstrap"
+ headerAgentToken = "X-Arcane-Agent-Token" // #nosec G101: header name, not a credential
+ headerApiKey = "X-API-Key" // #nosec G101: header name, not a credential
+ agentPairingPrefix = "/api/environments/0/agent/pair"
+)
+
+// ContextKey is a type for context keys used by Huma handlers.
+type ContextKey string
+
+const (
+ // ContextKeyUserID is the context key for the authenticated user's ID.
+ ContextKeyUserID ContextKey = "userID"
+ // ContextKeyCurrentUser is the context key for the authenticated user model.
+ ContextKeyCurrentUser ContextKey = "currentUser"
+ // ContextKeyUserIsAdmin is the context key for whether the user is an admin.
+ ContextKeyUserIsAdmin ContextKey = "userIsAdmin"
+)
+
+// GetUserIDFromContext retrieves the user ID from the context.
+func GetUserIDFromContext(ctx context.Context) (string, bool) {
+ userID, ok := ctx.Value(ContextKeyUserID).(string)
+ return userID, ok
+}
+
+// GetCurrentUserFromContext retrieves the current user from the context.
+func GetCurrentUserFromContext(ctx context.Context) (*models.User, bool) {
+ u, ok := ctx.Value(ContextKeyCurrentUser).(*models.User)
+ return u, ok
+}
+
+// IsAdminFromContext checks if the current user is an admin.
+func IsAdminFromContext(ctx context.Context) bool {
+ isAdmin, ok := ctx.Value(ContextKeyUserIsAdmin).(bool)
+ return ok && isAdmin
+}
+
+// securityRequirements holds parsed security requirements from an operation.
+type securityRequirements struct {
+ isRequired bool
+ bearerAuth bool
+ apiKeyAuth bool
+}
+
+// parseSecurityRequirements extracts security requirements from a Huma operation.
+func parseSecurityRequirements(ctx huma.Context) securityRequirements {
+ reqs := securityRequirements{}
+ if ctx.Operation() == nil || len(ctx.Operation().Security) == 0 {
+ return reqs
+ }
+ for _, secReq := range ctx.Operation().Security {
+ if _, ok := secReq["BearerAuth"]; ok {
+ reqs.isRequired = true
+ reqs.bearerAuth = true
+ }
+ if _, ok := secReq["ApiKeyAuth"]; ok {
+ reqs.isRequired = true
+ reqs.apiKeyAuth = true
+ }
+ }
+ return reqs
+}
+
+// tryBearerAuth attempts Bearer token authentication.
+func tryBearerAuth(ctx huma.Context, authService *services.AuthService) (*models.User, bool) {
+ token := extractBearerToken(ctx)
+ if token == "" {
+ return nil, false
+ }
+ user, err := authService.VerifyToken(ctx.Context(), token)
+ if err != nil || user == nil {
+ return nil, false
+ }
+ return user, true
+}
+
+// tryApiKeyAuth checks if API key authentication should be allowed through.
+func tryApiKeyAuth(ctx huma.Context) bool {
+ return ctx.Header(headerApiKey) != ""
+}
+
+// tryAgentAuth checks if the request is from an authenticated agent.
+// Returns a sudo agent user if the agent token is valid.
+func tryAgentAuth(ctx huma.Context, cfg *config.Config) (*models.User, bool) {
+ if cfg == nil || !cfg.AgentMode {
+ return nil, false
+ }
+
+ path := ctx.URL().Path
+
+ // Check for agent bootstrap pairing
+ if strings.HasPrefix(path, agentPairingPrefix) &&
+ cfg.AgentBootstrapToken != "" &&
+ ctx.Header(headerAgentBootstrap) == cfg.AgentBootstrapToken {
+ return createAgentSudoUser(), true
+ }
+
+ // Check for agent token
+ if tok := ctx.Header(headerAgentToken); tok != "" && cfg.AgentToken != "" && tok == cfg.AgentToken {
+ return createAgentSudoUser(), true
+ }
+
+ return nil, false
+}
+
+// createAgentSudoUser creates a sudo user for agent authentication.
+func createAgentSudoUser() *models.User {
+ email := "[email protected]"
+ return &models.User{
+ BaseModel: models.BaseModel{ID: "agent"},
+ Email: &email,
+ Roles: []string{"admin"},
+ }
+}
+
+// NewAuthBridge creates a Huma middleware that validates JWT tokens and
+// enforces security requirements defined on operations.
+func NewAuthBridge(authService *services.AuthService, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {
+ return func(ctx huma.Context, next func(huma.Context)) {
+ if authService == nil {
+ next(ctx)
+ return
+ }
+
+ // Check agent authentication first (if in agent mode)
+ if cfg != nil && cfg.AgentMode {
+ if user, ok := tryAgentAuth(ctx, cfg); ok {
+ newCtx := setUserInContext(ctx.Context(), user)
+ ctx = huma.WithContext(ctx, newCtx)
+ next(ctx)
+ return
+ }
+ }
+
+ reqs := parseSecurityRequirements(ctx)
+ if !reqs.isRequired {
+ next(ctx)
+ return
+ }
+
+ if reqs.bearerAuth {
+ if user, ok := tryBearerAuth(ctx, authService); ok {
+ newCtx := setUserInContext(ctx.Context(), user)
+ ctx = huma.WithContext(ctx, newCtx)
+ next(ctx)
+ return
+ }
+ }
+
+ if reqs.apiKeyAuth && tryApiKeyAuth(ctx) {
+ next(ctx)
+ return
+ }
+
+ // Write unauthorized response directly
+ ctx.SetStatus(http.StatusUnauthorized)
+ ctx.SetHeader("Content-Type", "application/json")
+ _, _ = ctx.BodyWriter().Write([]byte(`{"$schema":"","title":"Unauthorized","status":401,"detail":"Unauthorized: valid authentication required"}`))
+ }
+}
+
+// extractBearerToken extracts the JWT token from Authorization header or cookie.
+func extractBearerToken(ctx huma.Context) string {
+ // Try Authorization header first
+ authHeader := ctx.Header("Authorization")
+ if len(authHeader) > 7 && strings.ToLower(authHeader[:7]) == "bearer " {
+ return authHeader[7:]
+ }
+
+ // Try cookie as fallback
+ cookieHeader := ctx.Header("Cookie")
+ if cookieHeader != "" {
+ return extractTokenFromCookieHeader(cookieHeader)
+ }
+
+ return ""
+}
+
+// extractTokenFromCookieHeader parses the token cookie from a Cookie header string.
+func extractTokenFromCookieHeader(cookieHeader string) string {
+ cookies := strings.Split(cookieHeader, ";")
+ for _, c := range cookies {
+ c = strings.TrimSpace(c)
+ if strings.HasPrefix(c, "token=") {
+ return strings.TrimPrefix(c, "token=")
+ }
+ if strings.HasPrefix(c, "__Host-token=") {
+ return strings.TrimPrefix(c, "__Host-token=")
+ }
+ }
+ return ""
+}
+
+// setUserInContext adds the authenticated user to the context.
+func setUserInContext(ctx context.Context, user *models.User) context.Context {
+ ctx = context.WithValue(ctx, ContextKeyUserID, user.ID)
+ ctx = context.WithValue(ctx, ContextKeyCurrentUser, user)
+ ctx = context.WithValue(ctx, ContextKeyUserIsAdmin, userHasRole(user, "admin"))
+ return ctx
+}
+
+func userHasRole(user *models.User, role string) bool {
+ for _, r := range user.Roles {
+ if r == role {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index 066750e85..e2494735e 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -51,21 +51,11 @@ func (m *AuthMiddleware) WithApiKeyValidator(validator ApiKeyValidator) *AuthMid
return &clone
}
-func (m *AuthMiddleware) WithAdminRequired() *AuthMiddleware {
- clone := *m
- clone.options.AdminRequired = true
- return &clone
-}
func (m *AuthMiddleware) WithAdminNotRequired() *AuthMiddleware {
clone := *m
clone.options.AdminRequired = false
return &clone
}
-func (m *AuthMiddleware) WithSuccessOptional() *AuthMiddleware {
- clone := *m
- clone.options.SuccessOptional = true
- return &clone
-}
func (m *AuthMiddleware) Add() gin.HandlerFunc {
return func(c *gin.Context) {
@@ -229,34 +219,3 @@ func userHasRole(user *models.User, role string) bool {
}
return false
}
-
-func GetCurrentUserID(c *gin.Context) (string, bool) {
- userID, exists := c.Get("userID")
- if !exists {
- return "", false
- }
- userIDStr, ok := userID.(string)
- return userIDStr, ok
-}
-
-func GetCurrentUser(c *gin.Context) (*models.User, bool) {
- user, exists := c.Get("currentUser")
- if !exists {
- return nil, false
- }
- u, ok := user.(*models.User)
- return u, ok
-}
-
-func RequireAuthentication(c *gin.Context) (*models.User, bool) {
- user, exists := GetCurrentUser(c)
- if !exists {
- c.JSON(http.StatusUnauthorized, models.APIError{
- Code: models.APIErrorCodeUnauthorized,
- Message: "Authentication required",
- })
- c.Abort()
- return nil, false
- }
- return user, true
-}
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index b4dca0a00..1a573ffea 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -16,75 +16,99 @@ import (
"github.com/gin-gonic/gin"
)
-// EnvResolver should return the environment api url, optional access token, whether the env is enabled, and an error.
-type EnvResolver func(ctx context.Context, id string) (apiURL string, accessToken *string, enabled bool, err error)
-
-// NewEnvProxyMiddlewareWithParam returns a gin middleware that proxies requests whose environment id
-// is remote. paramName is the URL param key (e.g. "id") that contains the environment id when using
-// router groups; if that param is not present the middleware will attempt to auto-detect the id
-// by parsing the request path after the first "/environments/" segment.
-func NewEnvProxyMiddlewareWithParam(localID string, paramName string, resolver EnvResolver, envService *services.EnvironmentService) gin.HandlerFunc {
- m := &EnvironmentMiddleware{
- localID: localID,
- resolver: resolver,
- envService: envService,
- httpClient: &http.Client{
- Timeout: 60 * time.Second,
- },
- }
- return m.handle(paramName)
-}
+const (
+ environmentsPathMarker = "/environments/"
+ proxyTimeout = 60 * time.Second
+)
+// EnvResolver resolves an environment ID to its connection details.
+// Returns: apiURL, accessToken, enabled, error
+type EnvResolver func(ctx context.Context, id string) (string, *string, bool, error)
+
+// EnvironmentMiddleware proxies requests for remote environments to their respective agents.
type EnvironmentMiddleware struct {
localID string
+ paramName string
resolver EnvResolver
envService *services.EnvironmentService
httpClient *http.Client
}
-func (m *EnvironmentMiddleware) handle(paramName string) gin.HandlerFunc {
- return func(c *gin.Context) {
- envID := m.extractEnvironmentID(c, paramName)
+// NewEnvProxyMiddlewareWithParam creates middleware that proxies requests to remote environments.
+// - localID: the ID representing the local environment (requests to this ID are not proxied)
+// - paramName: the URL parameter name containing the environment ID (e.g., "id")
+// - resolver: function to resolve environment ID to connection details
+// - envService: environment service for additional lookups
+func NewEnvProxyMiddlewareWithParam(localID, paramName string, resolver EnvResolver, envService *services.EnvironmentService) gin.HandlerFunc {
+ m := &EnvironmentMiddleware{
+ localID: localID,
+ paramName: paramName,
+ resolver: resolver,
+ envService: envService,
+ httpClient: &http.Client{Timeout: proxyTimeout},
+ }
+ return m.Handle
+}
- if envID == "" || envID == m.localID {
- c.Next()
- return
- }
+// Handle is the main middleware handler.
+func (m *EnvironmentMiddleware) Handle(c *gin.Context) {
+ envID := m.extractEnvironmentID(c)
- apiURL, accessToken, enabled, err := m.resolver(c.Request.Context(), envID)
- if err != nil || apiURL == "" {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found"}})
- c.Abort()
- return
- }
- if !enabled {
- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Environment is disabled"}})
- c.Abort()
- return
- }
+ // Local environment or no environment - continue to next handler
+ if envID == "" || envID == m.localID {
+ c.Next()
+ return
+ }
- target := m.buildTargetURL(c, envID, apiURL)
+ // Resolve remote environment
+ apiURL, accessToken, enabled, err := m.resolver(c.Request.Context(), envID)
+ if err != nil || apiURL == "" {
+ c.JSON(http.StatusNotFound, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Environment not found"},
+ })
+ c.Abort()
+ return
+ }
- if m.isWebSocketRequest(c) {
- m.handleWebSocket(c, target, accessToken, envID)
- return
- }
+ if !enabled {
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Environment is disabled"},
+ })
+ c.Abort()
+ return
+ }
+
+ // Build target URL and proxy the request
+ target := m.buildTargetURL(c, envID, apiURL)
+ if m.isWebSocketUpgrade(c) {
+ m.proxyWebSocket(c, target, accessToken, envID)
+ } else {
m.proxyHTTP(c, target, accessToken)
}
}
-func (m *EnvironmentMiddleware) extractEnvironmentID(c *gin.Context, paramName string) string {
- envID := c.Param(paramName)
- if envID != "" {
+// extractEnvironmentID gets the environment ID from the request.
+// Only processes paths containing "/environments/" to avoid conflicts with other routes.
+func (m *EnvironmentMiddleware) extractEnvironmentID(c *gin.Context) string {
+ requestPath := c.Request.URL.Path
+
+ // Skip non-environment routes (e.g., /api-keys/{id})
+ if !strings.Contains(requestPath, environmentsPathMarker) {
+ return ""
+ }
+
+ // Try path parameter first
+ if envID := c.Param(m.paramName); envID != "" {
return envID
}
- const marker = "/environments/"
- if idx := strings.Index(c.Request.URL.Path, marker); idx >= 0 {
- rest := c.Request.URL.Path[idx+len(marker):]
- parts := strings.SplitN(rest, "/", 2)
- if len(parts) > 0 && parts[0] != "" {
+ // Fall back to parsing the URL path
+ if idx := strings.Index(requestPath, environmentsPathMarker); idx >= 0 {
+ rest := requestPath[idx+len(environmentsPathMarker):]
+ if parts := strings.SplitN(rest, "/", 2); len(parts) > 0 && parts[0] != "" {
return parts[0]
}
}
@@ -92,14 +116,19 @@ func (m *EnvironmentMiddleware) extractEnvironmentID(c *gin.Context, paramName s
return ""
}
+// buildTargetURL constructs the proxy target URL.
func (m *EnvironmentMiddleware) buildTargetURL(c *gin.Context, envID, apiURL string) string {
+ // Remove the environment prefix from the path
prefix := "/api/environments/" + envID
suffix := strings.TrimPrefix(c.Request.URL.Path, prefix)
- if !strings.HasPrefix(suffix, "/") && suffix != "" {
+ if suffix != "" && !strings.HasPrefix(suffix, "/") {
suffix = "/" + suffix
}
+ // Build target: apiURL + /api/environments/{localID} + suffix
target := strings.TrimRight(apiURL, "/") + path.Join("/api/environments/", m.localID) + suffix
+
+ // Append query string if present
if qs := c.Request.URL.RawQuery; qs != "" {
target += "?" + qs
}
@@ -107,78 +136,51 @@ func (m *EnvironmentMiddleware) buildTargetURL(c *gin.Context, envID, apiURL str
return target
}
-func (m *EnvironmentMiddleware) isWebSocketRequest(c *gin.Context) bool {
+// isWebSocketUpgrade checks if this is a WebSocket upgrade request.
+func (m *EnvironmentMiddleware) isWebSocketUpgrade(c *gin.Context) bool {
return strings.EqualFold(c.GetHeader("Upgrade"), "websocket") ||
strings.Contains(strings.ToLower(c.GetHeader("Connection")), "upgrade")
}
-func (m *EnvironmentMiddleware) handleWebSocket(c *gin.Context, target string, accessToken *string, envID string) {
- wsTarget := m.convertToWebSocketURL(target)
- hdr := m.buildWebSocketHeaders(c, accessToken)
+// proxyWebSocket handles WebSocket proxy requests.
+func (m *EnvironmentMiddleware) proxyWebSocket(c *gin.Context, target string, accessToken *string, envID string) {
+ wsTarget := httpToWebSocketURL(target)
+ headers := m.buildWebSocketHeaders(c, accessToken)
- if err := wsutil.ProxyHTTP(c.Writer, c.Request, wsTarget, hdr); err != nil {
+ if err := wsutil.ProxyHTTP(c.Writer, c.Request, wsTarget, headers); err != nil {
slog.Error("websocket proxy failed", "env_id", envID, "target", wsTarget, "err", err)
}
c.Abort()
}
-func (m *EnvironmentMiddleware) convertToWebSocketURL(target string) string {
- if strings.HasPrefix(target, "https://") {
- return "wss://" + strings.TrimPrefix(target, "https://")
- }
- if strings.HasPrefix(target, "http://") {
- return "ws://" + strings.TrimPrefix(target, "http://")
- }
- return target
-}
-
-func (m *EnvironmentMiddleware) buildWebSocketHeaders(c *gin.Context, accessToken *string) http.Header {
- hdr := http.Header{}
-
- // Forward API key header if present
- if apiKey := c.GetHeader("X-Api-Token"); apiKey != "" {
- hdr.Set("X-Api-Token", apiKey)
- }
-
- if auth := c.GetHeader("Authorization"); auth != "" {
- hdr.Set("Authorization", auth)
- } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {
- hdr.Set("Authorization", "Bearer "+cookieToken)
- }
-
- if hdr.Get("Authorization") == "" && hdr.Get("X-Api-Token") == "" {
- if cookieHeader := c.Request.Header.Get("Cookie"); cookieHeader != "" {
- hdr.Set("Cookie", cookieHeader)
- }
- }
-
- if accessToken != nil && *accessToken != "" {
- hdr.Set("X-Arcane-Agent-Token", *accessToken)
- }
-
- return hdr
-}
-
+// proxyHTTP handles standard HTTP proxy requests.
func (m *EnvironmentMiddleware) proxyHTTP(c *gin.Context, target string, accessToken *string) {
req, err := m.createProxyRequest(c, target, accessToken)
if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to create proxy request"}})
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to create proxy request"},
+ })
c.Abort()
return
}
resp, err := m.httpClient.Do(req)
if err != nil {
- c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": fmt.Sprintf("Proxy request failed: %v", err)}})
+ c.JSON(http.StatusBadGateway, gin.H{
+ "success": false,
+ "data": gin.H{"error": fmt.Sprintf("Proxy request failed: %v", err)},
+ })
c.Abort()
return
}
defer resp.Body.Close()
- m.copyResponseToClient(c, resp)
+ m.writeProxyResponse(c, resp)
c.Abort()
}
+// createProxyRequest builds the HTTP request to forward to the remote environment.
func (m *EnvironmentMiddleware) createProxyRequest(c *gin.Context, target string, accessToken *string) (*http.Request, error) {
req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, target, c.Request.Body)
if err != nil {
@@ -194,12 +196,56 @@ func (m *EnvironmentMiddleware) createProxyRequest(c *gin.Context, target string
return req, nil
}
-func (m *EnvironmentMiddleware) copyResponseToClient(c *gin.Context, resp *http.Response) {
- hop := remenv.BuildHopByHopHeaders(resp.Header)
- remenv.CopyResponseHeaders(resp.Header, c.Writer.Header(), hop)
+// writeProxyResponse copies the proxy response back to the client.
+func (m *EnvironmentMiddleware) writeProxyResponse(c *gin.Context, resp *http.Response) {
+ hopByHop := remenv.BuildHopByHopHeaders(resp.Header)
+ remenv.CopyResponseHeaders(resp.Header, c.Writer.Header(), hopByHop)
c.Status(resp.StatusCode)
if c.Request.Method != http.MethodHead {
_, _ = io.Copy(c.Writer, resp.Body)
}
}
+
+// buildWebSocketHeaders creates headers for WebSocket proxy requests.
+func (m *EnvironmentMiddleware) buildWebSocketHeaders(c *gin.Context, accessToken *string) http.Header {
+ headers := http.Header{}
+
+ // Forward API key if present
+ if apiKey := c.GetHeader("X-Api-Key"); apiKey != "" {
+ headers.Set("X-Api-Key", apiKey)
+ }
+
+ // Forward authorization (header or cookie)
+ if auth := c.GetHeader("Authorization"); auth != "" {
+ headers.Set("Authorization", auth)
+ } else if token, err := c.Cookie("token"); err == nil && token != "" {
+ headers.Set("Authorization", "Bearer "+token)
+ }
+
+ // Forward cookies if no other auth is present
+ if headers.Get("Authorization") == "" && headers.Get("X-Api-Token") == "" {
+ if cookies := c.Request.Header.Get("Cookie"); cookies != "" {
+ headers.Set("Cookie", cookies)
+ }
+ }
+
+ // Set agent token for remote environment authentication
+ if accessToken != nil && *accessToken != "" {
+ headers.Set("X-Arcane-Agent-Token", *accessToken)
+ }
+
+ return headers
+}
+
+// httpToWebSocketURL converts an HTTP(S) URL to WS(S).
+func httpToWebSocketURL(url string) string {
+ switch {
+ case strings.HasPrefix(url, "https://"):
+ return "wss://" + strings.TrimPrefix(url, "https://")
+ case strings.HasPrefix(url, "http://"):
+ return "ws://" + strings.TrimPrefix(url, "http://")
+ default:
+ return url
+ }
+}
diff --git a/backend/internal/services/api_key_service.go b/backend/internal/services/api_key_service.go
index e6ba7d38d..888e91440 100644
--- a/backend/internal/services/api_key_service.go
+++ b/backend/internal/services/api_key_service.go
@@ -58,7 +58,7 @@ func (s *ApiKeyService) validateApiKeyHash(hash, key string) error {
return s.userService.ValidatePassword(hash, key)
}
-func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req apikey.Create) (*apikey.ApiKeyCreatedDto, error) {
+func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, req apikey.CreateApiKey) (*apikey.ApiKeyCreatedDto, error) {
rawKey, err := s.generateApiKey()
if err != nil {
return nil, err
@@ -157,7 +157,7 @@ func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.Query
return result, paginationResp, nil
}
-func (s *ApiKeyService) UpdateApiKey(ctx context.Context, id string, req apikey.Update) (*apikey.ApiKey, error) {
+func (s *ApiKeyService) UpdateApiKey(ctx context.Context, id string, req apikey.UpdateApiKey) (*apikey.ApiKey, error) {
var ak models.ApiKey
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index fc58d4b06..742a2ec37 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -61,7 +61,7 @@ func (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]mode
return registries, nil
}
-func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, params pagination.QueryParams) ([]containerregistry.Response, pagination.Response, error) {
+func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, params pagination.QueryParams) ([]containerregistry.ContainerRegistry, pagination.Response, error) {
var registries []models.ContainerRegistry
q := s.db.WithContext(ctx).Model(&models.ContainerRegistry{})
@@ -96,7 +96,7 @@ func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, p
return nil, pagination.Response{}, fmt.Errorf("failed to paginate container registries: %w", err)
}
- out, mapErr := mapper.MapSlice[models.ContainerRegistry, containerregistry.Response](registries)
+ out, mapErr := mapper.MapSlice[models.ContainerRegistry, containerregistry.ContainerRegistry](registries)
if mapErr != nil {
return nil, pagination.Response{}, fmt.Errorf("failed to map registries: %w", mapErr)
}
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 969118e4c..4c7f173c6 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -407,15 +407,15 @@ func (s *ContainerService) readAllLogs(logs io.ReadCloser, logsChan chan<- strin
return nil
}
-func (s *ContainerService) ListContainersPaginated(ctx context.Context, params pagination.QueryParams, includeAll bool) ([]containertypes.Summary, pagination.Response, error) {
+func (s *ContainerService) ListContainersPaginated(ctx context.Context, params pagination.QueryParams, includeAll bool) ([]containertypes.Summary, pagination.Response, containertypes.StatusCounts, error) {
dockerClient, err := s.dockerService.GetClient()
if err != nil {
- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)
+ return nil, pagination.Response{}, containertypes.StatusCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)
}
dockerContainers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: includeAll})
if err != nil {
- return nil, pagination.Response{}, fmt.Errorf("failed to list Docker containers: %w", err)
+ return nil, pagination.Response{}, containertypes.StatusCounts{}, fmt.Errorf("failed to list Docker containers: %w", err)
}
items := make([]containertypes.Summary, 0, len(dockerContainers))
@@ -485,6 +485,18 @@ func (s *ContainerService) ListContainersPaginated(ctx context.Context, params p
result := pagination.SearchOrderAndPaginate(items, params, config)
+ // Calculate status counts from items (before pagination)
+ counts := containertypes.StatusCounts{
+ TotalContainers: len(items),
+ }
+ for _, c := range items {
+ if c.State == "running" {
+ counts.RunningContainers++
+ } else {
+ counts.StoppedContainers++
+ }
+ }
+
totalPages := int64(0)
if params.Limit > 0 {
totalPages = (int64(result.TotalCount) + int64(params.Limit) - 1) / int64(params.Limit)
@@ -503,7 +515,7 @@ func (s *ContainerService) ListContainersPaginated(ctx context.Context, params p
GrandTotalItems: int64(result.TotalAvailable),
}
- return result.Items, paginationResp, nil
+ return result.Items, paginationResp, counts, nil
}
// CreateExec creates an exec instance in the container
diff --git a/backend/internal/services/docker_client_service.go b/backend/internal/services/docker_client_service.go
index 00f781a15..013e3b6d9 100644
--- a/backend/internal/services/docker_client_service.go
+++ b/backend/internal/services/docker_client_service.go
@@ -105,7 +105,7 @@ func (s *DockerClientService) GetAllImages(ctx context.Context) ([]image.Summary
return images, inuse, unused, total, nil
}
-func (s *DockerClientService) GetAllNetworks(ctx context.Context) (_ []network.Summary, totalNetworks int, inuseNetworks int, unusedNetworks int, error error) {
+func (s *DockerClientService) GetAllNetworks(ctx context.Context) (_ []network.Summary, inuseNetworks int, unusedNetworks int, totalNetworks int, error error) {
dockerClient, err := s.GetClient()
if err != nil {
return nil, 0, 0, 0, fmt.Errorf("failed to connect to Docker: %w", err)
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 6d018e832..8e9558bc0 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -97,7 +97,7 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)
return &environment, nil
}
-func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams) ([]environment.Response, pagination.Response, error) {
+func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, params pagination.QueryParams) ([]environment.Environment, pagination.Response, error) {
var envs []models.Environment
q := s.db.WithContext(ctx).Model(&models.Environment{})
@@ -126,7 +126,7 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, para
return nil, pagination.Response{}, fmt.Errorf("failed to paginate environments: %w", err)
}
- out, mapErr := mapper.MapSlice[models.Environment, environment.Response](envs)
+ out, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)
if mapErr != nil {
return nil, pagination.Response{}, fmt.Errorf("failed to map environments: %w", mapErr)
}
diff --git a/backend/internal/services/event_service.go b/backend/internal/services/event_service.go
index 36c2cd382..61a9e2fc5 100644
--- a/backend/internal/services/event_service.go
+++ b/backend/internal/services/event_service.go
@@ -77,7 +77,7 @@ func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest)
return event, nil
}
-func (s *EventService) CreateEventFromDto(ctx context.Context, req event.Create) (*event.Response, error) {
+func (s *EventService) CreateEventFromDto(ctx context.Context, req event.CreateEvent) (*event.Event, error) {
severity := models.EventSeverity(req.Severity)
if severity == "" {
severity = models.EventSeverityInfo
@@ -110,7 +110,7 @@ func (s *EventService) CreateEventFromDto(ctx context.Context, req event.Create)
return s.toEventDto(event), nil
}
-func (s *EventService) ListEventsPaginated(ctx context.Context, params pagination.QueryParams) ([]event.Response, pagination.Response, error) {
+func (s *EventService) ListEventsPaginated(ctx context.Context, params pagination.QueryParams) ([]event.Event, pagination.Response, error) {
var events []models.Event
q := s.db.WithContext(ctx).Model(&models.Event{})
@@ -143,7 +143,7 @@ func (s *EventService) ListEventsPaginated(ctx context.Context, params paginatio
return nil, pagination.Response{}, fmt.Errorf("failed to paginate events: %w", err)
}
- eventDtos, mapErr := mapper.MapSlice[models.Event, event.Response](events)
+ eventDtos, mapErr := mapper.MapSlice[models.Event, event.Event](events)
if mapErr != nil {
return nil, pagination.Response{}, fmt.Errorf("failed to map events: %w", mapErr)
}
@@ -151,7 +151,7 @@ func (s *EventService) ListEventsPaginated(ctx context.Context, params paginatio
return eventDtos, paginationResp, nil
}
-func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]event.Response, pagination.Response, error) {
+func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]event.Event, pagination.Response, error) {
var events []models.Event
q := s.db.WithContext(ctx).Model(&models.Event{}).Where("environment_id = ?", environmentID)
@@ -181,7 +181,7 @@ func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, envi
return nil, pagination.Response{}, fmt.Errorf("failed to paginate events: %w", err)
}
- eventDtos, mapErr := mapper.MapSlice[models.Event, event.Response](events)
+ eventDtos, mapErr := mapper.MapSlice[models.Event, event.Event](events)
if mapErr != nil {
return nil, pagination.Response{}, fmt.Errorf("failed to map events: %w", mapErr)
}
@@ -429,13 +429,13 @@ var eventDefinitions = map[models.EventType]struct {
models.EventTypeUserLogout: {"User logged out: %s", "User '%s' has logged out", models.EventSeverityInfo},
}
-func (s *EventService) toEventDto(e *models.Event) *event.Response {
+func (s *EventService) toEventDto(e *models.Event) *event.Event {
var metadata map[string]interface{}
if e.Metadata != nil {
metadata = map[string]interface{}(e.Metadata)
}
- return &event.Response{
+ return &event.Event{
ID: e.ID,
Type: string(e.Type),
Severity: string(e.Severity),
diff --git a/backend/internal/services/network_service.go b/backend/internal/services/network_service.go
index 222db9921..198ad8469 100644
--- a/backend/internal/services/network_service.go
+++ b/backend/internal/services/network_service.go
@@ -123,17 +123,34 @@ func (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneRepor
return &report, nil
}
-func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagination.QueryParams) ([]networktypes.Summary, pagination.Response, error) {
+func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagination.QueryParams) ([]networktypes.Summary, pagination.Response, networktypes.UsageCounts, error) {
dockerClient, err := s.dockerService.GetClient()
if err != nil {
- return nil, pagination.Response{}, fmt.Errorf("failed to connect to Docker: %w", err)
+ return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)
}
containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})
if err != nil {
- return nil, pagination.Response{}, fmt.Errorf("failed to list containers: %w", err)
+ return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to list containers: %w", err)
}
+ inUseByID, inUseByName := s.buildNetworkUsageMaps(containers)
+
+ rawNets, err := dockerClient.NetworkList(ctx, network.ListOptions{})
+ if err != nil {
+ return nil, pagination.Response{}, networktypes.UsageCounts{}, fmt.Errorf("failed to list Docker networks: %w", err)
+ }
+
+ items := s.convertToNetworkSummaries(rawNets, inUseByID, inUseByName)
+ config := s.buildNetworkPaginationConfig()
+ result := pagination.SearchOrderAndPaginate(items, params, config)
+ counts := s.calculateNetworkUsageCounts(items)
+ paginationResp := s.buildPaginationResponse(result, params)
+
+ return result.Items, paginationResp, counts, nil
+}
+
+func (s *NetworkService) buildNetworkUsageMaps(containers []container.Summary) (map[string]bool, map[string]bool) {
inUseByID := make(map[string]bool)
inUseByName := make(map[string]bool)
for _, c := range containers {
@@ -147,12 +164,10 @@ func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagin
inUseByName[netName] = true
}
}
+ return inUseByID, inUseByName
+}
- rawNets, err := dockerClient.NetworkList(ctx, network.ListOptions{})
- if err != nil {
- return nil, pagination.Response{}, fmt.Errorf("failed to list Docker networks: %w", err)
- }
-
+func (s *NetworkService) convertToNetworkSummaries(rawNets []network.Summary, inUseByID, inUseByName map[string]bool) []networktypes.Summary {
items := make([]networktypes.Summary, 0, len(rawNets))
for _, n := range rawNets {
netDto := networktypes.NewSummary(n)
@@ -160,76 +175,101 @@ func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagin
netDto.IsDefault = dockerutil.IsDefaultNetwork(netDto.Name)
items = append(items, netDto)
}
+ return items
+}
- config := pagination.Config[networktypes.Summary]{
+func (s *NetworkService) buildNetworkPaginationConfig() pagination.Config[networktypes.Summary] {
+ return pagination.Config[networktypes.Summary]{
SearchAccessors: []pagination.SearchAccessor[networktypes.Summary]{
func(n networktypes.Summary) (string, error) { return n.Name, nil },
func(n networktypes.Summary) (string, error) { return n.Driver, nil },
func(n networktypes.Summary) (string, error) { return n.Scope, nil },
func(n networktypes.Summary) (string, error) { return n.ID, nil },
},
- SortBindings: []pagination.SortBinding[networktypes.Summary]{
- {
- Key: "name",
- Fn: func(a, b networktypes.Summary) int {
- return strings.Compare(a.Name, b.Name)
- },
- },
- {
- Key: "driver",
- Fn: func(a, b networktypes.Summary) int {
- return strings.Compare(a.Driver, b.Driver)
- },
- },
- {
- Key: "scope",
- Fn: func(a, b networktypes.Summary) int {
- return strings.Compare(a.Scope, b.Scope)
- },
- },
- {
- Key: "created",
- Fn: func(a, b networktypes.Summary) int {
- if a.Created.Before(b.Created) {
- return -1
- }
- if a.Created.After(b.Created) {
- return 1
- }
- return 0
- },
- },
- {
- Key: "inUse",
- Fn: func(a, b networktypes.Summary) int {
- if a.InUse == b.InUse {
- return 0
- }
- if a.InUse {
- return -1
- }
- return 1
- },
- },
+ SortBindings: s.buildNetworkSortBindings(),
+ FilterAccessors: s.buildNetworkFilterAccessors(),
+ }
+}
+
+func (s *NetworkService) buildNetworkSortBindings() []pagination.SortBinding[networktypes.Summary] {
+ return []pagination.SortBinding[networktypes.Summary]{
+ {
+ Key: "name",
+ Fn: func(a, b networktypes.Summary) int { return strings.Compare(a.Name, b.Name) },
},
- FilterAccessors: []pagination.FilterAccessor[networktypes.Summary]{
- {
- Key: "inUse",
- Fn: func(n networktypes.Summary, filterValue string) bool {
- if filterValue == "true" {
- return n.InUse
- }
- if filterValue == "false" {
- return !n.InUse
- }
- return true
- },
+ {
+ Key: "driver",
+ Fn: func(a, b networktypes.Summary) int { return strings.Compare(a.Driver, b.Driver) },
+ },
+ {
+ Key: "scope",
+ Fn: func(a, b networktypes.Summary) int { return strings.Compare(a.Scope, b.Scope) },
+ },
+ {
+ Key: "created",
+ Fn: s.compareNetworkCreated,
+ },
+ {
+ Key: "inUse",
+ Fn: s.compareNetworkInUse,
+ },
+ }
+}
+
+func (s *NetworkService) compareNetworkCreated(a, b networktypes.Summary) int {
+ if a.Created.Before(b.Created) {
+ return -1
+ }
+ if a.Created.After(b.Created) {
+ return 1
+ }
+ return 0
+}
+
+func (s *NetworkService) compareNetworkInUse(a, b networktypes.Summary) int {
+ if a.InUse == b.InUse {
+ return 0
+ }
+ if a.InUse {
+ return -1
+ }
+ return 1
+}
+
+func (s *NetworkService) buildNetworkFilterAccessors() []pagination.FilterAccessor[networktypes.Summary] {
+ return []pagination.FilterAccessor[networktypes.Summary]{
+ {
+ Key: "inUse",
+ Fn: func(n networktypes.Summary, filterValue string) bool {
+ if filterValue == "true" {
+ return n.InUse
+ }
+ if filterValue == "false" {
+ return !n.InUse
+ }
+ return true
},
},
}
+}
- result := pagination.SearchOrderAndPaginate(items, params, config)
+func (s *NetworkService) calculateNetworkUsageCounts(items []networktypes.Summary) networktypes.UsageCounts {
+ counts := networktypes.UsageCounts{
+ Total: len(items),
+ }
+ for _, n := range items {
+ if n.InUse {
+ counts.Inuse++
+ } else if !n.IsDefault {
+ // Only count non-default networks as unused
+ // Default networks (bridge, host, none, ingress) are never "unused"
+ counts.Unused++
+ }
+ }
+ return counts
+}
+func (s *NetworkService) buildPaginationResponse(result pagination.FilterResult[networktypes.Summary], params pagination.QueryParams) pagination.Response {
totalPages := int64(0)
if params.Limit > 0 {
totalPages = (int64(result.TotalCount) + int64(params.Limit) - 1) / int64(params.Limit)
@@ -240,13 +280,11 @@ func (s *NetworkService) ListNetworksPaginated(ctx context.Context, params pagin
page = (params.Start / params.Limit) + 1
}
- paginationResp := pagination.Response{
+ return pagination.Response{
TotalPages: totalPages,
TotalItems: int64(result.TotalCount),
CurrentPage: page,
ItemsPerPage: params.Limit,
GrandTotalItems: int64(result.TotalAvailable),
}
-
- return result.Items, paginationResp, nil
}
diff --git a/backend/internal/services/playwright_service.go b/backend/internal/services/playwright_service.go
index ad4ad6c54..cf47d2e2d 100644
--- a/backend/internal/services/playwright_service.go
+++ b/backend/internal/services/playwright_service.go
@@ -60,7 +60,7 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (
var createdKeys []*apikey.ApiKeyCreatedDto
for i := 0; i < count; i++ {
- req := apikey.Create{
+ req := apikey.CreateApiKey{
Name: fmt.Sprintf("test-api-key-%d", i+1),
Description: stringPtr(fmt.Sprintf("Test API key %d for Playwright tests", i+1)),
}
diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.go
index 6ae7a7f44..6203339a9 100644
--- a/backend/internal/services/updater_service.go
+++ b/backend/internal/services/updater_service.go
@@ -346,7 +346,7 @@ func (s *UpdaterService) pruneImageIDs(ctx context.Context, ids []string) error
return nil
}
-func (s *UpdaterService) GetStatus() map[string]any {
+func (s *UpdaterService) GetStatus() updater.Status {
containerIDs := make([]string, 0, len(s.updatingContainers))
for id := range s.updatingContainers {
containerIDs = append(containerIDs, id)
@@ -356,11 +356,11 @@ func (s *UpdaterService) GetStatus() map[string]any {
projectIDs = append(projectIDs, id)
}
- return map[string]any{
- "updatingContainers": len(s.updatingContainers),
- "updatingProjects": len(s.updatingProjects),
- "containerIds": containerIDs,
- "projectIds": projectIDs,
+ return updater.Status{
+ UpdatingContainers: len(s.updatingContainers),
+ UpdatingProjects: len(s.updatingProjects),
+ ContainerIds: containerIDs,
+ ProjectIds: projectIDs,
}
}
diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.go
index 2cfd3805e..9f748b573 100644
--- a/backend/internal/services/user_service.go
+++ b/backend/internal/services/user_service.go
@@ -324,7 +324,7 @@ func (s *UserService) UpgradePasswordHash(ctx context.Context, userID, password
})
}
-func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.QueryParams) ([]user.Response, pagination.Response, error) {
+func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.QueryParams) ([]user.User, pagination.Response, error) {
var users []models.User
query := s.db.WithContext(ctx).Model(&models.User{})
@@ -341,7 +341,7 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.
return nil, pagination.Response{}, fmt.Errorf("failed to paginate users: %w", err)
}
- result := make([]user.Response, len(users))
+ result := make([]user.User, len(users))
for i, u := range users {
result[i] = toUserResponseDto(u)
}
@@ -349,8 +349,8 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.
return result, paginationResp, nil
}
-func toUserResponseDto(u models.User) user.Response {
- return user.Response{
+func toUserResponseDto(u models.User) user.User {
+ return user.User{
ID: u.ID,
Username: u.Username,
DisplayName: u.DisplayName,
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index 8bb36a868..5dab153cf 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -206,6 +206,38 @@ func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool,
return inUse, containerIDs, nil
}
+// VolumeSizeData holds size information for a volume.
+type VolumeSizeData struct {
+ Size int64
+ RefCount int64
+}
+
+// GetVolumeSizes returns disk usage data for all volumes.
+// This is a slow operation as it calls Docker's DiskUsage API.
+func (s *VolumeService) GetVolumeSizes(ctx context.Context) (map[string]VolumeSizeData, error) {
+ dockerClient, err := s.dockerService.GetClient()
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
+ }
+
+ usageVolumes, err := docker.GetVolumeUsageData(ctx, dockerClient)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get volume usage data: %w", err)
+ }
+
+ result := make(map[string]VolumeSizeData, len(usageVolumes))
+ for _, v := range usageVolumes {
+ if v.UsageData != nil {
+ result[v.Name] = VolumeSizeData{
+ Size: v.UsageData.Size,
+ RefCount: v.UsageData.RefCount,
+ }
+ }
+ }
+
+ return result, nil
+}
+
func (s *VolumeService) enrichVolumesWithUsageData(volumes []*volume.Volume, usageVolumes []volume.Volume) []volume.Volume {
result := make([]volume.Volume, 0, len(volumes))
for _, v := range volumes {
@@ -370,27 +402,46 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params paginat
return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)
}
- volListBody, err := dockerClient.VolumeList(ctx, volume.ListOptions{})
- if err != nil {
- return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to list Docker volumes: %w", err)
+ // Run volume list and container list in parallel for better performance
+ type volumeListResult struct {
+ volumes []*volume.Volume
+ err error
}
-
- usageVolumes, duErr := docker.GetVolumeUsageData(ctx, dockerClient)
- if duErr != nil {
- slog.WarnContext(ctx, "failed to load volume usage data",
- slog.String("error", duErr.Error()))
- usageVolumes = nil
+ type containerMapResult struct {
+ containerMap map[string][]string
+ err error
}
- volumes := s.enrichVolumesWithUsageData(volListBody.Volumes, usageVolumes)
+ volChan := make(chan volumeListResult, 1)
+ containerChan := make(chan containerMapResult, 1)
- volumeContainerMap, err := s.buildVolumeContainerMap(ctx, dockerClient)
- if err != nil {
+ go func() {
+ volListBody, err := dockerClient.VolumeList(ctx, volume.ListOptions{})
+ volChan <- volumeListResult{volumes: volListBody.Volumes, err: err}
+ }()
+
+ go func() {
+ containerMap, err := s.buildVolumeContainerMap(ctx, dockerClient)
+ containerChan <- containerMapResult{containerMap: containerMap, err: err}
+ }()
+
+ // Wait for both results
+ volResult := <-volChan
+ if volResult.err != nil {
+ return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to list Docker volumes: %w", volResult.err)
+ }
+
+ containerResult := <-containerChan
+ volumeContainerMap := containerResult.containerMap
+ if containerResult.err != nil {
slog.WarnContext(ctx, "failed to build volume-container map",
- slog.String("error", err.Error()))
+ slog.String("error", containerResult.err.Error()))
volumeContainerMap = make(map[string][]string)
}
+ // Skip usage data - it's fetched separately via GetVolumeSizes endpoint for lazy loading
+ volumes := s.enrichVolumesWithUsageData(volResult.volumes, nil)
+
items := make([]volumetypes.Volume, 0, len(volumes))
for _, v := range volumes {
volDto := volumetypes.NewSummary(v)
diff --git a/backend/internal/utils/cookie/cookie_util.go b/backend/internal/utils/cookie/cookie_util.go
index 3db0187b8..e22e1126f 100644
--- a/backend/internal/utils/cookie/cookie_util.go
+++ b/backend/internal/utils/cookie/cookie_util.go
@@ -23,14 +23,6 @@ func tokenCookieName(c *gin.Context) string {
return InsecureTokenCookieName
}
-func CreateTokenCookie(c *gin.Context, maxAgeInSeconds int, token string) {
- if maxAgeInSeconds < 0 {
- maxAgeInSeconds = 0
- }
- name := tokenCookieName(c)
- c.SetCookie(name, token, maxAgeInSeconds, "/", "", isSecure(c), true)
-}
-
func ClearTokenCookie(c *gin.Context) {
name := tokenCookieName(c)
c.SetCookie(name, "", -1, "/", "", isSecure(c), true)
@@ -44,18 +36,64 @@ func GetTokenCookie(c *gin.Context) (string, error) {
return c.Cookie(InsecureTokenCookieName)
}
-func CreateOidcStateCookie(c *gin.Context, value string, maxAgeInSeconds int) {
- c.SetSameSite(http.SameSiteLaxMode)
+// BuildTokenCookieString builds a Set-Cookie header string for Huma handlers.
+// Uses the insecure cookie name since we can't detect TLS from context.
+// For secure contexts, the middleware should handle the __Host- prefix.
+func BuildTokenCookieString(maxAgeInSeconds int, token string) string {
if maxAgeInSeconds < 0 {
maxAgeInSeconds = 0
}
- c.SetCookie(OidcStateCookieName, value, maxAgeInSeconds, "/", "", c.Request.TLS != nil, true)
+ cookie := &http.Cookie{
+ Name: InsecureTokenCookieName,
+ Value: token,
+ Path: "/",
+ MaxAge: maxAgeInSeconds,
+ HttpOnly: true,
+ SameSite: http.SameSiteLaxMode,
+ }
+ return cookie.String()
}
-func GetOidcStateCookie(c *gin.Context) (string, error) {
- return c.Cookie(OidcStateCookieName)
+// BuildClearTokenCookieString builds a Set-Cookie header string to clear the token cookie.
+func BuildClearTokenCookieString() string {
+ cookie := &http.Cookie{
+ Name: InsecureTokenCookieName,
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ HttpOnly: true,
+ SameSite: http.SameSiteLaxMode,
+ }
+ return cookie.String()
}
-func ClearOidcStateCookie(c *gin.Context) {
- c.SetCookie(OidcStateCookieName, "", -1, "/", "", c.Request.TLS != nil, true)
+// BuildOidcStateCookieString builds a Set-Cookie header string for the OIDC state cookie.
+func BuildOidcStateCookieString(value string, maxAgeInSeconds int, secure bool) string {
+ if maxAgeInSeconds < 0 {
+ maxAgeInSeconds = 0
+ }
+ cookie := &http.Cookie{
+ Name: OidcStateCookieName,
+ Value: value,
+ Path: "/",
+ MaxAge: maxAgeInSeconds,
+ HttpOnly: true,
+ Secure: secure,
+ SameSite: http.SameSiteLaxMode,
+ }
+ return cookie.String()
+}
+
+// BuildClearOidcStateCookieString builds a Set-Cookie header string to clear the OIDC state cookie.
+func BuildClearOidcStateCookieString(secure bool) string {
+ cookie := &http.Cookie{
+ Name: OidcStateCookieName,
+ Value: "",
+ Path: "/",
+ MaxAge: -1,
+ HttpOnly: true,
+ Secure: secure,
+ SameSite: http.SameSiteLaxMode,
+ }
+ return cookie.String()
}
diff --git a/backend/internal/utils/http/cache.go b/backend/internal/utils/http/cache.go
deleted file mode 100644
index 06afb577a..000000000
--- a/backend/internal/utils/http/cache.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package http
-
-import (
- "strconv"
- "time"
-
- "github.com/gin-gonic/gin"
-)
-
-func SetCacheControlHeader(ctx *gin.Context, maxAge, staleWhileRevalidate time.Duration) {
- _, ok := ctx.GetQuery("skip-cache")
- if !ok {
- maxAgeSeconds := strconv.Itoa(int(maxAge.Seconds()))
- staleWhileRevalidateSeconds := strconv.Itoa(int(staleWhileRevalidate.Seconds()))
- ctx.Header("Cache-Control", "public, max-age="+maxAgeSeconds+", stale-while-revalidate="+staleWhileRevalidateSeconds)
- }
-
-}
diff --git a/backend/internal/utils/pagination/params.go b/backend/internal/utils/pagination/params.go
index 04392d7b4..fd3b69e63 100644
--- a/backend/internal/utils/pagination/params.go
+++ b/backend/internal/utils/pagination/params.go
@@ -36,8 +36,8 @@ func ExtractListModifiersQueryParams(c *gin.Context) QueryParams {
Search: search,
},
SortParams{
- sort: sortField,
- order: SortOrder(sortOrder),
+ Sort: sortField,
+ Order: SortOrder(sortOrder),
},
PaginationParams{
Start: start,
diff --git a/backend/internal/utils/pagination/reflect.go b/backend/internal/utils/pagination/reflect.go
index f6af7b09e..cbd6e76ce 100644
--- a/backend/internal/utils/pagination/reflect.go
+++ b/backend/internal/utils/pagination/reflect.go
@@ -10,8 +10,8 @@ import (
)
func PaginateAndSortDB(params QueryParams, query *gorm.DB, result interface{}) (Response, error) {
- sortColumn := params.sort
- sortDirection := string(params.order)
+ sortColumn := params.Sort
+ sortDirection := string(params.Order)
if sortDirection == "" {
sortDirection = "asc"
diff --git a/backend/internal/utils/pagination/sort.go b/backend/internal/utils/pagination/sort.go
index 64e1e7d1f..4585a9fe6 100644
--- a/backend/internal/utils/pagination/sort.go
+++ b/backend/internal/utils/pagination/sort.go
@@ -10,8 +10,8 @@ const (
)
type SortParams struct {
- sort string
- order SortOrder
+ Sort string
+ Order SortOrder
}
type SortOption[T any] func(a, b T) int
@@ -22,9 +22,9 @@ type SortBinding[T any] struct {
func sortFunction[T any](items []T, params SortParams, sorts []SortBinding[T]) []T {
for _, sort := range sorts {
- if sort.Key == params.sort {
+ if sort.Key == params.Sort {
fn := sort.Fn
- if params.order == SortDesc {
+ if params.Order == SortDesc {
fn = reverSortFn(fn)
}
slices.SortStableFunc(items, fn)
diff --git a/docker/Dockerfile b/docker/Dockerfile
index 0f8db9ba6..8e3f1911f 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -4,11 +4,21 @@ ARG BUILD_TAGS=""
# Stage 1: Build Frontend
FROM --platform=$BUILDPLATFORM node:25-trixie-slim AS frontend-builder
RUN npm install -g --force [email protected] && corepack enable
+ENV PNPM_HOME="/pnpm"
+ENV PATH="$PNPM_HOME:$PATH"
+ENV CI=true
WORKDIR /build
-COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
-COPY frontend/package.json ./frontend/package.json
+
+COPY pnpm-lock.yaml pnpm-workspace.yaml ./
+
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
+ pnpm fetch
+
+COPY package.json ./
COPY frontend ./frontend
-RUN --mount=type=cache,target=/root/.pnpm-store pnpm -C frontend install --frozen-lockfile
+
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
+ pnpm install -r --offline
ENV BUILD_PATH=dist
RUN pnpm -C frontend build
@@ -22,14 +32,15 @@ WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl git tzdata jq \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
-COPY ./.arcane.json ./arcane.json
-COPY ./go.work ./go.work
-COPY ./types ./types
-COPY ./cli ./cli
-COPY ./backend/go.mod ./backend/go.sum ./backend/
+COPY go.work ./
+COPY types ./types
+COPY cli ./cli
+COPY backend/go.mod backend/go.sum ./backend/
WORKDIR /build/backend
RUN --mount=type=cache,target=/go/pkg/mod go mod download
-COPY ./backend ./
+COPY backend ./
+COPY .arcane.json ../arcane.json
+
COPY --from=frontend-builder /build/frontend/dist ./frontend/dist
RUN --mount=type=cache,target=/root/.cache/go-build \
VERSION=$(jq -r '.version // "dev"' ../arcane.json) && \
diff --git a/docker/Dockerfile-agent b/docker/Dockerfile-agent
index c9dbb803c..50d8ecfce 100644
--- a/docker/Dockerfile-agent
+++ b/docker/Dockerfile-agent
@@ -10,15 +10,15 @@ WORKDIR /build
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates tzdata curl jq \
&& apt-get clean && rm -rf /var/lib/apt/lists/*
-COPY ./.arcane.json ./arcane.json
-COPY ./go.work ./go.work
-COPY ./types ./types
-COPY ./cli ./cli
-COPY ./backend/go.mod ./backend/go.sum ./backend/
+COPY go.work ./
+COPY types ./types
+COPY cli ./cli
+COPY backend/go.mod backend/go.sum ./backend/
WORKDIR /build/backend
-RUN go mod download
+RUN --mount=type=cache,target=/go/pkg/mod go mod download
-COPY ./backend ./
+COPY backend ./
+COPY .arcane.json ../arcane.json
RUN --mount=type=cache,target=/root/.cache/go-build \
VERSION=$(jq -r '.version // "dev"' ../arcane.json) && \
diff --git a/docker/Dockerfile.dev b/docker/Dockerfile.dev
index 99fefffaa..1fed770fb 100644
--- a/docker/Dockerfile.dev
+++ b/docker/Dockerfile.dev
@@ -7,22 +7,24 @@ RUN npm install -g --force corepack && corepack enable pnpm
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
+ENV CI=true
WORKDIR /app
-# Copy lockfile first for better layer caching
-COPY pnpm-lock.yaml ./
+# pnpm fetch only requires lockfile
+COPY pnpm-lock.yaml pnpm-workspace.yaml ./
# Fetch dependencies with cache mount
-RUN --mount=type=cache,target=/pnpm/store \
- pnpm fetch --frozen-lockfile
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
+ pnpm fetch
-# Copy package files and install
-COPY package.json pnpm-workspace.yaml ./
-COPY frontend/package.json ./frontend/package.json
+# Copy package files and frontend source
+COPY package.json ./
+COPY frontend ./frontend
-RUN --mount=type=cache,target=/pnpm/store \
- pnpm install --frozen-lockfile --offline
+# Install from the store (offline)
+RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
+ pnpm install -r --offline
ENV NODE_ENV=development \
PORT=3000
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index a307d4810..e66ef9c3b 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1403,7 +1403,7 @@
"api_key_important_warning": "This is the only time you will see this key. Make sure to copy it and store it securely.",
"api_key_copied_success": "API key copied to clipboard",
"api_key_page_title": "API Keys",
- "api_key_page_description": "Manage API keys for programmatic access to Arcane",
+ "api_key_page_description": "Manage API keys for programmatic access to Arcane. View the <a href=\"/api/docs\" target=\"_blank\" class=\"text-primary hover:underline\">API Reference</a> for usage details.",
"api_key_updated_success": "API key \"{name}\" updated successfully",
"api_key_update_failed": "Failed to update API key \"{name}\"",
"api_key_created_success": "API key \"{name}\" created successfully",
@@ -1418,5 +1418,6 @@
"api_key_bulk_delete_failed": "Failed to delete {count} API key(s)",
"common_done": "Done",
"common_important": "Important",
- "select_a_date": "Select a date"
+ "select_a_date": "Select a date",
+ "api_reference": "API Reference"
}
diff --git a/frontend/package.json b/frontend/package.json
index b2b949ab8..2b12c18a9 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -51,7 +51,6 @@
"@sveltejs/vite-plugin-svelte": "^6.2.1",
"@tailwindcss/vite": "^4.1.16",
"@types/bytes": "^3.1.5",
- "@types/dockerode": "^3.3.47",
"@types/js-yaml": "^4.0.9",
"@types/node": "^24.10.1",
"bits-ui": "^2.14.4",
diff --git a/frontend/src/lib/components/dialogs/create-container-dialog.svelte b/frontend/src/lib/components/dialogs/create-container-dialog.svelte
index e983e5c48..6e1a1ab2d 100644
--- a/frontend/src/lib/components/dialogs/create-container-dialog.svelte
+++ b/frontend/src/lib/components/dialogs/create-container-dialog.svelte
@@ -18,7 +18,7 @@
import DatabaseIcon from '@lucide/svelte/icons/database';
import ShieldIcon from '@lucide/svelte/icons/shield';
import SettingsIcon from '@lucide/svelte/icons/settings';
- import type { ContainerCreateOptions } from 'dockerode';
+ import type { ContainerCreateRequest } from '$lib/types/container.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import SelectWithLabel from '../form/select-with-label.svelte';
@@ -26,7 +26,7 @@
type CreateContainerFormProps = {
open: boolean;
- onSubmit: (data: ContainerCreateOptions) => void;
+ onSubmit: (data: ContainerCreateRequest) => void;
isLoading: boolean;
availableImages?: string[];
availableNetworks?: string[];
@@ -211,11 +211,11 @@
});
// Parse port bindings
- const dynamicPortBindings: Record<string, Array<{ HostPort: string }>> = {};
+ const dynamicPortBindings: Record<string, Array<{ hostPort: string }>> = {};
portMappings.forEach((mapping) => {
if (mapping.container.trim() && mapping.host.trim()) {
const containerPort = `${mapping.container.trim()}/${mapping.protocol}`;
- dynamicPortBindings[containerPort] = [{ HostPort: mapping.host.trim() }];
+ dynamicPortBindings[containerPort] = [{ hostPort: mapping.host.trim() }];
}
});
@@ -241,34 +241,27 @@
const labels = parseKeyValuePairs(data.labels || '');
const exposedPorts = parsePortList(data.exposedPorts || '');
- const options: ContainerCreateOptions = {
+ const options: ContainerCreateRequest = {
name: data.containerName.trim(),
- Image: data.image.trim(),
- Cmd: data.command.trim() ? data.command.trim().split(' ') : undefined,
- WorkingDir: data.workingDir.trim() || undefined,
- User: data.user.trim() || undefined,
- Hostname: data.hostname.trim() || undefined,
- Domainname: data.domainname.trim() || undefined,
- AttachStdout: data.attachStdout,
- AttachStderr: data.attachStderr,
- AttachStdin: data.attachStdin,
- Tty: data.tty,
- OpenStdin: data.openStdin,
- StdinOnce: data.stdinOnce,
- Env: dynamicEnvVars.length > 0 ? dynamicEnvVars : undefined,
- Labels: Object.keys(labels).length > 0 ? labels : undefined,
- ExposedPorts: Object.keys(exposedPorts).length > 0 ? exposedPorts : undefined,
- HostConfig: {
- Binds: allBinds.length > 0 ? allBinds : undefined,
- PortBindings: Object.keys(dynamicPortBindings).length > 0 ? dynamicPortBindings : undefined,
- NetworkMode: data.networkDisabled ? 'none' : undefined,
- PublishAllPorts: data.publishAllPorts,
- Privileged: data.privileged,
- ReadonlyRootfs: data.readonlyRootfs,
- AutoRemove: data.autoRemove,
- RestartPolicy: {
- Name: data.restartPolicy,
- MaximumRetryCount: data.restartPolicy === 'on-failure' ? data.restartMaxRetries : undefined
+ image: data.image.trim(),
+ cmd: data.command.trim() ? data.command.trim().split(' ') : undefined,
+ workingDir: data.workingDir.trim() || undefined,
+ user: data.user.trim() || undefined,
+ tty: data.tty,
+ openStdin: data.openStdin,
+ stdinOnce: data.stdinOnce,
+ env: dynamicEnvVars.length > 0 ? dynamicEnvVars : undefined,
+ labels: Object.keys(labels).length > 0 ? labels : undefined,
+ exposedPorts: Object.keys(exposedPorts).length > 0 ? exposedPorts : undefined,
+ hostConfig: {
+ binds: allBinds.length > 0 ? allBinds : undefined,
+ portBindings: Object.keys(dynamicPortBindings).length > 0 ? dynamicPortBindings : undefined,
+ networkMode: data.networkDisabled ? 'none' : undefined,
+ privileged: data.privileged,
+ autoRemove: data.autoRemove,
+ restartPolicy: {
+ name: data.restartPolicy as 'no' | 'always' | 'on-failure' | 'unless-stopped',
+ maximumRetryCount: data.restartPolicy === 'on-failure' ? data.restartMaxRetries : undefined
}
}
};
diff --git a/frontend/src/lib/components/logs/log-viewer.svelte b/frontend/src/lib/components/logs/log-viewer.svelte
index 02b9dc086..40946284d 100644
--- a/frontend/src/lib/components/logs/log-viewer.svelte
+++ b/frontend/src/lib/components/logs/log-viewer.svelte
@@ -147,8 +147,8 @@
const envId = currentEnv?.id || 'local';
const basePath =
type === 'project'
- ? `/api/environments/${envId}/projects/${projectId}/logs/ws`
- : `/api/environments/${envId}/containers/${containerId}/logs/ws`;
+ ? `/api/environments/${envId}/ws/projects/${projectId}/logs`
+ : `/api/environments/${envId}/ws/containers/${containerId}/logs`;
return buildWebSocketEndpoint(`${basePath}?follow=true&tail=${tailLines}&timestamps=true&format=json&batched=true`);
}
diff --git a/frontend/src/lib/components/sheets/create-network-sheet.svelte b/frontend/src/lib/components/sheets/create-network-sheet.svelte
index abeed9390..8e4f45783 100644
--- a/frontend/src/lib/components/sheets/create-network-sheet.svelte
+++ b/frontend/src/lib/components/sheets/create-network-sheet.svelte
@@ -9,7 +9,7 @@
import { Spinner } from '$lib/components/ui/spinner/index.js';
import NetworkIcon from '@lucide/svelte/icons/network';
import XIcon from '@lucide/svelte/icons/x';
- import type { NetworkCreateOptions } from 'dockerode';
+ import type { NetworkCreateOptions } from '$lib/types/network.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import SelectWithLabel from '../form/select-with-label.svelte';
@@ -17,7 +17,7 @@
type CreateNetworkFormProps = {
open: boolean;
- onSubmit: (data: NetworkCreateOptions) => void;
+ onSubmit: (name: string, options: NetworkCreateOptions) => void;
isLoading: boolean;
};
@@ -109,34 +109,33 @@
const driverOptions = parseKeyValuePairs(data.driverOptions || '');
const options: NetworkCreateOptions = {
- Name: data.networkName.trim(),
- Driver: data.networkDriver,
- CheckDuplicate: data.checkDuplicate,
- Internal: data.internal,
- Labels: Object.keys(finalLabels).length > 0 ? finalLabels : undefined,
- Options: Object.keys(driverOptions).length > 0 ? driverOptions : undefined
+ driver: data.networkDriver,
+ checkDuplicate: data.checkDuplicate,
+ internal: data.internal,
+ labels: Object.keys(finalLabels).length > 0 ? finalLabels : undefined,
+ options: Object.keys(driverOptions).length > 0 ? driverOptions : undefined
};
// Add IPAM configuration if enabled
if (data.enableIpam && (data.subnet?.trim() || data.gateway?.trim())) {
- const ipamConfig: { Subnet?: string; Gateway?: string } = {};
+ const ipamConfig: { subnet?: string; gateway?: string } = {};
if (data.subnet?.trim()) {
- ipamConfig.Subnet = data.subnet.trim();
+ ipamConfig.subnet = data.subnet.trim();
}
if (data.gateway?.trim()) {
- ipamConfig.Gateway = data.gateway.trim();
+ ipamConfig.gateway = data.gateway.trim();
}
if (Object.keys(ipamConfig).length > 0) {
- options.IPAM = {
- Driver: 'default',
- Config: [ipamConfig]
+ options.ipam = {
+ driver: 'default',
+ config: [ipamConfig]
};
}
}
- onSubmit(options);
+ onSubmit(data.networkName.trim(), options);
}
function handleOpenChange(newOpenState: boolean) {
diff --git a/frontend/src/lib/components/sheets/create-volume-sheet.svelte b/frontend/src/lib/components/sheets/create-volume-sheet.svelte
index 8d130d3f7..397d520f9 100644
--- a/frontend/src/lib/components/sheets/create-volume-sheet.svelte
+++ b/frontend/src/lib/components/sheets/create-volume-sheet.svelte
@@ -5,7 +5,7 @@
import * as Accordion from '$lib/components/ui/accordion/index.js';
import { Spinner } from '$lib/components/ui/spinner/index.js';
import HardDriveIcon from '@lucide/svelte/icons/hard-drive';
- import type { VolumeCreateOptions } from 'dockerode';
+ import type { VolumeCreateRequest } from '$lib/types/volume.type';
import { z } from 'zod/v4';
import { createForm, preventDefault } from '$lib/utils/form.utils';
import SelectWithLabel from '../form/select-with-label.svelte';
@@ -13,7 +13,7 @@
type CreateVolumeFormProps = {
open: boolean;
- onSubmit: (data: VolumeCreateOptions) => void;
+ onSubmit: (data: VolumeCreateRequest) => void;
isLoading: boolean;
};
@@ -71,11 +71,11 @@
const driverOpts = parseKeyValuePairs(data.volumeOptText || '');
const labels = parseKeyValuePairs(data.volumeLabels || '');
- const volumeOptions: VolumeCreateOptions = {
- Name: data.volumeName.trim(),
- Driver: data.volumeDriver,
- DriverOpts: Object.keys(driverOpts).length ? driverOpts : undefined,
- Labels: Object.keys(labels).length ? labels : undefined
+ const volumeOptions: VolumeCreateRequest = {
+ name: data.volumeName.trim(),
+ driver: data.volumeDriver,
+ driverOpts: Object.keys(driverOpts).length ? driverOpts : undefined,
+ labels: Object.keys(labels).length ? labels : undefined
};
onSubmit(volumeOptions);
diff --git a/frontend/src/lib/layouts/settings-page-layout.svelte b/frontend/src/lib/layouts/settings-page-layout.svelte
index a6b8269ab..dc810ec81 100644
--- a/frontend/src/lib/layouts/settings-page-layout.svelte
+++ b/frontend/src/lib/layouts/settings-page-layout.svelte
@@ -162,7 +162,7 @@
</div>
</div>
{#if description}
- <p class="text-muted-foreground mt-1 text-sm sm:text-base">{description}</p>
+ <p class="text-muted-foreground mt-1 text-sm sm:text-base">{@html description}</p>
{/if}
</div>
</div>
diff --git a/frontend/src/lib/services/api-service.ts b/frontend/src/lib/services/api-service.ts
index 75b3b066d..a8c3cc88d 100644
--- a/frontend/src/lib/services/api-service.ts
+++ b/frontend/src/lib/services/api-service.ts
@@ -7,7 +7,8 @@ function extractServerMessage(data: any, includeErrors = false): string | undefi
return inner;
}
if (inner) {
- const msg = inner.error || inner.message || inner.error_description;
+ // Support both old format (error/message) and Huma RFC 7807 format (detail)
+ const msg = inner.error || inner.message || inner.detail || inner.error_description;
if (msg) return msg;
if (includeErrors && Array.isArray(inner.errors) && inner.errors.length) {
return inner.errors[0]?.message || inner.errors[0];
diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.ts
index 178117f99..608a643e4 100644
--- a/frontend/src/lib/services/container-service.ts
+++ b/frontend/src/lib/services/container-service.ts
@@ -1,12 +1,18 @@
import BaseAPIService from './api-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
-import type { ContainerStatusCounts, ContainerSummaryDto, ContainerStats } from '$lib/types/container.type';
+import type {
+ ContainerStatusCounts,
+ ContainerSummaryDto,
+ ContainerStats,
+ ContainerCreateRequest
+} from '$lib/types/container.type';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
import { transformPaginationParams } from '$lib/utils/params.util';
-import type { ContainerCreateOptions } from 'dockerode';
+
+export type ContainersPaginatedResponse = Paginated<ContainerSummaryDto, ContainerStatusCounts>;
export class ContainerService extends BaseAPIService {
- async getContainers(options?: SearchPaginationSortRequest): Promise<Paginated<ContainerSummaryDto>> {
+ async getContainers(options?: SearchPaginationSortRequest): Promise<ContainersPaginatedResponse> {
const envId = await environmentStore.getCurrentEnvironmentId();
const params = transformPaginationParams(options);
const res = await this.api.get(`/environments/${envId}/containers`, { params });
@@ -30,7 +36,7 @@ export class ContainerService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));
}
- async createContainer(options: ContainerCreateOptions): Promise<any> {
+ async createContainer(options: ContainerCreateRequest): Promise<any> {
const envId = await environmentStore.getCurrentEnvironmentId();
return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));
}
diff --git a/frontend/src/lib/services/network-service.ts b/frontend/src/lib/services/network-service.ts
index e1f87308a..eabd691bd 100644
--- a/frontend/src/lib/services/network-service.ts
+++ b/frontend/src/lib/services/network-service.ts
@@ -1,12 +1,13 @@
import BaseAPIService from './api-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
-import type { NetworkSummaryDto, NetworkUsageCounts, NetworkCreateRequest, NetworkCreateDto } from '$lib/types/network.type';
+import type { NetworkSummaryDto, NetworkUsageCounts, NetworkCreateRequest, NetworkCreateOptions } from '$lib/types/network.type';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
-import type { NetworkCreateOptions } from 'dockerode';
import { transformPaginationParams } from '$lib/utils/params.util';
+export type NetworksPaginatedResponse = Paginated<NetworkSummaryDto, NetworkUsageCounts>;
+
export class NetworkService extends BaseAPIService {
- async getNetworks(options?: SearchPaginationSortRequest): Promise<Paginated<NetworkSummaryDto>> {
+ async getNetworks(options?: SearchPaginationSortRequest): Promise<NetworksPaginatedResponse> {
const envId = await environmentStore.getCurrentEnvironmentId();
const params = transformPaginationParams(options);
const res = await this.api.get(`/environments/${envId}/networks`, { params });
@@ -24,7 +25,7 @@ export class NetworkService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${envId}/networks/${networkId}`));
}
- async createNetwork(name: string, options: NetworkCreateDto): Promise<any> {
+ async createNetwork(name: string, options: NetworkCreateOptions): Promise<any> {
const envId = await environmentStore.getCurrentEnvironmentId();
const request: NetworkCreateRequest = {
name,
diff --git a/frontend/src/lib/services/volume-service.ts b/frontend/src/lib/services/volume-service.ts
index 2ed18e3b2..b7d08b645 100644
--- a/frontend/src/lib/services/volume-service.ts
+++ b/frontend/src/lib/services/volume-service.ts
@@ -1,12 +1,20 @@
import BaseAPIService from './api-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
-import type { VolumeSummaryDto, VolumeDetailDto, VolumeUsageDto, VolumeUsageCounts } from '$lib/types/volume.type';
+import type {
+ VolumeSummaryDto,
+ VolumeDetailDto,
+ VolumeUsageDto,
+ VolumeUsageCounts,
+ VolumeCreateRequest,
+ VolumeSizeInfo
+} from '$lib/types/volume.type';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
-import type { VolumeCreateOptions } from 'dockerode';
import { transformPaginationParams } from '$lib/utils/params.util';
+export type VolumesPaginatedResponse = Paginated<VolumeSummaryDto, VolumeUsageCounts>;
+
export class VolumeService extends BaseAPIService {
- async getVolumes(options?: SearchPaginationSortRequest): Promise<Paginated<VolumeSummaryDto>> {
+ async getVolumes(options?: SearchPaginationSortRequest): Promise<VolumesPaginatedResponse> {
const envId = await environmentStore.getCurrentEnvironmentId();
const params = transformPaginationParams(options);
const res = await this.api.get(`/environments/${envId}/volumes`, { params });
@@ -29,7 +37,13 @@ export class VolumeService extends BaseAPIService {
return res.data.data;
}
- async createVolume(options: VolumeCreateOptions): Promise<any> {
+ async getVolumeSizes(): Promise<VolumeSizeInfo[]> {
+ const envId = await environmentStore.getCurrentEnvironmentId();
+ const res = await this.api.get(`/environments/${envId}/volumes/sizes`);
+ return res.data.data;
+ }
+
+ async createVolume(options: VolumeCreateRequest): Promise<any> {
const envId = await environmentStore.getCurrentEnvironmentId();
return this.handleResponse(this.api.post(`/environments/${envId}/volumes`, options));
}
diff --git a/frontend/src/lib/types/container.type.ts b/frontend/src/lib/types/container.type.ts
index 560accd0a..18d46c69f 100644
--- a/frontend/src/lib/types/container.type.ts
+++ b/frontend/src/lib/types/container.type.ts
@@ -12,6 +12,51 @@ export interface BaseContainer {
status: string;
}
+// Container creation types
+export interface PortBinding {
+ hostIp?: string;
+ hostPort: string;
+}
+
+export interface RestartPolicy {
+ name: 'no' | 'always' | 'on-failure' | 'unless-stopped';
+ maximumRetryCount?: number;
+}
+
+export interface HostConfigCreate {
+ binds?: string[];
+ portBindings?: Record<string, PortBinding[]>;
+ restartPolicy?: RestartPolicy;
+ networkMode?: string;
+ privileged?: boolean;
+ autoRemove?: boolean;
+ memory?: number;
+ memorySwap?: number;
+ nanoCpus?: number;
+ cpuShares?: number;
+}
+
+export interface NetworkingConfig {
+ endpointsConfig?: Record<string, { aliases?: string[] }>;
+}
+
+export interface ContainerCreateRequest {
+ name?: string;
+ image: string;
+ cmd?: string[];
+ entrypoint?: string[];
+ env?: string[];
+ exposedPorts?: Record<string, {}>;
+ hostConfig?: HostConfigCreate;
+ networkingConfig?: NetworkingConfig;
+ labels?: Record<string, string>;
+ workingDir?: string;
+ user?: string;
+ tty?: boolean;
+ openStdin?: boolean;
+ stdinOnce?: boolean;
+}
+
export interface ContainerSummaryDto extends BaseContainer {
ports: ContainerPorts[];
hostConfig: ContainerHostConfig;
diff --git a/frontend/src/lib/types/network.type.ts b/frontend/src/lib/types/network.type.ts
index 123292aa0..2b7223c84 100644
--- a/frontend/src/lib/types/network.type.ts
+++ b/frontend/src/lib/types/network.type.ts
@@ -1,49 +1,59 @@
-import type { IPAM } from 'dockerode';
+export interface IPAMConfig {
+ subnet?: string;
+ gateway?: string;
+ ipRange?: string;
+ auxAddress?: Record<string, string>;
+}
+
+export interface IPAM {
+ driver?: string;
+ options?: Record<string, string>;
+ config?: IPAMConfig[];
+}
-export interface NetworkCreateDto {
- Driver?: string;
- CheckDuplicate?: boolean;
- Internal?: boolean;
- Attachable?: boolean;
- Ingress?: boolean;
- IPAM?: IPAM;
- EnableIPv6?: boolean;
- Options?: Record<string, string>;
- Labels?: Record<string, string>;
+export interface NetworkCreateOptions {
+ driver?: string;
+ checkDuplicate?: boolean;
+ internal?: boolean;
+ attachable?: boolean;
+ ingress?: boolean;
+ ipam?: IPAM;
+ enableIPv6?: boolean;
+ options?: Record<string, string>;
+ labels?: Record<string, string>;
}
+// Request sent to backend
export interface NetworkCreateRequest {
name: string;
- options: NetworkCreateDto;
+ options: NetworkCreateOptions;
}
export interface NetworkUsageCounts {
- networksInuse: number;
- networksUnused: number;
- totalNetworks: number;
+ inuse: number;
+ unused: number;
+ total: number;
}
export interface ContainerEndpointDto {
- Name: string;
- EndpointID: string;
- MacAddress: string;
- IPv4Address: string;
- IPv6Address: string;
+ name: string;
+ endpointId: string;
+ macAddress: string;
+ ipv4Address: string;
+ ipv6Address: string;
}
export interface IPAMSubnetDto {
- Subnet: string;
- Gateway?: string;
- IPRange?: string;
- // Support both keys we see in Docker variants
- AuxAddress?: Record<string, string>;
- AuxiliaryAddresses?: Record<string, string>;
+ subnet: string;
+ gateway?: string;
+ ipRange?: string;
+ auxAddress?: Record<string, string>;
}
export interface IPAMDto {
- Driver: string;
- Options?: Record<string, string>;
- Config?: IPAMSubnetDto[];
+ driver: string;
+ options?: Record<string, string>;
+ config?: IPAMSubnetDto[];
}
export interface NetworkSummaryDto {
@@ -51,7 +61,7 @@ export interface NetworkSummaryDto {
name: string;
driver: string;
scope: string;
- created: string; // ISO RFC3339 string
+ created: string;
options?: Record<string, string> | null;
labels?: Record<string, string> | null;
inUse: boolean;
diff --git a/frontend/src/lib/types/pagination.type.ts b/frontend/src/lib/types/pagination.type.ts
index e935d4914..9d8067883 100644
--- a/frontend/src/lib/types/pagination.type.ts
+++ b/frontend/src/lib/types/pagination.type.ts
@@ -26,9 +26,10 @@ export type PaginationResponse = {
grandTotalItems?: number;
};
-export type Paginated<T> = {
+export type Paginated<T, C = unknown> = {
data: T[];
pagination: PaginationResponse;
+ counts?: C;
};
// export interface PaginatedApiResponse<T> {
diff --git a/frontend/src/lib/types/volume.type.ts b/frontend/src/lib/types/volume.type.ts
index 05390e3eb..350b68b96 100644
--- a/frontend/src/lib/types/volume.type.ts
+++ b/frontend/src/lib/types/volume.type.ts
@@ -3,6 +3,13 @@ export interface VolumeUsageData {
refCount: number;
}
+export interface VolumeCreateRequest {
+ name: string;
+ driver?: string;
+ driverOpts?: Record<string, string>;
+ labels?: Record<string, string>;
+}
+
export interface VolumeSummaryDto {
id: string;
name: string;
@@ -27,7 +34,13 @@ export interface VolumeUsageDto {
}
export interface VolumeUsageCounts {
- volumesInuse: number;
- volumesUnused: number;
- totalVolumes: number;
+ inuse: number;
+ unused: number;
+ total: number;
+}
+
+export interface VolumeSizeInfo {
+ name: string;
+ size: number;
+ refCount: number;
}
diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.ts
index 219f35c25..edd69ab63 100644
--- a/frontend/src/lib/utils/ws.ts
+++ b/frontend/src/lib/utils/ws.ts
@@ -171,7 +171,7 @@ export function createStatsWebSocket(opts: {
const buildUrl = () => {
const envId = opts.getEnvId() || '0';
const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
- return `${protocol}://${location.host}/api/environments/${envId}/system/stats/ws`;
+ return `${protocol}://${location.host}/api/environments/${envId}/ws/system/stats`;
};
return new ReconnectingWebSocket<SystemStats>({
@@ -198,7 +198,7 @@ export function createContainerStatsWebSocket(opts: {
const buildUrl = () => {
const envId = opts.getEnvId() || '0';
const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
- return `${protocol}://${location.host}/api/environments/${envId}/containers/${opts.containerId}/stats/ws`;
+ return `${protocol}://${location.host}/api/environments/${envId}/ws/containers/${opts.containerId}/stats`;
};
return new ReconnectingWebSocket<any>({
diff --git a/frontend/src/routes/(app)/containers/+page.svelte b/frontend/src/routes/(app)/containers/+page.svelte
index 3a62aabb0..2e5b7d8b6 100644
--- a/frontend/src/routes/(app)/containers/+page.svelte
+++ b/frontend/src/routes/(app)/containers/+page.svelte
@@ -31,12 +31,10 @@
{
containers: {
fetch: () => containerService.getContainers(requestOptions),
- onSuccess: (data) => (containers = data),
- errorMessage: m.common_refresh_failed({ resource: m.containers_title() })
- },
- counts: {
- fetch: () => containerService.getContainerStatusCounts(),
- onSuccess: (data) => (containerStatusCounts = data),
+ onSuccess: (data) => {
+ containers = data;
+ containerStatusCounts = data.counts ?? { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 };
+ },
errorMessage: m.common_refresh_failed({ resource: m.containers_title() })
}
},
@@ -111,7 +109,13 @@
]);
</script>
-<ResourcePageLayout title={m.containers_title()} subtitle={m.containers_subtitle()} {actionButtons} {statCards} statCardsColumns={3}>
+<ResourcePageLayout
+ title={m.containers_title()}
+ subtitle={m.containers_subtitle()}
+ {actionButtons}
+ {statCards}
+ statCardsColumns={3}
+>
{#snippet mainContent()}
<ContainerTable bind:containers bind:selectedIds bind:requestOptions {baseServerUrl} />
{/snippet}
diff --git a/frontend/src/routes/(app)/containers/+page.ts b/frontend/src/routes/(app)/containers/+page.ts
index ec2bf6951..a06869b26 100644
--- a/frontend/src/routes/(app)/containers/+page.ts
+++ b/frontend/src/routes/(app)/containers/+page.ts
@@ -10,11 +10,17 @@ export const load: PageLoad = async () => {
sort: { column: 'created', direction: 'desc' }
} satisfies SearchPaginationSortRequest);
- const [containers, containerStatusCounts, settings] = await Promise.all([
+ // containers includes counts, settings is separate
+ const [containers, settings] = await Promise.all([
containerService.getContainers(containerRequestOptions),
- containerService.getContainerStatusCounts(),
settingsService.getSettings()
]);
- return { containers, containerStatusCounts, containerRequestOptions, settings };
+ return {
+ containers,
+ containerRequestOptions,
+ settings,
+ // Use counts from the containers response
+ containerStatusCounts: containers.counts ?? { runningContainers: 0, stoppedContainers: 0, totalContainers: 0 }
+ };
};
diff --git a/frontend/src/routes/(app)/containers/components/ContainerShell.svelte b/frontend/src/routes/(app)/containers/components/ContainerShell.svelte
index 673c47e93..6792af58f 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerShell.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerShell.svelte
@@ -54,7 +54,7 @@
const envId = await environmentStore.getCurrentEnvironmentId();
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const host = window.location.host;
- websocketUrl = `${protocol}//${host}/api/environments/${envId}/containers/${containerId}/exec/ws?shell=${encodeURIComponent(shell)}`;
+ websocketUrl = `${protocol}//${host}/api/environments/${envId}/ws/containers/${containerId}/exec?cmd=${encodeURIComponent(shell)}`;
})();
}
diff --git a/frontend/src/routes/(app)/networks/+page.svelte b/frontend/src/routes/(app)/networks/+page.svelte
index a5013f851..bb5fd7581 100644
--- a/frontend/src/routes/(app)/networks/+page.svelte
+++ b/frontend/src/routes/(app)/networks/+page.svelte
@@ -2,8 +2,7 @@
import NetworkIcon from '@lucide/svelte/icons/network';
import EthernetPortIcon from '@lucide/svelte/icons/ethernet-port';
import { toast } from 'svelte-sonner';
- import type { NetworkCreateOptions } from 'dockerode';
- import type { NetworkCreateDto } from '$lib/types/network.type';
+ import type { NetworkCreateOptions } from '$lib/types/network.type';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import CreateNetworkSheet from '$lib/components/sheets/create-network-sheet.svelte';
@@ -29,12 +28,10 @@
{
networks: {
fetch: () => networkService.getNetworks(requestOptions),
- onSuccess: (data) => (networks = data),
- errorMessage: m.common_refresh_failed({ resource: m.networks_title() })
- },
- counts: {
- fetch: () => networkService.getNetworkUsageCounts(),
- onSuccess: (data) => (networkUsageCounts = data),
+ onSuccess: (data) => {
+ networks = data;
+ networkUsageCounts = data.counts ?? { inuse: 0, unused: 0, total: 0 };
+ },
errorMessage: m.common_refresh_failed({ resource: m.networks_title() })
}
},
@@ -44,22 +41,10 @@
useEnvironmentRefresh(refresh);
- async function handleCreate(options: NetworkCreateOptions) {
+ async function handleCreate(name: string, options: NetworkCreateOptions) {
isLoading.create = true;
- const name = options.Name?.trim() || m.common_unknown();
- const dto: NetworkCreateDto = {
- Driver: options.Driver,
- CheckDuplicate: options.CheckDuplicate,
- Internal: options.Internal,
- Attachable: options.Attachable,
- Ingress: options.Ingress,
- IPAM: options.IPAM,
- EnableIPv6: options.EnableIPv6,
- Options: options.Options,
- Labels: options.Labels
- };
handleApiResultWithCallbacks({
- result: await tryCatch(networkService.createNetwork(name, dto)),
+ result: await tryCatch(networkService.createNetwork(name, options)),
message: m.common_create_failed({ resource: `${m.resource_network()} "${name}"` }),
setLoadingState: (v) => (isLoading.create = v),
onSuccess: async () => {
@@ -90,14 +75,14 @@
const statCards: StatCardConfig[] = $derived([
{
title: m.networks_total(),
- value: networkUsageCounts.totalNetworks,
+ value: networkUsageCounts.total,
icon: NetworkIcon,
iconColor: 'text-blue-500',
class: 'border-l-4 border-l-blue-500'
},
{
title: m.unused_networks(),
- value: networkUsageCounts.networksUnused,
+ value: networkUsageCounts.unused,
icon: EthernetPortIcon,
iconColor: 'text-amber-500',
class: 'border-l-4 border-l-amber-500'
diff --git a/frontend/src/routes/(app)/networks/+page.ts b/frontend/src/routes/(app)/networks/+page.ts
index 5bbaf4c77..e5824c41b 100644
--- a/frontend/src/routes/(app)/networks/+page.ts
+++ b/frontend/src/routes/(app)/networks/+page.ts
@@ -15,10 +15,13 @@ export const load: PageLoad = async () => {
}
} satisfies SearchPaginationSortRequest);
- const [networks, networkUsageCounts] = await Promise.all([
- networkService.getNetworks(networkRequestOptions),
- networkService.getNetworkUsageCounts()
- ]);
+ // Single API call - counts are included in the response
+ const networks = await networkService.getNetworks(networkRequestOptions);
- return { networks, networkRequestOptions, networkUsageCounts };
+ return {
+ networks,
+ networkRequestOptions,
+ // Use counts from the networks response
+ networkUsageCounts: networks.counts ?? { inuse: 0, unused: 0, total: 0 }
+ };
};
diff --git a/frontend/src/routes/(app)/networks/[networkId]/+page.svelte b/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
index b9bc7938e..26700b370 100644
--- a/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
+++ b/frontend/src/routes/(app)/networks/[networkId]/+page.svelte
@@ -262,7 +262,7 @@
</Card.Content>
</Card.Root>
- {#if network.ipam?.Config && network.ipam.Config.length > 0}
+ {#if network.ipam?.config && network.ipam.config.length > 0}
<Card.Root>
<Card.Header icon={SettingsIcon}>
<div class="flex flex-col space-y-1.5">
@@ -272,23 +272,23 @@
</Card.Header>
<Card.Content class="p-4">
<div class="space-y-3">
- {#each network.ipam.Config as config, i (i)}
+ {#each network.ipam.config as config, i (i)}
<Card.Root variant="outlined">
<Card.Content class="p-4">
<div class="space-y-2">
- {#if config.Subnet}
+ {#if config.subnet}
<div class="flex flex-col sm:flex-row sm:items-center">
<span class="text-muted-foreground w-full text-sm font-medium sm:w-24">{m.common_subnet()}:</span>
<code
class="bg-muted text-muted-foreground mt-1 cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs select-all sm:mt-0 sm:text-sm"
title="Click to select"
>
- {config.Subnet}
+ {config.subnet}
</code>
</div>
{/if}
- {#if config.Gateway}
+ {#if config.gateway}
<div class="flex flex-col sm:flex-row sm:items-center">
<span class="text-muted-foreground w-full text-sm font-medium sm:w-24"
>{m.networks_ipam_gateway_label()}:</span
@@ -297,12 +297,12 @@
class="bg-muted text-muted-foreground mt-1 cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs select-all sm:mt-0 sm:text-sm"
title="Click to select"
>
- {config.Gateway}
+ {config.gateway}
</code>
</div>
{/if}
- {#if config.IPRange}
+ {#if config.ipRange}
<div class="flex flex-col sm:flex-row sm:items-center">
<span class="text-muted-foreground w-full text-sm font-medium sm:w-24"
>{m.networks_ipam_iprange_label()}:</span
@@ -311,16 +311,16 @@
class="bg-muted text-muted-foreground mt-1 cursor-pointer rounded px-1.5 py-0.5 font-mono text-xs select-all sm:mt-0 sm:text-sm"
title="Click to select"
>
- {config.IPRange}
+ {config.ipRange}
</code>
</div>
{/if}
- {#if (config.AuxiliaryAddresses && Object.keys(config.AuxiliaryAddresses).length > 0) || (config.AuxAddress && Object.keys(config.AuxAddress).length > 0)}
+ {#if config.auxAddress && Object.keys(config.auxAddress).length > 0}
<div class="mt-3">
<p class="text-muted-foreground mb-1 text-sm font-medium">{m.networks_ipam_aux_addresses_label()}:</p>
<ul class="ml-4 space-y-1">
- {#each Object.entries(config.AuxiliaryAddresses ?? config.AuxAddress ?? {}) as [name, addr] (name)}
+ {#each Object.entries(config.auxAddress) as [name, addr] (name)}
<li class="flex font-mono text-xs">
<span class="text-muted-foreground mr-2">{name}:</span>
<code
@@ -338,18 +338,18 @@
{/each}
</div>
- {#if network.ipam.Driver}
+ {#if network.ipam.driver}
<div class="mt-4 flex items-center">
<span class="text-muted-foreground mr-2 text-sm font-medium">{m.networks_ipam_driver_label()}:</span>
- <StatusBadge variant="cyan" text={network.ipam.Driver} />
+ <StatusBadge variant="cyan" text={network.ipam.driver} />
</div>
{/if}
- {#if network.ipam.Options && Object.keys(network.ipam.Options).length > 0}
+ {#if network.ipam.options && Object.keys(network.ipam.options).length > 0}
<div class="mt-4">
<p class="text-muted-foreground mb-2 text-sm font-medium">{m.networks_ipam_options_label()}</p>
<div class="bg-muted/50 rounded-lg border p-3">
- {#each Object.entries(network.ipam.Options) as [key, value] (key)}
+ {#each Object.entries(network.ipam.options) as [key, value] (key)}
<div class="mb-1 flex justify-between font-mono text-xs last:mb-0">
<span class="text-muted-foreground">{key}:</span>
<span>{value}</span>
diff --git a/frontend/src/routes/(app)/volumes/+page.svelte b/frontend/src/routes/(app)/volumes/+page.svelte
index d083d94bf..a2b97f4df 100644
--- a/frontend/src/routes/(app)/volumes/+page.svelte
+++ b/frontend/src/routes/(app)/volumes/+page.svelte
@@ -6,7 +6,7 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import CreateVolumeSheet from '$lib/components/sheets/create-volume-sheet.svelte';
- import type { VolumeCreateOptions } from 'dockerode';
+ import type { VolumeCreateRequest } from '$lib/types/volume.type';
import VolumeTable from './volume-table.svelte';
import { m } from '$lib/paraglide/messages';
import { volumeService } from '$lib/services/volume-service';
@@ -29,12 +29,11 @@
{
volumes: {
fetch: () => volumeService.getVolumes(requestOptions),
- onSuccess: (data) => (volumes = data),
- errorMessage: m.common_refresh_failed({ resource: m.volumes_title() })
- },
- counts: {
- fetch: () => volumeService.getVolumeUsageCounts(),
- onSuccess: (data) => (volumeUsageCounts = data),
+ onSuccess: (data) => {
+ volumes = data;
+ // Extract counts from the response - they're included in the list endpoint
+ volumeUsageCounts = data.counts ?? { inuse: 0, unused: 0, total: 0 };
+ },
errorMessage: m.common_refresh_failed({ resource: m.volumes_title() })
}
},
@@ -44,9 +43,9 @@
useEnvironmentRefresh(refresh);
- async function handleCreate(options: VolumeCreateOptions) {
+ async function handleCreate(options: VolumeCreateRequest) {
isLoading.creating = true;
- const name = options.Name?.trim() || m.common_unknown();
+ const name = options.name?.trim() || m.common_unknown();
handleApiResultWithCallbacks({
result: await tryCatch(volumeService.createVolume(options)),
message: m.common_create_failed({ resource: `${m.resource_volume()} "${name}"` }),
@@ -81,21 +80,21 @@
const statCards: StatCardConfig[] = $derived([
{
title: m.volumes_stat_total(),
- value: volumeUsageCounts.totalVolumes,
+ value: volumeUsageCounts.total,
icon: HardDriveIcon,
iconColor: 'text-blue-500',
class: 'border-l-4 border-l-blue-500'
},
{
title: m.volumes_stat_used(),
- value: volumeUsageCounts.volumesInuse,
+ value: volumeUsageCounts.inuse,
icon: ArchiveRestoreIcon,
iconColor: 'text-green-500',
class: 'border-l-4 border-l-green-500'
},
{
title: m.volumes_stat_unused(),
- value: volumeUsageCounts.volumesUnused,
+ value: volumeUsageCounts.unused,
icon: ArchiveXIcon,
iconColor: 'text-red-500',
class: 'border-l-4 border-l-red-500'
diff --git a/frontend/src/routes/(app)/volumes/+page.ts b/frontend/src/routes/(app)/volumes/+page.ts
index c04c679dd..f9c72ac55 100644
--- a/frontend/src/routes/(app)/volumes/+page.ts
+++ b/frontend/src/routes/(app)/volumes/+page.ts
@@ -15,10 +15,13 @@ export const load: PageLoad = async () => {
}
} satisfies SearchPaginationSortRequest);
- const [volumes, volumeUsageCounts] = await Promise.all([
- volumeService.getVolumes(volumeRequestOptions),
- volumeService.getVolumeUsageCounts()
- ]);
+ // Single API call - counts are included in the response
+ const volumes = await volumeService.getVolumes(volumeRequestOptions);
- return { volumes, volumeRequestOptions, volumeUsageCounts };
+ return {
+ volumes,
+ volumeRequestOptions,
+ // Use counts from the volumes response
+ volumeUsageCounts: volumes.counts ?? { inuse: 0, unused: 0, total: 0 }
+ };
};
diff --git a/frontend/src/routes/(app)/volumes/volume-table.svelte b/frontend/src/routes/(app)/volumes/volume-table.svelte
index 18582c65e..25eaeccd5 100644
--- a/frontend/src/routes/(app)/volumes/volume-table.svelte
+++ b/frontend/src/routes/(app)/volumes/volume-table.svelte
@@ -14,16 +14,18 @@
import { format } from 'date-fns';
import { truncateString } from '$lib/utils/string.utils';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
- import type { VolumeSummaryDto } from '$lib/types/volume.type';
+ import type { VolumeSummaryDto, VolumeSizeInfo } from '$lib/types/volume.type';
import type { ColumnSpec } from '$lib/components/arcane-table';
import { UniversalMobileCard } from '$lib/components/arcane-table/index.js';
import DatabaseIcon from '@lucide/svelte/icons/database';
import CalendarIcon from '@lucide/svelte/icons/calendar';
- import HardDriveIcon from '@lucide/svelte/icons/hard-drive';
+ import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle';
import { m } from '$lib/paraglide/messages';
import { volumeService } from '$lib/services/volume-service';
import bytes from 'bytes';
+ type FieldVisibility = Record<string, boolean>;
+
let {
volumes = $bindable(),
selectedIds = $bindable(),
@@ -38,6 +40,21 @@
removing: false
});
+ // Lazy load volume sizes - this is a slow operation
+ let volumeSizesPromise = $state<Promise<Map<string, VolumeSizeInfo>> | null>(null);
+
+ // Start loading sizes when component mounts or volumes change
+ $effect(() => {
+ if (volumes.data.length > 0) {
+ volumeSizesPromise = loadVolumeSizes();
+ }
+ });
+
+ async function loadVolumeSizes(): Promise<Map<string, VolumeSizeInfo>> {
+ const sizes = await volumeService.getVolumeSizes();
+ return new Map(sizes.map((s) => [s.name, s]));
+ }
+
async function handleRemoveVolumeConfirm(name: string) {
const safeName = name?.trim() || m.common_unknown();
openConfirmDialog({
@@ -143,8 +160,21 @@
{/snippet}
{#snippet SizeCell({ item }: { item: VolumeSummaryDto })}
- {#if item.size >= 0}
- <span class="text-sm tabular-nums">{bytes.format(item.size)}</span>
+ {#if volumeSizesPromise}
+ {#await volumeSizesPromise}
+ <span class="text-muted-foreground flex items-center gap-1 text-sm">
+ <LoaderCircleIcon class="size-3 animate-spin" />
+ </span>
+ {:then sizesMap}
+ {@const sizeInfo = sizesMap.get(item.name)}
+ {#if sizeInfo && sizeInfo.size >= 0}
+ <span class="text-sm tabular-nums">{bytes.format(sizeInfo.size)}</span>
+ {:else}
+ <span class="text-muted-foreground text-sm">-</span>
+ {/if}
+ {:catch}
+ <span class="text-muted-foreground text-sm">-</span>
+ {/await}
{:else}
<span class="text-muted-foreground text-sm">-</span>
{/if}
@@ -161,7 +191,7 @@
}: {
row: any;
item: VolumeSummaryDto;
- mobileFieldVisibility: Record<string, boolean>;
+ mobileFieldVisibility: FieldVisibility;
})}
<UniversalMobileCard
{item}
@@ -186,14 +216,6 @@
icon: DatabaseIcon,
iconVariant: 'gray' as const,
show: mobileFieldVisibility.driver ?? true
- },
- {
- label: m.common_size(),
- getValue: (item: VolumeSummaryDto) =>
- item.usageData && item.usageData.size >= 0 ? bytes.format(item.usageData.size) : '-',
- icon: HardDriveIcon,
- iconVariant: 'gray' as const,
- show: (mobileFieldVisibility.size ?? true) && !!item.usageData
}
]}
footer={(mobileFieldVisibility.createdAt ?? true)
diff --git a/go.work.sum b/go.work.sum
index a90db0ccc..b05dde3d1 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -36,6 +36,7 @@ github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki
github.com/alecthomas/kingpin/v2 v2.4.0/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE=
github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
+github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA=
github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY=
github.com/apache/arrow/go/v10 v10.0.1/go.mod h1:YvhnlEePVnBS4+0z3fhPfUy7W1Ikj0Ih0vcRo/gZ1M0=
github.com/apache/thrift v0.16.0/go.mod h1:PHK3hniurgQaNMZYaCLEqXKsYK8upmhPbmdP2FXSqgU=
@@ -65,7 +66,6 @@ github.com/aws/smithy-go v1.22.5/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/checkpoint-restore/checkpointctl v1.4.0/go.mod h1:ynQ52zQBazgcTZuxpwTFzRinIcAf0haDTC1X1LA/FKA=
github.com/checkpoint-restore/go-criu/v7 v7.2.0/go.mod h1:u0LCWLg0w4yqqu14aXhiB4YD3a1qd8EcCEg7vda5dwo=
-github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY=
github.com/chzyer/readline v1.5.1/go.mod h1:Eh+b79XXUwfKfcPLepksvw2tcLE/Ct21YObkaSkeBlk=
github.com/cilium/ebpf v0.16.0/go.mod h1:L7u2Blt2jMM/vLAVgjxluxtBKlz3/GWjB0dMOEngfwE=
github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
@@ -93,6 +93,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N
github.com/cyberphone/json-canonicalization v0.0.0-20241213102144-19d51d7fe467/go.mod h1:uzvlm1mxhHkdfqitSA92i7Se+S9ksOn3a3qmv/kyOCw=
github.com/cyphar/filepath-securejoin v0.4.1/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI=
github.com/cznic/mathutil v0.0.0-20180504122225-ca4c9f2c1369/go.mod h1:e6NPNENfs9mPDVNRekM7lKScauxd5kXTr1Mfyig6TDM=
+github.com/danielgtaylor/mexpr v1.9.1/go.mod h1:kAivYNRnBeE/IJinqBvVFvLrX54xX//9zFYwADo4Bc8=
+github.com/danielgtaylor/shorthand/v2 v2.2.0/go.mod h1:t5QfaNf7DPru9ZLIIhPQSO7Gyvajm3euw7LxB/MTUqE=
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE=
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA=
@@ -103,11 +105,13 @@ github.com/envoyproxy/go-control-plane v0.13.5-0.20251024222203-75eaa193e329/go.
github.com/envoyproxy/go-control-plane/envoy v1.35.0/go.mod h1:09qwbGVuSWWAyN5t/b3iyVfz5+z8QWGrzkoqm/8SbEs=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU=
+github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM=
github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw=
github.com/form3tech-oss/jwt-go v3.2.5+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k=
github.com/francoispqt/gojay v1.2.13/go.mod h1:ehT5mTG4ua4581f1++1WLG0vPdaA9HaiDsoyrBGkyDY=
github.com/fsouza/fake-gcs-server v1.17.0/go.mod h1:D1rTE4YCyHFNa99oyJJ5HyclvN/0uQR+pM/VdlL83bw=
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
+github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/go-jose/go-jose/v3 v3.0.0/go.mod h1:RNkWWRld676jZEYoV3+XK8L2ZnNSvIsxFMht0mSX+u8=
github.com/go-openapi/jsonpointer v0.21.0/go.mod h1:IUyH9l/+uyhIYQ/PXVA41Rexl+kOkAPDdXEYns6fzUY=
github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=
@@ -116,6 +120,7 @@ github.com/gobuffalo/here v0.6.0/go.mod h1:wAG085dHOYqUpf+Ap+WOdrPTp5IYcDAs/x7PL
github.com/gocql/gocql v0.0.0-20210515062232-b7ef815b4556/go.mod h1:DL0ekTmBSTdlNF25Orwt/JMzqIq3EJ4MVa/J/uK64OY=
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
+github.com/gofiber/fiber/v2 v2.52.7/go.mod h1:YEcBbO/FB+5M1IZNBP9FO3J9281zgPAreiI1oqg8nDw=
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI=
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
@@ -168,11 +173,12 @@ github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQ
github.com/knqyf263/go-plugin v0.9.0/go.mod h1:2z5lCO1/pez6qGo8CvCxSlBFSEat4MEp1DrnA+f7w8Q=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/ktrysmt/go-bitbucket v0.6.4/go.mod h1:9u0v3hsd2rqCHRIpbir1oP7F58uo5dq19sBYvuMoyQ4=
+github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
+github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec/go.mod h1:TmwEoGCwIti7BCeJ9hescZgRtatxRE+A72pCoPfmcfk=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/manifoldco/promptui v0.9.0/go.mod h1:ka04sppxSGFAtxX0qhlYQjISsg9mR4GWtQEhdbn6Pgg=
github.com/markbates/pkger v0.15.1/go.mod h1:0JoVlrol20BSywW79rN3kdFFsE5xYM+rSCQDXbLhiuI=
-github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mdlayher/socket v0.5.1/go.mod h1:TjPLHI1UgwEv5J1B5q0zTZq12A/6H7nKmtTanQE37IQ=
github.com/mdlayher/vsock v1.2.1/go.mod h1:NRfCibel++DgeMD8z/hP+PPTjlNJsdPOmxcnENvE+SE=
@@ -235,8 +241,12 @@ github.com/tonistiigi/go-actions-cache v0.0.0-20250626083717-378c5ed1ddd9/go.mod
github.com/tonistiigi/go-archvariant v1.0.0/go.mod h1:TxFmO5VS6vMq2kvs3ht04iPXtu2rUT/erOnGFYfk5Ho=
github.com/tonistiigi/jaeger-ui-rest v0.0.0-20250408171107-3dd17559e117/go.mod h1:3Ez1Paeg+0Ghu3KwpEGC1HgZ4CHDlg+Ez/5Baeomk54=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
+github.com/uptrace/bunrouter v1.0.23/go.mod h1:O3jAcl+5qgnF+ejhgkmbceEk0E/mqaK+ADOocdNpY8M=
github.com/urfave/cli v1.22.17/go.mod h1:b0ht0aqgH/6pBYzzxURyrM4xXNgsoT/n2ZzwQiEhNVo=
github.com/urfave/cli/v2 v2.27.7/go.mod h1:CyNAG/xg+iAOg0N4MPGZqVmv2rCoP267496AOXUZjA4=
+github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
+github.com/valyala/fasthttp v1.62.0/go.mod h1:FCINgr4GKdKqV8Q0xv8b+UxPV+H/O5nNFo3D+r54Htg=
+github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
github.com/vbauerster/mpb/v8 v8.10.2/go.mod h1:+Ja4P92E3/CorSZgfDtK46D7AVbDqmBQRTmyTqPElo0=
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9c7cd766e..fbc370a84 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -136,9 +136,6 @@ importers:
'@types/bytes':
specifier: ^3.1.5
version: 3.1.5
- '@types/dockerode':
- specifier: ^3.3.47
- version: 3.3.47
'@types/js-yaml':
specifier: ^4.0.9
version: 4.0.9
@@ -1525,12 +1522,6 @@ packages:
resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==}
- '@types/[email protected]':
- resolution: {integrity: sha512-yKpAGEuKRSS8wwx0joknWxsmLha78wNMe9R2S3UNsVOkZded8UqOrV8KoeDXoXsjndxwyF3eIhyClGbO1SEhEg==}
-
- '@types/[email protected]':
- resolution: {integrity: sha512-ShM1mz7rCjdssXt7Xz0u1/R2BJC7piWa3SJpUBiVjCf2A3XNn4cP6pUVaD8bLanpPVVn4IKzJuw3dOvkJ8IbYw==}
-
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
@@ -1540,9 +1531,6 @@ packages:
resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}
- '@types/[email protected]':
- resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}
-
resolution: {integrity: sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==}
@@ -1554,9 +1542,6 @@ packages:
resolution: {integrity: sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==}
- '@types/[email protected]':
- resolution: {integrity: sha512-N1ASjp/nXH3ovBHddRJpli4ozpk6UdDYIX4RJWFa9L1YKnzdhTlVmiGHm4DZnj/jLbqZpes4aeR30EFGQtvhQQ==}
-
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
@@ -3051,9 +3036,6 @@ packages:
resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
-
resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==}
@@ -4296,17 +4278,6 @@ snapshots:
dependencies:
'@types/node': 24.10.1
- '@types/[email protected]':
- dependencies:
- '@types/node': 24.10.1
- '@types/ssh2': 1.15.5
-
- '@types/[email protected]':
- dependencies:
- '@types/docker-modem': 3.0.6
- '@types/node': 24.10.1
- '@types/ssh2': 1.15.5
-
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -4314,10 +4285,6 @@ snapshots:
optional: true
- '@types/[email protected]':
- dependencies:
- undici-types: 5.26.5
-
dependencies:
undici-types: 7.16.0
@@ -4330,10 +4297,6 @@ snapshots:
dependencies:
csstype: 3.2.3
- '@types/[email protected]':
- dependencies:
- '@types/node': 18.19.130
-
optional: true
@@ -5882,8 +5845,6 @@ snapshots:
-
diff --git a/tests/spec/image-updates.spec.ts b/tests/spec/image-updates.spec.ts
new file mode 100644
index 000000000..c43ac40d7
--- /dev/null
+++ b/tests/spec/image-updates.spec.ts
@@ -0,0 +1,337 @@
+import { test, expect, type Page } from '@playwright/test';
+import { fetchImagesWithRetry } from '../utils/fetch.util';
+
+const ROUTES = {
+ page: '/images',
+ apiImageUpdatesCheckBatch: '/api/environments/0/image-updates/check-batch',
+ apiImageUpdatesCheckAll: '/api/environments/0/image-updates/check-all',
+ apiImageUpdatesSummary: '/api/environments/0/image-updates/summary',
+};
+
+interface BatchUpdateResponse {
+ success: boolean;
+ data: Record<
+ string,
+ {
+ hasUpdate: boolean;
+ updateType: string;
+ currentVersion?: string;
+ latestVersion?: string;
+ currentDigest?: string;
+ latestDigest?: string;
+ checkTime: string;
+ responseTimeMs: number;
+ error?: string;
+ authMethod?: string;
+ authUsername?: string;
+ authRegistry?: string;
+ usedCredential?: boolean;
+ }
+ >;
+}
+
+interface UpdateSummary {
+ success: boolean;
+ data: {
+ totalImages: number;
+ imagesWithUpdates: number;
+ digestUpdates: number;
+ errorsCount: number;
+ };
+}
+
+async function navigateToImages(page: Page) {
+ await page.goto(ROUTES.page);
+ await page.waitForLoadState('networkidle');
+}
+
+let realImages: any[] = [];
+
+test.beforeEach(async ({ page }) => {
+ await navigateToImages(page);
+
+ try {
+ const images = await fetchImagesWithRetry(page);
+ realImages = Array.isArray(images) ? images : [];
+ } catch {
+ realImages = [];
+ }
+});
+
+test.describe('Image Update UI - Check All Updates Button', () => {
+ test('should display the Check Updates button on images page', async ({ page }) => {
+ await navigateToImages(page);
+
+ // Look for the Check Updates button in the action bar
+ const checkUpdatesButton = page.getByRole('button', { name: /check.*update/i });
+ await expect(checkUpdatesButton).toBeVisible();
+ });
+
+ test('should trigger bulk update check when clicking Check Updates button', async ({ page }) => {
+ await navigateToImages(page);
+
+ // Find and click the Check Updates button
+ const checkUpdatesButton = page.getByRole('button', { name: /check.*update/i });
+ await expect(checkUpdatesButton).toBeVisible();
+
+ // Click the button
+ await checkUpdatesButton.click();
+
+ // Wait for the loading state or completion toast
+ // The button should show a loading state or we should see a toast notification
+ await expect(async () => {
+ // Either button shows loading state
+ const buttonText = await checkUpdatesButton.textContent();
+ const isLoading = buttonText?.toLowerCase().includes('checking');
+
+ // Or a toast appears
+ const toast = page.locator('li[data-sonner-toast]');
+ const toastVisible = await toast.isVisible().catch(() => false);
+
+ expect(isLoading || toastVisible).toBeTruthy();
+ }).toPass({ timeout: 30000 });
+
+ // Eventually a success or completion toast should appear
+ await expect(page.locator('li[data-sonner-toast]')).toBeVisible({ timeout: 60000 });
+ });
+});
+
+test.describe('Image Update UI - Individual Image Update Check via Hover Card', () => {
+ test('should display update status icons in the images table', async ({ page }) => {
+ test.skip(!realImages.length, 'No images available');
+
+ await navigateToImages(page);
+
+ // Wait for the table to load
+ await expect(page.locator('table')).toBeVisible();
+
+ // Check that image rows exist
+ const rows = page.locator('tbody tr');
+ await expect(rows.first()).toBeVisible();
+ });
+
+ test('should show hover card tooltip when hovering over update status icon', async ({ page }) => {
+ test.skip(!realImages.length, 'No images available');
+
+ await navigateToImages(page);
+
+ // Wait for images table
+ await expect(page.locator('table')).toBeVisible();
+
+ // Find the first row's update status area (the Updates column)
+ const firstRow = page.locator('tbody tr').first();
+ await expect(firstRow).toBeVisible();
+
+ // Look for the update status icon trigger element (Tooltip.Trigger wraps a span)
+ const updateStatusTrigger = firstRow.locator('span.inline-flex').first();
+ const hasTrigger = await updateStatusTrigger.isVisible().catch(() => false);
+
+ if (hasTrigger) {
+ // Hover to trigger tooltip
+ await updateStatusTrigger.hover();
+
+ // Wait for tooltip content to appear
+ await page.waitForTimeout(500);
+
+ // Check if tooltip/hover card content appeared
+ const tooltipContent = page.locator('[data-radix-popper-content-wrapper], [role="tooltip"]');
+ const tooltipVisible = await tooltipContent.isVisible().catch(() => false);
+
+ // The hover card should be visible after hovering
+ if (tooltipVisible) {
+ await expect(tooltipContent).toBeVisible();
+ }
+ }
+ });
+
+ test('should allow triggering individual image update check from hover card', async ({ page }) => {
+ test.skip(!realImages.length, 'No images available');
+
+ // Find an image with valid repo/tag for update checking
+ const testImage = realImages.find((img) => img.repo && img.tag && img.repo !== '<none>' && img.tag !== '<none>');
+ test.skip(!testImage, 'No suitable image found for update check');
+
+ await navigateToImages(page);
+ await expect(page.locator('table')).toBeVisible();
+
+ // Find the row for our test image or the first row with a valid image
+ const rows = page.locator('tbody tr');
+ const firstRow = rows.first();
+ await expect(firstRow).toBeVisible();
+
+ // Look for the update status trigger (could be a button or icon)
+ const updateTrigger = firstRow.locator('span.inline-flex button, span.inline-flex svg').first();
+ const hasUpdateTrigger = await updateTrigger.isVisible().catch(() => false);
+
+ if (hasUpdateTrigger) {
+ // If it's a clickable button (for unchecked images), click it
+ const isButton = await updateTrigger.evaluate((el) => el.tagName.toLowerCase() === 'button').catch(() => false);
+
+ if (isButton) {
+ await updateTrigger.click();
+
+ // Wait for checking to complete (either a toast or state change)
+ await expect(async () => {
+ const toast = page.locator('li[data-sonner-toast]');
+ const toastVisible = await toast.isVisible().catch(() => false);
+ expect(toastVisible).toBeTruthy();
+ }).toPass({ timeout: 30000 });
+ } else {
+ // If it's an icon, hover to show the tooltip with recheck button
+ await updateTrigger.hover();
+ await page.waitForTimeout(500);
+
+ // Look for the recheck button in the tooltip
+ const recheckButton = page.locator('[data-radix-popper-content-wrapper] button, [role="tooltip"] button').first();
+ const hasRecheckButton = await recheckButton.isVisible().catch(() => false);
+
+ if (hasRecheckButton) {
+ await recheckButton.click();
+
+ // Wait for the check to complete
+ await expect(async () => {
+ const toast = page.locator('li[data-sonner-toast]');
+ const toastVisible = await toast.isVisible().catch(() => false);
+ expect(toastVisible).toBeTruthy();
+ }).toPass({ timeout: 30000 });
+ }
+ }
+ }
+ });
+});
+
+test.describe('Image Update API Endpoints', () => {
+ test('should check batch image updates via API', async ({ page }) => {
+ const imageRefs = ['nginx:latest', 'alpine:latest'];
+
+ const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {
+ data: {
+ imageRefs,
+ },
+ });
+
+ expect(res.status()).toBe(200);
+
+ const json = (await res.json()) as BatchUpdateResponse;
+ expect(json.success).toBe(true);
+ expect(json.data).toBeDefined();
+ expect(typeof json.data).toBe('object');
+ });
+
+ test('should check all images for updates via API', async ({ page }) => {
+ const res = await page.request.post(ROUTES.apiImageUpdatesCheckAll, {
+ data: {},
+ });
+
+ expect(res.status()).toBe(200);
+
+ const json = (await res.json()) as BatchUpdateResponse;
+ expect(json.success).toBe(true);
+ expect(json.data).toBeDefined();
+ });
+
+ test('should get update summary via API', async ({ page }) => {
+ const res = await page.request.get(ROUTES.apiImageUpdatesSummary);
+
+ expect(res.status()).toBe(200);
+
+ const json = (await res.json()) as UpdateSummary;
+ expect(json.success).toBe(true);
+ expect(json.data).toBeDefined();
+ expect(typeof json.data.totalImages).toBe('number');
+ expect(typeof json.data.imagesWithUpdates).toBe('number');
+ expect(typeof json.data.digestUpdates).toBe('number');
+ expect(typeof json.data.errorsCount).toBe('number');
+ });
+});
+
+test.describe('Image Update UI Integration', () => {
+ test('should display update status icon in images table', async ({ page }) => {
+ test.skip(!realImages.length, 'No images available');
+
+ await navigateToImages(page);
+
+ // Wait for the table to load
+ await expect(page.locator('table')).toBeVisible();
+
+ // Check that image rows exist
+ const rows = page.locator('tbody tr');
+ await expect(rows.first()).toBeVisible();
+ });
+
+ test('should display update information in image detail page', async ({ page }) => {
+ test.skip(!realImages.length, 'No images available');
+
+ const testImage = realImages.find((img) => img.repoTags?.[0] && !img.repoTags[0].includes('<none>'));
+ test.skip(!testImage, 'No suitable image found');
+
+ // Navigate to image detail
+ await page.goto(`/images/${encodeURIComponent(testImage.id)}`);
+ await page.waitForLoadState('networkidle');
+
+ // The detail page should load
+ await expect(page.locator('h1, h2, [data-testid="image-detail"]').first()).toBeVisible({
+ timeout: 10000,
+ });
+ });
+});
+
+test.describe('Batch Update Checks', () => {
+ test('should handle empty batch request', async ({ page }) => {
+ const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {
+ data: {
+ imageRefs: [],
+ },
+ });
+
+ expect(res.status()).toBe(200);
+
+ const json = (await res.json()) as BatchUpdateResponse;
+ expect(json.success).toBe(true);
+ expect(Object.keys(json.data).length).toBe(0);
+ });
+
+ test('should return results for each image in batch', async ({ page }) => {
+ const imageRefs = ['nginx:latest', 'alpine:latest', 'busybox:latest'];
+
+ const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {
+ data: {
+ imageRefs,
+ },
+ });
+
+ expect(res.status()).toBe(200);
+
+ const json = (await res.json()) as BatchUpdateResponse;
+ expect(json.success).toBe(true);
+
+ // Each requested image should have a result
+ for (const ref of imageRefs) {
+ expect(json.data[ref]).toBeDefined();
+ }
+ });
+
+ test('should handle mixed valid and invalid images in batch', async ({ page }) => {
+ const imageRefs = ['nginx:latest', 'invalid-registry.example.com/nonexistent:latest'];
+
+ const res = await page.request.post(ROUTES.apiImageUpdatesCheckBatch, {
+ data: {
+ imageRefs,
+ },
+ });
+
+ expect(res.status()).toBe(200);
+
+ const json = (await res.json()) as BatchUpdateResponse;
+ expect(json.success).toBe(true);
+
+ // nginx should succeed
+ expect(json.data['nginx:latest']).toBeDefined();
+
+ // Invalid image should have an error
+ const invalidResult = json.data['invalid-registry.example.com/nonexistent:latest'];
+ if (invalidResult) {
+ expect(invalidResult.error || invalidResult.hasUpdate === false).toBeTruthy();
+ }
+ });
+});
diff --git a/tests/spec/network.spec.ts b/tests/spec/network.spec.ts
index 23088e4d8..acfb607c4 100644
--- a/tests/spec/network.spec.ts
+++ b/tests/spec/network.spec.ts
@@ -8,7 +8,7 @@ async function navigateToNetworks(page: Page) {
}
let realNetworks: NetworkSummary[] = [];
-let networkCount: NetworkUsageCounts = { networksInuse: 0, networksUnused: 0, totalNetworks: 0 };
+let networkCount: NetworkUsageCounts = { inuse: 0, unused: 0, total: 0 };
test.beforeEach(async ({ page }) => {
await navigateToNetworks(page);
@@ -25,8 +25,18 @@ test.describe('Networks Page', () => {
test('Stat cards show correct counts', async ({ page }) => {
await navigateToNetworks(page);
- await expect(page.locator('p:has-text("Total Networks") + p')).toHaveText(String(networkCount.totalNetworks));
- await expect(page.locator('p:has-text("Unused Networks") + p')).toHaveText(String(networkCount.networksUnused));
+
+ // Fetch counts directly in the test to ensure we have fresh data
+ const counts = await fetchNetworksCountsWithRetry(page);
+
+ console.log('Network Counts:', counts);
+
+ // Use the div filter locator to find stat cards
+ const totalValue = page.locator('div').filter({ hasText: 'Total Networks' }).nth(5).locator('p').nth(1);
+ const unusedValue = page.locator('div').filter({ hasText: 'Unused Networks' }).nth(5).locator('p').nth(1);
+
+ await expect(totalValue).toHaveText(String(counts.total));
+ await expect(unusedValue).toHaveText(String(counts.unused));
});
test('Table displays when networks exist, else empty state', async ({ page }) => {
diff --git a/tests/spec/volumes.spec.ts b/tests/spec/volumes.spec.ts
index a1bdb9bb9..8ecadd2a8 100644
--- a/tests/spec/volumes.spec.ts
+++ b/tests/spec/volumes.spec.ts
@@ -3,7 +3,7 @@ import { fetchVolumeCountsWithRetry, fetchVolumesWithRetry } from '../utils/fetc
import { VolumeUsageCounts } from 'types/volumes.type';
let realVolumes: any[] = [];
-let volumeCount: VolumeUsageCounts = { volumesInuse: 0, volumesUnused: 0, totalVolumes: 0 };
+let volumeCount: VolumeUsageCounts = { inuse: 0, unused: 0, total: 0 };
test.beforeEach(async ({ page }) => {
await page.goto('/volumes');
@@ -41,8 +41,13 @@ test.describe('Volumes Page', () => {
test('Correct Volume Stat Card Counts', async ({ page }) => {
await page.goto('/volumes');
+ await page.waitForLoadState('networkidle');
- await expect(page.locator('p:has-text("Total Volumes") + p')).toHaveText(volumeCount.totalVolumes.toString());
+ const totalCard = page
+ .locator('div')
+ .filter({ hasText: /^Total Volumes/ })
+ .first();
+ await expect(totalCard.locator('p').nth(1)).toHaveText(volumeCount.total.toString());
});
test('Create Volume Sheet Opens', async ({ page }) => {
diff --git a/tests/types/image.type.ts b/tests/types/image.type.ts
index d007b1890..a9a2844c3 100644
--- a/tests/types/image.type.ts
+++ b/tests/types/image.type.ts
@@ -4,3 +4,26 @@ export interface ImageUsageCounts {
totalImages: number;
totalImageSize: number;
}
+
+export interface ImageUpdateInfo {
+ hasUpdate: boolean;
+ updateType: string;
+ currentVersion?: string;
+ latestVersion?: string;
+ currentDigest?: string;
+ latestDigest?: string;
+ checkTime: string;
+ responseTimeMs: number;
+ error?: string;
+ authMethod?: 'none' | 'anonymous' | 'credential' | 'unknown';
+ authUsername?: string;
+ authRegistry?: string;
+ usedCredential?: boolean;
+}
+
+export interface ImageUpdateSummary {
+ totalImages: number;
+ imagesWithUpdates: number;
+ digestUpdates: number;
+ errorsCount: number;
+}
diff --git a/tests/types/networks.type.ts b/tests/types/networks.type.ts
index defcf290a..e9de86938 100644
--- a/tests/types/networks.type.ts
+++ b/tests/types/networks.type.ts
@@ -1,7 +1,7 @@
export interface NetworkUsageCounts {
- networksInuse: number;
- networksUnused: number;
- totalNetworks: number;
+ inuse: number;
+ unused: number;
+ total: number;
}
export type NetworkSummary = {
diff --git a/tests/types/volumes.type.ts b/tests/types/volumes.type.ts
index b355417a0..8a92daf8d 100644
--- a/tests/types/volumes.type.ts
+++ b/tests/types/volumes.type.ts
@@ -1,5 +1,5 @@
export interface VolumeUsageCounts {
- volumesInuse: number;
- volumesUnused: number;
- totalVolumes: number;
+ inuse: number;
+ unused: number;
+ total: number;
}
diff --git a/tests/utils/fetch.util.ts b/tests/utils/fetch.util.ts
index 2c1b429d2..2832c575a 100644
--- a/tests/utils/fetch.util.ts
+++ b/tests/utils/fetch.util.ts
@@ -34,8 +34,9 @@ export async function fetchVolumeCountsWithRetry(page: Page, maxRetries = 3): Pr
async () => {
const res = await page.request.get('/api/environments/0/volumes/counts');
const json = await res.json().catch(() => null);
- const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];
- return (data ?? []) as VolumeUsageCounts;
+ // API returns { success: true, data: { inuse, unused, total } }
+ const data = json?.data ?? { inuse: 0, unused: 0, total: 0 };
+ return data as VolumeUsageCounts;
},
maxRetries,
800
@@ -85,8 +86,9 @@ export async function fetchNetworksCountsWithRetry(page: Page, maxRetries = 3):
async () => {
const res = await page.request.get('/api/environments/0/networks/counts');
const json = await res.json().catch(() => null);
- const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];
- return (data ?? []) as NetworkUsageCounts;
+ // API returns { success: true, data: { inuse, unused, total } }
+ const data = json?.data ?? { inuse: 0, unused: 0, total: 0 };
+ return data as NetworkUsageCounts;
},
maxRetries,
800
diff --git a/types/apikey/apikey.go b/types/apikey/apikey.go
index 4d9e1731d..544d941d8 100644
--- a/types/apikey/apikey.go
+++ b/types/apikey/apikey.go
@@ -2,31 +2,35 @@ package apikey
import "time"
-type Create struct {
- Name string `json:"name" binding:"required"`
- Description *string `json:"description,omitempty"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty"`
+// Create represents the request body for creating an API key.
+type CreateApiKey struct {
+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key"`
+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Optional expiration date for the API key"`
}
+// ApiKey represents an API key without the secret.
type ApiKey struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Description *string `json:"description,omitempty"`
- KeyPrefix string `json:"keyPrefix"`
- UserID string `json:"userId"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty"`
- LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
- CreatedAt time.Time `json:"createdAt"`
- UpdatedAt *time.Time `json:"updatedAt,omitempty"`
+ ID string `json:"id" doc:"Unique identifier of the API key"`
+ Name string `json:"name" doc:"Name of the API key"`
+ Description *string `json:"description,omitempty" doc:"Description of the API key"`
+ KeyPrefix string `json:"keyPrefix" doc:"Prefix of the API key for identification"`
+ UserID string `json:"userId" doc:"ID of the user who owns the API key"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Expiration date of the API key"`
+ LastUsedAt *time.Time `json:"lastUsedAt,omitempty" doc:"Last time the API key was used"`
+ CreatedAt time.Time `json:"createdAt" doc:"Creation timestamp"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty" doc:"Last update timestamp"`
}
+// ApiKeyCreatedDto represents a newly created API key with the full secret.
type ApiKeyCreatedDto struct {
ApiKey
- Key string `json:"key"`
+ Key string `json:"key" doc:"The full API key secret (only shown once)"`
}
-type Update struct {
- Name *string `json:"name,omitempty"`
- Description *string `json:"description,omitempty"`
- ExpiresAt *time.Time `json:"expiresAt,omitempty"`
+// Update represents the request body for updating an API key.
+type UpdateApiKey struct {
+ Name *string `json:"name,omitempty" maxLength:"255" doc:"New name for the API key"`
+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"New description for the API key"`
+ ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"New expiration date for the API key"`
}
diff --git a/types/auth/auth.go b/types/auth/auth.go
index 7c1569d42..2efbdeb82 100644
--- a/types/auth/auth.go
+++ b/types/auth/auth.go
@@ -1,32 +1,39 @@
package auth
-type Login struct {
- // Username of the user.
- //
- // Required: true
- Username string `json:"username" binding:"required"`
+import (
+ "time"
+
+ "go.getarcane.app/types/user"
+)
- // Password of the user.
- //
- // Required: true
- Password string `json:"password" binding:"required"`
+// Login represents the login request body.
+type Login struct {
+ Username string `json:"username" minLength:"1" maxLength:"255" doc:"Username of the user" example:"admin"`
+ Password string `json:"password" minLength:"1" doc:"Password of the user"`
}
+// Refresh represents the token refresh request body.
type Refresh struct {
- // RefreshToken is the refresh token used to obtain a new access token.
- //
- // Required: true
- RefreshToken string `json:"refreshToken" binding:"required"`
+ RefreshToken string `json:"refreshToken" minLength:"1" doc:"Refresh token used to obtain a new access token"`
}
+// PasswordChange represents the password change request body.
type PasswordChange struct {
- // CurrentPassword is the current password of the user.
- //
- // Required: false
- CurrentPassword string `json:"currentPassword"`
+ CurrentPassword string `json:"currentPassword,omitempty" doc:"Current password of the user (required for non-OIDC users)"`
+ NewPassword string `json:"newPassword" minLength:"8" doc:"New password for the user"`
+}
+
+// LoginResponse represents the successful login response data.
+type LoginResponse struct {
+ Token string `json:"token" doc:"JWT access token"`
+ RefreshToken string `json:"refreshToken" doc:"Refresh token for obtaining new access tokens"`
+ ExpiresAt time.Time `json:"expiresAt" doc:"Expiration time of the access token"`
+ User user.User `json:"user" doc:"Authenticated user information"`
+}
- // NewPassword is the new password for the user.
- //
- // Required: true
- NewPassword string `json:"newPassword" binding:"required"`
+// TokenRefreshResponse represents the successful token refresh response data.
+type TokenRefreshResponse struct {
+ Token string `json:"token" doc:"New JWT access token"`
+ RefreshToken string `json:"refreshToken" doc:"New refresh token"`
+ ExpiresAt time.Time `json:"expiresAt" doc:"Expiration time of the new access token"`
}
diff --git a/types/auth/oidc.go b/types/auth/oidc.go
index 397ee74af..870bb1cbc 100644
--- a/types/auth/oidc.go
+++ b/types/auth/oidc.go
@@ -1,5 +1,11 @@
package auth
+import (
+ "time"
+
+ "go.getarcane.app/types/user"
+)
+
// OidcUserInfo represents user information retrieved from an OIDC provider.
type OidcUserInfo struct {
// Subject is the unique identifier for the user at the OIDC provider.
@@ -112,3 +118,90 @@ type OidcAuthUrlRequest struct {
// Required: true
RedirectUri string `json:"redirectUri"`
}
+
+// OidcAuthUrlResponse contains the generated OIDC authorization URL.
+type OidcAuthUrlResponse struct {
+ // AuthUrl is the URL to redirect the user to for OIDC authentication.
+ //
+ // Required: true
+ AuthUrl string `json:"authUrl"`
+}
+
+// OidcConfigResponse contains the OIDC client configuration.
+type OidcConfigResponse struct {
+ // ClientID is the OAuth 2.0 client identifier.
+ //
+ // Required: true
+ ClientID string `json:"clientId"`
+
+ // RedirectUri is the URI to redirect to after authentication.
+ //
+ // Required: true
+ RedirectUri string `json:"redirectUri"`
+
+ // IssuerUrl is the OIDC provider's issuer URL.
+ //
+ // Required: true
+ IssuerUrl string `json:"issuerUrl"`
+
+ // AuthorizationEndpoint is the URL of the authorization endpoint.
+ //
+ // Required: true
+ AuthorizationEndpoint string `json:"authorizationEndpoint"`
+
+ // TokenEndpoint is the URL of the token endpoint.
+ //
+ // Required: true
+ TokenEndpoint string `json:"tokenEndpoint"`
+
+ // UserinfoEndpoint is the URL of the userinfo endpoint.
+ //
+ // Required: true
+ UserinfoEndpoint string `json:"userinfoEndpoint"`
+
+ // Scopes is the space-separated list of OAuth scopes requested.
+ //
+ // Required: true
+ Scopes string `json:"scopes"`
+}
+
+// OidcCallbackRequest contains the OIDC callback parameters.
+type OidcCallbackRequest struct {
+ // Code is the authorization code from the OIDC provider.
+ //
+ // Required: true
+ Code string `json:"code"`
+
+ // State is the state parameter from the OIDC provider for CSRF protection.
+ //
+ // Required: true
+ State string `json:"state"`
+}
+
+// OidcCallbackResponse contains the response from OIDC callback processing.
+type OidcCallbackResponse struct {
+ // Success indicates if the authentication was successful.
+ //
+ // Required: true
+ Success bool `json:"success"`
+
+ // Token is the JWT access token.
+ //
+ // Required: true
+ Token string `json:"token"`
+
+ // RefreshToken is the refresh token for obtaining new access tokens.
+ //
+ // Required: true
+ RefreshToken string `json:"refreshToken"`
+
+ // ExpiresAt is the expiration time of the access token.
+ //
+ // Required: true
+ ExpiresAt time.Time `json:"expiresAt"`
+
+ // User contains the authenticated user information.
+ //
+ // Required: true
+ User user.User `json:"user"`
+}
diff --git a/types/base/response.go b/types/base/response.go
index af6f369cc..499801861 100644
--- a/types/base/response.go
+++ b/types/base/response.go
@@ -1,43 +1,33 @@
package base
// ErrorResponse represents an error response.
-//
-// @Description Error response with error message
type ErrorResponse struct {
- Error string `json:"error"`
+ Error string `json:"error" doc:"Error message describing what went wrong"`
}
// MessageResponse represents a simple message response.
-//
-// @Description Simple message response
type MessageResponse struct {
- Message string `json:"message"`
+ Message string `json:"message" doc:"Response message"`
}
// PaginationResponse contains pagination metadata.
-//
-// @Description Pagination metadata
type PaginationResponse struct {
- TotalPages int64 `json:"totalPages"`
- TotalItems int64 `json:"totalItems"`
- CurrentPage int `json:"currentPage"`
- ItemsPerPage int `json:"itemsPerPage"`
- GrandTotalItems int64 `json:"grandTotalItems,omitempty"`
+ TotalPages int64 `json:"totalPages" doc:"Total number of pages"`
+ TotalItems int64 `json:"totalItems" doc:"Total number of items in the current filtered set"`
+ CurrentPage int `json:"currentPage" doc:"Current page number (1-indexed)"`
+ ItemsPerPage int `json:"itemsPerPage" doc:"Number of items per page"`
+ GrandTotalItems int64 `json:"grandTotalItems,omitempty" doc:"Total number of items without filters"`
}
// ApiResponse is a generic wrapper for API responses.
-//
-// @Description Generic API response wrapper
type ApiResponse[T any] struct {
- Success bool `json:"success"`
- Data T `json:"data"`
+ Success bool `json:"success" doc:"Whether the request was successful"`
+ Data T `json:"data" doc:"Response data"`
}
// Paginated is a generic wrapper for paginated responses.
-//
-// @Description Generic paginated response wrapper
type Paginated[T any] struct {
- Success bool `json:"success"`
- Data []T `json:"data"`
- Pagination PaginationResponse `json:"pagination"`
+ Success bool `json:"success" doc:"Whether the request was successful"`
+ Data []T `json:"data" doc:"Array of items for the current page"`
+ Pagination PaginationResponse `json:"pagination" doc:"Pagination metadata"`
}
diff --git a/types/containerregistry/container_registry.go b/types/containerregistry/container_registry.go
index 2e68fdcfc..63125d4f4 100644
--- a/types/containerregistry/container_registry.go
+++ b/types/containerregistry/container_registry.go
@@ -2,7 +2,8 @@ package containerregistry
import "time"
-type Response struct {
+// Registry represents a container registry in API responses.
+type ContainerRegistry struct {
// ID of the container registry.
//
// Required: true
diff --git a/types/environment/environment.go b/types/environment/environment.go
index 6e2e49f5c..667c1d425 100644
--- a/types/environment/environment.go
+++ b/types/environment/environment.go
@@ -66,7 +66,16 @@ type Test struct {
Message *string `json:"message,omitempty"`
}
-type Response struct {
+// TestConnectionRequest is the request body for testing a connection.
+type TestConnectionRequest struct {
+ // ApiUrl is an optional URL to test instead of the saved one.
+ //
+ // Required: false
+ ApiUrl *string `json:"apiUrl,omitempty"`
+}
+
+// Environment represents an environment in API responses.
+type Environment struct {
// ID of the environment.
//
// Required: true
@@ -92,3 +101,19 @@ type Response struct {
// Required: true
Enabled bool `json:"enabled"`
}
+
+// AgentPairRequest is the request body for pairing with an agent.
+type AgentPairRequest struct {
+ // Rotate indicates if the token should be rotated.
+ //
+ // Required: false
+ Rotate *bool `json:"rotate,omitempty"`
+}
+
+// AgentPairResponse is the response from pairing with an agent.
+type AgentPairResponse struct {
+ // Token is the pairing token.
+ //
+ // Required: true
+ Token string `json:"token"`
+}
diff --git a/types/event/event.go b/types/event/event.go
index 5d59b9ae7..4897ed34e 100644
--- a/types/event/event.go
+++ b/types/event/event.go
@@ -2,7 +2,8 @@ package event
import "time"
-type Response struct {
+// Event represents an event in API responses.
+type Event struct {
// ID of the event.
//
// Required: true
@@ -79,7 +80,7 @@ type Response struct {
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
}
-type Create struct {
+type CreateEvent struct {
// Type of the event.
//
// Required: true
@@ -140,7 +141,7 @@ type ListReponse struct {
// Events is a list of events.
//
// Required: true
- Events []Response `json:"events"`
+ Events []Event `json:"events"`
// Total number of events.
//
diff --git a/types/image/image.go b/types/image/image.go
index a16825d4a..cfcb5f4a5 100644
--- a/types/image/image.go
+++ b/types/image/image.go
@@ -301,7 +301,17 @@ type PullOptions struct {
// ImageName is the name of the image to pull.
//
// Required: true
- ImageName string `json:"imageName" binding:"required"`
+ ImageName string `json:"imageName" minLength:"1" doc:"Name of the image to pull (e.g., nginx)"`
+
+ // Tag is the tag of the image to pull. Defaults to 'latest'.
+ //
+ // Required: false
+ Tag string `json:"tag,omitempty" doc:"Tag of the image to pull (e.g., latest)"`
+
+ // Auth for authenticating with private registries (legacy field name).
+ //
+ // Required: false
+ Auth *containerregistry.Credential `json:"auth,omitempty"`
// Credentials for authenticating with private registries.
//
@@ -309,6 +319,28 @@ type PullOptions struct {
Credentials []containerregistry.Credential `json:"credentials,omitempty"`
}
+// GetFullImageName returns the image name with tag.
+func (p PullOptions) GetFullImageName() string {
+ if p.Tag != "" && p.Tag != "latest" {
+ return p.ImageName + ":" + p.Tag
+ }
+ if p.Tag == "latest" && !strings.Contains(p.ImageName, ":") {
+ return p.ImageName + ":latest"
+ }
+ return p.ImageName
+}
+
+// GetCredentials returns credentials from either the Auth or Credentials field.
+func (p PullOptions) GetCredentials() []containerregistry.Credential {
+ if len(p.Credentials) > 0 {
+ return p.Credentials
+ }
+ if p.Auth != nil {
+ return []containerregistry.Credential{*p.Auth}
+ }
+ return nil
+}
+
// NewDetailSummary creates a DetailSummary from a Docker image inspect response.
// It converts the Docker API types to the application's DetailSummary type,
// handling nested structs and converting exposed ports from Docker's nat.PortSet
diff --git a/types/imageupdate/image_update.go b/types/imageupdate/image_update.go
index ace436262..ec7a477ac 100644
--- a/types/imageupdate/image_update.go
+++ b/types/imageupdate/image_update.go
@@ -107,4 +107,11 @@ type BatchImageUpdateRequest struct {
Credentials []containerregistry.Credential `json:"credentials,omitempty"`
}
+type CheckAllImagesRequest struct {
+ // Credentials is a list of container registry credentials for authentication.
+ //
+ // Required: false
+ Credentials []containerregistry.Credential `json:"credentials,omitempty"`
+}
+
type BatchResponse map[string]*Response
diff --git a/types/meta/template_meta.go b/types/meta/template_meta.go
index e74db9fbc..9c8fe04cf 100644
--- a/types/meta/template_meta.go
+++ b/types/meta/template_meta.go
@@ -1,7 +1,7 @@
package meta
// Template represents metadata about a template.
-type Template struct {
+type TemplateMeta struct {
// Version of the template.
//
// Required: false
diff --git a/types/network/network.go b/types/network/network.go
index 35cd7c6d8..46297ff2b 100644
--- a/types/network/network.go
+++ b/types/network/network.go
@@ -57,17 +57,17 @@ type UsageCounts struct {
// Inuse is the number of networks currently in use.
//
// Required: true
- Inuse int `json:"networksInuse"`
+ Inuse int `json:"inuse"`
// Unused is the number of networks not in use.
//
// Required: true
- Unused int `json:"networksUnused"`
+ Unused int `json:"unused"`
// Total is the total number of networks.
//
// Required: true
- Total int `json:"totalNetworks"`
+ Total int `json:"total"`
}
type Inspect struct {
@@ -144,6 +144,101 @@ type CreateResponse struct {
Warning string `json:"warning,omitempty"`
}
+// CreateRequest contains the parameters for creating a network.
+type CreateRequest struct {
+ // Name is the name of the network to create.
+ //
+ // Required: true
+ Name string `json:"name" minLength:"1" doc:"Name of the network"`
+
+ // Options contains network creation options.
+ //
+ // Required: false
+ Options CreateOptions `json:"options" doc:"Network creation options"`
+}
+
+// IPAMConfig contains IP address management configuration for a subnet.
+type IPAMConfig struct {
+ Subnet string `json:"subnet,omitempty"`
+ Gateway string `json:"gateway,omitempty"`
+ IPRange string `json:"ipRange,omitempty"`
+ AuxAddress map[string]string `json:"auxAddress,omitempty"`
+}
+
+// IPAM contains IP Address Management configuration.
+type IPAM struct {
+ Driver string `json:"driver,omitempty"`
+ Options map[string]string `json:"options,omitempty"`
+ Config []IPAMConfig `json:"config,omitempty"`
+}
+
+// CreateOptions contains options for creating a network.
+type CreateOptions struct {
+ // Driver is the network driver to use (e.g., bridge, overlay).
+ Driver string `json:"driver,omitempty" doc:"Network driver (e.g., bridge, overlay)"`
+
+ // CheckDuplicate requests daemon to check for networks with same name.
+ CheckDuplicate bool `json:"checkDuplicate,omitempty" doc:"Check for duplicate network names"`
+
+ // Internal restricts external access to the network.
+ Internal bool `json:"internal,omitempty" doc:"Restrict external access to the network"`
+
+ // Attachable allows manual container attachment in swarm mode.
+ Attachable bool `json:"attachable,omitempty" doc:"Allow manual container attachment"`
+
+ // Ingress enables routing-mesh for swarm cluster.
+ Ingress bool `json:"ingress,omitempty" doc:"Enable routing-mesh for swarm cluster"`
+
+ // IPAM configuration for the network.
+ IPAM *IPAM `json:"ipam,omitempty" doc:"IP Address Management configuration"`
+
+ // EnableIPv6 enables IPv6 networking.
+ EnableIPv6 bool `json:"enableIPv6,omitempty" doc:"Enable IPv6 networking"`
+
+ // Options are driver-specific options.
+ Options map[string]string `json:"options,omitempty" doc:"Driver-specific options"`
+
+ // Labels are user-defined metadata.
+ Labels map[string]string `json:"labels,omitempty" doc:"User-defined labels"`
+}
+
+// ToDockerCreateOptions converts to Docker SDK CreateOptions.
+func (o CreateOptions) ToDockerCreateOptions() network.CreateOptions {
+ var enableIPv6 *bool
+ if o.EnableIPv6 {
+ enableIPv6 = &o.EnableIPv6
+ }
+
+ opts := network.CreateOptions{
+ Driver: o.Driver,
+ Internal: o.Internal,
+ Attachable: o.Attachable,
+ Ingress: o.Ingress,
+ EnableIPv6: enableIPv6,
+ Options: o.Options,
+ Labels: o.Labels,
+ }
+
+ // Convert IPAM if present
+ if o.IPAM != nil {
+ dockerIPAM := &network.IPAM{
+ Driver: o.IPAM.Driver,
+ Options: o.IPAM.Options,
+ }
+ for _, cfg := range o.IPAM.Config {
+ dockerIPAM.Config = append(dockerIPAM.Config, network.IPAMConfig{
+ Subnet: cfg.Subnet,
+ Gateway: cfg.Gateway,
+ IPRange: cfg.IPRange,
+ AuxAddress: cfg.AuxAddress,
+ })
+ }
+ opts.IPAM = dockerIPAM
+ }
+
+ return opts
+}
+
type PruneReport struct {
// NetworksDeleted is a list of network IDs that were deleted.
//
diff --git a/types/project/project.go b/types/project/project.go
index 4cf5e2fc8..3a046f291 100644
--- a/types/project/project.go
+++ b/types/project/project.go
@@ -23,8 +23,8 @@ type IncludeFile struct {
Content string `json:"content"`
}
-// Create is used to create a new project.
-type Create struct {
+// CreateProject is used to create a new project.
+type CreateProject struct {
// Name of the project.
//
// Required: true
@@ -41,8 +41,8 @@ type Create struct {
EnvContent *string `json:"envContent,omitempty"`
}
-// Update is used to update a project.
-type Update struct {
+// UpdateProject is used to update a project.
+type UpdateProject struct {
// Name of the project.
//
// Required: false
diff --git a/types/system/health.go b/types/system/health.go
new file mode 100644
index 000000000..07df4b0ec
--- /dev/null
+++ b/types/system/health.go
@@ -0,0 +1,9 @@
+package system
+
+// HealthResponse contains the health status of the API.
+type HealthResponse struct {
+ // Status indicates the health status (e.g., "UP", "DOWN").
+ //
+ // Required: true
+ Status string `json:"status"`
+}
diff --git a/types/template/template.go b/types/template/template.go
index 7ad21e2f6..faebf7c84 100644
--- a/types/template/template.go
+++ b/types/template/template.go
@@ -102,7 +102,7 @@ type RemoteRegistry struct {
}
// Registry represents a local registry configuration.
-type Registry struct {
+type TemplateRegistry struct {
BaseRegistry
// ID is the unique identifier of the registry.
@@ -176,10 +176,128 @@ type Template struct {
// Registry is the registry information if the template is from a registry.
//
// Required: false
- Registry *Registry `json:"registry,omitempty"`
+ Registry *TemplateRegistry `json:"registry,omitempty"`
// Metadata contains additional metadata about the template.
//
// Required: false
- Metadata *meta.Template `json:"metadata,omitempty"`
+ Metadata *meta.TemplateMeta `json:"metadata,omitempty"`
+}
+
+// CreateRequest represents the request to create a template.
+type CreateRequest struct {
+ // Name of the template.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // Description of the template.
+ //
+ // Required: false
+ Description string `json:"description"`
+
+ // Content is the Docker Compose file content.
+ //
+ // Required: true
+ Content string `json:"content"`
+
+ // EnvContent is the environment file content.
+ //
+ // Required: false
+ EnvContent string `json:"envContent"`
+}
+
+// UpdateRequest represents the request to update a template.
+type UpdateRequest struct {
+ // Name of the template.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // Description of the template.
+ //
+ // Required: false
+ Description string `json:"description"`
+
+ // Content is the Docker Compose file content.
+ //
+ // Required: true
+ Content string `json:"content"`
+
+ // EnvContent is the environment file content.
+ //
+ // Required: false
+ EnvContent string `json:"envContent"`
+}
+
+// DefaultTemplatesResponse contains the default compose and env templates.
+type DefaultTemplatesResponse struct {
+ // ComposeTemplate is the default Docker Compose template content.
+ //
+ // Required: true
+ ComposeTemplate string `json:"composeTemplate"`
+
+ // EnvTemplate is the default environment template content.
+ //
+ // Required: true
+ EnvTemplate string `json:"envTemplate"`
+}
+
+// SaveDefaultTemplatesRequest represents the request to save default templates.
+type SaveDefaultTemplatesRequest struct {
+ // ComposeContent is the Docker Compose template content.
+ //
+ // Required: true
+ ComposeContent string `json:"composeContent"`
+
+ // EnvContent is the environment template content.
+ //
+ // Required: false
+ EnvContent string `json:"envContent"`
+}
+
+// CreateRegistryRequest represents the request to create a template registry.
+type CreateRegistryRequest struct {
+ // Name of the registry.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // URL of the registry.
+ //
+ // Required: true
+ URL string `json:"url"`
+
+ // Description of the registry.
+ //
+ // Required: false
+ Description string `json:"description"`
+
+ // Enabled indicates if the registry is enabled.
+ //
+ // Required: false
+ Enabled bool `json:"enabled"`
+}
+
+// UpdateRegistryRequest represents the request to update a template registry.
+type UpdateRegistryRequest struct {
+ // Name of the registry.
+ //
+ // Required: true
+ Name string `json:"name"`
+
+ // URL of the registry.
+ //
+ // Required: true
+ URL string `json:"url"`
+
+ // Description of the registry.
+ //
+ // Required: false
+ Description string `json:"description"`
+
+ // Enabled indicates if the registry is enabled.
+ //
+ // Required: false
+ Enabled bool `json:"enabled"`
}
diff --git a/types/types.go b/types/types.go
index ab1254f4c..750651d18 100644
--- a/types/types.go
+++ b/types/types.go
@@ -1 +1,5 @@
package types
+
+const (
+ LOCAL_DOCKER_ENVIRONMENT_ID = "0"
+)
diff --git a/types/updater/updater.go b/types/updater/updater.go
index 74283357a..9ca73c8aa 100644
--- a/types/updater/updater.go
+++ b/types/updater/updater.go
@@ -114,3 +114,26 @@ type Result struct {
// Required: true
Items []ResourceResult `json:"items"`
}
+
+// Status represents the current status of the updater.
+type Status struct {
+ // UpdatingContainers is the count of containers currently being updated.
+ //
+ // Required: true
+ UpdatingContainers int `json:"updatingContainers"`
+
+ // UpdatingProjects is the count of projects currently being updated.
+ //
+ // Required: true
+ UpdatingProjects int `json:"updatingProjects"`
+
+ // ContainerIds is a list of container IDs currently being updated.
+ //
+ // Required: true
+ ContainerIds []string `json:"containerIds"`
+
+ // ProjectIds is a list of project IDs currently being updated.
+ //
+ // Required: true
+ ProjectIds []string `json:"projectIds"`
+}
diff --git a/types/user/user.go b/types/user/user.go
index 3164b290c..988dae5a2 100644
--- a/types/user/user.go
+++ b/types/user/user.go
@@ -1,112 +1,34 @@
package user
-type Create struct {
- // Username of the user.
- //
- // Required: true
- Username string `json:"username" binding:"required"`
-
- // Password of the user.
- //
- // Required: true
- Password string `json:"password" binding:"required"`
-
- // DisplayName of the user.
- //
- // Required: false
- DisplayName *string `json:"displayName,omitempty"`
-
- // Email address of the user.
- //
- // Required: false
- Email *string `json:"email,omitempty"`
-
- // Roles assigned to the user.
- //
- // Required: false
- Roles []string `json:"roles,omitempty"`
-
- // Locale of the user.
- //
- // Required: false
- Locale *string `json:"locale,omitempty"`
+// CreateUser represents the request body for creating a new user.
+type CreateUser struct {
+ Username string `json:"username" minLength:"1" maxLength:"255" doc:"Username of the user" example:"johndoe"`
+ Password string `json:"password" minLength:"8" doc:"Password of the user"`
+ DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user" example:"John Doe"`
+ Email *string `json:"email,omitempty" format:"email" doc:"Email address of the user" example:"[email protected]"`
+ Roles []string `json:"roles,omitempty" doc:"Roles assigned to the user" example:"[\"user\"]"`
+ Locale *string `json:"locale,omitempty" doc:"Locale preference of the user" example:"en-US"`
}
-type Update struct {
- // DisplayName of the user.
- //
- // Required: false
- DisplayName *string `json:"displayName,omitempty"`
-
- // Email address of the user.
- //
- // Required: false
- Email *string `json:"email,omitempty"`
-
- // Roles assigned to the user.
- //
- // Required: false
- Roles []string `json:"roles,omitempty"`
-
- // Locale of the user.
- //
- // Required: false
- Locale *string `json:"locale,omitempty"`
-
- // Password of the user.
- //
- // Required: false
- Password *string `json:"password,omitempty"`
+// UpdateUser represents the request body for updating a user.
+type UpdateUser struct {
+ DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user"`
+ Email *string `json:"email,omitempty" format:"email" doc:"Email address of the user"`
+ Roles []string `json:"roles,omitempty" doc:"Roles assigned to the user"`
+ Locale *string `json:"locale,omitempty" doc:"Locale preference of the user"`
+ Password *string `json:"password,omitempty" minLength:"8" doc:"New password for the user"`
}
-type Response struct {
- // ID of the user.
- //
- // Required: true
- ID string `json:"id"`
-
- // Username of the user.
- //
- // Required: true
- Username string `json:"username"`
-
- // DisplayName of the user.
- //
- // Required: false
- DisplayName *string `json:"displayName,omitempty"`
-
- // Email address of the user.
- //
- // Required: false
- Email *string `json:"email,omitempty"`
-
- // Roles assigned to the user.
- //
- // Required: true
- Roles []string `json:"roles"`
-
- // OidcSubjectId of the user.
- //
- // Required: false
- OidcSubjectId *string `json:"oidcSubjectId,omitempty"`
-
- // Locale of the user.
- //
- // Required: false
- Locale *string `json:"locale,omitempty"`
-
- // CreatedAt is the date and time at which the user was created.
- //
- // Required: false
- CreatedAt string `json:"createdAt,omitempty"`
-
- // UpdatedAt is the date and time at which the user was last updated.
- //
- // Required: false
- UpdatedAt string `json:"updatedAt,omitempty"`
-
- // RequiresPasswordChange indicates if the user is required to change their password.
- //
- // Required: true
- RequiresPasswordChange bool `json:"requiresPasswordChange"`
+// User represents a user in API responses.
+type User struct {
+ ID string `json:"id" doc:"Unique identifier of the user" example:"550e8400-e29b-41d4-a716-446655440000"`
+ Username string `json:"username" doc:"Username of the user" example:"johndoe"`
+ DisplayName *string `json:"displayName,omitempty" doc:"Display name of the user" example:"John Doe"`
+ Email *string `json:"email,omitempty" doc:"Email address of the user" example:"[email protected]"`
+ Roles []string `json:"roles" doc:"Roles assigned to the user" example:"[\"user\", \"admin\"]"`
+ OidcSubjectId *string `json:"oidcSubjectId,omitempty" doc:"OIDC subject identifier for SSO users"`
+ Locale *string `json:"locale,omitempty" doc:"Locale preference of the user" example:"en-US"`
+ CreatedAt string `json:"createdAt,omitempty" doc:"Date and time when the user was created"`
+ UpdatedAt string `json:"updatedAt,omitempty" doc:"Date and time when the user was last updated"`
+ RequiresPasswordChange bool `json:"requiresPasswordChange" doc:"Whether the user must change their password"`
}
diff --git a/types/version/version.go b/types/version/version.go
index 5331ff208..5b059e343 100644
--- a/types/version/version.go
+++ b/types/version/version.go
@@ -1,5 +1,6 @@
package version
+// Info contains detailed version information about the application.
type Info struct {
// CurrentVersion is the current version string.
//
@@ -66,3 +67,26 @@ type Info struct {
// Required: false
ReleaseURL string `json:"releaseUrl,omitempty"`
}
+
+// Check contains simplified version check information.
+type Check struct {
+ // CurrentVersion is the current version string.
+ //
+ // Required: true
+ CurrentVersion string `json:"currentVersion"`
+
+ // NewestVersion is the newest available version string.
+ //
+ // Required: false
+ NewestVersion string `json:"newestVersion,omitempty"`
+
+ // UpdateAvailable indicates if an update is available.
+ //
+ // Required: true
+ UpdateAvailable bool `json:"updateAvailable"`
+
+ // ReleaseURL is the URL to the release page.
+ //
+ // Required: false
+ ReleaseURL string `json:"releaseUrl,omitempty"`
+}
diff --git a/types/volume/volume.go b/types/volume/volume.go
index f22b2f667..34155de9f 100644
--- a/types/volume/volume.go
+++ b/types/volume/volume.go
@@ -65,17 +65,17 @@ type UsageCounts struct {
// Inuse is the number of volumes currently in use.
//
// Required: true
- Inuse int `json:"volumesInuse"`
+ Inuse int `json:"inuse"`
// Unused is the number of volumes not in use.
//
// Required: true
- Unused int `json:"volumesUnused"`
+ Unused int `json:"unused"`
// Total is the total number of volumes.
//
// Required: true
- Total int `json:"totalVolumes"`
+ Total int `json:"total"`
}
// PruneReport is the result of a volume prune operation.
@@ -96,22 +96,22 @@ type Create struct {
// Name of the volume.
//
// Required: true
- Name string `json:"name" binding:"required"`
+ Name string `json:"name" minLength:"1" doc:"Name of the volume"`
// Driver is the volume driver to use.
//
// Required: false
- Driver string `json:"driver"`
+ Driver string `json:"driver,omitempty" doc:"Volume driver (e.g., local, nfs)"`
- // Labels contains user-defined metadata for the volume.
+ // DriverOpts contains driver-specific options.
//
// Required: false
- Labels map[string]string `json:"labels"`
+ DriverOpts map[string]string `json:"driverOpts,omitempty" doc:"Driver-specific options"`
- // Options contains driver-specific options.
+ // Labels contains user-defined metadata for the volume.
//
// Required: false
- Options map[string]string `json:"options"`
+ Labels map[string]string `json:"labels,omitempty" doc:"User-defined labels"`
}
// NewSummary creates a Volume from a docker volume.Volume, calculating InUse