Skip to content

Modern Docker Management, Designed for Everyone

refactor: network and volume handling in frontend and backend

Kyle Mendell6f2442ad2663
diff --git a/backend/go.mod b/backend/go.mod
index c2aa00dc4..b1dcbb24d 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -14,6 +14,7 @@ require (
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/golang-migrate/migrate/v4 v4.18.3
github.com/google/uuid v1.6.0
+ github.com/jinzhu/copier v0.4.0
github.com/joho/godotenv v1.5.1
github.com/shirou/gopsutil/v3 v3.24.5
golang.org/x/crypto v0.38.0
@@ -52,7 +53,6 @@ require (
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.6.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
- github.com/jinzhu/copier v0.4.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/jonboulle/clockwork v0.5.0 // indirect
diff --git a/backend/internal/api/auth_handler.go b/backend/internal/api/auth_handler.go
index 98cee9a46..d33c6282e 100644
--- a/backend/internal/api/auth_handler.go
+++ b/backend/internal/api/auth_handler.go
@@ -57,26 +57,26 @@ type PasswordChangeRequest struct {
func (h *AuthHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, LoginResponse{
- Success: false,
- Error: "Invalid request format",
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Invalid request format"},
})
return
}
localAuthEnabled, err := h.authService.IsLocalAuthEnabled(c.Request.Context())
if err != nil {
- c.JSON(http.StatusInternalServerError, LoginResponse{
- Success: false,
- Error: "Failed to check authentication settings",
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to check authentication settings"},
})
return
}
if !localAuthEnabled {
- c.JSON(http.StatusBadRequest, LoginResponse{
- Success: false,
- Error: "Local authentication is disabled",
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Local authentication is disabled"},
})
return
}
@@ -85,7 +85,6 @@ func (h *AuthHandler) Login(c *gin.Context) {
// Handle password change required
if errors.Is(err, services.ErrPasswordChangeRequired) && user != nil {
- // If we received a token pair, set the cookie so the password change call is authenticated.
if tokenPair != nil {
c.SetSameSite(http.SameSiteLaxMode)
maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
@@ -96,34 +95,38 @@ func (h *AuthHandler) Login(c *gin.Context) {
c.SetCookie("token", tokenPair.AccessToken, maxAge, "/", "", secure, true)
}
- c.JSON(http.StatusOK, LoginResponse{
- Success: true,
- RequirePasswordChange: true,
- Token: func() string {
- if tokenPair != nil {
- return tokenPair.AccessToken
- }
- return ""
- }(),
- RefreshToken: func() string {
- if tokenPair != nil {
- return tokenPair.RefreshToken
- }
- return ""
- }(),
- ExpiresAt: func() time.Time {
- if tokenPair != nil {
- return tokenPair.ExpiresAt
- }
- return time.Time{}
- }(),
- User: &dto.UserResponseDto{
- ID: user.ID,
- Username: user.Username,
- DisplayName: user.DisplayName,
- Email: user.Email,
- Roles: user.Roles,
- OidcSubjectId: user.OidcSubjectId,
+ var out dto.UserResponseDto
+ if mapErr := dto.MapStruct(user, &out); mapErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to map user"},
+ })
+ return
+ }
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "requirePasswordChange": true,
+ "token": func() string {
+ if tokenPair != nil {
+ return tokenPair.AccessToken
+ }
+ return ""
+ }(),
+ "refreshToken": func() string {
+ if tokenPair != nil {
+ return tokenPair.RefreshToken
+ }
+ return ""
+ }(),
+ "expiresAt": func() time.Time {
+ if tokenPair != nil {
+ return tokenPair.ExpiresAt
+ }
+ return time.Time{}
+ }(),
+ "user": out,
},
})
return
@@ -145,9 +148,9 @@ func (h *AuthHandler) Login(c *gin.Context) {
errorMsg = "Authentication failed"
}
- c.JSON(statusCode, LoginResponse{
- Success: false,
- Error: errorMsg,
+ c.JSON(statusCode, gin.H{
+ "success": false,
+ "data": gin.H{"error": errorMsg},
})
return
}
@@ -161,31 +164,33 @@ func (h *AuthHandler) Login(c *gin.Context) {
secure := c.Request.TLS != nil
c.SetCookie("token", tokenPair.AccessToken, maxAge, "/", "", secure, true)
- // Return successful response
- c.JSON(http.StatusOK, LoginResponse{
- Success: true,
- Token: tokenPair.AccessToken,
- RefreshToken: tokenPair.RefreshToken,
- ExpiresAt: tokenPair.ExpiresAt,
- User: &dto.UserResponseDto{
- ID: user.ID,
- Username: user.Username,
- DisplayName: user.DisplayName,
- Email: user.Email,
- Roles: user.Roles,
- OidcSubjectId: user.OidcSubjectId, // add
+ var out dto.UserResponseDto
+ if mapErr := dto.MapStruct(user, &out); mapErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to map user"},
+ })
+ 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) {
- // Clear the authentication cookie
c.SetSameSite(http.SameSiteLaxMode)
c.SetCookie("token", "", -1, "/", "", false, true)
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Logged out successfully",
+ "data": gin.H{"message": "Logged out successfully"},
})
}
@@ -194,7 +199,7 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
- "error": "Not authenticated",
+ "data": gin.H{"error": "Not authenticated"},
})
return
}
@@ -203,18 +208,23 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to get user information",
+ "data": gin.H{"error": "Failed to get user information"},
+ })
+ return
+ }
+
+ var out dto.UserResponseDto
+ if mapErr := dto.MapStruct(user, &out); mapErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to map user"},
})
return
}
- c.JSON(http.StatusOK, dto.UserResponseDto{
- ID: user.ID,
- Username: user.Username,
- DisplayName: user.DisplayName,
- Email: user.Email,
- Roles: user.Roles,
- OidcSubjectId: user.OidcSubjectId,
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": out,
})
}
@@ -223,7 +233,7 @@ func (h *AuthHandler) RefreshToken(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid request format",
+ "data": gin.H{"error": "Invalid request format"},
})
return
}
@@ -244,12 +254,11 @@ func (h *AuthHandler) RefreshToken(c *gin.Context) {
c.JSON(statusCode, gin.H{
"success": false,
- "error": errorMsg,
+ "data": gin.H{"error": errorMsg},
})
return
}
- // Set new token cookie
c.SetSameSite(http.SameSiteLaxMode)
maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
if maxAge < 0 {
@@ -259,10 +268,12 @@ func (h *AuthHandler) RefreshToken(c *gin.Context) {
c.SetCookie("token", tokenPair.AccessToken, maxAge, "/", "", secure, true)
c.JSON(http.StatusOK, gin.H{
- "success": true,
- "token": tokenPair.AccessToken,
- "refreshToken": tokenPair.RefreshToken,
- "expiresAt": tokenPair.ExpiresAt,
+ "success": true,
+ "data": gin.H{
+ "token": tokenPair.AccessToken,
+ "refreshToken": tokenPair.RefreshToken,
+ "expiresAt": tokenPair.ExpiresAt,
+ },
})
}
@@ -271,7 +282,7 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
- "error": "Not authenticated",
+ "data": gin.H{"error": "Not authenticated"},
})
return
}
@@ -280,16 +291,15 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid request format",
+ "data": gin.H{"error": "Invalid request format"},
})
return
}
- // For password change after login, current password is required
if !user.RequirePasswordChange && req.CurrentPassword == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Current password is required",
+ "data": gin.H{"error": "Current password is required"},
})
return
}
@@ -316,13 +326,13 @@ func (h *AuthHandler) ChangePassword(c *gin.Context) {
c.JSON(statusCode, gin.H{
"success": false,
- "error": errorMsg,
+ "data": gin.H{"error": errorMsg},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Password changed successfully",
+ "data": gin.H{"message": "Password changed successfully"},
})
}
diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.go
index 64c387cda..a205c6d97 100644
--- a/backend/internal/api/container_handler.go
+++ b/backend/internal/api/container_handler.go
@@ -34,7 +34,7 @@ func (h *ContainerHandler) PullImage(c *gin.Context) {
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"success": false,
- "error": "Container not found: " + err.Error(),
+ "data": gin.H{"error": "Container not found: " + err.Error()},
})
return
}
@@ -43,29 +43,31 @@ func (h *ContainerHandler) PullImage(c *gin.Context) {
if imageName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Container has no image to pull",
+ "data": gin.H{"error": "Container has no image to pull"},
})
return
}
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
err = h.imageService.PullImage(c.Request.Context(), imageName, c.Writer, *currentUser)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to pull image: " + err.Error(),
+ "data": gin.H{"error": "Failed to pull image: " + err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Image pulled successfully",
- "image": imageName,
+ "data": gin.H{"message": "Image pulled successfully", "image": imageName},
})
}
@@ -74,7 +76,7 @@ func (h *ContainerHandler) List(c *gin.Context) {
if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid pagination or sort parameters: " + err.Error(),
+ "data": gin.H{"error": "Invalid pagination or sort parameters: " + err.Error()},
})
return
}
@@ -88,28 +90,11 @@ func (h *ContainerHandler) List(c *gin.Context) {
includeAll := true
- if req.Pagination.Page == 0 && req.Pagination.Limit == 0 {
- containers, err := h.containerService.ListContainers(c.Request.Context(), includeAll)
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": err.Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": containers,
- })
- return
- }
-
containers, pagination, err := h.containerService.ListContainersPaginated(c.Request.Context(), req, includeAll)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to list containers: " + err.Error(),
+ "data": gin.H{"error": "Failed to list containers: " + err.Error()},
})
return
}
@@ -128,14 +113,16 @@ func (h *ContainerHandler) GetByID(c *gin.Context) {
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
+ details := dto.NewContainerDetailsDto(container)
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": container,
+ "data": details,
})
}
@@ -144,20 +131,23 @@ func (h *ContainerHandler) Start(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
if err := h.containerService.StartContainer(c.Request.Context(), id, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Container started successfully",
+ "data": gin.H{"message": "Container started successfully"},
})
}
@@ -166,20 +156,23 @@ func (h *ContainerHandler) Stop(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
if err := h.containerService.StopContainer(c.Request.Context(), id, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Container stopped successfully",
+ "data": gin.H{"message": "Container stopped successfully"},
})
}
@@ -188,20 +181,23 @@ func (h *ContainerHandler) Restart(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
if err := h.containerService.RestartContainer(c.Request.Context(), id, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Container restarted successfully",
+ "data": gin.H{"message": "Container restarted successfully"},
})
}
@@ -213,7 +209,7 @@ func (h *ContainerHandler) GetLogs(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
@@ -231,20 +227,23 @@ func (h *ContainerHandler) Delete(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
if err := h.containerService.DeleteContainer(c.Request.Context(), id, force, removeVolumes, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Container deleted successfully",
+ "data": gin.H{"message": "Container deleted successfully"},
})
}
@@ -253,7 +252,7 @@ func (h *ContainerHandler) IsImageInUse(c *gin.Context) {
if imageID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Image ID is required",
+ "data": gin.H{"error": "Image ID is required"},
})
return
}
@@ -262,7 +261,7 @@ func (h *ContainerHandler) IsImageInUse(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to list containers: " + err.Error(),
+ "data": gin.H{"error": "Failed to list containers: " + err.Error()},
})
return
}
@@ -277,7 +276,7 @@ func (h *ContainerHandler) IsImageInUse(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "inUse": inUse,
+ "data": gin.H{"inUse": inUse},
})
}
@@ -286,7 +285,7 @@ func (h *ContainerHandler) Create(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid request format: " + err.Error(),
+ "data": gin.H{"error": "Invalid request format: " + err.Error()},
})
return
}
@@ -310,7 +309,7 @@ func (h *ContainerHandler) Create(c *gin.Context) {
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid port format: " + err.Error(),
+ "data": gin.H{"error": "Invalid port format: " + err.Error()},
})
return
}
@@ -351,7 +350,10 @@ func (h *ContainerHandler) Create(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
containerJSON, err := h.containerService.CreateContainer(
@@ -365,20 +367,22 @@ func (h *ContainerHandler) Create(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
+ out := dto.ContainerCreatedDto{
+ 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": gin.H{
- "id": containerJSON.ID,
- "name": containerJSON.Name,
- "image": containerJSON.Config.Image,
- "status": containerJSON.State.Status,
- "created": containerJSON.Created,
- },
+ "data": out,
})
}
@@ -388,7 +392,7 @@ func (h *ContainerHandler) GetStats(c *gin.Context) {
if containerID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Container ID is required",
+ "data": gin.H{"error": "Container ID is required"},
})
return
}
@@ -400,7 +404,7 @@ func (h *ContainerHandler) GetStats(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": gin.H{"error": err.Error()},
})
return
}
@@ -416,7 +420,7 @@ func (h *ContainerHandler) GetStatsStream(c *gin.Context) {
if containerID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Container ID is required",
+ "data": gin.H{"error": "Container ID is required"},
})
return
}
@@ -464,7 +468,7 @@ func (h *ContainerHandler) GetLogsStream(c *gin.Context) {
if containerID == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Container ID is required",
+ "data": gin.H{"error": "Container ID is required"},
})
return
}
diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.go
index 93ec08a32..79c46a21c 100644
--- a/backend/internal/api/image_handler.go
+++ b/backend/internal/api/image_handler.go
@@ -4,8 +4,8 @@ import (
"fmt"
"log/slog"
"net/http"
- "strings"
+ "github.com/docker/docker/api/types/image"
"github.com/gin-gonic/gin"
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/middleware"
@@ -30,7 +30,7 @@ func (h *ImageHandler) List(c *gin.Context) {
if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid pagination or sort parameters: " + err.Error(),
+ "data": dto.MessageDto{Message: "Invalid pagination or sort parameters: " + err.Error()},
})
return
}
@@ -46,7 +46,7 @@ func (h *ImageHandler) List(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to list images: " + err.Error(),
+ "data": dto.MessageDto{Message: "Failed to list images: " + err.Error()},
})
return
}
@@ -63,13 +63,15 @@ func (h *ImageHandler) GetByID(c *gin.Context) {
img, err := h.imageService.GetImageByID(c.Request.Context(), id)
if err != nil {
- c.JSON(http.StatusNotFound, gin.H{"success": false, "error": err.Error()})
+ c.JSON(http.StatusNotFound, gin.H{"success": false, "data": dto.MessageDto{Message: err.Error()}})
return
}
+ out := dto.NewImageDetailSummaryDto(img)
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": dto.NewImageDetailSummaryDto(img),
+ "data": out,
})
}
@@ -79,20 +81,20 @@ func (h *ImageHandler) Remove(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
return
}
if err := h.imageService.RemoveImage(c.Request.Context(), id, force, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Image removed successfully",
+ "data": dto.MessageDto{Message: "Image removed successfully"},
})
}
@@ -103,7 +105,7 @@ func (h *ImageHandler) Pull(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid request body: " + err.Error(),
+ "data": dto.MessageDto{Message: "Invalid request body: " + err.Error()},
})
return
}
@@ -115,33 +117,15 @@ func (h *ImageHandler) Pull(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
return
}
- err := h.imageService.PullImage(ctx, req.ImageName, c.Writer, *currentUser)
- if err != nil {
- if !c.Writer.Written() {
- if strings.Contains(err.Error(), "not found") || strings.Contains(err.Error(), "manifest unknown") {
- c.JSON(http.StatusNotFound, gin.H{
- "success": false,
- "error": fmt.Sprintf("Failed to pull image '%s': %s. Ensure the image name and tag are correct and the image exists in the registry.", req.ImageName, err.Error()),
- })
- } else {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": fmt.Sprintf("Failed to pull image '%s': %s", req.ImageName, err.Error()),
- })
- }
- } else {
- slog.ErrorContext(ctx, "Error during image pull stream or post-stream operation",
- slog.String("imageName", req.ImageName),
- slog.String("error", err.Error()))
- fmt.Fprintf(c.Writer, `{"error": {"code": 500, "message": "Stream interrupted or post-stream operation failed: %s"}}\n`, strings.ReplaceAll(err.Error(), "\"", "'"))
- if flusher, ok := c.Writer.(http.Flusher); ok {
- flusher.Flush()
- }
- }
+ if err := h.imageService.PullImage(ctx, req.ImageName, c.Writer, *currentUser); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": dto.MessageDto{Message: fmt.Sprintf("Failed to pull image '%s': %s", req.ImageName, err.Error())},
+ })
return
}
@@ -156,14 +140,16 @@ func (h *ImageHandler) Prune(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
+ out := dto.NewImagePruneReportDto(*report)
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": report,
+ "data": out,
})
}
@@ -174,14 +160,20 @@ func (h *ImageHandler) GetHistory(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
+ out, mapErr := dto.MapSlice[image.HistoryResponseItem, dto.ImageHistoryItemDto](history)
+ if mapErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": dto.MessageDto{Message: mapErr.Error()}})
+ return
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": history,
+ "data": out,
})
}
@@ -192,15 +184,13 @@ func (h *ImageHandler) GetTotalSize(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": gin.H{
- "totalSize": total,
- },
+ "data": dto.TotalImageSizeDto{TotalSize: total},
})
}
diff --git a/backend/internal/api/network_handler.go b/backend/internal/api/network_handler.go
index 4e0eec89a..e2d158511 100644
--- a/backend/internal/api/network_handler.go
+++ b/backend/internal/api/network_handler.go
@@ -5,6 +5,7 @@ import (
"github.com/docker/docker/api/types/network"
"github.com/gin-gonic/gin"
+ "github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/middleware"
"github.com/ofkm/arcane-backend/internal/services"
"github.com/ofkm/arcane-backend/internal/utils"
@@ -25,7 +26,7 @@ func (h *NetworkHandler) List(c *gin.Context) {
if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid pagination or sort parameters: " + err.Error(),
+ "data": dto.MessageDto{Message: "Invalid pagination or sort parameters: " + err.Error()},
})
return
}
@@ -37,48 +38,11 @@ func (h *NetworkHandler) List(c *gin.Context) {
req.Pagination.Limit = 20
}
- driver := c.Query("driver")
- scope := c.Query("scope")
- userDefined := c.Query("user_defined") == "true"
- defaults := c.Query("defaults") == "true"
-
- if req.Pagination.Page == 0 && req.Pagination.Limit == 0 {
- var networks []network.Summary
- var err error
-
- switch {
- case driver != "":
- networks, err = h.networkService.GetNetworksByDriver(c.Request.Context(), driver)
- case scope != "":
- networks, err = h.networkService.GetNetworksByScope(c.Request.Context(), scope)
- case userDefined:
- networks, err = h.networkService.GetUserDefinedNetworks(c.Request.Context())
- case defaults:
- networks, err = h.networkService.GetDefaultNetworks(c.Request.Context())
- default:
- networks, err = h.networkService.ListNetworks(c.Request.Context())
- }
-
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": err.Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": networks,
- })
- return
- }
-
networks, pagination, err := h.networkService.ListNetworksPaginated(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to list networks: " + err.Error(),
+ "data": dto.MessageDto{Message: "Failed to list networks: " + err.Error()},
})
return
}
@@ -93,18 +57,24 @@ func (h *NetworkHandler) List(c *gin.Context) {
func (h *NetworkHandler) GetByID(c *gin.Context) {
id := c.Param("networkId")
- network, err := h.networkService.GetNetworkByID(c.Request.Context(), id)
+ networkInspect, err := h.networkService.GetNetworkByID(c.Request.Context(), id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
+ out, mapErr := dto.MapOne[network.Inspect, dto.NetworkInspectDto](*networkInspect)
+ if mapErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": dto.MessageDto{Message: mapErr.Error()}})
+ return
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": network,
+ "data": out,
})
}
@@ -117,28 +87,34 @@ func (h *NetworkHandler) Create(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
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,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
+ out, mapErr := dto.MapOne[network.CreateResponse, dto.NetworkCreateResponseDto](*response)
+ if mapErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": dto.MessageDto{Message: mapErr.Error()}})
+ return
+ }
+
c.JSON(http.StatusCreated, gin.H{
"success": true,
- "data": response,
+ "data": out,
})
}
@@ -147,20 +123,20 @@ func (h *NetworkHandler) Remove(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
return
}
if err := h.networkService.RemoveNetwork(c.Request.Context(), id, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Network removed successfully",
+ "data": dto.MessageDto{Message: "Network removed successfully"},
})
}
@@ -175,27 +151,27 @@ func (h *NetworkHandler) ConnectContainer(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
return
}
if err := h.networkService.ConnectContainer(c.Request.Context(), networkID, req.ContainerID, req.Config, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Container connected to network successfully",
+ "data": dto.MessageDto{Message: "Container connected to network successfully"},
})
}
@@ -210,27 +186,27 @@ func (h *NetworkHandler) DisconnectContainer(c *gin.Context) {
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
return
}
if err := h.networkService.DisconnectContainer(c.Request.Context(), networkID, req.ContainerID, req.Force, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Container disconnected from network successfully",
+ "data": dto.MessageDto{Message: "Container disconnected from network successfully"},
})
}
@@ -239,13 +215,19 @@ func (h *NetworkHandler) Prune(c *gin.Context) {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": err.Error(),
+ "data": dto.MessageDto{Message: err.Error()},
})
return
}
+ out, mapErr := dto.MapOne[network.PruneReport, dto.NetworkPruneReportDto](*report)
+ if mapErr != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": dto.MessageDto{Message: mapErr.Error()}})
+ return
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": report,
+ "data": out,
})
}
diff --git a/backend/internal/api/stack_handler.go b/backend/internal/api/stack_handler.go
index 303c05480..01eddf215 100644
--- a/backend/internal/api/stack_handler.go
+++ b/backend/internal/api/stack_handler.go
@@ -77,42 +77,37 @@ func (h *StackHandler) ListStacks(c *gin.Context) {
func (h *StackHandler) CreateStack(c *gin.Context) {
var req dto.CreateStackDto
if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": err.Error()})
return
}
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
stack, err := h.stackService.CreateStack(c.Request.Context(), req.Name, req.ComposeContent, req.EnvContent, *currentUser)
if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": err.Error()})
return
}
- // Convert to response DTO
- response := dto.CreateStackResponseDto{
- ID: stack.ID,
- Name: stack.Name,
- Path: stack.Path,
- Status: string(stack.Status),
- ServiceCount: stack.ServiceCount,
- RunningCount: stack.RunningCount,
- AutoUpdate: stack.AutoUpdate,
- IsExternal: stack.IsExternal,
- IsLegacy: stack.IsLegacy,
- IsRemote: stack.IsRemote,
- CreatedAt: stack.CreatedAt.Format(time.RFC3339),
- UpdatedAt: stack.UpdatedAt.Format(time.RFC3339),
+ var response dto.CreateStackResponseDto
+ if err := dto.MapStruct(stack, &response); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "failed to map response"})
+ return
}
-
+ response.Status = string(stack.Status)
+ response.CreatedAt = stack.CreatedAt.Format(time.RFC3339)
+ response.UpdatedAt = stack.UpdatedAt.Format(time.RFC3339)
if stack.DirName != nil {
response.DirName = *stack.DirName
}
- c.JSON(http.StatusCreated, response)
+ c.JSON(http.StatusCreated, gin.H{
+ "success": true,
+ "data": response,
+ })
}
func (h *StackHandler) GetStack(c *gin.Context) {
@@ -145,8 +140,9 @@ func (h *StackHandler) GetStack(c *gin.Context) {
var serviceCount, runningCount int
if services != nil {
serviceCount = len(services)
- for _, service := range services {
- if service.Status == "running" || service.Status == "Up" {
+ for _, s := range services {
+ st := strings.ToLower(strings.TrimSpace(s.Status))
+ if st == "running" || st == "up" {
runningCount++
}
}
@@ -155,27 +151,33 @@ func (h *StackHandler) GetStack(c *gin.Context) {
runningCount = stack.RunningCount
}
- stackResponse := map[string]interface{}{
- "id": stack.ID,
- "name": stack.Name,
- "path": stack.Path,
- "composeContent": composeContent,
- "envContent": envContent,
- "status": stack.Status,
- "serviceCount": serviceCount,
- "runningCount": runningCount,
- "createdAt": stack.CreatedAt,
- "updatedAt": stack.UpdatedAt,
- "autoUpdate": stack.AutoUpdate,
- "isExternal": stack.IsExternal,
- "isLegacy": stack.IsLegacy,
- "isRemote": stack.IsRemote,
- "services": services,
+ var resp dto.StackDetailsDto
+ if err := dto.MapStruct(stack, &resp); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "failed to map response"})
+ return
+ }
+ resp.Status = string(stack.Status)
+ resp.CreatedAt = stack.CreatedAt.Format(time.RFC3339)
+ resp.UpdatedAt = stack.UpdatedAt.Format(time.RFC3339)
+ if stack.DirName != nil {
+ resp.DirName = *stack.DirName
+ }
+ resp.ComposeContent = composeContent
+ resp.EnvContent = envContent
+ resp.ServiceCount = serviceCount
+ resp.RunningCount = runningCount
+ if services != nil {
+ // pass-through as []any to avoid changing service shape
+ raw := make([]any, len(services))
+ for i := range services {
+ raw[i] = services[i]
+ }
+ resp.Services = raw
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "stack": stackResponse,
+ "data": resp,
})
}
@@ -245,25 +247,30 @@ func (h *StackHandler) UpdateStack(c *gin.Context) {
services = nil
}
- stackResponse := map[string]interface{}{
- "id": updatedStack.ID,
- "name": updatedStack.Name,
- "path": updatedStack.Path,
- "status": updatedStack.Status,
- "serviceCount": len(services),
- "runningCount": updatedStack.RunningCount,
- "createdAt": updatedStack.CreatedAt,
- "updatedAt": updatedStack.UpdatedAt,
- "autoUpdate": updatedStack.AutoUpdate,
- "isExternal": updatedStack.IsExternal,
- "isLegacy": updatedStack.IsLegacy,
- "isRemote": updatedStack.IsRemote,
- "services": services,
+ var resp dto.StackDetailsDto
+ if err := dto.MapStruct(updatedStack, &resp); err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "failed to map response"})
+ return
+ }
+ resp.Status = string(updatedStack.Status)
+ resp.CreatedAt = updatedStack.CreatedAt.Format(time.RFC3339)
+ resp.UpdatedAt = updatedStack.UpdatedAt.Format(time.RFC3339)
+ if updatedStack.DirName != nil {
+ resp.DirName = *updatedStack.DirName
+ }
+ resp.ServiceCount = len(services)
+ resp.RunningCount = updatedStack.RunningCount
+ if services != nil {
+ raw := make([]any, len(services))
+ for i := range services {
+ raw[i] = services[i]
+ }
+ resp.Services = raw
}
c.JSON(http.StatusOK, gin.H{
"success": true,
- "stack": stackResponse,
+ "data": resp,
})
}
@@ -275,7 +282,7 @@ func (h *StackHandler) DeleteStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
err := h.stackService.DeleteStack(c.Request.Context(), stackID, *currentUser)
@@ -289,7 +296,7 @@ func (h *StackHandler) DeleteStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack deleted successfully",
+ "data": gin.H{"message": "Stack deleted successfully"},
})
}
@@ -309,7 +316,7 @@ func (h *StackHandler) StartStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
if err := h.stackService.DeployStack(c.Request.Context(), stackID, *currentUser); err != nil {
@@ -322,7 +329,7 @@ func (h *StackHandler) StartStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack started successfully",
+ "data": gin.H{"message": "Stack started successfully"},
})
}
@@ -334,7 +341,7 @@ func (h *StackHandler) StopStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
if err := h.stackService.StopStack(c.Request.Context(), stackID, *currentUser); err != nil {
@@ -347,7 +354,7 @@ func (h *StackHandler) StopStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack stopped successfully",
+ "data": gin.H{"message": "Stack stopped successfully"},
})
}
@@ -359,7 +366,7 @@ func (h *StackHandler) RestartStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
if err := h.stackService.RestartStack(c.Request.Context(), stackID, *currentUser); err != nil {
@@ -372,7 +379,7 @@ func (h *StackHandler) RestartStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack restarted successfully",
+ "data": gin.H{"message": "Stack restarted successfully"},
})
}
@@ -392,7 +399,7 @@ func (h *StackHandler) RedeployStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
if err := h.stackService.RedeployStack(c.Request.Context(), stackID, req.Profiles, req.EnvOverrides, *currentUser); err != nil {
@@ -405,7 +412,7 @@ func (h *StackHandler) RedeployStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack redeployed successfully",
+ "data": gin.H{"message": "Stack redeployed successfully"},
})
}
@@ -417,7 +424,7 @@ func (h *StackHandler) DownStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
if err := h.stackService.DownStack(c.Request.Context(), stackID, *currentUser); err != nil {
@@ -430,7 +437,7 @@ func (h *StackHandler) DownStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack brought down successfully",
+ "data": gin.H{"message": "Stack brought down successfully"},
})
}
@@ -450,7 +457,7 @@ func (h *StackHandler) DestroyStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
if err := h.stackService.DestroyStack(c.Request.Context(), stackID, req.RemoveFiles, req.RemoveVolumes, *currentUser); err != nil {
@@ -463,7 +470,7 @@ func (h *StackHandler) DestroyStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack destroyed successfully",
+ "data": gin.H{"message": "Stack destroyed successfully"},
})
}
@@ -472,8 +479,7 @@ func (h *StackHandler) PullStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack images pulled successfully",
- "stackId": stackID,
+ "data": gin.H{"message": "Stack images pulled successfully", "stackId": stackID},
})
}
@@ -499,7 +505,7 @@ func (h *StackHandler) DeployStack(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "User not authenticated"})
return
}
if err := h.stackService.DeployStack(c.Request.Context(), stackID, *currentUser); err != nil {
@@ -512,7 +518,7 @@ func (h *StackHandler) DeployStack(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Stack deployed successfully",
+ "data": gin.H{"message": "Stack deployed successfully"},
})
}
@@ -553,7 +559,7 @@ func (h *StackHandler) PullImages(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Images pulled successfully",
+ "data": gin.H{"message": "Images pulled successfully"},
})
}
@@ -587,11 +593,14 @@ func (h *StackHandler) ConvertDockerRun(c *gin.Context) {
return
}
- c.JSON(http.StatusOK, models.ConvertDockerRunResponse{
- Success: true,
- DockerCompose: dockerCompose,
- EnvVars: envVars,
- ServiceName: serviceName,
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": models.ConvertDockerRunResponse{
+ Success: true,
+ DockerCompose: dockerCompose,
+ EnvVars: envVars,
+ ServiceName: serviceName,
+ },
})
}
diff --git a/backend/internal/api/user_handler.go b/backend/internal/api/user_handler.go
index d9a6ecdad..b08a67137 100644
--- a/backend/internal/api/user_handler.go
+++ b/backend/internal/api/user_handler.go
@@ -38,7 +38,6 @@ func (h *UserHandler) ListUsers(c *gin.Context) {
req.Pagination.Limit = 20
}
- // For non-paginated requests (when both page and limit are default/zero)
if req.Pagination.Page == 1 && req.Pagination.Limit == 20 && req.Search == "" && req.Sort.Column == "" {
users, err := h.userService.ListUsers(c.Request.Context())
if err != nil {
@@ -49,16 +48,13 @@ func (h *UserHandler) ListUsers(c *gin.Context) {
return
}
- var userResponses []dto.UserResponseDto
- for _, user := range users {
- userResponses = append(userResponses, dto.UserResponseDto{
- ID: user.ID,
- Username: user.Username,
- DisplayName: user.DisplayName,
- Email: user.Email,
- Roles: user.Roles,
- OidcSubjectId: user.OidcSubjectId,
+ userResponses, err := dto.MapSlice[models.User, dto.UserResponseDto](users)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to map users"},
})
+ return
}
c.JSON(http.StatusOK, gin.H{
@@ -127,16 +123,18 @@ func (h *UserHandler) CreateUser(c *gin.Context) {
return
}
+ out, err := dto.MapOne[*models.User, dto.UserResponseDto](createdUser)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to map user"},
+ })
+ return
+ }
+
c.JSON(http.StatusCreated, gin.H{
"success": true,
- "data": dto.UserResponseDto{
- ID: createdUser.ID,
- Username: createdUser.Username,
- DisplayName: createdUser.DisplayName,
- Email: createdUser.Email,
- Roles: createdUser.Roles,
- OidcSubjectId: createdUser.OidcSubjectId,
- },
+ "data": out,
})
}
@@ -152,16 +150,18 @@ func (h *UserHandler) GetUser(c *gin.Context) {
return
}
+ out, err := dto.MapOne[*models.User, dto.UserResponseDto](user)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to map user"},
+ })
+ return
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": dto.UserResponseDto{
- ID: user.ID,
- Username: user.Username,
- DisplayName: user.DisplayName,
- Email: user.Email,
- Roles: user.Roles,
- OidcSubjectId: user.OidcSubjectId,
- },
+ "data": out,
})
}
@@ -208,16 +208,18 @@ func (h *UserHandler) UpdateUser(c *gin.Context) {
return
}
+ out, err := dto.MapOne[*models.User, dto.UserResponseDto](updatedUser)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Failed to map user"},
+ })
+ return
+ }
+
c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": dto.UserResponseDto{
- ID: updatedUser.ID,
- Username: updatedUser.Username,
- DisplayName: updatedUser.DisplayName,
- Email: updatedUser.Email,
- Roles: updatedUser.Roles,
- OidcSubjectId: updatedUser.OidcSubjectId,
- },
+ "data": out,
})
}
diff --git a/backend/internal/api/volume_handler.go b/backend/internal/api/volume_handler.go
index 2a9f08272..17c1c1dbf 100644
--- a/backend/internal/api/volume_handler.go
+++ b/backend/internal/api/volume_handler.go
@@ -5,16 +5,17 @@ import (
"github.com/docker/docker/api/types/volume"
"github.com/gin-gonic/gin"
+ "github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/middleware"
- "github.com/ofkm/arcane-backend/internal/services"
+ github_com_ofkm_arcane_backend_internal_services "github.com/ofkm/arcane-backend/internal/services"
"github.com/ofkm/arcane-backend/internal/utils"
)
type VolumeHandler struct {
- volumeService *services.VolumeService
+ volumeService *github_com_ofkm_arcane_backend_internal_services.VolumeService
}
-func NewVolumeHandler(volumeService *services.VolumeService) *VolumeHandler {
+func NewVolumeHandler(volumeService *github_com_ofkm_arcane_backend_internal_services.VolumeService) *VolumeHandler {
return &VolumeHandler{
volumeService: volumeService,
}
@@ -25,11 +26,12 @@ func (h *VolumeHandler) List(c *gin.Context) {
if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
- "error": "Invalid pagination or sort parameters: " + err.Error(),
+ "data": gin.H{"error": "Invalid pagination or sort parameters: " + err.Error()},
})
return
}
+ // defaults like container handler
if req.Pagination.Page == 0 {
req.Pagination.Page = 1
}
@@ -39,38 +41,11 @@ func (h *VolumeHandler) List(c *gin.Context) {
driver := c.Query("driver")
- if req.Pagination.Page == 0 && req.Pagination.Limit == 0 {
- volumes, err := h.volumeService.ListVolumesWithUsage(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "error": err.Error(),
- })
- return
- }
-
- if driver != "" {
- filtered := make([]map[string]interface{}, 0)
- for _, vol := range volumes {
- if volDriver, ok := vol["Driver"].(string); ok && volDriver == driver {
- filtered = append(filtered, vol)
- }
- }
- volumes = filtered
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": volumes,
- })
- return
- }
-
- volumes, pagination, err := h.volumeService.ListVolumesPaginated(c.Request.Context(), req)
+ volumes, pagination, err := h.volumeService.ListVolumesPaginated(c.Request.Context(), req, driver)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
- "error": "Failed to list volumes: " + err.Error(),
+ "data": gin.H{"error": "Failed to list volumes: " + err.Error()},
})
return
}
@@ -85,31 +60,27 @@ func (h *VolumeHandler) List(c *gin.Context) {
func (h *VolumeHandler) GetByName(c *gin.Context) {
name := c.Param("volumeName")
- volume, err := h.volumeService.GetVolumeByName(c.Request.Context(), name)
+ vol, err := h.volumeService.GetVolumeByName(c.Request.Context(), name)
if err != nil {
- c.JSON(404, gin.H{
- "error": err.Error(),
+ c.JSON(http.StatusNotFound, gin.H{
+ "success": false,
+ "data": gin.H{"error": err.Error()},
})
return
}
- c.JSON(200, gin.H{
+ c.JSON(http.StatusOK, gin.H{
"success": true,
- "data": volume,
+ "data": vol,
})
}
func (h *VolumeHandler) Create(c *gin.Context) {
- var req struct {
- Name string `json:"name"`
- Driver string `json:"driver"`
- Labels map[string]string `json:"labels"`
- Options map[string]string `json:"options"`
- }
-
+ var req dto.CreateVolumeDto
if err := c.ShouldBindJSON(&req); err != nil {
- c.JSON(400, gin.H{
- "error": "Invalid request: " + err.Error(),
+ c.JSON(http.StatusBadRequest, gin.H{
+ "success": false,
+ "data": gin.H{"error": "Invalid request: " + err.Error()},
})
return
}
@@ -123,21 +94,24 @@ func (h *VolumeHandler) Create(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
response, err := h.volumeService.CreateVolume(c.Request.Context(), options, *currentUser)
if err != nil {
- c.JSON(500, gin.H{
- "error": err.Error(),
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": err.Error()},
})
return
}
- c.JSON(201, gin.H{
+ c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": response,
- "message": "Volume created successfully",
})
}
@@ -147,35 +121,39 @@ func (h *VolumeHandler) Remove(c *gin.Context) {
currentUser, exists := middleware.GetCurrentUser(c)
if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ c.JSON(http.StatusUnauthorized, gin.H{
+ "success": false,
+ "data": gin.H{"error": "User not authenticated"},
+ })
return
}
if err := h.volumeService.DeleteVolume(c.Request.Context(), name, force, *currentUser); err != nil {
- c.JSON(500, gin.H{
- "error": err.Error(),
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": err.Error()},
})
return
}
- c.JSON(200, gin.H{
+ c.JSON(http.StatusOK, gin.H{
"success": true,
- "message": "Volume removed successfully",
+ "data": gin.H{"message": "Volume removed successfully"},
})
}
func (h *VolumeHandler) Prune(c *gin.Context) {
report, err := h.volumeService.PruneVolumes(c.Request.Context())
if err != nil {
- c.JSON(500, gin.H{
- "error": err.Error(),
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": err.Error()},
})
return
}
- c.JSON(200, gin.H{
+ c.JSON(http.StatusOK, gin.H{
"success": true,
"data": report,
- "message": "Volumes pruned successfully",
})
}
@@ -184,13 +162,14 @@ func (h *VolumeHandler) GetUsage(c *gin.Context) {
inUse, containers, err := h.volumeService.GetVolumeUsage(c.Request.Context(), name)
if err != nil {
- c.JSON(500, gin.H{
- "error": err.Error(),
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "data": gin.H{"error": err.Error()},
})
return
}
- c.JSON(200, gin.H{
+ c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"inUse": inUse,
diff --git a/backend/internal/dto/container_dto.go b/backend/internal/dto/container_dto.go
index a507d675a..745056b57 100644
--- a/backend/internal/dto/container_dto.go
+++ b/backend/internal/dto/container_dto.go
@@ -1,6 +1,9 @@
package dto
import (
+ "strconv"
+ "strings"
+
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
)
@@ -91,9 +94,7 @@ type ContainerSummaryDto struct {
Mounts []MountDto `json:"mounts"`
}
-// Mapper from Docker's container.Summary to DTO
func NewContainerSummaryDto(c container.Summary) ContainerSummaryDto {
- // Ports
ports := make([]PortDto, 0, len(c.Ports))
for _, p := range c.Ports {
ports = append(ports, PortDto{
@@ -104,7 +105,6 @@ func NewContainerSummaryDto(c container.Summary) ContainerSummaryDto {
})
}
- // Mounts
mounts := make([]MountDto, 0, len(c.Mounts))
for _, m := range c.Mounts {
mounts = append(mounts, MountDto{
@@ -119,7 +119,6 @@ func NewContainerSummaryDto(c container.Summary) ContainerSummaryDto {
})
}
- // Networks
networks := map[string]NetworkDto{}
if c.NetworkSettings != nil && c.NetworkSettings.Networks != nil {
for name, n := range c.NetworkSettings.Networks {
@@ -176,3 +175,188 @@ func mapEndpointSettings(n *network.EndpointSettings) NetworkDto {
DNSNames: n.DNSNames,
}
}
+
+type ContainerStateDto struct {
+ Status string `json:"status"`
+ Running bool `json:"running"`
+ ExitCode int `json:"exitCode,omitempty"`
+ StartedAt string `json:"startedAt,omitempty"`
+ FinishedAt string `json:"finishedAt,omitempty"`
+}
+
+type ContainerConfigDetailsDto struct {
+ Env []string `json:"env,omitempty"`
+ Cmd []string `json:"cmd,omitempty"`
+ Entrypoint []string `json:"entrypoint,omitempty"`
+ WorkingDir string `json:"workingDir,omitempty"`
+ User string `json:"user,omitempty"`
+}
+
+type HostConfigDetailsDto struct {
+ RestartPolicy string `json:"restartPolicy,omitempty"`
+ Privileged bool `json:"privileged,omitempty"`
+ AutoRemove bool `json:"autoRemove,omitempty"`
+ NanoCPUs int64 `json:"nanoCpus,omitempty"`
+ Memory int64 `json:"memory,omitempty"`
+}
+
+type ContainerDetailsDto struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Image string `json:"image"`
+ ImageID string `json:"imageId"`
+ Created string `json:"created"`
+ State ContainerStateDto `json:"state"`
+ Config ContainerConfigDetailsDto `json:"config"`
+ HostConfig HostConfigDetailsDto `json:"hostConfig"`
+ NetworkSettings NetworkSettingsDto `json:"networkSettings"`
+ Ports []PortDto `json:"ports"`
+ Mounts []MountDto `json:"mounts"`
+ Labels map[string]string `json:"labels,omitempty"`
+}
+
+type ContainerCreatedDto struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Image string `json:"image"`
+ Status string `json:"status"`
+ Created string `json:"created"`
+}
+
+func NewContainerDetailsDto(c *container.InspectResponse) ContainerDetailsDto {
+ ports := make([]PortDto, 0)
+ if c.NetworkSettings != nil && c.NetworkSettings.Ports != nil {
+ for p, bindings := range c.NetworkSettings.Ports {
+ privatePort, _ := strconv.Atoi(p.Port())
+ typ := string(p.Proto())
+
+ // When no host bindings exist, still include the private port
+ if len(bindings) == 0 {
+ ports = append(ports, PortDto{
+ PrivatePort: privatePort,
+ Type: typ,
+ })
+ continue
+ }
+ for _, b := range bindings {
+ pub, _ := strconv.Atoi(b.HostPort)
+ ports = append(ports, PortDto{
+ IP: b.HostIP,
+ PrivatePort: privatePort,
+ PublicPort: pub,
+ Type: typ,
+ })
+ }
+ }
+ }
+
+ mounts := make([]MountDto, 0, len(c.Mounts))
+ for _, m := range c.Mounts {
+ mounts = append(mounts, mapMountPoint(m))
+ }
+
+ networks := map[string]NetworkDto{}
+ if c.NetworkSettings != nil && c.NetworkSettings.Networks != nil {
+ for name, n := range c.NetworkSettings.Networks {
+ networks[name] = mapEndpointSettings(n)
+ }
+ }
+
+ var host HostConfigDetailsDto
+ if c.HostConfig != nil {
+ host = HostConfigDetailsDto{
+ RestartPolicy: string(c.HostConfig.RestartPolicy.Name),
+ Privileged: c.HostConfig.Privileged,
+ AutoRemove: c.HostConfig.AutoRemove,
+ NanoCPUs: c.HostConfig.NanoCPUs,
+ Memory: c.HostConfig.Memory,
+ }
+ }
+
+ var cfg ContainerConfigDetailsDto
+ labels := map[string]string{}
+ imageName := ""
+ if c.Config != nil {
+ cfg = ContainerConfigDetailsDto{
+ Env: append([]string{}, c.Config.Env...),
+ Cmd: append([]string{}, c.Config.Cmd...),
+ Entrypoint: append([]string{}, c.Config.Entrypoint...),
+ WorkingDir: c.Config.WorkingDir,
+ User: c.Config.User,
+ }
+ imageName = c.Config.Image
+ if c.Config.Labels != nil {
+ for k, v := range c.Config.Labels {
+ labels[k] = v
+ }
+ }
+ }
+
+ name := strings.TrimPrefix(c.Name, "/")
+
+ out := ContainerDetailsDto{
+ ID: c.ID,
+ Name: name,
+ Image: imageName,
+ ImageID: c.Image,
+ Created: c.Created,
+ State: ContainerStateDto{
+ Status: safeStateStatus(c),
+ Running: safeStateRunning(c),
+ ExitCode: safeStateExitCode(c),
+ StartedAt: safeStateStartedAt(c),
+ FinishedAt: safeStateFinishedAt(c),
+ },
+ Config: cfg,
+ HostConfig: host,
+ NetworkSettings: NetworkSettingsDto{
+ Networks: networks,
+ },
+ Ports: ports,
+ Mounts: mounts,
+ Labels: labels,
+ }
+
+ return out
+}
+
+func mapMountPoint(m container.MountPoint) MountDto {
+ return MountDto{
+ Type: string(m.Type),
+ Name: m.Name,
+ Source: m.Source,
+ Destination: m.Destination,
+ Driver: m.Driver,
+ Mode: m.Mode,
+ RW: m.RW,
+ Propagation: string(m.Propagation),
+ }
+}
+
+func safeStateStatus(c *container.InspectResponse) string {
+ if c.State == nil {
+ return ""
+ }
+ return c.State.Status
+}
+func safeStateRunning(c *container.InspectResponse) bool {
+ return c.State != nil && c.State.Running
+}
+func safeStateExitCode(c *container.InspectResponse) int {
+ if c.State == nil {
+ return 0
+ }
+ return c.State.ExitCode
+}
+func safeStateStartedAt(c *container.InspectResponse) string {
+ if c.State == nil {
+ return ""
+ }
+ return c.State.StartedAt
+}
+func safeStateFinishedAt(c *container.InspectResponse) string {
+ if c.State == nil {
+ return ""
+ }
+ return c.State.FinishedAt
+}
diff --git a/backend/internal/dto/dto_map.go b/backend/internal/dto/dto_map.go
index ba0534313..7b1705388 100644
--- a/backend/internal/dto/dto_map.go
+++ b/backend/internal/dto/dto_map.go
@@ -8,6 +8,26 @@ import (
"github.com/jinzhu/copier"
)
+// MapSlice maps []S -> []D and returns the new slice
+func MapSlice[S any, D any](source []S) ([]D, error) {
+ dest := make([]D, len(source))
+ for i := range source {
+ if err := MapStruct(source[i], &dest[i]); err != nil {
+ return nil, fmt.Errorf("failed to map field %d: %w", i, err)
+ }
+ }
+ return dest, nil
+}
+
+// MapOne maps S -> D and returns the new value
+func MapOne[S any, D any](source S) (D, error) {
+ var dest D
+ if err := MapStruct(source, &dest); err != nil {
+ return dest, err
+ }
+ return dest, nil
+}
+
func MapStructList[S any, D any](source []S, destination *[]D) (err error) {
*destination = make([]D, len(source))
diff --git a/backend/internal/dto/image_dto.go b/backend/internal/dto/image_dto.go
index c0512aaba..241990dff 100644
--- a/backend/internal/dto/image_dto.go
+++ b/backend/internal/dto/image_dto.go
@@ -183,3 +183,53 @@ func NewImageDetailSummaryDto(src *image.InspectResponse) ImageDetailSummaryDto
return out
}
+
+// Used for GET /images/:imageId
+type ImageInspectDto struct {
+ ID string `json:"id"`
+ RepoTags []string `json:"repoTags"`
+ RepoDigests []string `json:"repoDigests"`
+ Size int64 `json:"size"`
+ Created string `json:"created"`
+ OS string `json:"os"`
+ Architecture string `json:"architecture"`
+ Author string `json:"author"`
+ Comment string `json:"comment"`
+}
+
+type ImageHistoryItemDto struct {
+ ID string `json:"id"`
+ Created int64 `json:"created"`
+ CreatedBy string `json:"createdBy"`
+ Tags []string `json:"tags"`
+ Size int64 `json:"size"`
+ Comment string `json:"comment"`
+}
+
+type ImagePruneReportDto struct {
+ ImagesDeleted []string `json:"imagesDeleted"`
+ SpaceReclaimed int64 `json:"spaceReclaimed"`
+}
+
+func NewImagePruneReportDto(src image.PruneReport) ImagePruneReportDto {
+ out := ImagePruneReportDto{
+ ImagesDeleted: make([]string, 0, len(src.ImagesDeleted)),
+ SpaceReclaimed: int64(src.SpaceReclaimed),
+ }
+ for _, d := range src.ImagesDeleted {
+ if d.Deleted != "" {
+ out.ImagesDeleted = append(out.ImagesDeleted, d.Deleted)
+ } else if d.Untagged != "" {
+ out.ImagesDeleted = append(out.ImagesDeleted, d.Untagged)
+ }
+ }
+ return out
+}
+
+type MessageDto struct {
+ Message string `json:"message"`
+}
+
+type TotalImageSizeDto struct {
+ TotalSize int64 `json:"totalSize"`
+}
diff --git a/backend/internal/dto/network_dto.go b/backend/internal/dto/network_dto.go
new file mode 100644
index 000000000..079e71699
--- /dev/null
+++ b/backend/internal/dto/network_dto.go
@@ -0,0 +1,54 @@
+package dto
+
+import (
+ "time"
+
+ "github.com/docker/docker/api/types/network"
+)
+
+type NetworkSummaryDto struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Driver string `json:"driver"`
+ Scope string `json:"scope"`
+ Created time.Time `json:"created"`
+ Options map[string]string `json:"options"`
+ Labels map[string]string `json:"labels"`
+}
+
+type NetworkInspectDto struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Driver string `json:"driver"`
+ Scope string `json:"scope"`
+ Created time.Time `json:"created"`
+ Options map[string]string `json:"options"`
+ Labels map[string]string `json:"labels"`
+ Containers map[string]network.EndpointResource `json:"containers"`
+ IPAM network.IPAM `json:"ipam"`
+ Internal bool `json:"internal"`
+ Attachable bool `json:"attachable"`
+ Ingress bool `json:"ingress"`
+}
+
+type NetworkCreateResponseDto struct {
+ ID string `json:"id"`
+ Warning string `json:"warning,omitempty"`
+}
+
+type NetworkPruneReportDto struct {
+ NetworksDeleted []string `json:"networksDeleted"`
+ SpaceReclaimed uint64 `json:"spaceReclaimed"`
+}
+
+func NewNetworkSummaryDto(s network.Summary) NetworkSummaryDto {
+ return NetworkSummaryDto{
+ ID: s.ID,
+ Name: s.Name,
+ Driver: s.Driver,
+ Scope: s.Scope,
+ Created: s.Created,
+ Options: s.Options,
+ Labels: s.Labels,
+ }
+}
diff --git a/backend/internal/dto/stack_dto.go b/backend/internal/dto/stack_dto.go
index 4198bc914..8eaa6ef33 100644
--- a/backend/internal/dto/stack_dto.go
+++ b/backend/internal/dto/stack_dto.go
@@ -39,3 +39,22 @@ type DestroyStackDto struct {
RemoveFiles bool `json:"removeFiles,omitempty"`
RemoveVolumes bool `json:"removeVolumes,omitempty"`
}
+
+type StackDetailsDto struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ DirName string `json:"dirName,omitempty"`
+ Path string `json:"path"`
+ ComposeContent string `json:"composeContent,omitempty"`
+ EnvContent string `json:"envContent,omitempty"`
+ Status string `json:"status"`
+ ServiceCount int `json:"serviceCount"`
+ RunningCount int `json:"runningCount"`
+ AutoUpdate bool `json:"autoUpdate"`
+ IsExternal bool `json:"isExternal"`
+ IsLegacy bool `json:"isLegacy"`
+ IsRemote bool `json:"isRemote"`
+ CreatedAt string `json:"createdAt"`
+ UpdatedAt string `json:"updatedAt"`
+ Services []any `json:"services,omitempty"`
+}
diff --git a/backend/internal/dto/volume_dto.go b/backend/internal/dto/volume_dto.go
new file mode 100644
index 000000000..abfc4c8d9
--- /dev/null
+++ b/backend/internal/dto/volume_dto.go
@@ -0,0 +1,41 @@
+package dto
+
+import "github.com/docker/docker/api/types/volume"
+
+type VolumeDto struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Driver string `json:"driver"`
+ Mountpoint string `json:"mountpoint"`
+ Scope string `json:"scope"`
+ Options map[string]string `json:"options"`
+ Labels map[string]string `json:"labels"`
+ CreatedAt string `json:"createdAt"`
+ InUse bool `json:"inUse"`
+}
+
+func NewVolumeDto(v volume.Volume, inUse bool) VolumeDto {
+ return VolumeDto{
+ ID: v.Name,
+ Name: v.Name,
+ Driver: v.Driver,
+ Mountpoint: v.Mountpoint,
+ Scope: v.Scope,
+ Options: v.Options,
+ Labels: v.Labels,
+ CreatedAt: v.CreatedAt,
+ InUse: inUse,
+ }
+}
+
+type VolumePruneReportDto struct {
+ VolumesDeleted []string `json:"volumesDeleted"`
+ SpaceReclaimed uint64 `json:"spaceReclaimed"`
+}
+
+type CreateVolumeDto struct {
+ Name string `json:"name" binding:"required"`
+ Driver string `json:"driver"`
+ Labels map[string]string `json:"labels"`
+ Options map[string]string `json:"options"`
+}
diff --git a/backend/internal/services/network_service.go b/backend/internal/services/network_service.go
index 9bcb1ea9c..f28542b84 100644
--- a/backend/internal/services/network_service.go
+++ b/backend/internal/services/network_service.go
@@ -3,11 +3,14 @@ package services
import (
"context"
"fmt"
+ "sort"
"strings"
+ "time"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/network"
"github.com/ofkm/arcane-backend/internal/database"
+ "github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/utils"
)
@@ -292,79 +295,80 @@ func (s *NetworkService) GetUserDefinedNetworks(ctx context.Context) ([]network.
}
//nolint:gocognit
-func (s *NetworkService) ListNetworksPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
- networks, err := s.ListNetworks(ctx)
+func (s *NetworkService) ListNetworksPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]dto.NetworkSummaryDto, utils.PaginationResponse, error) {
+ // Fetch from Docker
+ nets, err := s.ListNetworks(ctx)
if err != nil {
return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list Docker networks: %w", err)
}
- var result []map[string]interface{}
- for _, network := range networks {
- networkData := map[string]interface{}{
- "ID": network.ID,
- "Name": network.Name,
- "Driver": network.Driver,
- "Scope": network.Scope,
- "Created": network.Created,
- "Internal": network.Internal,
- "Attachable": network.Attachable,
- "Ingress": network.Ingress,
- "ConfigFrom": network.ConfigFrom,
- "ConfigOnly": network.ConfigOnly,
- "Containers": network.Containers,
- "Options": network.Options,
- "Labels": network.Labels,
- }
-
- result = append(result, networkData)
+ // Map to DTOs
+ items := make([]dto.NetworkSummaryDto, 0, len(nets))
+ for _, n := range nets {
+ items = append(items, dto.NewNetworkSummaryDto(n))
}
+ // Search filter
if req.Search != "" {
- filtered := make([]map[string]interface{}, 0)
- searchLower := strings.ToLower(req.Search)
- for _, network := range result {
- if name, ok := network["Name"].(string); ok {
- if strings.Contains(strings.ToLower(name), searchLower) {
- filtered = append(filtered, network)
- continue
- }
- }
- if driver, ok := network["Driver"].(string); ok {
- if strings.Contains(strings.ToLower(driver), searchLower) {
- filtered = append(filtered, network)
- continue
- }
- }
- if scope, ok := network["Scope"].(string); ok {
- if strings.Contains(strings.ToLower(scope), searchLower) {
- filtered = append(filtered, network)
- continue
- }
+ search := strings.ToLower(req.Search)
+ filtered := make([]dto.NetworkSummaryDto, 0, len(items))
+ for _, n := range items {
+ if strings.Contains(strings.ToLower(n.Name), search) ||
+ strings.Contains(strings.ToLower(n.Driver), search) ||
+ strings.Contains(strings.ToLower(n.Scope), search) {
+ filtered = append(filtered, n)
}
}
- result = filtered
+ items = filtered
}
- totalItems := len(result)
+ totalItems := len(items)
- if req.Sort.Column != "" {
- utils.SortSliceByField(result, req.Sort.Column, req.Sort.Direction)
+ // Sort
+ if col := strings.TrimSpace(strings.ToLower(req.Sort.Column)); col != "" {
+ dir := utils.NormalizeSortDirection(req.Sort.Direction)
+ desc := dir == "desc"
+ lessStr := func(a, b string) bool {
+ if desc {
+ return a > b
+ }
+ return a < b
+ }
+ lessTime := func(a, b time.Time) bool {
+ if desc {
+ return a.After(b)
+ }
+ return a.Before(b)
+ }
+
+ sort.Slice(items, func(i, j int) bool {
+ a, b := items[i], items[j]
+ switch col {
+ case "name":
+ return lessStr(a.Name, b.Name)
+ case "driver":
+ return lessStr(a.Driver, b.Driver)
+ case "scope":
+ return lessStr(a.Scope, b.Scope)
+ case "created":
+ return lessTime(a.Created, b.Created)
+ default:
+ return false
+ }
+ })
}
startIdx := (req.Pagination.Page - 1) * req.Pagination.Limit
endIdx := startIdx + req.Pagination.Limit
-
- if startIdx > len(result) {
- startIdx = len(result)
+ if startIdx > len(items) {
+ startIdx = len(items)
}
- if endIdx > len(result) {
- endIdx = len(result)
+ if endIdx > len(items) {
+ endIdx = len(items)
}
-
+ pageItems := []dto.NetworkSummaryDto{}
if startIdx < endIdx {
- result = result[startIdx:endIdx]
- } else {
- result = []map[string]interface{}{}
+ pageItems = items[startIdx:endIdx]
}
totalPages := (totalItems + req.Pagination.Limit - 1) / req.Pagination.Limit
@@ -375,5 +379,5 @@ func (s *NetworkService) ListNetworksPaginated(ctx context.Context, req utils.So
ItemsPerPage: req.Pagination.Limit,
}
- return result, pagination, nil
+ return pageItems, pagination, nil
}
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index f3869a297..df6986fd1 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -3,6 +3,7 @@ package services
import (
"context"
"fmt"
+ "sort"
"strings"
"time"
@@ -11,6 +12,7 @@ import (
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/ofkm/arcane-backend/internal/database"
+ "github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/utils"
)
@@ -74,19 +76,6 @@ func (s *VolumeService) containersUsingVolume(ctx context.Context, dockerClient
return inUse, using, nil
}
-func toVolumeMap(v volume.Volume, inUse bool) map[string]interface{} {
- return map[string]interface{}{
- "Name": v.Name,
- "Driver": v.Driver,
- "Mountpoint": v.Mountpoint,
- "Scope": v.Scope,
- "Options": v.Options,
- "Labels": v.Labels,
- "CreatedAt": v.CreatedAt,
- "InUse": inUse,
- }
-}
-
func (s *VolumeService) ListVolumes(ctx context.Context) ([]volume.Volume, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
@@ -108,7 +97,7 @@ func (s *VolumeService) ListVolumes(ctx context.Context) ([]volume.Volume, error
return vols, nil
}
-func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*volume.Volume, error) {
+func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*dto.VolumeDto, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
@@ -120,21 +109,29 @@ func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*volu
return nil, fmt.Errorf("volume not found: %w", err)
}
- return &vol, nil
+ inUse, _, _ := s.containersUsingVolume(ctx, dockerClient, vol.Name)
+
+ v := dto.NewVolumeDto(vol, inUse)
+ return &v, nil
}
-func (s *VolumeService) CreateVolume(ctx context.Context, options volume.CreateOptions, user models.User) (*volume.Volume, error) {
+func (s *VolumeService) CreateVolume(ctx context.Context, options volume.CreateOptions, user models.User) (*dto.VolumeDto, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
}
defer dockerClient.Close()
- vol, err := dockerClient.VolumeCreate(ctx, options)
+ created, err := dockerClient.VolumeCreate(ctx, options)
if err != nil {
return nil, fmt.Errorf("failed to create volume: %w", err)
}
+ vol, err := dockerClient.VolumeInspect(ctx, created.Name)
+ if err != nil {
+ return nil, fmt.Errorf("failed to inspect created volume: %w", err)
+ }
+
if s.db != nil {
dbVolume := &models.Volume{
BaseModel: models.BaseModel{CreatedAt: time.Now()},
@@ -146,7 +143,6 @@ func (s *VolumeService) CreateVolume(ctx context.Context, options volume.CreateO
s.db.WithContext(ctx).Create(dbVolume)
}
- // Log volume creation event
metadata := models.JSON{
"action": "create",
"driver": vol.Driver,
@@ -156,7 +152,8 @@ func (s *VolumeService) CreateVolume(ctx context.Context, options volume.CreateO
fmt.Printf("Could not log volume creation action: %s\n", logErr)
}
- return &vol, nil
+ dtoVol := dto.NewVolumeDto(vol, false)
+ return &dtoVol, nil
}
func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force bool, user models.User) error {
@@ -174,7 +171,6 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force boo
s.db.WithContext(ctx).Delete(&models.Volume{}, "name = ?", name)
}
- // Log volume deletion event
metadata := models.JSON{
"action": "delete",
"name": name,
@@ -187,7 +183,7 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force boo
return nil
}
-func (s *VolumeService) PruneVolumes(ctx context.Context) (*volume.PruneReport, error) {
+func (s *VolumeService) PruneVolumes(ctx context.Context) (*dto.VolumePruneReportDto, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
@@ -201,7 +197,6 @@ func (s *VolumeService) PruneVolumes(ctx context.Context) (*volume.PruneReport,
return nil, fmt.Errorf("failed to prune volumes: %w", err)
}
- // Log volume prune event (system user)
metadata := models.JSON{
"action": "prune",
"volumesDeleted": len(report.VolumesDeleted),
@@ -211,22 +206,35 @@ func (s *VolumeService) PruneVolumes(ctx context.Context) (*volume.PruneReport,
fmt.Printf("Could not log volume prune action: %s\n", logErr)
}
- return &report, nil
+ return &dto.VolumePruneReportDto{
+ VolumesDeleted: report.VolumesDeleted,
+ SpaceReclaimed: report.SpaceReclaimed,
+ }, nil
}
-func (s *VolumeService) GetVolumesByDriver(ctx context.Context, driver string) ([]volume.Volume, error) {
+func (s *VolumeService) GetVolumesByDriver(ctx context.Context, driver string) ([]dto.VolumeDto, error) {
volumes, err := s.ListVolumes(ctx)
if err != nil {
return nil, err
}
- var filtered []volume.Volume
- for _, vol := range volumes {
- if vol.Driver == driver {
- filtered = append(filtered, vol)
- }
+ dockerClient, err := s.dockerService.CreateConnection(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)
}
+ defer dockerClient.Close()
+ usage, err := s.buildVolumeUsageMap(ctx, dockerClient)
+ if err != nil {
+ return nil, err
+ }
+
+ var filtered []dto.VolumeDto
+ for _, v := range volumes {
+ if v.Driver == driver {
+ filtered = append(filtered, dto.NewVolumeDto(v, usage[v.Name]))
+ }
+ }
return filtered, nil
}
@@ -249,7 +257,7 @@ func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool,
}
//nolint:gocognit
-func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]map[string]interface{}, utils.PaginationResponse, error) {
+func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.SortedPaginationRequest, driver string) ([]dto.VolumeDto, utils.PaginationResponse, error) {
volumes, err := s.ListVolumes(ctx)
if err != nil {
return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list Docker volumes: %w", err)
@@ -266,22 +274,21 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.Sort
return nil, utils.PaginationResponse{}, err
}
- var result []map[string]interface{}
+ result := make([]dto.VolumeDto, 0, len(volumes))
for _, v := range volumes {
- result = append(result, toVolumeMap(v, volumeUsageMap[v.Name]))
+ if driver != "" && v.Driver != driver {
+ continue
+ }
+ result = append(result, dto.NewVolumeDto(v, volumeUsageMap[v.Name]))
}
if req.Search != "" {
- filtered := make([]map[string]interface{}, 0, len(result))
+ filtered := make([]dto.VolumeDto, 0, len(result))
searchLower := strings.ToLower(req.Search)
for _, vol := range result {
- if name, ok := vol["Name"].(string); ok && strings.Contains(strings.ToLower(name), searchLower) {
+ if strings.Contains(strings.ToLower(vol.Name), searchLower) ||
+ strings.Contains(strings.ToLower(vol.Driver), searchLower) {
filtered = append(filtered, vol)
- continue
- }
- if driver, ok := vol["Driver"].(string); ok && strings.Contains(strings.ToLower(driver), searchLower) {
- filtered = append(filtered, vol)
- continue
}
}
result = filtered
@@ -290,7 +297,7 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.Sort
totalItems := len(result)
if req.Sort.Column != "" {
- utils.SortSliceByField(result, req.Sort.Column, req.Sort.Direction)
+ sortVolumes(result, req.Sort.Column, req.Sort.Direction)
}
startIdx := (req.Pagination.Page - 1) * req.Pagination.Limit
@@ -303,10 +310,9 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.Sort
endIdx = len(result)
}
+ pageItems := []dto.VolumeDto{}
if startIdx < endIdx {
- result = result[startIdx:endIdx]
- } else {
- result = []map[string]interface{}{}
+ pageItems = result[startIdx:endIdx]
}
totalPages := (totalItems + req.Pagination.Limit - 1) / req.Pagination.Limit
@@ -317,10 +323,10 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.Sort
ItemsPerPage: req.Pagination.Limit,
}
- return result, pagination, nil
+ return pageItems, pagination, nil
}
-func (s *VolumeService) ListVolumesWithUsage(ctx context.Context) ([]map[string]interface{}, error) {
+func (s *VolumeService) ListVolumesWithUsage(ctx context.Context, driver string) ([]dto.VolumeDto, error) {
volumes, err := s.ListVolumes(ctx)
if err != nil {
return nil, fmt.Errorf("failed to list Docker volumes: %w", err)
@@ -337,10 +343,74 @@ func (s *VolumeService) ListVolumesWithUsage(ctx context.Context) ([]map[string]
return nil, err
}
- var result []map[string]interface{}
+ var result []dto.VolumeDto
for _, v := range volumes {
- result = append(result, toVolumeMap(v, volumeUsageMap[v.Name]))
+ if driver != "" && v.Driver != driver {
+ continue
+ }
+ result = append(result, dto.NewVolumeDto(v, volumeUsageMap[v.Name]))
}
return result, nil
}
+
+func sortVolumes(items []dto.VolumeDto, field, direction string) {
+ dir := utils.NormalizeSortDirection(direction)
+ f := strings.ToLower(strings.TrimSpace(field))
+ desc := dir == "desc"
+
+ lessStr := func(a, b string) bool {
+ if desc {
+ return a > b
+ }
+ return a < b
+ }
+ lessBool := func(a, b bool) bool {
+ if desc {
+ return a && !b
+ }
+ return !a && b
+ }
+ parseTime := func(s string) (time.Time, bool) {
+ if s == "" {
+ return time.Time{}, false
+ }
+ if t, err := time.Parse(time.RFC3339, s); err == nil {
+ return t, true
+ }
+ return time.Time{}, false
+ }
+ lessTime := func(aS, bS string) bool {
+ aT, aOk := parseTime(aS)
+ bT, bOk := parseTime(bS)
+ if aOk && bOk {
+ if desc {
+ return aT.After(bT)
+ }
+ return aT.Before(bT)
+ }
+
+ return lessStr(aS, bS)
+ }
+
+ sort.Slice(items, func(i, j int) bool {
+ a, b := items[i], items[j]
+ switch f {
+ case "name":
+ return lessStr(a.Name, b.Name)
+ case "driver":
+ return lessStr(a.Driver, b.Driver)
+ case "mountpoint":
+ return lessStr(a.Mountpoint, b.Mountpoint)
+ case "scope":
+ return lessStr(a.Scope, b.Scope)
+ case "created", "createdat":
+ return lessTime(a.CreatedAt, b.CreatedAt)
+ case "inuse":
+ return lessBool(a.InUse, b.InUse)
+ default:
+ // no-op keeps original order
+ return false
+ }
+ })
+}
diff --git a/frontend/src/lib/components/badges/status-badge.svelte b/frontend/src/lib/components/badges/status-badge.svelte
index c8f4b72a2..1d8bec155 100644
--- a/frontend/src/lib/components/badges/status-badge.svelte
+++ b/frontend/src/lib/components/badges/status-badge.svelte
@@ -20,41 +20,64 @@
| 'rose'
| 'orange';
+ type MinWidth = 'none' | '16' | '20' | '24' | '28';
+
let {
text,
variant = 'gray',
+ minWidth = '20',
class: className = '',
...restProps
} = $props<{
text: string;
variant?: Variant;
+ minWidth?: MinWidth;
class?: string;
}>();
+ const minWidthClasses: Record<MinWidth, string> = {
+ none: '',
+ '16': 'min-w-16', // 4rem
+ '20': 'min-w-20', // 5rem (default)
+ '24': 'min-w-24', // 6rem
+ '28': 'min-w-28' // 7rem
+ };
+
const variantStyles: Record<Variant, string> = {
- red: 'bg-red-500/15 text-red-700 border border-red-700/20',
- purple: 'bg-purple-500/15 text-purple-700 border border-purple-700/20',
- green: 'bg-green-500/20 text-green-600 border border-green-600/20',
- blue: 'bg-blue-500/15 text-blue-700 border border-blue-700/20',
- gray: 'bg-gray-400/15 text-gray-600 border border-gray-600/20',
- amber: 'bg-amber-500/20 text-amber-600 border border-amber-600/20',
- pink: 'bg-pink-500/15 text-pink-700 border border-pink-700/20',
- indigo: 'bg-indigo-500/15 text-indigo-700 border border-indigo-700/20',
- cyan: 'bg-cyan-500/15 text-cyan-700 border border-cyan-700/20',
- lime: 'bg-lime-500/15 text-lime-700 border border-lime-700/20',
- emerald: 'bg-emerald-500/20 text-emerald-700 border border-emerald-700/20',
- teal: 'bg-teal-500/15 text-teal-700 border border-teal-700/20',
- sky: 'bg-sky-500/15 text-sky-700 border border-sky-700/20',
- violet: 'bg-violet-500/15 text-violet-700 border border-violet-700/20',
- fuchsia: 'bg-fuchsia-500/15 text-fuchsia-700 border border-fuchsia-700/20',
- rose: 'bg-rose-500/15 text-rose-700 border border-rose-700/20',
- orange: 'bg-orange-500/15 text-orange-700 border border-orange-700/20'
+ red: 'bg-red-500/25 text-red-800 border border-red-700/30 dark:bg-red-500/30 dark:text-red-200 dark:border-red-300/30',
+ purple:
+ 'bg-purple-500/25 text-purple-800 border border-purple-700/30 dark:bg-purple-500/30 dark:text-purple-200 dark:border-purple-300/30',
+ green:
+ 'bg-green-500/30 text-green-800 border border-green-700/30 dark:bg-green-500/35 dark:text-green-200 dark:border-green-300/30',
+ blue: 'bg-blue-500/25 text-blue-800 border border-blue-700/30 dark:bg-blue-500/30 dark:text-blue-200 dark:border-blue-300/30',
+ gray: 'bg-gray-400/25 text-gray-800 border border-gray-700/30 dark:bg-gray-400/30 dark:text-gray-200 dark:border-gray-300/30',
+ amber:
+ 'bg-amber-500/30 text-amber-800 border border-amber-700/30 dark:bg-amber-500/35 dark:text-amber-200 dark:border-amber-300/30',
+ pink: 'bg-pink-500/25 text-pink-800 border border-pink-700/30 dark:bg-pink-500/30 dark:text-pink-200 dark:border-pink-300/30',
+ indigo:
+ 'bg-indigo-500/25 text-indigo-800 border border-indigo-700/30 dark:bg-indigo-500/30 dark:text-indigo-200 dark:border-indigo-300/30',
+ cyan: 'bg-cyan-500/25 text-cyan-800 border border-cyan-700/30 dark:bg-cyan-500/30 dark:text-cyan-200 dark:border-cyan-300/30',
+ lime: 'bg-lime-500/25 text-lime-800 border border-lime-700/30 dark:bg-lime-500/30 dark:text-lime-200 dark:border-lime-300/30',
+ emerald:
+ 'bg-emerald-500/30 text-emerald-800 border border-emerald-700/30 dark:bg-emerald-500/35 dark:text-emerald-200 dark:border-emerald-300/30',
+ teal: 'bg-teal-500/25 text-teal-800 border border-teal-700/30 dark:bg-teal-500/30 dark:text-teal-200 dark:border-teal-300/30',
+ sky: 'bg-sky-500/25 text-sky-800 border border-sky-700/30 dark:bg-sky-500/30 dark:text-sky-200 dark:border-sky-300/30',
+ violet:
+ 'bg-violet-500/25 text-violet-800 border border-violet-700/30 dark:bg-violet-500/30 dark:text-violet-200 dark:border-violet-300/30',
+ fuchsia:
+ 'bg-fuchsia-500/25 text-fuchsia-800 border border-fuchsia-700/30 dark:bg-fuchsia-500/30 dark:text-fuchsia-200 dark:border-fuchsia-300/30',
+ rose: 'bg-rose-500/25 text-rose-800 border border-rose-700/30 dark:bg-rose-500/30 dark:text-rose-200 dark:border-rose-300/30',
+ orange:
+ 'bg-orange-500/25 text-orange-800 border border-orange-700/30 dark:bg-orange-500/30 dark:text-orange-200 dark:border-orange-300/30'
};
+
+ const resolvedMinWidth = minWidth as MinWidth;
</script>
<span
class={cn(
- 'inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium',
+ 'inline-flex items-center justify-center whitespace-nowrap rounded-full px-2.5 py-0.5 text-xs font-medium text-center',
+ minWidthClasses[resolvedMinWidth],
variantStyles[variant as Variant],
className
)}
diff --git a/frontend/src/lib/services/api/appconfig-api-service.ts b/frontend/src/lib/services/api/appconfig-api-service.ts
deleted file mode 100644
index c5083498e..000000000
--- a/frontend/src/lib/services/api/appconfig-api-service.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import BaseAPIService from './api-service';
-import type { AppConfig } from '$lib/types/application-configuration';
-
-export default class AppConfigAPIService extends BaseAPIService {
- async getConfig(): Promise<AppConfig> {
- return this.handleResponse(this.api.get('/config'));
- }
-
- async updateConfig(config: Partial<AppConfig>): Promise<AppConfig> {
- return this.handleResponse(this.api.put('/config', config));
- }
-
- async resetConfig(): Promise<AppConfig> {
- return this.handleResponse(this.api.post('/config/reset'));
- }
-
- async getVersion(): Promise<string> {
- const response = await this.api.get('/config/version');
- return response.data.version;
- }
-}
diff --git a/frontend/src/lib/services/api/auth-api-service.ts b/frontend/src/lib/services/api/auth-api-service.ts
index d09d868b7..84ec8bb4d 100644
--- a/frontend/src/lib/services/api/auth-api-service.ts
+++ b/frontend/src/lib/services/api/auth-api-service.ts
@@ -10,11 +10,21 @@ export interface LoginCredentials {
password: string;
}
+type LoginResponseData = {
+ token: string;
+ refreshToken: string;
+ expiresAt: string;
+ user: User;
+ requirePasswordChange?: boolean;
+};
+
export class AuthService extends BaseAPIService {
async login(credentials: LoginCredentials): Promise<User> {
try {
- const response = await this.api.post('/auth/login', credentials);
- const user = response.data.user as User;
+ const data = await this.handleResponse<LoginResponseData>(
+ this.api.post('/auth/login', credentials)
+ );
+ const user = data.user as User;
userStore.setUser(user);
diff --git a/frontend/src/lib/services/api/environment-api-service.ts b/frontend/src/lib/services/api/environment-api-service.ts
index 4f76fb0ce..5ddcd5b5b 100644
--- a/frontend/src/lib/services/api/environment-api-service.ts
+++ b/frontend/src/lib/services/api/environment-api-service.ts
@@ -18,6 +18,8 @@ import type {
import { browser } from '$app/environment';
import type { ContainerSummaryDto } from '$lib/types/container.type';
import type { ImageSummaryDto } from '$lib/types/image.type';
+import type { NetworkSummaryDto } from '$lib/types/network.type';
+import type { VolumeSummaryDto, VolumeDetailDto, VolumeUsageDto } from '$lib/types/volume.type';
export class EnvironmentAPIService extends BaseAPIService {
private async getCurrentEnvironmentId(): Promise<string> {
@@ -162,46 +164,11 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}/history`));
}
- async getNetworks(
- pagination?: PaginationRequest,
- sort?: SortRequest,
- search?: string,
- filters?: Record<string, string>
- ): Promise<any[] | PaginatedApiResponse<any>> {
+ async getNetworks(options?: SearchPaginationSortRequest): Promise<Paginated<NetworkSummaryDto>> {
const envId = await this.getCurrentEnvironmentId();
- if (!pagination) {
- const response = await this.handleResponse<{ networks?: any[] }>(
- this.api.get(`/environments/${envId}/networks`)
- );
- return Array.isArray(response.networks)
- ? response.networks
- : Array.isArray(response)
- ? response
- : [];
- }
-
- const params: any = {
- 'pagination[page]': pagination.page,
- 'pagination[limit]': pagination.limit
- };
-
- if (sort) {
- params['sort[column]'] = sort.column;
- params['sort[direction]'] = sort.direction;
- }
-
- if (search) {
- params.search = search;
- }
-
- if (filters) {
- Object.entries(filters).forEach(([key, value]) => {
- params[key] = value;
- });
- }
-
- return this.handleResponse(this.api.get(`/environments/${envId}/networks`, { params }));
+ const res = await this.api.get(`/environments/${envId}/networks`, { params: options });
+ return res.data;
}
async getNetwork(networkId: string): Promise<any> {
@@ -219,56 +186,25 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));
}
- async getVolumes(
- pagination?: PaginationRequest,
- sort?: SortRequest,
- search?: string,
- filters?: Record<string, string>
- ): Promise<any[] | PaginatedApiResponse<any>> {
+ async getVolumes(options?: SearchPaginationSortRequest): Promise<Paginated<VolumeSummaryDto>> {
const envId = await this.getCurrentEnvironmentId();
- if (!pagination) {
- const response = await this.handleResponse<{ volumes?: any[] }>(
- this.api.get(`/environments/${envId}/volumes`)
- );
- return Array.isArray(response.volumes)
- ? response.volumes
- : Array.isArray(response)
- ? response
- : [];
- }
-
- const params: any = {
- 'pagination[page]': pagination.page,
- 'pagination[limit]': pagination.limit
- };
-
- if (sort) {
- params['sort[column]'] = sort.column;
- params['sort[direction]'] = sort.direction;
- }
-
- if (search) {
- params.search = search;
- }
-
- if (filters) {
- Object.entries(filters).forEach(([key, value]) => {
- params[key] = value;
- });
- }
-
- return this.handleResponse(this.api.get(`/environments/${envId}/volumes`, { params }));
+ const res = await this.api.get(`/environments/${envId}/volumes`, { params: options });
+ return res.data;
}
- async getVolume(volumeName: string): Promise<any> {
+ async getVolume(volumeName: string): Promise<VolumeDetailDto> {
const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}`));
+ return this.handleResponse(
+ this.api.get(`/environments/${envId}/volumes/${volumeName}`)
+ ) as Promise<VolumeDetailDto>;
}
- async getVolumeUsage(volumeName: string): Promise<any> {
+ async getVolumeUsage(volumeName: string): Promise<VolumeUsageDto> {
const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`));
+ return this.handleResponse(
+ this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`)
+ ) as Promise<VolumeUsageDto>;
}
async createVolume(options: VolumeCreateOptions): Promise<any> {
diff --git a/frontend/src/lib/services/api/index.ts b/frontend/src/lib/services/api/index.ts
index 0c9ac95b2..a02adccae 100644
--- a/frontend/src/lib/services/api/index.ts
+++ b/frontend/src/lib/services/api/index.ts
@@ -6,7 +6,6 @@ import UserAPIService from './user-api-service';
import SettingsAPIService from './settings-api-service';
import TemplateRegistryAPIService from './template-registry-api-service';
import OidcAPIService from './oidc-api-service';
-import AppConfigAPIService from './appconfig-api-service';
import AutoUpdateAPIService from './autoupdate-api-service';
import ConverterAPIService from './converter-api-service';
import ContainerRegistryAPIService from './container-registry-api-service';
@@ -22,7 +21,6 @@ export const userAPI = new UserAPIService();
export const settingsAPI = new SettingsAPIService();
export const templateRegistryAPI = new TemplateRegistryAPIService();
export const oidcAPI = new OidcAPIService();
-export const appConfigAPI = new AppConfigAPIService();
export const converterAPI = new ConverterAPIService();
export const containerRegistryAPI = new ContainerRegistryAPIService();
export const autoUpdateAPI = new AutoUpdateAPIService();
@@ -39,7 +37,6 @@ interface APIServices {
settings: SettingsAPIService;
templateRegistry: TemplateRegistryAPIService;
oidc: OidcAPIService;
- appConfig: AppConfigAPIService;
converter: ConverterAPIService;
containerRegistry: ContainerRegistryAPIService;
autoUpdate: AutoUpdateAPIService;
@@ -57,7 +54,6 @@ const apiServices: APIServices = {
settings: settingsAPI,
templateRegistry: templateRegistryAPI,
oidc: oidcAPI,
- appConfig: appConfigAPI,
converter: converterAPI,
containerRegistry: containerRegistryAPI,
autoUpdate: autoUpdateAPI,
diff --git a/frontend/src/lib/types/network.type.ts b/frontend/src/lib/types/network.type.ts
index 9b56c3943..69e2895c0 100644
--- a/frontend/src/lib/types/network.type.ts
+++ b/frontend/src/lib/types/network.type.ts
@@ -1,121 +1,154 @@
export interface NetworkCreateOptions {
- name: string;
- driver?: string;
- internal?: boolean;
- attachable?: boolean;
- ingress?: boolean;
- ipam?: IPAMConfig;
- enableIPv6?: boolean;
- options?: Record<string, string>;
- labels?: Record<string, string>;
- checkDuplicate?: boolean;
+ name: string;
+ driver?: string;
+ internal?: boolean;
+ attachable?: boolean;
+ ingress?: boolean;
+ ipam?: IPAMConfig;
+ enableIPv6?: boolean;
+ options?: Record<string, string>;
+ labels?: Record<string, string>;
+ checkDuplicate?: boolean;
}
export interface IPAMConfig {
- driver?: string;
- config?: IPAMSubnet[];
- options?: Record<string, string>;
+ driver?: string;
+ config?: IPAMSubnet[];
+ options?: Record<string, string>;
}
export interface IPAMSubnet {
- subnet?: string;
- gateway?: string;
- ipRange?: string;
- auxAddress?: Record<string, string>;
-}
-
-export interface NetworkSummary {
- ID: string;
- Name: string;
- Driver: string;
- Scope: string;
- Internal: boolean;
- Attachable: boolean;
- Ingress: boolean;
- ConfigFrom?: NetworkConfigFrom;
- ConfigOnly: boolean;
- Containers?: Record<string, ContainerEndpoint> | null;
- Options?: Record<string, string> | null;
- Labels?: Record<string, string> | null;
- Created: string;
+ subnet?: string;
+ gateway?: string;
+ ipRange?: string;
+ auxAddress?: Record<string, string>;
}
export interface NetworkConfigFrom {
- Network: string;
+ Network: string;
}
export interface ContainerEndpoint {
- Name: string;
- EndpointID: string;
- MacAddress: string;
- IPv4Address: string;
- IPv6Address: string;
+ Name: string;
+ EndpointID: string;
+ MacAddress: string;
+ IPv4Address: string;
+ IPv6Address: string;
}
export interface NetworkInspect {
- Name: string;
- ID: string;
- Created: string;
- Scope: string;
- Driver: string;
- EnableIPv6: boolean;
- IPAM?: IPAM;
- Internal: boolean;
- Attachable: boolean;
- Ingress: boolean;
- ConfigFrom?: NetworkConfigFrom;
- ConfigOnly: boolean;
- Containers?: Record<string, ContainerEndpoint> | null;
- Options?: Record<string, string> | null;
- Labels?: Record<string, string> | null;
+ Name: string;
+ ID: string;
+ Created: string;
+ Scope: string;
+ Driver: string;
+ EnableIPv6: boolean;
+ IPAM?: IPAM;
+ Internal: boolean;
+ Attachable: boolean;
+ Ingress: boolean;
+ ConfigFrom?: NetworkConfigFrom;
+ ConfigOnly: boolean;
+ Containers?: Record<string, ContainerEndpoint> | null;
+ Options?: Record<string, string> | null;
+ Labels?: Record<string, string> | null;
}
export interface IPAM {
- Driver: string;
- Config?: IPAMSubnetInfo[];
- Options?: Record<string, string>;
+ Driver: string;
+ Config?: IPAMSubnetInfo[];
+ Options?: Record<string, string>;
}
export interface IPAMSubnetInfo {
- Subnet: string;
- Gateway?: string;
- IPRange?: string;
- AuxAddress?: Record<string, string>;
+ Subnet: string;
+ Gateway?: string;
+ IPRange?: string;
+ AuxAddress?: Record<string, string>;
}
export interface NetworkConnect {
- containerId: string;
- config?: NetworkEndpointSettings;
+ containerId: string;
+ config?: NetworkEndpointSettings;
}
export interface NetworkDisconnect {
- containerId: string;
- force?: boolean;
+ containerId: string;
+ force?: boolean;
}
export interface NetworkEndpointSettings {
- ipamConfig?: EndpointIPAMConfig;
- links?: string[];
- aliases?: string[];
- networkId?: string;
- endpointId?: string;
- gateway?: string;
- ipAddress?: string;
- ipPrefixLen?: number;
- ipv6Gateway?: string;
- globalIPv6Address?: string;
- globalIPv6PrefixLen?: number;
- macAddress?: string;
- driverOpts?: Record<string, string>;
+ ipamConfig?: EndpointIPAMConfig;
+ links?: string[];
+ aliases?: string[];
+ networkId?: string;
+ endpointId?: string;
+ gateway?: string;
+ ipAddress?: string;
+ ipPrefixLen?: number;
+ ipv6Gateway?: string;
+ globalIPv6Address?: string;
+ globalIPv6PrefixLen?: number;
+ macAddress?: string;
+ driverOpts?: Record<string, string>;
}
export interface EndpointIPAMConfig {
- ipv4Address?: string;
- ipv6Address?: string;
- linkLocalIPs?: string[];
+ ipv4Address?: string;
+ ipv6Address?: string;
+ linkLocalIPs?: string[];
}
export interface NetworkPruneResponse {
- networksDeleted: string[];
- spaceReclaimed: number;
-}
\ No newline at end of file
+ networksDeleted: string[];
+ spaceReclaimed: number;
+}
+
+export interface ContainerEndpointDto {
+ 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>;
+}
+
+export interface IPAMDto {
+ Driver: string;
+ Options?: Record<string, string>;
+ Config?: IPAMSubnetDto[];
+}
+
+export interface NetworkSummaryDto {
+ id: string;
+ name: string;
+ driver: string;
+ scope: string;
+ created: string; // ISO RFC3339 string
+ options?: Record<string, string> | null;
+ labels?: Record<string, string> | null;
+}
+
+export interface NetworkInspectDto {
+ id: string;
+ name: string;
+ driver: string;
+ scope: string;
+ created: string;
+ options?: Record<string, string> | null;
+ labels?: Record<string, string> | null;
+ containers?: Record<string, ContainerEndpointDto> | null;
+ ipam?: IPAMDto;
+ internal: boolean;
+ attachable: boolean;
+ ingress: boolean;
+ enableIPv6?: boolean;
+}
diff --git a/frontend/src/lib/types/statuses.ts b/frontend/src/lib/types/statuses.ts
index c2dcb0883..87f4748fa 100644
--- a/frontend/src/lib/types/statuses.ts
+++ b/frontend/src/lib/types/statuses.ts
@@ -1,4 +1,7 @@
-export const statusVariantMap: Record<string, 'red' | 'purple' | 'green' | 'blue' | 'gray' | 'amber'> = {
+export const statusVariantMap: Record<
+ string,
+ 'red' | 'purple' | 'green' | 'blue' | 'gray' | 'amber'
+> = {
running: 'green',
deployed: 'green',
stopped: 'red',
@@ -6,5 +9,6 @@ export const statusVariantMap: Record<string, 'red' | 'purple' | 'green' | 'blue
pending: 'amber',
creating: 'blue',
updating: 'blue',
- deleting: 'purple'
+ deleting: 'purple',
+ exited: 'red'
};
diff --git a/frontend/src/lib/types/volume.type.ts b/frontend/src/lib/types/volume.type.ts
new file mode 100644
index 000000000..1f6460c00
--- /dev/null
+++ b/frontend/src/lib/types/volume.type.ts
@@ -0,0 +1,20 @@
+export interface VolumeSummaryDto {
+ id: string;
+ name: string;
+ driver: string;
+ mountpoint: string;
+ scope: string;
+ options: Record<string, string> | null;
+ labels: Record<string, string>;
+ createdAt: string;
+ inUse: boolean;
+}
+
+export interface VolumeDetailDto extends VolumeSummaryDto {
+ containers: string[];
+}
+
+export interface VolumeUsageDto {
+ inUse: boolean;
+ containers: string[];
+}
diff --git a/frontend/src/routes/compose/+page.ts b/frontend/src/routes/compose/+page.ts
index b09c574d3..eb11394cc 100644
--- a/frontend/src/routes/compose/+page.ts
+++ b/frontend/src/routes/compose/+page.ts
@@ -6,7 +6,7 @@ export const load: PageLoad = async () => {
const projectRequestOptions: SearchPaginationSortRequest = {
pagination: {
page: 1,
- limit: 10
+ limit: 20
},
sort: {
column: 'name',
diff --git a/frontend/src/routes/containers/+page.svelte b/frontend/src/routes/containers/+page.svelte
index 01c058fce..663b841b0 100644
--- a/frontend/src/routes/containers/+page.svelte
+++ b/frontend/src/routes/containers/+page.svelte
@@ -42,7 +42,7 @@
isLoading.refreshing = true;
handleApiResultWithCallbacks({
result: await tryCatch(environmentAPI.getContainers(requestOptions)),
- message: 'Failed to Refresh Containers for Updates',
+ message: 'Failed to Refresh Containers',
setLoadingState: (value) => (isLoading.refreshing = value),
async onSuccess(newContainers) {
containers = newContainers;
diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelte
index a4496eeaa..9ed32dca0 100644
--- a/frontend/src/routes/dashboard/+page.svelte
+++ b/frontend/src/routes/dashboard/+page.svelte
@@ -2,7 +2,6 @@
import * as Card from '$lib/components/ui/card/index.js';
import { Button } from '$lib/components/ui/button/index.js';
import {
- AlertCircle,
Box,
HardDrive,
RefreshCw,
@@ -15,13 +14,12 @@
Cpu,
Container
} from '@lucide/svelte';
- import * as Alert from '$lib/components/ui/alert/index.js';
import { capitalizeFirstLetter } from '$lib/utils/string.utils';
import { toast } from 'svelte-sonner';
import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
- import { systemAPI, environmentAPI, settingsAPI } from '$lib/services/api';
+ import { systemAPI, settingsAPI } from '$lib/services/api';
import { openConfirmDialog } from '$lib/components/confirm-dialog';
import { onMount } from 'svelte';
import type { PruneType } from '$lib/types/actions.type';
@@ -29,14 +27,13 @@
import MeterMetric from '$lib/components/meter-metric.svelte';
import DockerIcon from '$lib/icons/docker-icon.svelte';
import type { SystemStats } from '$lib/models/system-stats';
- import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import DashboardContainerTable from './dash-container-table.svelte';
import DashboardImageTable from './dash-image-table.svelte';
- import type { ContainerSummaryDto } from '$lib/types/container.type';
let { data } = $props();
let containers = $state(data.containers);
let images = $state(data.images);
+ let dockerInfo = $state(data.dockerInfo);
let dashboardStates = $state({
dockerInfo: data.dockerInfo,
@@ -66,10 +63,8 @@
containers: [] as Array<{ date: Date; value: number }>
});
- const runningContainers = $derived(containers.data.filter((s) => s.state === 'running').length);
const stoppedContainers = $derived(containers.data.filter((s) => s.state != 'running').length);
const totalContainers = $derived(containers.pagination.totalItems);
- const totalImages = $derived(images.pagination.totalItems);
const currentStats = $derived(dashboardStates.systemStats || liveSystemStats);
function addToHistoricalData(stats: SystemStats) {
@@ -99,77 +94,12 @@
}
}
- historicalData.containers.push({ date: now, value: runningContainers });
+ historicalData.containers.push({ date: now, value: dockerInfo!.containersRunning });
if (historicalData.containers.length > maxPoints) {
historicalData.containers = historicalData.containers.slice(-maxPoints);
}
}
- function getContainerDisplayName(container: ContainerSummaryDto): string {
- if (container.names && container.names.length > 0) {
- return container.names[0].startsWith('/')
- ? container.names[0].substring(1)
- : container.names[0];
- }
- return container.id?.substring(0, 12) || 'Unknown';
- }
-
- // async function onContainerRefresh(options: SearchPaginationSortRequest) {
- // const response = await environmentAPI.getContainers(
- // options.pagination,
- // options.sort,
- // options.search,
- // options.filters
- // );
-
- // if (Array.isArray(response)) {
- // dashboardStates.containers = response;
- // return {
- // data: response,
- // pagination: {
- // totalPages: 1,
- // totalItems: response.length,
- // currentPage: options.pagination?.page || 1,
- // itemsPerPage: response.length
- // }
- // };
- // } else {
- // dashboardStates.containers = response.data || [];
- // return {
- // data: response.data || [],
- // pagination: response.pagination
- // };
- // }
- // }
-
- // async function onImageRefresh(options: SearchPaginationSortRequest) {
- // const response = await environmentAPI.getImages(
- // options.pagination,
- // options.sort,
- // options.search,
- // options.filters
- // );
-
- // if (Array.isArray(response)) {
- // dashboardStates.images = response;
- // return {
- // data: response,
- // pagination: {
- // totalPages: 1,
- // totalItems: response.length,
- // currentPage: options.pagination?.page || 1,
- // itemsPerPage: response.length
- // }
- // };
- // } else {
- // dashboardStates.images = response.data || [];
- // return {
- // data: response.data || [],
- // pagination: response.pagination
- // };
- // }
- // }
-
async function fetchLiveSystemStats() {
if (!hasInitialStatsLoaded) {
isLoading.loadingStats = true;
@@ -209,7 +139,6 @@
if (isLoading.refreshing) return;
isLoading.refreshing = true;
- // Set all loading states to true at start
isLoading.loadingDockerInfo = true;
isLoading.loadingImages = true;
@@ -218,7 +147,6 @@
tryCatch(settingsAPI.getSettings())
]);
- // Handle results and clear individual loading states
if (dockerInfoResult.status === 'fulfilled' && !dockerInfoResult.value.error) {
dashboardStates.dockerInfo = dockerInfoResult.value.data;
}
@@ -269,7 +197,8 @@
}
async function handleStopAll() {
- if (isLoading.stopping || !dashboardStates.dockerInfo || runningContainers === 0) return;
+ if (isLoading.stopping || !dashboardStates.dockerInfo || dockerInfo?.containersRunning === 0)
+ return;
openConfirmDialog({
title: 'Stop All Containers',
message: 'Are you sure you want to stop all running containers?',
@@ -320,7 +249,6 @@
</script>
<div class="space-y-8">
- <!-- Header -->
<div class="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div class="space-y-1">
<h1 class="text-3xl font-bold tracking-tight">Dashboard</h1>
@@ -345,7 +273,6 @@
</Button>
</div>
- <!-- Quick Actions -->
<section>
<h2 class="mb-3 text-lg font-semibold tracking-tight">Quick Actions</h2>
{#if isLoading.loadingDockerInfo}
@@ -389,7 +316,7 @@
<button
class="group bg-card flex items-center rounded-lg border p-3 shadow-sm ring-offset-background transition-all hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-60"
disabled={!dashboardStates.dockerInfo ||
- runningContainers === 0 ||
+ dockerInfo?.containersRunning === 0 ||
isLoading.starting ||
isLoading.stopping ||
isLoading.pruning}
@@ -438,7 +365,6 @@
{/if}
</section>
- <!-- System Overview -->
<section>
<DropdownCard
id="system-overview"
@@ -452,10 +378,10 @@
title="Running Containers"
icon={Container}
description="Active containers"
- currentValue={isLoading.loadingStats ? undefined : runningContainers}
+ currentValue={isLoading.loadingStats ? undefined : dockerInfo?.containersRunning}
formatValue={(v) => v.toString()}
maxValue={Math.max(totalContainers, 1)}
- footerText={`${runningContainers} of ${totalContainers} running`}
+ footerText={`${dockerInfo?.containersRunning} of ${totalContainers} running`}
unit="containers"
loading={isLoading.loadingStats}
/>
@@ -503,7 +429,6 @@
/>
</div>
- <!-- Always show these cards but with loading states -->
<div class="mt-6 grid grid-cols-1 gap-4 md:grid-cols-3">
<Card.Root class="rounded-lg border shadow-sm">
<Card.Content class="p-4">
diff --git a/frontend/src/routes/dashboard/dash-container-table.svelte b/frontend/src/routes/dashboard/dash-container-table.svelte
index 95f927526..5a3b52ad9 100644
--- a/frontend/src/routes/dashboard/dash-container-table.svelte
+++ b/frontend/src/routes/dashboard/dash-container-table.svelte
@@ -76,7 +76,7 @@
<span class="text-sm">{item.image}</span>
</Table.Cell>
<Table.Cell class="py-3 md:py-3.5">
- {@const stateVariant = statusVariantMap[item.state.toLowerCase()] || 'grey'}
+ {@const stateVariant = statusVariantMap[item.state.toLowerCase()] || 'gray'}
<StatusBadge variant={stateVariant} text={capitalizeFirstLetter(item.state)} />
</Table.Cell>
<Table.Cell class="py-3 md:py-3.5">{item.status}</Table.Cell>
diff --git a/frontend/src/routes/images/image-table.svelte b/frontend/src/routes/images/image-table.svelte
index c919f0ea0..bb1c13d5c 100644
--- a/frontend/src/routes/images/image-table.svelte
+++ b/frontend/src/routes/images/image-table.svelte
@@ -18,6 +18,7 @@
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import FilterDropdown from '$lib/components/dropdowns/filter-dropdown.svelte';
import type { ImageSummaryDto } from '$lib/types/image.type';
+ import { formatFriendlyDate } from '$lib/utils/date.utils';
let {
images = $bindable(),
@@ -300,7 +301,9 @@
>
</Table.Cell>
<Table.Cell class="py-3 md:py-3.5">{formatBytes(item.size)}</Table.Cell>
- <Table.Cell>{new Date((item.created || 0) * 1000).toLocaleDateString()}</Table.Cell>
+ <Table.Cell
+ >{formatFriendlyDate(new Date((item.created || 0) * 1000).toISOString())}</Table.Cell
+ >
<Table.Cell>
{#if item.inUse}
<StatusBadge text="In Use" variant="green" />
diff --git a/frontend/src/routes/networks/+page.svelte b/frontend/src/routes/networks/+page.svelte
index 9813b1d92..dfa471ac1 100644
--- a/frontend/src/routes/networks/+page.svelte
+++ b/frontend/src/routes/networks/+page.svelte
@@ -1,8 +1,7 @@
<script lang="ts">
import { Network, EthernetPort } from '@lucide/svelte';
- import * as Alert from '$lib/components/ui/alert/index.js';
import { toast } from 'svelte-sonner';
- import type { NetworkCreateOptions, NetworkInspectInfo } from 'dockerode';
+ import type { NetworkCreateOptions } from 'dockerode';
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import CreateNetworkSheet from '$lib/components/sheets/create-network-sheet.svelte';
@@ -10,103 +9,32 @@
import ArcaneButton from '$lib/components/arcane-button.svelte';
import StatCard from '$lib/components/stat-card.svelte';
import NetworkTable from './network-table.svelte';
- import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
- import type { PageData } from './$types';
- interface NetworkWithId extends NetworkInspectInfo {
- id: string;
- }
-
- let { data }: { data: PageData } = $props();
+ let { data } = $props();
- let networks = $state<NetworkInspectInfo[]>([]);
- let paginatedNetworks = $state<Paginated<NetworkWithId & { ID: string }> | null>(null);
+ let networks = $state(data.networks);
+ let requestOptions = $state(data.networkRequestOptions);
let selectedIds = $state<string[]>([]);
- let error = $state<string | null>(null);
let isCreateDialogOpen = $state(false);
- let requestOptions = $state<SearchPaginationSortRequest>(data.networkRequestOptions);
let isLoading = $state({
create: false,
refresh: false
});
- $effect(() => {
- if (data.networks) {
- if (Array.isArray(data.networks)) {
- networks = data.networks;
- const paginatedData: Paginated<NetworkWithId & { ID: string }> = {
- data: data.networks.map((n) => ({ ...n, id: n.ID, ID: n.ID })),
- pagination: {
- totalPages: 1,
- totalItems: data.networks.length,
- currentPage: 1,
- itemsPerPage: data.networks.length
- }
- };
- paginatedNetworks = paginatedData;
- } else {
- const paginatedData: Paginated<NetworkWithId & { ID: string }> = {
- data: data.networks.data.map((n) => ({ ...n, id: n.ID, ID: n.ID })),
- pagination: data.networks.pagination
- };
- paginatedNetworks = paginatedData;
- networks = data.networks.data || [];
- }
- }
- });
-
- const totalNetworks = $derived(networks.length);
- const bridgeNetworks = $derived(networks.filter((n) => n.Driver === 'bridge').length);
-
- async function onRefresh(
- options: SearchPaginationSortRequest
- ): Promise<Paginated<NetworkWithId & { ID: string }>> {
- const response = await environmentAPI.getNetworks(
- options.pagination,
- options.sort,
- options.search,
- options.filters
- );
-
- if (Array.isArray(response)) {
- networks = response;
- const paginatedResponse: Paginated<NetworkWithId & { ID: string }> = {
- data: response.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
- pagination: {
- totalPages: 1,
- totalItems: response.length,
- currentPage: options.pagination?.page || 1,
- itemsPerPage: response.length
- }
- };
- paginatedNetworks = paginatedResponse;
- return paginatedResponse;
- } else {
- const paginatedResponse: Paginated<NetworkWithId & { ID: string }> = {
- data: response.data.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
- pagination: response.pagination
- };
- paginatedNetworks = paginatedResponse;
- networks = response.data || [];
- return paginatedResponse;
- }
- }
+ const totalNetworks = $derived(networks.data.length);
+ const bridgeNetworks = $derived(networks.data.filter((n) => n.driver === 'bridge').length);
async function refreshNetworks() {
isLoading.refresh = true;
- try {
- await onRefresh(requestOptions);
- } catch (error) {
- console.error('Failed to refresh networks:', error);
- toast.error('Failed to refresh networks');
- } finally {
- isLoading.refresh = false;
- }
- }
-
- async function onNetworksChanged() {
- await refreshNetworks();
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.getNetworks(requestOptions)),
+ message: 'Failed to Refresh Containers for Updates',
+ setLoadingState: (value) => (isLoading.refresh = value),
+ async onSuccess(newNetworks) {
+ networks = newNetworks;
+ }
+ });
}
async function handleCreateNetworkSubmit(options: NetworkCreateOptions) {
@@ -117,7 +45,7 @@
setLoadingState: (value) => (isLoading.create = value),
onSuccess: async () => {
toast.success(`Network "${options.Name}" Created Successfully.`);
- await refreshNetworks();
+ networks = await environmentAPI.getNetworks(requestOptions);
isCreateDialogOpen = false;
}
});
@@ -141,13 +69,6 @@
</div>
</div>
- {#if error}
- <Alert.Root variant="destructive">
- <Alert.Title>Error Loading Networks</Alert.Title>
- <Alert.Description>{error}</Alert.Description>
- </Alert.Root>
- {/if}
-
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
<StatCard
title="Total Networks"
@@ -166,19 +87,9 @@
</div>
<NetworkTable
- networks={paginatedNetworks || {
- data: networks.map((n) => ({ ...n, id: n.Id, ID: n.Id })),
- pagination: {
- totalPages: 1,
- totalItems: networks.length,
- currentPage: 1,
- itemsPerPage: networks.length
- }
- }}
+ bind:networks
bind:selectedIds
bind:requestOptions
- {onRefresh}
- {onNetworksChanged}
onCreateNetwork={() => (isCreateDialogOpen = true)}
/>
diff --git a/frontend/src/routes/networks/+page.ts b/frontend/src/routes/networks/+page.ts
index 1ce9938ef..83474d372 100644
--- a/frontend/src/routes/networks/+page.ts
+++ b/frontend/src/routes/networks/+page.ts
@@ -3,23 +3,18 @@ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { PageLoad } from './$types';
export const load: PageLoad = async () => {
- const networkRequestOptions: SearchPaginationSortRequest = {
- pagination: {
- page: 1,
- limit: 20
- },
- sort: {
- column: 'Name',
- direction: 'asc' as const
- }
- };
+ const networkRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'name',
+ direction: 'asc' as const
+ }
+ };
- const networks = await environmentAPI.getNetworks(
- networkRequestOptions.pagination,
- networkRequestOptions.sort,
- networkRequestOptions.search,
- networkRequestOptions.filters
- );
+ const networks = await environmentAPI.getNetworks(networkRequestOptions);
- return { networks, networkRequestOptions };
-};
\ No newline at end of file
+ return { networks, networkRequestOptions };
+};
diff --git a/frontend/src/routes/networks/[networkId]/+page.svelte b/frontend/src/routes/networks/[networkId]/+page.svelte
index b80a53dfe..5defcc50c 100644
--- a/frontend/src/routes/networks/[networkId]/+page.svelte
+++ b/frontend/src/routes/networks/[networkId]/+page.svelte
@@ -1,7 +1,19 @@
<script lang="ts">
import type { PageData } from './$types';
import * as Card from '$lib/components/ui/card/index.js';
- import { AlertCircle, HardDrive, Clock, Tag, Layers, Hash, Network, Globe, Settings, ListTree, Container } from '@lucide/svelte';
+ import {
+ AlertCircle,
+ HardDrive,
+ Clock,
+ Tag,
+ Layers,
+ Hash,
+ Network,
+ Globe,
+ Settings,
+ ListTree,
+ Container
+ } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import * as Alert from '$lib/components/ui/alert/index.js';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
@@ -14,18 +26,23 @@
import { handleApiResultWithCallbacks } from '$lib/utils/api.util';
import { tryCatch } from '$lib/utils/try-catch';
import { environmentAPI } from '$lib/services/api';
+ import type { NetworkInspectDto } from '$lib/types/network.type';
let { data }: { data: PageData } = $props();
- let { network }: { network: NetworkInspectInfo | null | undefined } = $derived(data);
+ let { network }: { network: NetworkInspectDto | null | undefined } = $derived(data);
let errorMessage = $state('');
let isRemoving = $state(false);
- const shortId = $derived(network?.Id?.substring(0, 12) || 'N/A');
- const createdDate = $derived(network?.Created ? formatDate(network.Created) : 'N/A');
- const connectedContainers = $derived(network?.Containers ? Object.values(network.Containers) : []);
+ const shortId = $derived(network?.id?.substring(0, 12) || 'N/A');
+ const createdDate = $derived(network?.created ? formatDate(network.created) : 'N/A');
+ const connectedContainers = $derived(
+ network?.containers ? Object.values(network.containers) : []
+ );
const inUse = $derived(connectedContainers.length > 0);
- const isPredefined = $derived(network?.Name === 'bridge' || network?.Name === 'host' || network?.Name === 'none');
+ const isPredefined = $derived(
+ network?.name === 'bridge' || network?.name === 'host' || network?.name === 'none'
+ );
function triggerRemove() {
if (isPredefined) {
@@ -34,24 +51,24 @@
return;
}
- if (!network?.Id) {
+ if (!network?.id) {
toast.error('Network ID is missing');
return;
}
openConfirmDialog({
title: 'Remove Network',
- message: `Are you sure you want to remove the network "${network?.Name || shortId}"? This action cannot be undone.`,
+ message: `Are you sure you want to remove the network "${network?.name || shortId}"? This action cannot be undone.`,
confirm: {
label: 'Remove',
destructive: true,
action: async () => {
handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.deleteNetwork(network.Id)),
+ result: await tryCatch(environmentAPI.deleteNetwork(network.id)),
message: 'Failed to remove network',
setLoadingState: (value) => (isRemoving = value),
onSuccess: async () => {
- toast.success(`Network "${network.Name || shortId}" removed successfully`);
+ toast.success(`Network "${network.name || shortId}" removed successfully`);
goto('/networks');
},
onError: (error) => {
@@ -74,7 +91,7 @@
</Breadcrumb.Item>
<Breadcrumb.Separator />
<Breadcrumb.Item>
- <Breadcrumb.Page>{network?.Name || shortId}</Breadcrumb.Page>
+ <Breadcrumb.Page>{network?.name || shortId}</Breadcrumb.Page>
</Breadcrumb.Item>
</Breadcrumb.List>
</Breadcrumb.Root>
@@ -83,7 +100,7 @@
<div class="flex flex-col">
<div class="flex items-center gap-3">
<h1 class="text-2xl font-bold tracking-tight">
- {network?.Name || 'Network Details'}
+ {network?.name || 'Network Details'}
</h1>
<div class="hidden sm:block">
@@ -102,12 +119,19 @@
<StatusBadge variant="blue" text="Predefined" />
{/if}
- <StatusBadge variant="purple" text={network?.Driver || 'Unknown'} />
+ <StatusBadge variant="purple" text={network?.driver || 'Unknown'} />
</div>
</div>
<div class="self-start">
- <ArcaneButton action="remove" customLabel="Remove Network" onClick={triggerRemove} loading={isRemoving} disabled={isRemoving || isPredefined} label={isPredefined ? 'Cannot remove predefined networks' : 'Delete Network'} />
+ <ArcaneButton
+ action="remove"
+ customLabel="Remove Network"
+ onClick={triggerRemove}
+ loading={isRemoving}
+ disabled={isRemoving || isPredefined}
+ label={isPredefined ? 'Cannot remove predefined networks' : 'Delete Network'}
+ />
</div>
</div>
</div>
@@ -133,47 +157,57 @@
<Card.Content class="pt-6">
<div class="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-2 lg:grid-cols-3">
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-gray-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-gray-500/10 p-2"
+ >
<Hash class="size-5 text-gray-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">ID</p>
- <p class="mt-1 truncate text-base font-semibold" title={network.Id}>{network.Id}</p>
+ <p class="mt-1 truncate text-base font-semibold" title={network.id}>{network.id}</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-blue-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-blue-500/10 p-2"
+ >
<Network class="size-5 text-blue-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Name</p>
- <p class="mt-1 text-base font-semibold break-words">{network.Name}</p>
+ <p class="mt-1 text-base font-semibold break-words">{network.name}</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-orange-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-orange-500/10 p-2"
+ >
<HardDrive class="size-5 text-orange-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Driver</p>
- <p class="mt-1 text-base font-semibold">{network.Driver}</p>
+ <p class="mt-1 text-base font-semibold">{network.driver}</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-purple-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-purple-500/10 p-2"
+ >
<Globe class="size-5 text-purple-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Scope</p>
- <p class="mt-1 text-base font-semibold capitalize">{network.Scope}</p>
+ <p class="mt-1 text-base font-semibold capitalize">{network.scope}</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-green-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-green-500/10 p-2"
+ >
<Clock class="size-5 text-green-500" />
</div>
<div class="min-w-0 flex-1">
@@ -183,37 +217,52 @@
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-yellow-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-yellow-500/10 p-2"
+ >
<Layers class="size-5 text-yellow-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Attachable</p>
<p class="mt-1 text-base font-semibold">
- <StatusBadge variant={network.Attachable ? 'green' : 'gray'} text={network.Attachable ? 'Yes' : 'No'} />
+ <StatusBadge
+ variant={network.attachable ? 'green' : 'gray'}
+ text={network.attachable ? 'Yes' : 'No'}
+ />
</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-red-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-red-500/10 p-2"
+ >
<Settings class="size-5 text-red-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Internal</p>
<p class="mt-1 text-base font-semibold">
- <StatusBadge variant={network.Internal ? 'blue' : 'gray'} text={network.Internal ? 'Yes' : 'No'} />
+ <StatusBadge
+ variant={network.internal ? 'blue' : 'gray'}
+ text={network.internal ? 'Yes' : 'No'}
+ />
</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-indigo-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-indigo-500/10 p-2"
+ >
<ListTree class="size-5 text-indigo-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">IPv6 Enabled</p>
<p class="mt-1 text-base font-semibold">
- <StatusBadge variant={network.EnableIPv6 ? 'indigo' : 'gray'} text={network.EnableIPv6 ? 'Yes' : 'No'} />
+ <StatusBadge
+ variant={network.enableIPv6 ? 'indigo' : 'gray'}
+ text={network.enableIPv6 ? 'Yes' : 'No'}
+ />
</p>
</div>
</div>
@@ -221,7 +270,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 class="border shadow-sm">
<Card.Header class="pb-0">
<Card.Title class="flex items-center gap-2 text-lg">
@@ -231,13 +280,17 @@
<Card.Description>IP Address Management settings for this network</Card.Description>
</Card.Header>
<Card.Content class="pt-6">
- {#each network.IPAM.Config as config, i (i)}
+ {#each network.ipam.Config as config, i (i)}
<div class="bg-card/50 mb-4 rounded-lg border p-4 last:mb-0">
<div class="space-y-2">
{#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">Subnet:</span>
- <code class="bg-muted text-muted-foreground mt-1 rounded px-1.5 py-0.5 font-mono text-xs sm:mt-0 sm:text-sm">
+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-24"
+ >Subnet:</span
+ >
+ <code
+ class="bg-muted text-muted-foreground mt-1 rounded px-1.5 py-0.5 font-mono text-xs sm:mt-0 sm:text-sm"
+ >
{config.Subnet}
</code>
</div>
@@ -245,8 +298,12 @@
{#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">Gateway:</span>
- <code class="bg-muted text-muted-foreground mt-1 rounded px-1.5 py-0.5 font-mono text-xs sm:mt-0 sm:text-sm">
+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-24"
+ >Gateway:</span
+ >
+ <code
+ class="bg-muted text-muted-foreground mt-1 rounded px-1.5 py-0.5 font-mono text-xs sm:mt-0 sm:text-sm"
+ >
{config.Gateway}
</code>
</div>
@@ -254,21 +311,29 @@
{#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">IP Range:</span>
- <code class="bg-muted text-muted-foreground mt-1 rounded px-1.5 py-0.5 font-mono text-xs sm:mt-0 sm:text-sm">
+ <span class="text-muted-foreground w-full text-sm font-medium sm:w-24"
+ >IP Range:</span
+ >
+ <code
+ class="bg-muted text-muted-foreground mt-1 rounded px-1.5 py-0.5 font-mono text-xs sm:mt-0 sm:text-sm"
+ >
{config.IPRange}
</code>
</div>
{/if}
- {#if config.AuxiliaryAddresses && Object.keys(config.AuxiliaryAddresses).length > 0}
+ {#if (config.AuxiliaryAddresses && Object.keys(config.AuxiliaryAddresses).length > 0) || (config.AuxAddress && Object.keys(config.AuxAddress).length > 0)}
<div class="mt-3">
- <p class="text-muted-foreground mb-1 text-sm font-medium">Auxiliary Addresses:</p>
+ <p class="text-muted-foreground mb-1 text-sm font-medium">
+ Auxiliary Addresses:
+ </p>
<ul class="ml-4 space-y-1">
- {#each Object.entries(config.AuxiliaryAddresses) as [name, addr] (name)}
+ {#each Object.entries(config.AuxiliaryAddresses ?? config.AuxAddress ?? {}) as [name, addr] (name)}
<li class="flex font-mono text-xs">
<span class="text-muted-foreground mr-2">{name}:</span>
- <code class="bg-muted text-muted-foreground rounded px-1 py-0.5">{addr}</code>
+ <code class="bg-muted text-muted-foreground rounded px-1 py-0.5"
+ >{addr}</code
+ >
</li>
{/each}
</ul>
@@ -278,18 +343,18 @@
</div>
{/each}
- {#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">IPAM Driver:</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">IPAM Options:</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>
@@ -310,7 +375,8 @@
Connected Containers
</Card.Title>
<Card.Description>
- {connectedContainers.length} container{connectedContainers.length === 1 ? '' : 's'} connected to this network
+ {connectedContainers.length} container{connectedContainers.length === 1 ? '' : 's'} connected
+ to this network
</Card.Description>
</Card.Header>
<Card.Content class="pt-6">
@@ -318,13 +384,18 @@
{#each connectedContainers as container (container.Name)}
<div class="flex flex-col p-3 sm:flex-row sm:items-center">
<div class="mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3">
- <a href="/containers/{container.Name}" class="text-primary flex items-center hover:underline">
+ <a
+ href="/containers/{container.Name}"
+ class="text-primary flex items-center hover:underline"
+ >
<Container class="text-muted-foreground mr-1.5 size-3.5" />
{container.Name}
</a>
</div>
<div class="w-full pl-0 sm:w-2/3 sm:pl-4">
- <code class="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-xs break-all sm:text-sm">
+ <code
+ class="bg-muted text-muted-foreground rounded px-1.5 py-0.5 font-mono text-xs break-all sm:text-sm"
+ >
{container.IPv4Address || container.IPv6Address || 'N/A'}
</code>
</div>
@@ -335,7 +406,7 @@
</Card.Root>
{/if}
- {#if network.Labels && Object.keys(network.Labels).length > 0}
+ {#if network.labels && Object.keys(network.labels).length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="pb-0">
<Card.Title class="flex items-center gap-2 text-lg">
@@ -346,12 +417,16 @@
</Card.Header>
<Card.Content class="pt-6">
<div class="bg-card divide-y rounded-lg border">
- {#each Object.entries(network.Labels) as [key, value] (key)}
+ {#each Object.entries(network.labels) as [key, value] (key)}
<div class="flex flex-col p-3 sm:flex-row">
- <div class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3">
+ <div
+ class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3"
+ >
{key}
</div>
- <div class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm">
+ <div
+ class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm"
+ >
{value}
</div>
</div>
@@ -361,7 +436,7 @@
</Card.Root>
{/if}
- {#if network.Options && Object.keys(network.Options).length > 0}
+ {#if network.options && Object.keys(network.options).length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="pb-0">
<Card.Title class="flex items-center gap-2 text-lg">
@@ -372,12 +447,16 @@
</Card.Header>
<Card.Content class="pt-6">
<div class="bg-card divide-y rounded-lg border">
- {#each Object.entries(network.Options) as [key, value] (key)}
+ {#each Object.entries(network.options) as [key, value] (key)}
<div class="flex flex-col p-3 sm:flex-row">
- <div class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3">
+ <div
+ class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3"
+ >
{key}
</div>
- <div class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm">
+ <div
+ class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm"
+ >
{value}
</div>
</div>
@@ -393,8 +472,15 @@
<Network class="text-muted-foreground size-10 opacity-70" />
</div>
<h2 class="mb-2 text-xl font-medium">Network Not Found</h2>
- <p class="text-muted-foreground mb-6">The requested network could not be found or is no longer available.</p>
- <ArcaneButton action="cancel" customLabel="Back to Networks" onClick={() => goto('/networks')} size="sm" />
+ <p class="text-muted-foreground mb-6">
+ The requested network could not be found or is no longer available.
+ </p>
+ <ArcaneButton
+ action="cancel"
+ customLabel="Back to Networks"
+ onClick={() => goto('/networks')}
+ size="sm"
+ />
</div>
{/if}
</div>
diff --git a/frontend/src/routes/networks/[networkId]/+page.ts b/frontend/src/routes/networks/[networkId]/+page.ts
index 99a26906f..65d8f6330 100644
--- a/frontend/src/routes/networks/[networkId]/+page.ts
+++ b/frontend/src/routes/networks/[networkId]/+page.ts
@@ -13,7 +13,7 @@ export const load: PageLoad = async ({ params }) => {
}
return {
- network: network
+ network
};
} catch (err: any) {
console.error('Failed to load network:', err);
diff --git a/frontend/src/routes/networks/network-table.svelte b/frontend/src/routes/networks/network-table.svelte
index a07fb6a48..bcb3b48a2 100644
--- a/frontend/src/routes/networks/network-table.svelte
+++ b/frontend/src/routes/networks/network-table.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import type { NetworkSummary } from '$lib/types/network.type';
+ import type { NetworkSummaryDto } from '$lib/types/network.type';
import ArcaneTable from '$lib/components/arcane-table.svelte';
import { Button } from '$lib/components/ui/button/index.js';
import { ScanSearch, Trash2, Ellipsis, Network } from '@lucide/svelte';
@@ -16,24 +16,17 @@
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
import * as Table from '$lib/components/ui/table';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
-
- interface NetworkWithId extends NetworkSummary {
- id: string;
- }
+ import { capitalizeFirstLetter } from '$lib/utils/string.utils';
let {
- networks,
+ networks = $bindable(),
selectedIds = $bindable(),
requestOptions = $bindable(),
- onRefresh,
- onNetworksChanged,
onCreateNetwork
}: {
- networks: Paginated<NetworkSummary>;
+ networks: Paginated<NetworkSummaryDto>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
- onRefresh: (options: SearchPaginationSortRequest) => Promise<Paginated<NetworkSummary>>;
- onNetworksChanged: () => Promise<void>;
onCreateNetwork: () => void;
} = $props();
@@ -41,33 +34,6 @@
remove: false
});
- const transformedNetworks = $derived.by(() => {
- const transformed: NetworkWithId[] = networks.data.map((network) => ({
- ...network,
- id: network.ID
- }));
-
- return {
- data: transformed,
- pagination: networks.pagination
- };
- });
-
- async function handleRefresh(
- options: SearchPaginationSortRequest
- ): Promise<Paginated<NetworkWithId>> {
- const result = await onRefresh(options);
- const transformed: NetworkWithId[] = result.data.map((network) => ({
- ...network,
- id: network.ID
- }));
-
- return {
- data: transformed,
- pagination: result.pagination
- };
- }
-
async function handleDeleteNetwork(id: string, name: string) {
if (DEFAULT_NETWORK_NAMES.has(name)) {
toast.error(`Cannot delete default network: ${name}`);
@@ -86,7 +52,7 @@
setLoadingState: (value) => (isLoading.remove = value),
onSuccess: async () => {
toast.success(`Network "${name}" Removed Successfully.`);
- await onNetworksChanged();
+ networks = await environmentAPI.getNetworks(requestOptions);
}
});
}
@@ -95,14 +61,14 @@
}
async function handleDeleteSelectedNetworks() {
- const selectedNetworkList = networks.data.filter((network) => selectedIds.includes(network.ID));
+ const selectedNetworkList = networks.data.filter((network) => selectedIds.includes(network.id));
const defaultNetworks = selectedNetworkList.filter((network) =>
- DEFAULT_NETWORK_NAMES.has(network.Name)
+ DEFAULT_NETWORK_NAMES.has(network.name)
);
if (defaultNetworks.length > 0) {
toast.error(
- `Cannot delete default networks: ${defaultNetworks.map((n) => n.Name).join(', ')}`
+ `Cannot delete default networks: ${defaultNetworks.map((n) => n.name).join(', ')}`
);
return;
}
@@ -120,23 +86,23 @@
let failureCount = 0;
for (const networkId of selectedIds) {
- const network = networks.data.find((n) => n.ID === networkId);
+ const network = networks.data.find((n) => n.id === networkId);
if (!network) continue;
const result = await tryCatch(environmentAPI.deleteNetwork(networkId));
if (result.error) {
failureCount++;
- toast.error(`Failed to delete network "${network.Name}": ${result.error.message}`);
+ toast.error(`Failed to delete network "${network.name}": ${result.error.message}`);
} else {
successCount++;
- toast.success(`Network "${network.Name}" deleted successfully.`);
+ toast.success(`Network "${network.name}" deleted successfully.`);
}
}
isLoading.remove = false;
if (successCount > 0) {
setTimeout(async () => {
- await onNetworksChanged();
+ networks = await environmentAPI.getNetworks(requestOptions);
}, 500);
}
selectedIds = [];
@@ -148,9 +114,9 @@
const isAnyLoading = $derived(Object.values(isLoading).some((loading) => loading));
const hasNetworks = $derived(networks?.data?.length > 0);
- const getConnectedContainers = (network: NetworkWithId) => {
- return network.Containers ? Object.keys(network.Containers).length : 0;
- };
+ // const getConnectedContainers = (network: NetworkSummaryDto) => {
+ // return network. ? Object.keys(network.Containers).length : 0;
+ // };
</script>
{#if hasNetworks}
@@ -176,15 +142,15 @@
</Card.Header>
<Card.Content>
<ArcaneTable
- items={transformedNetworks}
+ items={networks}
bind:requestOptions
bind:selectedIds
- onRefresh={handleRefresh}
+ onRefresh={async (options) => (networks = await environmentAPI.getNetworks(options))}
columns={[
- { label: 'Name', sortColumn: 'Name' },
- { label: 'Network ID', sortColumn: 'ID' },
- { label: 'Driver', sortColumn: 'Driver' },
- { label: 'Scope', sortColumn: 'Scope' },
+ { label: 'Name', sortColumn: 'name' },
+ { label: 'Network ID' },
+ { label: 'Driver', sortColumn: 'driver' },
+ { label: 'Scope', sortColumn: 'scope' },
{ label: ' ' }
]}
filterPlaceholder="Search networks..."
@@ -192,21 +158,28 @@
>
{#snippet rows({ item })}
<Table.Cell>
- <a class="font-medium hover:underline" href="/networks/{item.ID}/">{item.Name}</a>
+ <a class="font-medium hover:underline" href="/networks/{item.id}/">{item.name}</a>
</Table.Cell>
- <Table.Cell class="truncate font-mono text-sm">{item.ID}</Table.Cell>
+ <Table.Cell class="truncate font-mono text-sm">{item.id}</Table.Cell>
<Table.Cell>
<StatusBadge
- variant={item.Driver === 'bridge'
+ variant={item.driver === 'bridge'
? 'blue'
- : item.Driver === 'overlay'
+ : item.driver === 'overlay'
? 'purple'
- : 'gray'}
- text={item.Driver}
+ : item.driver === 'ipvlan'
+ ? 'red'
+ : item.driver === 'macvlan'
+ ? 'orange'
+ : 'gray'}
+ text={capitalizeFirstLetter(item.driver)}
/>
</Table.Cell>
<Table.Cell>
- <StatusBadge variant={item.Scope === 'local' ? 'green' : 'amber'} text={item.Scope} />
+ <StatusBadge
+ variant={item.scope === 'local' ? 'green' : 'amber'}
+ text={capitalizeFirstLetter(item.scope)}
+ />
</Table.Cell>
<Table.Cell>
<DropdownMenu.Root>
@@ -221,17 +194,17 @@
<DropdownMenu.Content align="end">
<DropdownMenu.Group>
<DropdownMenu.Item
- onclick={() => goto(`/networks/${item.ID}`)}
+ onclick={() => goto(`/networks/${item.id}`)}
disabled={isAnyLoading}
>
<ScanSearch class="size-4" />
Inspect
</DropdownMenu.Item>
- {#if !DEFAULT_NETWORK_NAMES.has(item.Name)}
+ {#if !DEFAULT_NETWORK_NAMES.has(item.name)}
<DropdownMenu.Item
variant="destructive"
- onclick={() => handleDeleteNetwork(item.ID, item.Name)}
- disabled={DEFAULT_NETWORK_NAMES.has(item.Name) || isAnyLoading}
+ onclick={() => handleDeleteNetwork(item.id, item.name)}
+ disabled={DEFAULT_NETWORK_NAMES.has(item.name) || isAnyLoading}
>
<Trash2 class="size-4" />
Remove
diff --git a/frontend/src/routes/volumes/+page.svelte b/frontend/src/routes/volumes/+page.svelte
index a362c3d91..c92131efd 100644
--- a/frontend/src/routes/volumes/+page.svelte
+++ b/frontend/src/routes/volumes/+page.svelte
@@ -1,78 +1,30 @@
<script lang="ts">
import { HardDrive, ArchiveRestore, ArchiveX } from '@lucide/svelte';
- import * as Alert from '$lib/components/ui/alert/index.js';
import { toast } from 'svelte-sonner';
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, VolumeInspectInfo } from 'dockerode';
+ import type { VolumeCreateOptions } from 'dockerode';
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { environmentAPI } from '$lib/services/api';
import StatCard from '$lib/components/stat-card.svelte';
import VolumeTable from './volume-table.svelte';
- import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
-
- type EnhancedVolumeInfo = VolumeInspectInfo & {
- InUse: boolean;
- CreatedAt: string;
- id: string;
- };
let { data } = $props();
- let volumes = $state<EnhancedVolumeInfo[]>(
- Array.isArray(data.volumes) ? data.volumes : data.volumes.data || []
- );
- let error = $state<string | null>(null);
+ let volumes = $state(data.volumes);
+ let requestOptions = $state(data.volumeRequestOptions);
let selectedIds = $state<string[]>([]);
- let requestOptions = $state<SearchPaginationSortRequest>(data.volumeRequestOptions);
-
- let isDialogOpen = $state({
- create: false
- });
+ let isCreateDialogOpen = $state(false);
let isLoading = $state({
creating: false,
refresh: false
});
- const totalVolumes = $derived(volumes.length);
- const usedVolumes = $derived(volumes.filter((v) => v.InUse).length);
- const unusedVolumes = $derived(volumes.filter((v) => !v.InUse).length);
-
- async function loadVolumes() {
- try {
- isLoading.refresh = true;
- const response = await environmentAPI.getVolumes(
- requestOptions.pagination,
- requestOptions.sort,
- requestOptions.search,
- requestOptions.filters
- );
- volumes = Array.isArray(response) ? response : response.data || [];
- error = null;
- } catch (err) {
- console.error('Failed to load volumes:', err);
- error = err instanceof Error ? err.message : 'Failed to load volumes';
- volumes = [];
- } finally {
- isLoading.refresh = false;
- }
- }
-
- async function onRefresh(options: SearchPaginationSortRequest) {
- requestOptions = options;
- await loadVolumes();
- return {
- data: volumes,
- pagination: {
- totalPages: Math.ceil(volumes.length / (requestOptions.pagination?.limit || 20)),
- totalItems: volumes.length,
- currentPage: requestOptions.pagination?.page || 1,
- itemsPerPage: requestOptions.pagination?.limit || 20
- }
- };
- }
+ const totalVolumes = $derived(volumes.data.length);
+ const usedVolumes = $derived(volumes.data.filter((v) => v.inUse).length);
+ const unusedVolumes = $derived(volumes.data.filter((v) => !v.inUse).length);
async function handleCreateVolumeSubmit(options: VolumeCreateOptions) {
isLoading.creating = true;
@@ -82,22 +34,22 @@
setLoadingState: (value) => (isLoading.creating = value),
onSuccess: async () => {
toast.success(`Volume "${options.Name}" Created Successfully.`);
- await loadVolumes();
- isDialogOpen.create = false;
+ volumes = await environmentAPI.getVolumes(requestOptions);
+ isCreateDialogOpen = false;
}
});
}
async function refreshVolumes() {
isLoading.refresh = true;
- try {
- await loadVolumes();
- } catch (error) {
- console.error('Failed to refresh volumes:', error);
- toast.error('Failed to refresh volumes');
- } finally {
- isLoading.refresh = false;
- }
+ handleApiResultWithCallbacks({
+ result: await tryCatch(environmentAPI.getVolumes(requestOptions)),
+ message: 'Failed to Refresh Volumes',
+ setLoadingState: (value) => (isLoading.refresh = value),
+ async onSuccess(newVolumes) {
+ volumes = newVolumes;
+ }
+ });
}
</script>
@@ -111,7 +63,7 @@
<ArcaneButton
action="create"
label="Create Volume"
- onClick={() => (isDialogOpen.create = true)}
+ onClick={() => (isCreateDialogOpen = true)}
loading={isLoading.creating}
disabled={isLoading.creating}
/>
@@ -125,13 +77,6 @@
</div>
</div>
- {#if error}
- <Alert.Root variant="destructive">
- <Alert.Title>Error Loading Volumes</Alert.Title>
- <Alert.Description>{error}</Alert.Description>
- </Alert.Root>
- {/if}
-
<div class="grid grid-cols-1 gap-4 sm:grid-cols-3">
<StatCard
title="Total Volumes"
@@ -156,16 +101,10 @@
/>
</div>
- <VolumeTable
- {volumes}
- bind:selectedIds
- bind:requestOptions
- {onRefresh}
- onVolumesChanged={loadVolumes}
- />
+ <VolumeTable bind:volumes bind:selectedIds bind:requestOptions />
<CreateVolumeSheet
- bind:open={isDialogOpen.create}
+ bind:open={isCreateDialogOpen}
isLoading={isLoading.creating}
onSubmit={handleCreateVolumeSubmit}
/>
diff --git a/frontend/src/routes/volumes/+page.ts b/frontend/src/routes/volumes/+page.ts
index d73e0b67a..0b8df2acb 100644
--- a/frontend/src/routes/volumes/+page.ts
+++ b/frontend/src/routes/volumes/+page.ts
@@ -3,23 +3,18 @@ import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';
import type { PageLoad } from './$types';
export const load: PageLoad = async () => {
- const volumeRequestOptions: SearchPaginationSortRequest = {
- pagination: {
- page: 1,
- limit: 20
- },
- sort: {
- column: 'Name',
- direction: 'asc' as const
- }
- };
+ const volumeRequestOptions: SearchPaginationSortRequest = {
+ pagination: {
+ page: 1,
+ limit: 20
+ },
+ sort: {
+ column: 'name',
+ direction: 'asc' as const
+ }
+ };
- const volumes = await environmentAPI.getVolumes(
- volumeRequestOptions.pagination,
- volumeRequestOptions.sort,
- volumeRequestOptions.search,
- volumeRequestOptions.filters
- );
+ const volumes = await environmentAPI.getVolumes(volumeRequestOptions);
- return { volumes, volumeRequestOptions };
-};
\ No newline at end of file
+ return { volumes, volumeRequestOptions };
+};
diff --git a/frontend/src/routes/volumes/[volumeName]/+page.svelte b/frontend/src/routes/volumes/[volumeName]/+page.svelte
index 1307f58e0..808d879be 100644
--- a/frontend/src/routes/volumes/[volumeName]/+page.svelte
+++ b/frontend/src/routes/volumes/[volumeName]/+page.svelte
@@ -1,11 +1,10 @@
<script lang="ts">
- import type { PageData } from './$types';
import * as Card from '$lib/components/ui/card/index.js';
import { HardDrive, Clock, Tag, Layers, Database, Globe, Info } from '@lucide/svelte';
import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';
import { goto } from '$app/navigation';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
- import { formatDate } from '$lib/utils/string.utils';
+ import { formatDate, truncateString } from '$lib/utils/string.utils';
import { openConfirmDialog } from '$lib/components/confirm-dialog/';
import { toast } from 'svelte-sonner';
import { tryCatch } from '$lib/utils/try-catch';
@@ -13,17 +12,18 @@
import ArcaneButton from '$lib/components/arcane-button.svelte';
import { environmentAPI } from '$lib/services/api';
- let { data }: { data: PageData } = $props();
- let { volume, inUse } = $derived(data);
+ let { data } = $props();
+ let volume = $state(data.volume);
let isLoading = $state({ remove: false });
- const createdDate = $derived(volume?.CreatedAt ? formatDate(volume.CreatedAt) : 'N/A');
+ const createdDate = $derived(volume.createdAt ? formatDate(volume.createdAt) : 'N/A');
async function handleRemoveVolumeConfirm(volumeName: string) {
let message = 'Are you sure you want to delete this volume? This action cannot be undone.';
- if (inUse) {
- message += '\n\n⚠️ Warning: This volume is currently in use by containers. Forcing removal may cause data loss or container issues.';
+ if (volume.inUse) {
+ message +=
+ '\n\n⚠️ Warning: This volume is currently in use by containers. Forcing removal may cause data loss or container issues.';
}
openConfirmDialog({
@@ -57,7 +57,7 @@
</Breadcrumb.Item>
<Breadcrumb.Separator />
<Breadcrumb.Item>
- <Breadcrumb.Page>{volume?.Name || 'Details'}</Breadcrumb.Page>
+ <Breadcrumb.Page>{volume.name}</Breadcrumb.Page>
</Breadcrumb.Item>
</Breadcrumb.List>
</Breadcrumb.Root>
@@ -66,29 +66,35 @@
<div class="flex flex-col">
<div class="flex items-center gap-3">
<h1 class="text-2xl font-bold tracking-tight">
- {volume?.Name || 'Volume Details'}
+ {volume.name}
</h1>
</div>
<div class="mt-2 flex gap-2">
- {#if inUse}
+ {#if volume.inUse}
<StatusBadge variant="green" text="In Use" />
{:else}
<StatusBadge variant="amber" text="Unused" />
{/if}
- {#if volume?.Driver}
- <StatusBadge variant="blue" text={volume.Driver} />
+ {#if volume.driver}
+ <StatusBadge variant="blue" text={volume.driver} />
{/if}
- {#if volume?.Scope}
- <StatusBadge variant="purple" text={volume.Scope} />
+ {#if volume.scope}
+ <StatusBadge variant="purple" text={volume.scope} />
{/if}
</div>
</div>
<div class="flex gap-2 self-start">
- <ArcaneButton action="remove" customLabel="Remove Volume" onClick={() => handleRemoveVolumeConfirm(volume?.Name)} loading={isLoading.remove} disabled={isLoading.remove} />
+ <ArcaneButton
+ action="remove"
+ customLabel="Remove Volume"
+ onClick={() => handleRemoveVolumeConfirm(volume.name)}
+ loading={isLoading.remove}
+ disabled={isLoading.remove}
+ />
</div>
</div>
</div>
@@ -106,27 +112,33 @@
<Card.Content class="pt-6">
<div class="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-2 lg:grid-cols-3">
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-gray-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-gray-500/10 p-2"
+ >
<Database class="size-5 text-gray-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Name</p>
- <p class="mt-1 text-base font-semibold break-words">{volume.Name}</p>
+ <p class="mt-1 text-base font-semibold break-words">{volume.name}</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-blue-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-blue-500/10 p-2"
+ >
<HardDrive class="size-5 text-blue-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Driver</p>
- <p class="mt-1 text-base font-semibold">{volume.Driver}</p>
+ <p class="mt-1 text-base font-semibold">{volume.driver}</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-green-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-green-500/10 p-2"
+ >
<Clock class="size-5 text-green-500" />
</div>
<div class="min-w-0 flex-1">
@@ -136,23 +148,27 @@
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-purple-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-purple-500/10 p-2"
+ >
<Globe class="size-5 text-purple-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Scope</p>
- <p class="mt-1 text-base font-semibold capitalize">{volume.Scope}</p>
+ <p class="mt-1 text-base font-semibold capitalize">{volume.scope}</p>
</div>
</div>
<div class="flex items-start gap-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-amber-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-amber-500/10 p-2"
+ >
<Info class="size-5 text-amber-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Status</p>
<p class="mt-1 text-base font-semibold">
- {#if inUse}
+ {#if volume.inUse}
<StatusBadge variant="green" text="In Use" />
{:else}
<StatusBadge variant="amber" text="Unused" />
@@ -162,13 +178,15 @@
</div>
<div class="col-span-1 flex items-start gap-3 sm:col-span-2 lg:col-span-3">
- <div class="flex size-10 shrink-0 items-center justify-center rounded-full bg-teal-500/10 p-2">
+ <div
+ class="flex size-10 shrink-0 items-center justify-center rounded-full bg-teal-500/10 p-2"
+ >
<Layers class="size-5 text-teal-500" />
</div>
<div class="min-w-0 flex-1">
<p class="text-muted-foreground text-sm font-medium">Mountpoint</p>
<div class="bg-muted/50 mt-2 rounded-lg border p-3">
- <code class="font-mono text-sm break-all">{volume.Mountpoint}</code>
+ <code class="font-mono text-sm break-all">{volume.mountpoint}</code>
</div>
</div>
</div>
@@ -176,7 +194,37 @@
</Card.Content>
</Card.Root>
- {#if volume.Labels && Object.keys(volume.Labels).length > 0}
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="pb-0">
+ <Card.Title class="flex items-center gap-2 text-lg">
+ <HardDrive class="text-primary size-5" />
+ Containers Using This Volume
+ </Card.Title>
+ <Card.Description>List of containers currently referencing this volume</Card.Description>
+ </Card.Header>
+ <Card.Content class="pt-6">
+ {#if volume.containers && volume.containers.length > 0}
+ <div class="divide-y rounded-lg border">
+ {#each volume.containers as id (id)}
+ <div class="flex items-center justify-between gap-3 p-3">
+ <code class="font-mono text-sm break-all">{truncateString(id, 48)}</code>
+ <a
+ href={`/containers/${id}`}
+ class="text-primary hover:underline text-sm"
+ title="View container details"
+ >
+ View
+ </a>
+ </div>
+ {/each}
+ </div>
+ {:else}
+ <div class="text-muted-foreground">No containers are currently using this volume.</div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+
+ {#if volume.labels && Object.keys(volume.labels).length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="pb-0">
<Card.Title class="flex items-center gap-2 text-lg">
@@ -187,12 +235,16 @@
</Card.Header>
<Card.Content class="pt-6">
<div class="bg-card divide-y rounded-lg border">
- {#each Object.entries(volume.Labels) as [key, value] (key)}
+ {#each Object.entries(volume.labels) as [key, value] (key)}
<div class="flex flex-col p-3 sm:flex-row">
- <div class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3">
+ <div
+ class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3"
+ >
{key}
</div>
- <div class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm">
+ <div
+ class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm"
+ >
{value}
</div>
</div>
@@ -202,7 +254,7 @@
</Card.Root>
{/if}
- {#if volume.Options && Object.keys(volume.Options).length > 0}
+ {#if volume.options && Object.keys(volume.options).length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="pb-0">
<Card.Title class="flex items-center gap-2 text-lg">
@@ -213,12 +265,16 @@
</Card.Header>
<Card.Content class="pt-6">
<div class="bg-card divide-y rounded-lg border">
- {#each Object.entries(volume.Options) as [key, value] (key)}
+ {#each Object.entries(volume.options) as [key, value] (key)}
<div class="flex flex-col p-3 sm:flex-row">
- <div class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3">
+ <div
+ class="text-muted-foreground mb-2 w-full font-medium break-all sm:mb-0 sm:w-1/3"
+ >
{key}
</div>
- <div class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm">
+ <div
+ class="bg-muted/50 w-full rounded p-2 font-mono text-xs break-all sm:w-2/3 sm:text-sm"
+ >
{value}
</div>
</div>
@@ -228,14 +284,16 @@
</Card.Root>
{/if}
- {#if (!volume.Labels || Object.keys(volume.Labels).length === 0) && (!volume.Options || Object.keys(volume.Options).length === 0)}
+ {#if (!volume.labels || Object.keys(volume.labels).length === 0) && (!volume.options || Object.keys(volume.options).length === 0)}
<Card.Root class="bg-muted/10 border shadow-sm">
<Card.Content class="pt-6 pb-6 text-center">
<div class="flex flex-col items-center justify-center">
<div class="bg-muted/30 mb-4 rounded-full p-3">
<Tag class="text-muted-foreground size-5 opacity-50" />
</div>
- <p class="text-muted-foreground">This volume has no additional labels or driver options.</p>
+ <p class="text-muted-foreground">
+ This volume has no additional labels or driver options.
+ </p>
</div>
</Card.Content>
</Card.Root>
@@ -247,9 +305,16 @@
<Database class="text-muted-foreground size-10 opacity-70" />
</div>
<h2 class="mb-2 text-xl font-medium">Volume Not Found</h2>
- <p class="text-muted-foreground mb-6">The requested volume could not be found or is no longer available.</p>
+ <p class="text-muted-foreground mb-6">
+ The requested volume could not be found or is no longer available.
+ </p>
- <ArcaneButton action="cancel" customLabel="Back to Volumes" onClick={() => goto('/volumes')} size="sm" />
+ <ArcaneButton
+ action="cancel"
+ customLabel="Back to Volumes"
+ onClick={() => goto('/volumes')}
+ size="sm"
+ />
</div>
{/if}
</div>
diff --git a/frontend/src/routes/volumes/[volumeName]/+page.ts b/frontend/src/routes/volumes/[volumeName]/+page.ts
index 5c2426d9d..4734a6ea7 100644
--- a/frontend/src/routes/volumes/[volumeName]/+page.ts
+++ b/frontend/src/routes/volumes/[volumeName]/+page.ts
@@ -6,16 +6,17 @@ export const load: PageLoad = async ({ params }) => {
const { volumeName } = params;
try {
- const volume = await environmentAPI.getVolume(volumeName);
+ const volumeBase = await environmentAPI.getVolume(volumeName);
+ const volumeUsage = await environmentAPI.getVolumeUsage(volumeName);
- if (!volume) {
- throw error(404, 'Volume not found');
- }
- const inUseResponse = await environmentAPI.getVolumeUsage(volumeName);
+ const volume = {
+ ...volumeBase,
+ inUse: volumeUsage,
+ containers: volumeUsage.containers
+ };
return {
- volume: volume,
- inUse: inUseResponse.data ? inUseResponse.data.inUse : false
+ volume
};
} catch (err: any) {
console.error('Failed to load volume:', err);
diff --git a/frontend/src/routes/volumes/volume-table.svelte b/frontend/src/routes/volumes/volume-table.svelte
index bf9ee915f..34f5e638f 100644
--- a/frontend/src/routes/volumes/volume-table.svelte
+++ b/frontend/src/routes/volumes/volume-table.svelte
@@ -1,8 +1,7 @@
<script lang="ts">
- import type { VolumeInspectInfo } from 'dockerode';
import ArcaneTable from '$lib/components/arcane-table.svelte';
import { Button } from '$lib/components/ui/button/index.js';
- import { Trash2, HardDrive, Ellipsis, ScanSearch, ChevronDown, Funnel } from '@lucide/svelte';
+ import { Trash2, HardDrive, Ellipsis, ScanSearch } from '@lucide/svelte';
import * as Card from '$lib/components/ui/card/index.js';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
@@ -18,25 +17,16 @@
import { environmentAPI } from '$lib/services/api';
import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
import FilterDropdown from '$lib/components/dropdowns/filter-dropdown.svelte';
-
- type EnhancedVolumeInfo = VolumeInspectInfo & {
- InUse: boolean;
- CreatedAt: string;
- id: string;
- };
+ import type { VolumeSummaryDto } from '$lib/types/volume.type';
let {
- volumes,
+ volumes = $bindable(),
selectedIds = $bindable(),
- requestOptions = $bindable(),
- onRefresh,
- onVolumesChanged
+ requestOptions = $bindable()
}: {
- volumes: EnhancedVolumeInfo[];
+ volumes: Paginated<VolumeSummaryDto>;
selectedIds: string[];
requestOptions: SearchPaginationSortRequest;
- onRefresh: (options: SearchPaginationSortRequest) => Promise<any>;
- onVolumesChanged: () => Promise<void>;
} = $props();
let volumeFilters = $state({
@@ -48,29 +38,13 @@
removing: false
});
- const volumesWithId = $derived(
- volumes.map((vol) => ({
- ...vol,
- id: vol.Name
- }))
- );
-
- const filteredVolumes = $derived(
- volumesWithId.filter((vol) => {
- const showBecauseUsed = volumeFilters.showUsed && vol.InUse;
- const showBecauseUnused = volumeFilters.showUnused && !vol.InUse;
+ const filteredVolumes: Paginated<VolumeSummaryDto> = $derived({
+ ...volumes,
+ data: volumes.data.filter((vol) => {
+ const showBecauseUsed = volumeFilters.showUsed && vol.inUse;
+ const showBecauseUnused = volumeFilters.showUnused && !vol.inUse;
return showBecauseUsed || showBecauseUnused;
})
- );
-
- const paginatedVolumes: Paginated<EnhancedVolumeInfo> = $derived({
- data: filteredVolumes,
- pagination: {
- totalPages: Math.ceil(filteredVolumes.length / (requestOptions.pagination?.limit || 20)),
- totalItems: filteredVolumes.length,
- currentPage: requestOptions.pagination?.page || 1,
- itemsPerPage: requestOptions.pagination?.limit || 20
- }
});
async function handleDeleteSelected() {
@@ -109,7 +83,7 @@
toast.success(
`Successfully removed ${successCount} volume${successCount > 1 ? 's' : ''}`
);
- await onVolumesChanged();
+ volumes = await environmentAPI.getVolumes(requestOptions);
}
if (failureCount > 0) {
@@ -137,7 +111,7 @@
setLoadingState: (value) => (isLoading.removing = value),
onSuccess: async () => {
toast.success(`Volume "${name}" Removed Successfully.`);
- await onVolumesChanged();
+ volumes = await environmentAPI.getVolumes(requestOptions);
}
});
}
@@ -146,7 +120,7 @@
}
</script>
-{#if filteredVolumes.length > 0}
+{#if volumes.data.length > 0}
<Card.Root class="border shadow-sm">
<Card.Header class="px-6">
<div class="flex items-center justify-between">
@@ -186,65 +160,75 @@
</div>
</Card.Header>
<Card.Content>
- <ArcaneTable
- items={paginatedVolumes}
- bind:requestOptions
- bind:selectedIds
- {onRefresh}
- columns={[
- { label: 'Name', sortColumn: 'Name' },
- { label: 'Status', sortColumn: 'InUse' },
- { label: 'Driver', sortColumn: 'Driver' },
- { label: 'Created', sortColumn: 'CreatedAt' },
- { label: ' ' }
- ]}
- filterPlaceholder="Search volumes..."
- noResultsMessage="No volumes found"
- >
- {#snippet rows({ item })}
- <Table.Cell>
- <a class="font-medium hover:underline" href="/volumes/{item.id}/" title={item.Name}>
- {truncateString(item.Name, 40)}
- </a>
- </Table.Cell>
- <Table.Cell>
- {#if item.InUse}
- <StatusBadge text="In Use" variant="green" />
- {:else}
- <StatusBadge text="Unused" variant="amber" />
- {/if}
- </Table.Cell>
- <Table.Cell>{item.Driver}</Table.Cell>
- <Table.Cell>{formatFriendlyDate(item.CreatedAt)}</Table.Cell>
- <Table.Cell>
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- {#snippet child({ props })}
- <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
- <span class="sr-only">Open menu</span>
- <Ellipsis />
- </Button>
- {/snippet}
- </DropdownMenu.Trigger>
- <DropdownMenu.Content align="end">
- <DropdownMenu.Group>
- <DropdownMenu.Item onclick={() => goto(`/volumes/${item.Name}`)}>
- <ScanSearch class="size-4" />
- Inspect
- </DropdownMenu.Item>
- <DropdownMenu.Item
- variant="destructive"
- onclick={() => handleRemoveVolumeConfirm(item.Name)}
- >
- <Trash2 class="size-4" />
- Remove
- </DropdownMenu.Item>
- </DropdownMenu.Group>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </Table.Cell>
- {/snippet}
- </ArcaneTable>
+ {#if filteredVolumes.data.length > 0}
+ <ArcaneTable
+ items={filteredVolumes}
+ bind:requestOptions
+ bind:selectedIds
+ onRefresh={async (options) => (volumes = await environmentAPI.getVolumes(options))}
+ columns={[
+ { label: 'Name', sortColumn: 'name' },
+ { label: 'Status', sortColumn: 'inUse' },
+ { label: 'Driver', sortColumn: 'driver' },
+ { label: 'Created', sortColumn: 'createdAt' },
+ { label: ' ' }
+ ]}
+ filterPlaceholder="Search volumes..."
+ noResultsMessage="No volumes found"
+ >
+ {#snippet rows({ item })}
+ <Table.Cell>
+ <a class="font-medium hover:underline" href="/volumes/{item.id}/" title={item.name}>
+ {truncateString(item.name, 40)}
+ </a>
+ </Table.Cell>
+ <Table.Cell>
+ {#if item.inUse}
+ <StatusBadge text="In Use" variant="green" />
+ {:else}
+ <StatusBadge text="Unused" variant="amber" />
+ {/if}
+ </Table.Cell>
+ <Table.Cell>{item.driver}</Table.Cell>
+ <Table.Cell>{formatFriendlyDate(item.createdAt)}</Table.Cell>
+ <Table.Cell>
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ {#snippet child({ props })}
+ <Button {...props} variant="ghost" size="icon" class="relative size-8 p-0">
+ <span class="sr-only">Open menu</span>
+ <Ellipsis />
+ </Button>
+ {/snippet}
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end">
+ <DropdownMenu.Group>
+ <DropdownMenu.Item onclick={() => goto(`/volumes/${item.id}`)}>
+ <ScanSearch class="size-4" />
+ Inspect
+ </DropdownMenu.Item>
+ <DropdownMenu.Item
+ variant="destructive"
+ onclick={() => handleRemoveVolumeConfirm(item.name)}
+ >
+ <Trash2 class="size-4" />
+ Remove
+ </DropdownMenu.Item>
+ </DropdownMenu.Group>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </Table.Cell>
+ {/snippet}
+ </ArcaneTable>
+ {:else}
+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">
+ <HardDrive class="text-muted-foreground mb-4 size-12 opacity-40" />
+ <p class="text-lg font-medium">No volumes match current filters</p>
+ <p class="text-muted-foreground mt-1 max-w-md text-sm">
+ Adjust your filters to see volumes
+ </p>
+ </div>
+ {/if}
</Card.Content>
</Card.Root>
{:else}