Skip to content

Modern Docker Management, Designed for Everyone

refactor: remove dead and unused code (#525)

Kyle Mendell856a4737fcf9
diff --git a/backend/internal/api/auth_handler.go b/backend/internal/api/auth_handler.go
index b2e4c4481..f9a1ed98f 100644
--- a/backend/internal/api/auth_handler.go
+++ b/backend/internal/api/auth_handler.go
@@ -154,9 +154,8 @@ func (h *AuthHandler) RefreshToken(c *gin.Context) {
}
func (h *AuthHandler) ChangePassword(c *gin.Context) {
- user, exists := middleware.GetCurrentUser(c)
- if !exists {
- c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": gin.H{"error": "Not authenticated"}})
+ user, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.go
index 3286d86ca..e239d66a1 100644
--- a/backend/internal/api/container_handler.go
+++ b/backend/internal/api/container_handler.go
@@ -121,16 +121,11 @@ func (h *ContainerHandler) PullImage(c *gin.Context) {
return
}
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
- err = h.imageService.PullImage(c.Request.Context(), imageName, c.Writer, *currentUser)
- if err != nil {
+ if err := h.imageService.PullImage(c.Request.Context(), imageName, c.Writer, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"data": gin.H{"error": "Failed to pull image: " + err.Error()},
@@ -202,12 +197,8 @@ func (h *ContainerHandler) GetByID(c *gin.Context) {
func (h *ContainerHandler) Start(c *gin.Context) {
id := c.Param("containerId")
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
if err := h.containerService.StartContainer(c.Request.Context(), id, *currentUser); err != nil {
@@ -227,12 +218,8 @@ func (h *ContainerHandler) Start(c *gin.Context) {
func (h *ContainerHandler) Stop(c *gin.Context) {
id := c.Param("containerId")
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
if err := h.containerService.StopContainer(c.Request.Context(), id, *currentUser); err != nil {
@@ -252,12 +239,8 @@ func (h *ContainerHandler) Stop(c *gin.Context) {
func (h *ContainerHandler) Restart(c *gin.Context) {
id := c.Param("containerId")
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
if err := h.containerService.RestartContainer(c.Request.Context(), id, *currentUser); err != nil {
@@ -298,12 +281,8 @@ func (h *ContainerHandler) Delete(c *gin.Context) {
force := c.Query("force") == "true"
removeVolumes := c.Query("volumes") == "true"
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
if err := h.containerService.DeleteContainer(c.Request.Context(), id, force, removeVolumes, *currentUser); err != nil {
@@ -342,39 +321,6 @@ func (h *ContainerHandler) GetContainerStatusCounts(c *gin.Context) {
})
}
-func (h *ContainerHandler) IsImageInUse(c *gin.Context) {
- imageID := c.Param("imageId")
- if imageID == "" {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": "Image ID is required"},
- })
- return
- }
-
- containers, _, _, _, err := h.dockerService.GetAllContainers(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": "Failed to list containers: " + err.Error()},
- })
- return
- }
-
- inUse := false
- for _, container := range containers {
- if container.ImageID == imageID || container.Image == imageID {
- inUse = true
- break
- }
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"inUse": inUse},
- })
-}
-
func (h *ContainerHandler) Create(c *gin.Context) {
var req dto.CreateContainerDto
if err := c.ShouldBindJSON(&req); err != nil {
@@ -443,12 +389,8 @@ func (h *ContainerHandler) Create(c *gin.Context) {
}
}
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
containerJSON, err := h.containerService.CreateContainer(
diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.go
index f0d20fa56..bb1f818b7 100644
--- a/backend/internal/api/environment_handler.go
+++ b/backend/internal/api/environment_handler.go
@@ -95,6 +95,7 @@ func NewEnvironmentHandler(
apiGroup.DELETE("/:id/images/:imageId", handler.RemoveImage)
apiGroup.POST("/:id/images/pull", handler.PullImage)
apiGroup.POST("/:id/images/prune", handler.PruneImages)
+ apiGroup.GET("/:id/images/counts", handler.GetImageUsageCounts)
apiGroup.GET("/:id/networks/counts", handler.GetNetworkUsageCounts)
apiGroup.GET("/:id/networks", handler.GetNetworks)
diff --git a/backend/internal/api/event_handler.go b/backend/internal/api/event_handler.go
index 94058852d..d2dba52b3 100644
--- a/backend/internal/api/event_handler.go
+++ b/backend/internal/api/event_handler.go
@@ -2,8 +2,6 @@ package api
import (
"net/http"
- "strconv"
- "time"
"github.com/gin-gonic/gin"
"github.com/ofkm/arcane-backend/internal/dto"
@@ -152,33 +150,3 @@ func (h *EventHandler) DeleteEvent(c *gin.Context) {
"data": gin.H{"message": "Event deleted successfully"},
})
}
-
-func (h *EventHandler) DeleteOldEvents(c *gin.Context) {
- daysStr := c.Query("days")
- if daysStr == "" {
- daysStr = c.Query("olderThanDays")
- }
-
- days, err := strconv.Atoi(daysStr)
- if err != nil || days <= 0 {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "data": gin.H{"error": "Invalid or missing 'days' parameter"},
- })
- return
- }
-
- duration := time.Duration(days) * 24 * time.Hour
- if err := h.eventService.DeleteOldEvents(c.Request.Context(), duration); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "data": gin.H{"error": "Failed to delete old events: " + err.Error()},
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{"message": "Old events deleted successfully"},
- })
-}
diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.go
index 2d88516af..0c9bb4b3d 100644
--- a/backend/internal/api/image_handler.go
+++ b/backend/internal/api/image_handler.go
@@ -87,9 +87,8 @@ func (h *ImageHandler) Remove(c *gin.Context) {
id := c.Param("imageId")
force := c.Query("force") == "true"
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
if err := h.imageService.RemoveImage(c.Request.Context(), id, force, *currentUser); err != nil {
@@ -123,9 +122,8 @@ func (h *ImageHandler) Pull(c *gin.Context) {
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.Header().Set("X-Accel-Buffering", "no")
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
diff --git a/backend/internal/api/network_handler.go b/backend/internal/api/network_handler.go
index a81ea5285..9cd3f1d9e 100644
--- a/backend/internal/api/network_handler.go
+++ b/backend/internal/api/network_handler.go
@@ -101,11 +101,11 @@ func (h *NetworkHandler) Create(c *gin.Context) {
return
}
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
+
response, err := h.networkService.CreateNetwork(c.Request.Context(), req.Name, req.Options, *currentUser)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -130,11 +130,11 @@ func (h *NetworkHandler) Create(c *gin.Context) {
func (h *NetworkHandler) Remove(c *gin.Context) {
id := c.Param("networkId")
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{"success": false, "data": dto.MessageDto{Message: "User not authenticated"}})
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
+
if err := h.networkService.RemoveNetwork(c.Request.Context(), id, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
diff --git a/backend/internal/api/system_handler.go b/backend/internal/api/system_handler.go
index 8bd35b750..10ce3d6bc 100644
--- a/backend/internal/api/system_handler.go
+++ b/backend/internal/api/system_handler.go
@@ -134,34 +134,6 @@ func (h *SystemHandler) GetDockerInfo(c *gin.Context) {
c.JSON(http.StatusOK, dockerInfo)
}
-func (h *SystemHandler) TestDockerConnection(c *gin.Context) {
- ctx := c.Request.Context()
-
- dockerClient, err := h.dockerService.CreateConnection(ctx)
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{
- "success": false,
- "error": "Failed to create Docker client: " + err.Error(),
- })
- return
- }
- defer dockerClient.Close()
-
- _, err = dockerClient.Ping(ctx)
- if err != nil {
- c.JSON(http.StatusServiceUnavailable, gin.H{
- "success": false,
- "error": "Docker is not accessible: " + err.Error(),
- })
- return
- }
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "message": "Docker connection successful",
- })
-}
-
func (h *SystemHandler) PruneAll(c *gin.Context) {
ctx := c.Request.Context()
slog.InfoContext(ctx, "System prune operation initiated")
diff --git a/backend/internal/api/volume_handler.go b/backend/internal/api/volume_handler.go
index 00112bb64..17659ba04 100644
--- a/backend/internal/api/volume_handler.go
+++ b/backend/internal/api/volume_handler.go
@@ -101,14 +101,11 @@ func (h *VolumeHandler) Create(c *gin.Context) {
DriverOpts: req.Options,
}
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
+
response, err := h.volumeService.CreateVolume(c.Request.Context(), options, *currentUser)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -128,14 +125,11 @@ func (h *VolumeHandler) Remove(c *gin.Context) {
name := c.Param("volumeName")
force := c.Query("force") == "true"
- currentUser, exists := middleware.GetCurrentUser(c)
- if !exists || currentUser == nil {
- c.JSON(http.StatusUnauthorized, gin.H{
- "success": false,
- "data": gin.H{"error": "User not authenticated"},
- })
+ currentUser, ok := middleware.RequireAuthentication(c)
+ if !ok {
return
}
+
if err := h.volumeService.DeleteVolume(c.Request.Context(), name, force, *currentUser); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
diff --git a/backend/internal/dto/dto_map.go b/backend/internal/dto/dto_map.go
index 3dd1380d8..db789a8d3 100644
--- a/backend/internal/dto/dto_map.go
+++ b/backend/internal/dto/dto_map.go
@@ -24,18 +24,6 @@ func MapOne[S any, D any](source S) (D, error) {
return dest, nil
}
-func MapStructList[S any, D any](source []S, destination *[]D) (err error) {
- *destination = make([]D, len(source))
-
- for i, item := range source {
- err = MapStruct(item, &((*destination)[i]))
- if err != nil {
- return fmt.Errorf("failed to map field %d: %w", i, err)
- }
- }
- return nil
-}
-
func MapStruct(source any, destination any) error {
return copier.CopyWithOption(destination, source, copier.Option{
DeepCopy: true,
diff --git a/backend/internal/job/analytics_job.go b/backend/internal/job/analytics_job.go
index 10b219076..c43b1256e 100644
--- a/backend/internal/job/analytics_job.go
+++ b/backend/internal/job/analytics_job.go
@@ -48,17 +48,6 @@ func NewAnalyticsJob(
}
}
-func RegisterAnalyticsJob(
- ctx context.Context,
- scheduler *Scheduler,
- settingsService *services.SettingsService,
- httpClient *http.Client,
- cfg *config.Config,
-) error {
- j := NewAnalyticsJob(scheduler, settingsService, httpClient, cfg)
- return j.Register(ctx)
-}
-
func (j *AnalyticsJob) Register(ctx context.Context) error {
if j.cfg.AnalyticsDisabled || !j.isProduction() {
slog.InfoContext(ctx, "analytics disabled or not in production; heartbeat job not registered",
@@ -81,36 +70,6 @@ func (j *AnalyticsJob) Register(ctx context.Context) error {
)
}
-func UpdateAnalyticsJobSchedule(
- ctx context.Context,
- scheduler *Scheduler,
- settingsService *services.SettingsService,
- httpClient *http.Client,
- cfg *config.Config,
-) error {
- j := NewAnalyticsJob(scheduler, settingsService, httpClient, cfg)
- return j.Reschedule(ctx)
-}
-
-func (j *AnalyticsJob) Reschedule(ctx context.Context) error {
- if j.cfg.AnalyticsDisabled || !j.isProduction() {
- j.scheduler.RemoveJobByName(AnalyticsJobName)
- slog.InfoContext(ctx, "analytics disabled or not in production; removed heartbeat job if present",
- "analyticsDisabled", j.cfg.AnalyticsDisabled, "env", j.cfg.Environment)
- return nil
- }
-
- slog.InfoContext(ctx, "analytics settings changed; rescheduling heartbeat job",
- "jobName", AnalyticsJobName, "interval", analyticsInterval.String())
-
- return j.scheduler.RescheduleDurationJobByName(ctx, AnalyticsJobName, analyticsInterval, j.Execute, true)
-}
-
-func (j *AnalyticsJob) Remove(ctx context.Context) {
- j.scheduler.RemoveJobByName(AnalyticsJobName)
- slog.InfoContext(ctx, "analytics heartbeat job removed", "jobName", AnalyticsJobName)
-}
-
func (j *AnalyticsJob) Execute(parentCtx context.Context) error {
if j.cfg.AnalyticsDisabled || !j.isProduction() {
slog.InfoContext(parentCtx, "analytics disabled or not in production; skipping heartbeat",
diff --git a/backend/internal/job/auto_update_job.go b/backend/internal/job/auto_update_job.go
index c2f307061..ccbb1d693 100644
--- a/backend/internal/job/auto_update_job.go
+++ b/backend/internal/job/auto_update_job.go
@@ -23,11 +23,6 @@ func NewAutoUpdateJob(scheduler *Scheduler, updaterService *services.UpdaterServ
}
}
-func RegisterAutoUpdateJob(ctx context.Context, scheduler *Scheduler, updaterService *services.UpdaterService, settingsService *services.SettingsService) error {
- j := NewAutoUpdateJob(scheduler, updaterService, settingsService)
- return j.Register(ctx)
-}
-
func (j *AutoUpdateJob) Register(ctx context.Context) error {
autoUpdateEnabled := j.settingsService.GetBoolSetting(ctx, "autoUpdate", false)
pollingEnabled := j.settingsService.GetBoolSetting(ctx, "pollingEnabled", true)
@@ -89,11 +84,6 @@ func (j *AutoUpdateJob) Execute(ctx context.Context) error {
return nil
}
-func UpdateAutoUpdateJobSchedule(ctx context.Context, scheduler *Scheduler, updaterService *services.UpdaterService, settingsService *services.SettingsService) error {
- j := NewAutoUpdateJob(scheduler, updaterService, settingsService)
- return j.Reschedule(ctx)
-}
-
func (j *AutoUpdateJob) Reschedule(ctx context.Context) error {
autoUpdateEnabled := j.settingsService.GetBoolSetting(ctx, "autoUpdate", false)
pollingEnabled := j.settingsService.GetBoolSetting(ctx, "pollingEnabled", true)
@@ -114,8 +104,3 @@ func (j *AutoUpdateJob) Reschedule(ctx context.Context) error {
return j.scheduler.RescheduleDurationJobByName(ctx, "auto-update", interval, j.Execute, false)
}
-
-func (j *AutoUpdateJob) Remove(ctx context.Context) {
- j.scheduler.RemoveJobByName("auto-update")
- slog.InfoContext(ctx, "auto-update job removed")
-}
diff --git a/backend/internal/job/image_polling_job.go b/backend/internal/job/image_polling_job.go
index 5434b5828..ac2561c85 100644
--- a/backend/internal/job/image_polling_job.go
+++ b/backend/internal/job/image_polling_job.go
@@ -23,11 +23,6 @@ func NewImagePollingJob(scheduler *Scheduler, imageUpdateService *services.Image
}
}
-func RegisterImagePollingJob(ctx context.Context, scheduler *Scheduler, imageUpdateService *services.ImageUpdateService, settingsService *services.SettingsService) error {
- j := NewImagePollingJob(scheduler, imageUpdateService, settingsService)
- return j.Register(ctx)
-}
-
func (j *ImagePollingJob) Register(ctx context.Context) error {
pollingEnabled := j.settingsService.GetBoolSetting(ctx, "pollingEnabled", true)
pollingInterval := j.settingsService.GetIntSetting(ctx, "pollingInterval", 60)
@@ -94,11 +89,6 @@ func (j *ImagePollingJob) Execute(ctx context.Context) error {
return nil
}
-func UpdateImagePollingJobSchedule(ctx context.Context, scheduler *Scheduler, imageUpdateService *services.ImageUpdateService, settingsService *services.SettingsService) error {
- j := NewImagePollingJob(scheduler, imageUpdateService, settingsService)
- return j.Reschedule(ctx)
-}
-
func (j *ImagePollingJob) Reschedule(ctx context.Context) error {
pollingEnabled := j.settingsService.GetBoolSetting(ctx, "pollingEnabled", true)
pollingInterval := j.settingsService.GetIntSetting(ctx, "pollingInterval", 60)
@@ -117,8 +107,3 @@ func (j *ImagePollingJob) Reschedule(ctx context.Context) error {
return j.scheduler.RescheduleDurationJobByName(ctx, "image-polling", interval, j.Execute, false)
}
-
-func (j *ImagePollingJob) Remove(ctx context.Context) {
- j.scheduler.RemoveJobByName("image-polling")
- slog.InfoContext(ctx, "image-polling job removed")
-}
diff --git a/backend/internal/job/stack_sync_job.go b/backend/internal/job/stack_sync_job.go
deleted file mode 100644
index aed044ca3..000000000
--- a/backend/internal/job/stack_sync_job.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package job
-
-import (
- "context"
- "fmt"
- "log/slog"
- "time"
-
- "github.com/go-co-op/gocron/v2"
- "github.com/ofkm/arcane-backend/internal/services"
-)
-
-const ProjectSyncJobName = "ProjectSync"
-
-func RegisterProjectSyncJob(
- ctx context.Context,
- scheduler *Scheduler,
- projectService *services.ProjectService,
-) error {
- slog.InfoContext(ctx, "Registering project sync job", "jobName", ProjectSyncJobName)
-
- taskFunc := func(jobCtx context.Context) error {
- slog.InfoContext(jobCtx, "Running project sync job", "jobName", ProjectSyncJobName)
-
- if err := projectService.SyncProjectsFromFileSystem(jobCtx); err != nil {
- slog.ErrorContext(jobCtx, "Failed to sync projects with filesystem",
- "jobName", ProjectSyncJobName,
- slog.Any("error", err))
- return err
- }
-
- slog.InfoContext(jobCtx, "Project sync job completed", "jobName", ProjectSyncJobName)
- return nil
- }
-
- jobDefinition := gocron.DurationJob(2 * time.Minute)
-
- err := scheduler.RegisterJob(
- ctx,
- ProjectSyncJobName,
- jobDefinition,
- taskFunc,
- true, // Run immediately on startup
- )
-
- if err != nil {
- return fmt.Errorf("failed to register project sync job %q: %w", ProjectSyncJobName, err)
- }
-
- slog.InfoContext(ctx, "Project sync job registered successfully", "jobName", ProjectSyncJobName)
- return nil
-}
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index db5011114..d08422e24 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -195,11 +195,6 @@ func GetCurrentUser(c *gin.Context) (*models.User, bool) {
return u, ok
}
-func IsAuthenticated(c *gin.Context) bool {
- _, exists := GetCurrentUser(c)
- return exists
-}
-
func RequireAuthentication(c *gin.Context) (*models.User, bool) {
user, exists := GetCurrentUser(c)
if !exists {
diff --git a/backend/internal/middleware/cors_middleware.go b/backend/internal/middleware/cors_middleware.go
index dba2b137c..f0ca74530 100644
--- a/backend/internal/middleware/cors_middleware.go
+++ b/backend/internal/middleware/cors_middleware.go
@@ -18,12 +18,6 @@ func NewCORSMiddleware(cfg *config.Config) *CORSMiddleware {
return &CORSMiddleware{cfg: cfg}
}
-func (m *CORSMiddleware) WithOrigins(origins []string) *CORSMiddleware {
- clone := *m
- clone.customOrigins = append([]string(nil), origins...)
- return &clone
-}
-
func (m *CORSMiddleware) Add() gin.HandlerFunc {
conf := cors.DefaultConfig()
conf.AllowOrigins = deriveAllowedOrigins(m.cfg, m.customOrigins)
@@ -68,7 +62,6 @@ func deriveAllowedOrigins(cfg *config.Config, custom []string) []string {
}
}
- // Dev defaults
if cfg == nil || cfg.Environment != "production" {
origins = append(origins,
"http://localhost:3000", "http://127.0.0.1:3000",
diff --git a/backend/internal/models/container.go b/backend/internal/models/container.go
index c1a6b437d..e43629fa9 100644
--- a/backend/internal/models/container.go
+++ b/backend/internal/models/container.go
@@ -21,7 +21,3 @@ type Container struct {
BaseModel
}
-
-func (Container) TableName() string {
- return "containers"
-}
diff --git a/backend/internal/models/errors.go b/backend/internal/models/errors.go
index bc1723fb3..be72b6baa 100644
--- a/backend/internal/models/errors.go
+++ b/backend/internal/models/errors.go
@@ -32,7 +32,6 @@ type APISuccessResponse struct {
Message string `json:"message,omitempty"`
}
-// APIError is a general API error type that implements error interface
type APIError struct {
Message string `json:"message"`
Code APIErrorCode `json:"code"`
@@ -60,7 +59,6 @@ func NewAPIError(message string, code APIErrorCode, statusCode int) *APIError {
}
}
-// NewAPIErrorWithDetails creates a new APIError with details
func NewAPIErrorWithDetails(message string, code APIErrorCode, statusCode int, details interface{}) *APIError {
return &APIError{
Message: message,
@@ -70,19 +68,6 @@ func NewAPIErrorWithDetails(message string, code APIErrorCode, statusCode int, d
}
}
-// Predefined API errors for common cases
-func NewBadRequestError(message string) *APIError {
- return NewAPIError(message, APIErrorCodeBadRequest, http.StatusBadRequest)
-}
-
-func NewUnauthorizedError(message string) *APIError {
- return NewAPIError(message, APIErrorCodeUnauthorized, http.StatusUnauthorized)
-}
-
-func NewForbiddenError(message string) *APIError {
- return NewAPIError(message, APIErrorCodeForbidden, http.StatusForbidden)
-}
-
func NewNotFoundError(message string) *APIError {
return NewAPIError(message, APIErrorCodeNotFound, http.StatusNotFound)
}
@@ -99,7 +84,6 @@ func NewValidationError(message string, details interface{}) *APIError {
return NewAPIErrorWithDetails(message, APIErrorCodeValidationError, http.StatusBadRequest, details)
}
-// Custom error types
type NotFoundError struct {
Message string
}
@@ -142,7 +126,6 @@ func (e *ValidationError) Error() string {
return e.Message
}
-// Helper function to convert any error to APIError
func ToAPIError(err error) *APIError {
var apiErr *APIError
if errors.As(err, &apiErr) {
diff --git a/backend/internal/models/network.go b/backend/internal/models/network.go
index e4819afbb..ed86bf5ef 100644
--- a/backend/internal/models/network.go
+++ b/backend/internal/models/network.go
@@ -16,7 +16,3 @@ type Network struct {
BaseModel
}
-
-func (Network) TableName() string {
- return "networks"
-}
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index 94758eb59..17e3420f4 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -408,18 +408,6 @@ func (s *AuthService) persistOidcTokens(user *models.User, tokenResp *dto.OidcTo
}
}
-func (s *AuthService) Logout(ctx context.Context, user *models.User) error {
- metadata := models.JSON{
- "action": "logout",
- "ipAddress": "", // Could be extracted from context if available
- }
- if logErr := s.eventService.LogUserEvent(ctx, models.EventTypeUserLogout, user.ID, user.Username, metadata); logErr != nil {
- fmt.Printf("Could not log user logout action: %s\n", logErr)
- }
-
- return nil
-}
-
func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string) (*TokenPair, error) {
token, err := jwt.ParseWithClaims(refreshToken, &jwt.RegisteredClaims{},
func(t *jwt.Token) (interface{}, error) {
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 792955ae9..19007552b 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -30,33 +30,6 @@ func NewContainerService(db *database.DB, eventService *EventService, dockerServ
return &ContainerService{db: db, eventService: eventService, dockerService: dockerService}
}
-func (s *ContainerService) PullContainerImage(ctx context.Context, containerID string) error {
- dockerClient, err := s.dockerService.CreateConnection(ctx)
- if err != nil {
- return fmt.Errorf("failed to connect to Docker: %w", err)
- }
- defer dockerClient.Close()
-
- container, err := s.GetContainerByID(ctx, containerID)
- if err != nil {
- return fmt.Errorf("failed to get container: %w", err)
- }
-
- imageName := container.Image
- if imageName == "" {
- return fmt.Errorf("container has no image to pull")
- }
-
- reader, err := dockerClient.ImagePull(ctx, imageName, image.PullOptions{})
- if err != nil {
- return fmt.Errorf("failed to pull image %s: %w", imageName, err)
- }
- defer reader.Close()
-
- _, err = io.Copy(io.Discard, reader)
- return err
-}
-
func (s *ContainerService) StartContainer(ctx context.Context, containerID string, user models.User) error {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 5193da515..4d5afa996 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -57,14 +57,6 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)
return &environment, nil
}
-func (s *EnvironmentService) ListEnvironments(ctx context.Context) ([]*models.Environment, error) {
- var environments []*models.Environment
- if err := s.db.WithContext(ctx).Order("created_at DESC").Find(&environments).Error; err != nil {
- return nil, fmt.Errorf("failed to list environments: %w", err)
- }
- return environments, nil
-}
-
func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]dto.EnvironmentDto, utils.PaginationResponse, error) {
var envs []models.Environment
q := s.db.WithContext(ctx).Model(&models.Environment{})
@@ -135,26 +127,26 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string) (str
url := strings.TrimRight(environment.ApiUrl, "/") + "/api/health"
req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, url, nil)
if err != nil {
- _ = s.updateEnvironmentStatus(ctx, id, string(models.EnvironmentStatusOffline))
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
return "offline", fmt.Errorf("failed to create request: %w", err)
}
resp, err := s.httpClient.Do(req)
if err != nil {
- _ = s.updateEnvironmentStatus(ctx, id, string(models.EnvironmentStatusOffline))
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
return "offline", fmt.Errorf("connection failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
- _ = s.updateEnvironmentStatus(ctx, id, string(models.EnvironmentStatusOnline))
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))
return "online", nil
}
- _ = s.updateEnvironmentStatus(ctx, id, string(models.EnvironmentStatusError))
+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))
return "error", fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
-func (s *EnvironmentService) updateEnvironmentStatus(ctx context.Context, id, status string) error {
+func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context, id, status string) error {
now := time.Now()
updates := map[string]interface{}{
"status": status,
@@ -167,20 +159,6 @@ func (s *EnvironmentService) updateEnvironmentStatus(ctx context.Context, id, st
return nil
}
-func (s *EnvironmentService) UpdateEnvironmentStatus(ctx context.Context, id, status string) error {
- now := time.Now()
- updates := map[string]interface{}{
- "status": status,
- "updated_at": &now,
- }
-
- if status == string(models.EnvironmentStatusOnline) {
- updates["last_seen"] = &now
- }
-
- return s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error
-}
-
func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, id string) error {
now := time.Now()
if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(map[string]interface{}{
@@ -193,39 +171,6 @@ func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, id
return nil
}
-func (s *EnvironmentService) GetOnlineEnvironments(ctx context.Context, timeoutMinutes int) ([]*models.Environment, error) {
- allEnvironments, err := s.ListEnvironments(ctx)
- if err != nil {
- return nil, err
- }
-
- var onlineEnvironments []*models.Environment
- for _, env := range allEnvironments {
- if s.IsEnvironmentOnline(env, timeoutMinutes) {
- onlineEnvironments = append(onlineEnvironments, env)
- }
- }
-
- return onlineEnvironments, nil
-}
-
-func (s *EnvironmentService) IsEnvironmentOnline(environment *models.Environment, timeoutMinutes int) bool {
- if !environment.Enabled {
- return false
- }
-
- if environment.Status != string(models.EnvironmentStatusOnline) {
- return false
- }
-
- if environment.LastSeen == nil {
- return false
- }
-
- timeoutDuration := time.Duration(timeoutMinutes) * time.Minute
- return time.Since(*environment.LastSeen) < timeoutDuration
-}
-
func (s *EnvironmentService) PairAgentWithBootstrap(ctx context.Context, apiUrl, bootstrapToken string) (string, error) {
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
@@ -307,7 +252,6 @@ func wsScheme(req *http.Request) string {
return "ws"
}
-// BuildLocalWSTarget returns ws URL and headers to proxy to this server.
func (s *EnvironmentService) BuildLocalWSTarget(req *http.Request, absolutePath string, agentToken string) (string, http.Header) {
u := &url.URL{
Scheme: wsScheme(req),
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 31f4f0452..fb9206a9b 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -314,21 +314,6 @@ func (s *ImageService) PruneImages(ctx context.Context, dangling bool) (*image.P
return &report, nil
}
-func (s *ImageService) GetImageHistory(ctx context.Context, id string) ([]image.HistoryResponseItem, error) {
- dockerClient, err := s.dockerService.CreateConnection(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed to connect to Docker: %w", err)
- }
- defer dockerClient.Close()
-
- history, err := dockerClient.ImageHistory(ctx, id)
- if err != nil {
- return nil, fmt.Errorf("failed to get image history: %w", err)
- }
-
- return history, nil
-}
-
func (s *ImageService) syncImagesToDatabase(ctx context.Context, dockerImages []image.Summary, dockerClient *client.Client) error {
inUseImageIDs := s.getInUseImageIDs(ctx, dockerClient)
currentDockerImageIDs := make([]string, 0, len(dockerImages))
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index 31fdda558..6d058e930 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -19,7 +19,6 @@ import (
registry "github.com/ofkm/arcane-backend/internal/utils/registry"
)
-// Local regex copies (previously referenced from utils.*VersionRegex)
var (
semanticVersionRegex = regexp.MustCompile(`^(?:v)?(\d+)\.(\d+)\.(\d+)$`)
dateVersionRegex = regexp.MustCompile(`^(\d{4})\.(\d{1,2})\.(\d{1,2})$`)
@@ -1110,57 +1109,6 @@ func (s *ImageUpdateService) CheckAllImages(ctx context.Context, limit int) (map
return s.CheckMultipleImages(ctx, imageRefs)
}
-func (s *ImageUpdateService) TriggerBulkUpdateCheck(ctx context.Context, imageIDs []string) error {
- // Log bulk update check start
- metadata := models.JSON{
- "action": "bulk_update_check",
- "imageIDs": imageIDs,
- "count": len(imageIDs),
- }
- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageScan, "", "bulk_check", systemUser.ID, systemUser.Username, "0", metadata); logErr != nil {
- slog.WarnContext(ctx, "Failed to log bulk update check start event",
- slog.String("error", logErr.Error()))
- }
-
- successCount := 0
- errorCount := 0
- for _, imageID := range imageIDs {
- _, err := s.CheckImageUpdateByID(ctx, imageID)
- if err != nil {
- errorCount++
- continue
- }
- successCount++
- }
-
- // Log bulk update check completion
- completionMetadata := models.JSON{
- "action": "bulk_update_check_complete",
- "totalImages": len(imageIDs),
- "successCount": successCount,
- "errorCount": errorCount,
- }
- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageScan, "", "bulk_check_complete", systemUser.ID, systemUser.Username, "0", completionMetadata); logErr != nil {
- slog.WarnContext(ctx, "Failed to log bulk update check completion event",
- slog.String("error", logErr.Error()))
- }
-
- return nil
-}
-
-func (s *ImageUpdateService) GetUpdateRecordByImageID(ctx context.Context, imageID string) (*models.ImageUpdateRecord, error) {
- var record models.ImageUpdateRecord
- err := s.db.WithContext(ctx).Where("id = ?", imageID).First(&record).Error
- if err != nil {
- return nil, err
- }
- return &record, nil
-}
-
-func (s *ImageUpdateService) DeleteUpdateRecord(ctx context.Context, imageID string) error {
- return s.db.WithContext(ctx).Where("id = ?", imageID).Delete(&models.ImageUpdateRecord{}).Error
-}
-
func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {
subQuery := s.db.WithContext(ctx).Model(&models.Image{}).Select("id")
return s.db.WithContext(ctx).
diff --git a/backend/internal/services/network_service.go b/backend/internal/services/network_service.go
index b504b76c3..7c94a878d 100644
--- a/backend/internal/services/network_service.go
+++ b/backend/internal/services/network_service.go
@@ -14,7 +14,6 @@ import (
"github.com/ofkm/arcane-backend/internal/dto"
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/utils"
- "github.com/ofkm/arcane-backend/internal/utils/docker"
)
type NetworkService struct {
@@ -125,68 +124,6 @@ func (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneRepor
return &report, nil
}
-func (s *NetworkService) GetNetworksByDriver(ctx context.Context, driver string) ([]network.Summary, error) {
- networks, _, _, _, err := s.dockerService.GetAllNetworks(ctx)
- if err != nil {
- return nil, err
- }
-
- var filtered []network.Summary
- for _, net := range networks {
- if net.Driver == driver {
- filtered = append(filtered, net)
- }
- }
-
- return filtered, nil
-}
-
-func (s *NetworkService) GetDefaultNetworks(ctx context.Context) ([]network.Summary, error) {
- networks, _, _, _, err := s.dockerService.GetAllNetworks(ctx)
- if err != nil {
- return nil, err
- }
-
- var defaults []network.Summary
- for _, net := range networks {
- if docker.IsDefaultNetwork(net.Name) {
- defaults = append(defaults, net)
- }
- }
- return defaults, nil
-}
-
-func (s *NetworkService) GetNetworksByScope(ctx context.Context, scope string) ([]network.Summary, error) {
- networks, _, _, _, err := s.dockerService.GetAllNetworks(ctx)
- if err != nil {
- return nil, err
- }
-
- var filtered []network.Summary
- for _, net := range networks {
- if net.Scope == scope {
- filtered = append(filtered, net)
- }
- }
-
- return filtered, nil
-}
-
-func (s *NetworkService) GetUserDefinedNetworks(ctx context.Context) ([]network.Summary, error) {
- networks, _, _, _, err := s.dockerService.GetAllNetworks(ctx)
- if err != nil {
- return nil, err
- }
-
- var userDefined []network.Summary
- for _, net := range networks {
- if !docker.IsDefaultNetwork(net.Name) {
- userDefined = append(userDefined, net)
- }
- }
- return userDefined, nil
-}
-
//nolint:gocognit
func (s *NetworkService) ListNetworksPaginated(ctx context.Context, req utils.SortedPaginationRequest) ([]dto.NetworkSummaryDto, utils.PaginationResponse, error) {
nets, _, _, _, err := s.dockerService.GetAllNetworks(ctx)
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index bd55e6aaa..4f3b44386 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -427,7 +427,6 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us
return fmt.Errorf("failed to update project status to deploying: %w", err)
}
- // Pre-pull all images using auth-aware ImageService
if perr := s.PullProjectImages(ctx, projectID, io.Discard); perr != nil {
slog.Warn("pre-pull images failed (continuing to compose up)", "projectID", projectID, "error", perr)
}
diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.go
index c4531d9d2..11e7ca296 100644
--- a/backend/internal/services/system_service.go
+++ b/backend/internal/services/system_service.go
@@ -326,64 +326,3 @@ func (s *SystemService) pruneNetworks(ctx context.Context, result *dto.PruneAllR
result.NetworksDeleted = report.NetworksDeleted
return nil
}
-
-func (s *SystemService) PruneSystem(ctx context.Context, all bool) (*dto.PruneAllResult, error) {
- slog.InfoContext(ctx, "Starting system-wide prune operation", slog.Bool("all", all))
-
- result := &dto.PruneAllResult{
- Success: true,
- }
-
- danglingOnly := true
- if all {
- pruneMode := s.settingsService.GetStringSetting(ctx, "dockerPruneMode", "dangling")
- danglingOnly = pruneMode == "dangling"
- slog.DebugContext(ctx, "Retrieved prune mode from settings",
- slog.String("prune_mode", pruneMode),
- slog.Bool("dangling_only", danglingOnly))
- }
-
- slog.DebugContext(ctx, "Starting container pruning")
- if err := s.pruneContainers(ctx, result); err != nil {
- result.Errors = append(result.Errors, fmt.Sprintf("Container pruning failed: %v", err))
- result.Success = false
- slog.ErrorContext(ctx, "Container pruning failed", slog.String("error", err.Error()))
- }
-
- slog.DebugContext(ctx, "Starting image pruning", slog.Bool("dangling_only", danglingOnly))
- if err := s.pruneImages(ctx, danglingOnly, result); err != nil {
- result.Errors = append(result.Errors, fmt.Sprintf("Image pruning failed: %v", err))
- result.Success = false
- slog.ErrorContext(ctx, "Image pruning failed", slog.String("error", err.Error()))
- }
-
- slog.DebugContext(ctx, "Starting build cache pruning", slog.Bool("prune_all_cache", !danglingOnly))
- if buildCacheErr := s.pruneBuildCache(ctx, result, !danglingOnly); buildCacheErr != nil {
- slog.WarnContext(ctx, "Build cache pruning encountered an error", slog.String("error", buildCacheErr.Error()))
- }
-
- slog.DebugContext(ctx, "Starting volume pruning")
- if err := s.pruneVolumes(ctx, result); err != nil {
- result.Errors = append(result.Errors, fmt.Sprintf("Volume pruning failed: %v", err))
- result.Success = false
- slog.ErrorContext(ctx, "Volume pruning failed", slog.String("error", err.Error()))
- }
-
- slog.DebugContext(ctx, "Starting network pruning")
- if err := s.pruneNetworks(ctx, result); err != nil {
- result.Errors = append(result.Errors, fmt.Sprintf("Network pruning failed: %v", err))
- result.Success = false
- slog.ErrorContext(ctx, "Network pruning failed", slog.String("error", err.Error()))
- }
-
- slog.InfoContext(ctx, "System-wide prune operation completed",
- slog.Bool("success", result.Success),
- slog.Int("containers_pruned", len(result.ContainersPruned)),
- slog.Int("images_deleted", len(result.ImagesDeleted)),
- slog.Int("volumes_deleted", len(result.VolumesDeleted)),
- slog.Int("networks_deleted", len(result.NetworksDeleted)),
- slog.Uint64("space_reclaimed", result.SpaceReclaimed),
- slog.Int("error_count", len(result.Errors)))
-
- return result, nil
-}
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index 0edbc676d..b2cd7e18a 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -220,32 +220,6 @@ func (s *VolumeService) PruneVolumesWithOptions(ctx context.Context, all bool) (
}, nil
}
-func (s *VolumeService) GetVolumesByDriver(ctx context.Context, driver string) ([]dto.VolumeDto, error) {
- volumes, err := s.ListVolumes(ctx)
- if err != nil {
- return nil, err
- }
-
- 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
-}
-
func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool, []string, error) {
dockerClient, err := s.dockerService.CreateConnection(ctx)
if err != nil {
@@ -334,34 +308,6 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.Sort
return pageItems, pagination, nil
}
-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)
- }
-
- dockerClient, err := s.dockerService.CreateConnection(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed to connect to Docker: %w", err)
- }
- defer dockerClient.Close()
-
- volumeUsageMap, err := s.buildVolumeUsageMap(ctx, dockerClient)
- if err != nil {
- return nil, err
- }
-
- var result []dto.VolumeDto
- for _, v := range volumes {
- 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))
diff --git a/backend/internal/utils/encryption.go b/backend/internal/utils/encryption.go
index 3848b178d..24d32224d 100644
--- a/backend/internal/utils/encryption.go
+++ b/backend/internal/utils/encryption.go
@@ -213,7 +213,3 @@ func Decrypt(ciphertext string) (string, error) {
return string(plaintext), nil
}
-
-func IsInitialized() bool {
- return encryptionKey != nil
-}
diff --git a/backend/internal/utils/fs/fs_templates.go b/backend/internal/utils/fs/fs_templates.go
index 35bb07cc5..f3e45b7bd 100644
--- a/backend/internal/utils/fs/fs_templates.go
+++ b/backend/internal/utils/fs/fs_templates.go
@@ -37,30 +37,6 @@ func ReadFolderComposeTemplate(baseDir, folder string) (string, *string, string,
return string(b), envPtr, desc, true, nil
}
-func ReadRootComposeTemplate(baseDir, fileName string) (string, string, *string, string, error) {
- ext := strings.ToLower(filepath.Ext(fileName))
- base := strings.TrimSuffix(fileName, ext)
- composePath := filepath.Join(baseDir, fileName)
-
- b, err := os.ReadFile(composePath)
- if err != nil {
- return "", "", nil, "", fmt.Errorf("read compose %s: %w", composePath, err)
- }
-
- var envPtr *string
- for _, envExt := range []string{".env.example", ".env"} {
- envPath := filepath.Join(baseDir, base+envExt)
- if eb, err := os.ReadFile(envPath); err == nil {
- env := string(eb)
- envPtr = &env
- break
- }
- }
-
- desc := fmt.Sprintf("Imported from %s/%s", baseDir, fileName)
- return base, string(b), envPtr, desc, nil
-}
-
func Slugify(in string) string {
in = strings.TrimSpace(strings.ToLower(in))
if in == "" {
diff --git a/backend/internal/utils/projects/cmds.go b/backend/internal/utils/projects/cmds.go
index 9de42beb2..defecc77d 100644
--- a/backend/internal/utils/projects/cmds.go
+++ b/backend/internal/utils/projects/cmds.go
@@ -14,7 +14,7 @@ func ComposePull(ctx context.Context, proj *types.Project) error {
return err
}
defer c.Close()
- return c.Pull(ctx, proj, api.PullOptions{})
+ return c.svc.Pull(ctx, proj, api.PullOptions{})
}
func ComposeRestart(ctx context.Context, proj *types.Project, services []string) error {
@@ -23,7 +23,7 @@ func ComposeRestart(ctx context.Context, proj *types.Project, services []string)
return err
}
defer c.Close()
- return c.Restart(ctx, proj, services)
+ return c.svc.Restart(ctx, proj.Name, api.RestartOptions{Services: services})
}
func ComposeUp(ctx context.Context, proj *types.Project, services []string) error {
@@ -41,7 +41,8 @@ func ComposeUp(ctx context.Context, proj *types.Project, services []string) erro
Services: proj.ServiceNames(),
Wait: true,
}
- return c.Up(ctx, proj, api.UpOptions{Create: upOptions, Start: startOptions})
+
+ return c.svc.Up(ctx, proj, api.UpOptions{Create: upOptions, Start: startOptions})
}
func ComposePs(ctx context.Context, proj *types.Project, services []string, all bool) ([]api.ContainerSummary, error) {
@@ -51,9 +52,7 @@ func ComposePs(ctx context.Context, proj *types.Project, services []string, all
}
defer c.Close()
- return c.Ps(ctx, proj, api.PsOptions{
- All: all,
- })
+ return c.svc.Ps(ctx, proj.Name, api.PsOptions{All: all})
}
func ComposeDown(ctx context.Context, proj *types.Project, removeVolumes bool) error {
@@ -62,7 +61,8 @@ func ComposeDown(ctx context.Context, proj *types.Project, removeVolumes bool) e
return err
}
defer c.Close()
- return c.Down(ctx, proj, api.DownOptions{RemoveOrphans: true, Volumes: removeVolumes})
+
+ return c.svc.Down(ctx, proj.Name, api.DownOptions{RemoveOrphans: true, Volumes: removeVolumes})
}
func ComposeLogs(ctx context.Context, projectName string, out io.Writer, follow bool, tail string) error {
@@ -71,5 +71,6 @@ func ComposeLogs(ctx context.Context, projectName string, out io.Writer, follow
return err
}
defer c.Close()
- return c.Logs(ctx, projectName, out, api.LogOptions{Follow: follow, Tail: tail})
+
+ return c.svc.Logs(ctx, projectName, writerConsumer{out: out}, api.LogOptions{Follow: follow, Tail: tail})
}
diff --git a/backend/internal/utils/projects/command.go b/backend/internal/utils/projects/command.go
deleted file mode 100644
index d3d504903..000000000
--- a/backend/internal/utils/projects/command.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package projects
-
-import (
- "context"
- "fmt"
- "os"
- "os/exec"
- "strings"
-
- "log/slog"
-)
-
-func RunComposeAction(ctx context.Context, composeFileFullPath, projectName, action string, extraArgs ...string) (string, error) {
- allowed := map[string]bool{
- "up": true,
- "down": true,
- "pull": true,
- "restart": true,
- "start": true,
- "stop": true,
- "logs": true,
- "deploy": true,
- "ps": true,
- }
-
- action = strings.TrimSpace(strings.ToLower(action))
- if !allowed[action] {
- return "", fmt.Errorf("unsupported compose action: %q", action)
- }
-
- args := []string{"-f", composeFileFullPath}
-
- switch action {
- case "up":
- args = append(args, "up", "-d")
- case "deploy":
- args = append(args, "up", "-d", "--remove-orphans")
- case "down":
- args = append(args, "down")
- case "pull":
- args = append(args, "pull")
- case "restart":
- args = append(args, "restart")
- case "start":
- args = append(args, "start")
- case "stop":
- args = append(args, "stop")
- case "logs":
- args = append(args, "logs", "--no-color")
- case "ps":
- args = append(args, "ps", "--format", "json")
- default:
- args = append(args, action)
- }
-
- if len(extraArgs) > 0 {
- args = append(args, extraArgs...)
- }
-
- cmd := exec.CommandContext(ctx, "docker-compose", args...)
- cmd.Env = append(os.Environ(), fmt.Sprintf("COMPOSE_PROJECT_NAME=%s", projectName))
-
- slog.Info("running docker-compose", "cmd", strings.Join(cmd.Args, " "), "project", projectName)
-
- out, err := cmd.CombinedOutput()
- output := string(out)
- if err != nil {
- slog.Error("docker-compose failed", "err", err, "output", output)
- return output, fmt.Errorf("docker-compose %s failed: %w; output: %s", action, err, output)
- }
-
- slog.Info("docker-compose completed", "action", action, "project", projectName)
- return output, nil
-}
diff --git a/backend/internal/utils/projects/compose.go b/backend/internal/utils/projects/compose.go
index c02313cfd..6d2cf82a3 100644
--- a/backend/internal/utils/projects/compose.go
+++ b/backend/internal/utils/projects/compose.go
@@ -5,7 +5,6 @@ import (
"io"
"strings"
- "github.com/compose-spec/compose-go/v2/types"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/flags"
"github.com/docker/compose/v2/pkg/api"
@@ -40,30 +39,6 @@ func (c *Client) Close() error {
return nil
}
-func (c *Client) Up(ctx context.Context, proj *types.Project, opts api.UpOptions) error {
- return c.svc.Up(ctx, proj, opts)
-}
-
-func (c *Client) Down(ctx context.Context, proj *types.Project, opts api.DownOptions) error {
- return c.svc.Down(ctx, proj.Name, opts)
-}
-
-func (c *Client) Pull(ctx context.Context, proj *types.Project, opts api.PullOptions) error {
- return c.svc.Pull(ctx, proj, opts)
-}
-
-func (c *Client) Restart(ctx context.Context, proj *types.Project, services []string) error {
- return c.svc.Restart(ctx, proj.Name, api.RestartOptions{Services: services})
-}
-
-func (c *Client) Create(ctx context.Context, proj *types.Project, opts api.CreateOptions) error {
- return c.svc.Create(ctx, proj, opts)
-}
-
-func (c *Client) Start(ctx context.Context, projectName string, opts api.StartOptions) error {
- return c.svc.Start(ctx, projectName, opts)
-}
-
type writerConsumer struct{ out io.Writer }
func (w writerConsumer) Register(container string) {}
@@ -88,11 +63,3 @@ func (w writerConsumer) Err(container, msg string) {
}
_, _ = io.WriteString(w.out, msg)
}
-
-func (c *Client) Logs(ctx context.Context, projectName string, out io.Writer, opts api.LogOptions) error {
- return c.svc.Logs(ctx, projectName, writerConsumer{out: out}, opts)
-}
-
-func (c *Client) Ps(ctx context.Context, proj *types.Project, opts api.PsOptions) ([]api.ContainerSummary, error) {
- return c.svc.Ps(ctx, proj.Name, opts)
-}
diff --git a/backend/internal/utils/projects/ps.go b/backend/internal/utils/projects/ps.go
deleted file mode 100644
index 4af0062ac..000000000
--- a/backend/internal/utils/projects/ps.go
+++ /dev/null
@@ -1,252 +0,0 @@
-package projects
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "strings"
-
- composetypes "github.com/compose-spec/compose-go/v2/types"
-)
-
-type PSInfo struct {
- Service string
- Image string
- Status string
- ContainerID string
- Ports []string
-}
-
-type ServiceStatus struct {
- Name string
- Image string
- Status string
- ContainerID string
- Ports []string
-}
-
-func ComposeServicesStatus(ctx context.Context, proj *composetypes.Project, composeFileFullPath, projectName string) ([]ServiceStatus, error) {
- if proj == nil {
- return nil, fmt.Errorf("compose project is nil")
- }
-
- services, byName := buildBaselineServices(proj)
-
- if out, err := RunComposeAction(ctx, composeFileFullPath, projectName, "ps"); err == nil {
- live := parseComposePS(out)
- if len(live) > 0 {
- mergeLiveStatuses(byName, live)
- }
- }
-
- return services, nil
-}
-
-func buildBaselineServices(proj *composetypes.Project) ([]ServiceStatus, map[string]*ServiceStatus) {
- services := make([]ServiceStatus, 0, len(proj.Services))
- byName := map[string]*ServiceStatus{}
-
- for _, svc := range proj.Services {
- item := ServiceStatus{
- Name: svc.Name,
- Image: svc.Image,
- Status: "not created",
- ContainerID: "",
- Ports: []string{},
- }
- for _, port := range svc.Ports {
- if port.Published != "" && port.Target != 0 {
- p := fmt.Sprintf("%s:%d", port.Published, port.Target)
- if port.Protocol != "" {
- p += "/" + port.Protocol
- }
- item.Ports = append(item.Ports, p)
- }
- }
- services = append(services, item)
- byName[svc.Name] = &services[len(services)-1]
- }
- return services, byName
-}
-
-func mergeLiveStatuses(byName map[string]*ServiceStatus, live []PSInfo) {
- for _, ls := range live {
- if dest, ok := byName[ls.Service]; ok {
- if strings.TrimSpace(ls.Status) != "" {
- dest.Status = ls.Status
- }
- if strings.TrimSpace(ls.ContainerID) != "" {
- dest.ContainerID = ls.ContainerID
- }
- if len(ls.Ports) > 0 {
- dest.Ports = ls.Ports
- }
- if strings.TrimSpace(ls.Image) != "" {
- dest.Image = ls.Image
- }
- }
- }
-}
-
-func ComposePS(ctx context.Context, dir, projectName string) ([]PSInfo, error) {
- composeFile, err := DetectComposeFile(dir)
- if err != nil {
- return nil, err
- }
- out, err := RunComposeAction(ctx, composeFile, projectName, "ps")
- if err != nil {
- return nil, err
- }
- return parseComposePS(out), nil
-}
-
-func parseComposePS(output string) []PSInfo {
- output = strings.TrimSpace(output)
- if output == "" {
- return nil
- }
-
- var services []PSInfo
-
- if strings.HasPrefix(output, "[") {
- var arr []map[string]any
- if err := json.Unmarshal([]byte(output), &arr); err == nil {
- for _, item := range arr {
- if svc, ok := parseComposeService(item); ok {
- services = append(services, svc)
- }
- }
- return services
- }
- }
-
- lines := strings.Split(output, "\n")
- for _, line := range lines {
- line = strings.TrimSpace(line)
- if line == "" {
- continue
- }
- var item map[string]any
- if err := json.Unmarshal([]byte(line), &item); err != nil {
- continue
- }
- if svc, ok := parseComposeService(item); ok {
- services = append(services, svc)
- }
- }
-
- return services
-}
-
-func parseComposeService(item map[string]any) (PSInfo, bool) {
- var svc PSInfo
-
- if v, ok := item["Service"].(string); ok && v != "" {
- svc.Service = v
- } else if v, ok := item["Name"].(string); ok && v != "" {
- svc.Service = v
- }
-
- if v, ok := item["Image"].(string); ok {
- svc.Image = v
- }
- if v, ok := item["State"].(string); ok {
- svc.Status = v
- } else if v, ok := item["Status"].(string); ok {
- svc.Status = v
- }
- if v, ok := item["ID"].(string); ok {
- svc.ContainerID = v
- } else if v, ok := item["ContainerID"].(string); ok {
- svc.ContainerID = v
- }
-
- svc.Ports = extractPortsFromItem(item)
- if pubs := extractPublishers(item); len(pubs) > 0 {
- svc.Ports = append(svc.Ports, pubs...)
- }
-
- if svc.Service == "" {
- return PSInfo{}, false
- }
- return svc, true
-}
-
-func extractPortsFromItem(item map[string]any) []string {
- var out []string
- if portsInterface, ok := item["Ports"]; ok {
- switch ports := portsInterface.(type) {
- case string:
- if ports != "" {
- out = append(out, ports)
- }
- case []any:
- for _, p := range ports {
- if ps, ok := p.(string); ok && ps != "" {
- out = append(out, ps)
- }
- }
- case []string:
- out = append(out, ports...)
- }
- }
- return out
-}
-
-func extractPublishers(item map[string]any) []string {
- var out []string
- if pubs, ok := item["Publishers"]; ok {
- if arr, ok := pubs.([]any); ok {
- return publishersFromArray(arr)
- }
- }
- return out
-}
-
-func publishersFromArray(arr []any) []string {
- var out []string
- for _, p := range arr {
- pm, ok := p.(map[string]any)
- if !ok {
- continue
- }
- if s := publisherToString(pm); s != "" {
- out = append(out, s)
- }
- }
- return out
-}
-
-func publisherToString(pm map[string]any) string {
- if url, ok := pm["URL"].(string); ok && strings.TrimSpace(url) != "" {
- return url
- }
-
- published := anyToString(pm["PublishedPort"])
- target := anyToString(pm["TargetPort"])
-
- proto := ""
- if v, ok := pm["Protocol"].(string); ok && v != "" {
- proto = "/" + v
- }
-
- if published != "" && target != "" {
- return fmt.Sprintf("%s:%s%s", published, target, proto)
- }
- return ""
-}
-
-func anyToString(v any) string {
- switch t := v.(type) {
- case float64:
- return fmt.Sprintf("%.0f", t)
- case int:
- return fmt.Sprintf("%d", t)
- case int64:
- return fmt.Sprintf("%d", t)
- case string:
- return t
- default:
- return ""
- }
-}
diff --git a/backend/internal/utils/registry/auth.go b/backend/internal/utils/registry/auth.go
index 329565c2b..ff73d9565 100644
--- a/backend/internal/utils/registry/auth.go
+++ b/backend/internal/utils/registry/auth.go
@@ -10,6 +10,8 @@ import (
"strings"
"time"
+ ref "github.com/distribution/reference"
+
"github.com/ofkm/arcane-backend/internal/models"
"github.com/ofkm/arcane-backend/internal/utils"
)
@@ -248,7 +250,7 @@ func GetChallengeRequest(ctx context.Context, u url.URL) (*http.Request, error)
// GetChallengeURL returns https://<host>/v2/ for a given image ref (normalized).
// host is normalized so docker.io => index.docker.io.
func GetChallengeURL(imageRef string) (url.URL, error) {
- named, err := parseNormalizedNamed(imageRef)
+ named, err := ref.ParseNormalizedNamed(imageRef)
if err != nil {
return url.URL{}, err
}
@@ -300,7 +302,7 @@ func GetAuthHeaderForImage(ctx context.Context, imageRef string, enabledRegs []m
chLower := strings.ToLower(strings.TrimSpace(ch))
- named, err := parseNormalizedNamed(imageRef)
+ named, err := ref.ParseNormalizedNamed(imageRef)
if err != nil {
return "", err
}
@@ -308,7 +310,7 @@ func GetAuthHeaderForImage(ctx context.Context, imageRef string, enabledRegs []m
if err != nil {
return "", err
}
- repo := referencePath(named)
+ repo := ref.Path(named)
switch {
case strings.HasPrefix(chLower, "basic"):
diff --git a/backend/internal/utils/registry/helpers.go b/backend/internal/utils/registry/helpers.go
index 661b16998..f90f74308 100644
--- a/backend/internal/utils/registry/helpers.go
+++ b/backend/internal/utils/registry/helpers.go
@@ -1,11 +1,13 @@
package registry
+import ref "github.com/distribution/reference"
+
func GetRegistryAddress(imageRef string) (string, error) {
- named, err := parseNormalizedNamed(imageRef)
+ named, err := ref.ParseNormalizedNamed(imageRef)
if err != nil {
return "", err
}
- addr := referenceDomain(named)
+ addr := ref.Domain(named)
if addr == DefaultRegistryDomain {
return DefaultRegistryHost, nil
}
diff --git a/backend/internal/utils/registry/manifest.go b/backend/internal/utils/registry/manifest.go
deleted file mode 100644
index 6a7e57f04..000000000
--- a/backend/internal/utils/registry/manifest.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package registry
-
-import "fmt"
-
-func BuildManifestURLFromRef(imageRef string) (string, error) {
- named, err := parseNormalizedNamed(imageRef)
- if err != nil {
- return "", err
- }
- named = tagNameOnly(named)
-
- host, err := GetRegistryAddress(named.String())
- if err != nil {
- return "", err
- }
-
- imgPath := referencePath(named)
-
- identifier := "latest"
- if dgst, ok := getDigest(named); ok {
- identifier = dgst
- } else if t, ok := getTag(named); ok {
- identifier = t
- }
-
- return fmt.Sprintf("https://%s/v2/%s/manifests/%s", host, imgPath, identifier), nil
-}
diff --git a/backend/internal/utils/registry/reference_shim.go b/backend/internal/utils/registry/reference_shim.go
deleted file mode 100644
index 5b0a08003..000000000
--- a/backend/internal/utils/registry/reference_shim.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package registry
-
-import (
- ref "github.com/distribution/reference"
-)
-
-func parseNormalizedNamed(s string) (ref.Named, error) {
- return ref.ParseNormalizedNamed(s)
-}
-
-func referencePath(n ref.Named) string {
- return ref.Path(n)
-}
-
-func tagNameOnly(n ref.Named) ref.Named {
- return ref.TagNameOnly(n)
-}
-
-func referenceDomain(n ref.Named) string {
- return ref.Domain(n)
-}
-
-func getTag(n ref.Named) (string, bool) {
- if nt, ok := n.(ref.NamedTagged); ok {
- return nt.Tag(), true
- }
- return "", false
-}
-
-func getDigest(n ref.Named) (string, bool) {
- if d, ok := n.(ref.Digested); ok {
- return d.Digest().String(), true
- }
- return "", false
-}
diff --git a/backend/internal/utils/registry/tags.go b/backend/internal/utils/registry/tags.go
index 26d86a85b..b2bed000d 100644
--- a/backend/internal/utils/registry/tags.go
+++ b/backend/internal/utils/registry/tags.go
@@ -65,12 +65,6 @@ func (c *Client) GetImageTags(ctx context.Context, registry, repository, token s
return all, nil
}
-func (c *Client) GetImageTagsTimed(ctx context.Context, registry, repository, token string) ([]string, time.Duration, error) {
- start := time.Now()
- t, err := c.GetImageTags(ctx, registry, repository, token)
- return t, time.Since(start), err
-}
-
func parseLinkHeader(h string) string {
if h == "" {
return ""
diff --git a/backend/internal/utils/struct_map_util.go b/backend/internal/utils/struct_map_util.go
deleted file mode 100644
index 66ddf5bbd..000000000
--- a/backend/internal/utils/struct_map_util.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package utils
-
-type Set[T comparable] map[T]struct{}
-
-func NewSet[T comparable](vals ...T) Set[T] {
- s := make(Set[T])
- for _, v := range vals {
- s[v] = struct{}{}
- }
- return s
-}
-
-func (s Set[T]) Add(vals ...T) {
- for _, v := range vals {
- s[v] = struct{}{}
- }
-}
-
-func (s Set[T]) Has(v T) bool {
- _, ok := s[v]
- return ok
-}
-
-func (s Set[T]) Remove(vals ...T) {
- for _, v := range vals {
- delete(s, v)
- }
-}
-
-func (s Set[T]) Items() []T {
- out := make([]T, 0, len(s))
- for v := range s {
- out = append(out, v)
- }
- return out
-}
-
-// NewEmptyStructMap returns map[K]struct{}{}
-func NewEmptyStructMap[K comparable]() map[K]struct{} {
- return make(map[K]struct{})
-}
diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelte
index 1aa3baf91..d1c6bce17 100644
--- a/frontend/src/lib/components/action-buttons.svelte
+++ b/frontend/src/lib/components/action-buttons.svelte
@@ -341,23 +341,6 @@
});
}
- async function handlePull() {
- if (type === 'container') {
- isLoading.pull = true;
- await handleApiResultWithCallbacks({
- result: await tryCatch(environmentAPI.pullContainerImage(id)),
- message: m.images_pull_failed(),
- setLoadingState: (value) => (isLoading.pull = value),
- onSuccess: async () => {
- toast.success(m.images_pulled_success());
- onActionComplete();
- }
- });
- } else {
- await handleProjectPull();
- }
- }
-
async function handleProjectPull() {
resetPullState();
projectPulling = true;
@@ -479,10 +462,8 @@
loading={projectPulling}
icon={DownloadIcon}
>
- <ArcaneButton action="pull" onclick={() => handlePull()} loading={projectPulling} />
+ <ArcaneButton action="pull" onclick={() => handleProjectPull()} loading={projectPulling} />
</ProgressPopover>
- {:else}
- <ArcaneButton action="pull" onclick={() => handlePull()} loading={uiLoading.pulling} />
{/if}
<ArcaneButton
diff --git a/frontend/src/lib/components/port-badges.svelte b/frontend/src/lib/components/port-badges.svelte
index efef45c28..cf880ba23 100644
--- a/frontend/src/lib/components/port-badges.svelte
+++ b/frontend/src/lib/components/port-badges.svelte
@@ -1,9 +1,9 @@
<script lang="ts">
- import type { PortDto } from '$lib/types/container.type';
+ import type { ContainerPorts } from '$lib/types/container.type';
import { m } from '$lib/paraglide/messages';
- let { ports = [] as PortDto[], baseServerUrl = '' } = $props<{
- ports?: PortDto[];
+ let { ports = [] as ContainerPorts[], baseServerUrl = '' } = $props<{
+ ports?: ContainerPorts[];
baseServerUrl?: string;
}>();
@@ -14,19 +14,19 @@
ip?: string | null;
};
- function getPublicPort(p: PortDto): string | null {
+ function getPublicPort(p: ContainerPorts): string | null {
return (p as any).publicPort?.toString?.() ?? (p as any).hostPort?.toString?.() ?? (p as any).published?.toString?.() ?? null;
}
- function getPrivatePort(p: PortDto): string {
+ function getPrivatePort(p: ContainerPorts): string {
return ((p as any).privatePort ?? (p as any).target ?? '?').toString();
}
- function getProto(p: PortDto): string | undefined {
+ function getProto(p: ContainerPorts): string | undefined {
return (p as any).type ?? (p as any).protocol ?? undefined;
}
- function normalize(p: PortDto): NormalizedPort | null {
+ function normalize(p: ContainerPorts): NormalizedPort | null {
const hostPort = getPublicPort(p);
if (!hostPort) return null;
return {
@@ -37,7 +37,7 @@
};
}
- function uniquePublished(list: PortDto[]): NormalizedPort[] {
+ function uniquePublished(list: ContainerPorts[]): NormalizedPort[] {
const map = new Map<string, NormalizedPort>();
for (const p of list) {
const n = normalize(p);
diff --git a/frontend/src/lib/services/api/auth-api-service.ts b/frontend/src/lib/services/api/auth-api-service.ts
index 2a2b52b98..65c8dc9e5 100644
--- a/frontend/src/lib/services/api/auth-api-service.ts
+++ b/frontend/src/lib/services/api/auth-api-service.ts
@@ -1,5 +1,4 @@
import { goto } from '$app/navigation';
-import { browser } from '$app/environment';
import { invalidateAll } from '$app/navigation';
import BaseAPIService from './api-service';
import userStore from '$lib/stores/user-store';
@@ -20,38 +19,14 @@ type LoginResponseData = {
export class AuthService extends BaseAPIService {
async login(credentials: LoginCredentials): Promise<User> {
- try {
- const data = await this.handleResponse<LoginResponseData>(this.api.post('/auth/login', credentials));
- const user = data.user as User;
-
- userStore.setUser(user);
-
- if (browser) {
- await invalidateAll();
- goto('/auth/login');
- }
-
- return user;
- } catch (error: any) {
- const errorMessage = error.response?.data?.error || 'Login failed';
- throw new Error(errorMessage);
- }
- }
+ const data = await this.handleResponse<LoginResponseData>(this.api.post('/auth/login', credentials));
+ const user = data.user as User;
- async logout(): Promise<void> {
- try {
- await this.api.post('/auth/logout');
- } catch (error) {
- console.error('Logout error:', error);
- } finally {
- // Clear user from store
- userStore.clearUser();
+ userStore.setUser(user);
+ await invalidateAll();
+ goto('/auth/login');
- if (browser) {
- await invalidateAll();
- goto('/auth/login');
- }
- }
+ return user;
}
async getCurrentUser(): Promise<User | null> {
@@ -68,14 +43,6 @@ export class AuthService extends BaseAPIService {
return null;
}
}
-
- async changePassword(oldPassword: string, newPassword: string): Promise<void> {
- const response = await this.api.post('/auth/password', {
- currentPassword: oldPassword,
- newPassword
- });
- return response.data;
- }
}
export const authService = new AuthService();
diff --git a/frontend/src/lib/services/api/container-registry-api-service.ts b/frontend/src/lib/services/api/container-registry-api-service.ts
index 3b01516c7..dd1ad8698 100644
--- a/frontend/src/lib/services/api/container-registry-api-service.ts
+++ b/frontend/src/lib/services/api/container-registry-api-service.ts
@@ -9,10 +9,6 @@ export default class ContainerRegistryAPIService extends BaseAPIService {
return res.data;
}
- async getAllRegistries(): Promise<ContainerRegistry[]> {
- return this.handleResponse(this.api.get(`/container-registries`));
- }
-
async getRegistry(id: string): Promise<ContainerRegistry> {
return this.handleResponse(this.api.get(`/container-registries/${id}`));
}
diff --git a/frontend/src/lib/services/api/environment-api-service.ts b/frontend/src/lib/services/api/environment-api-service.ts
index ad527f882..be5de323d 100644
--- a/frontend/src/lib/services/api/environment-api-service.ts
+++ b/frontend/src/lib/services/api/environment-api-service.ts
@@ -4,19 +4,16 @@ import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/envir
import type { ContainerCreateOptions, NetworkCreateOptions, VolumeCreateOptions, ContainerStats } from 'dockerode';
import type { Project, ProjectStatusCounts } from '$lib/types/project.type';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
-import { browser } from '$app/environment';
import type { ContainerStatusCounts, ContainerSummaryDto } from '$lib/types/container.type';
import type { ImageSummaryDto, ImageUpdateInfoDto, ImageUsageCounts } from '$lib/types/image.type';
import type { NetworkSummaryDto, NetworkUsageCounts } from '$lib/types/network.type';
import type { VolumeSummaryDto, VolumeDetailDto, VolumeUsageDto, VolumeUsageCounts } from '$lib/types/volume.type';
-import type { ImageUpdateSummary, ImageVersions, VersionComparison, CompareVersionRequest } from '$lib/types/image.type';
-import type { AutoUpdateCheck, AutoUpdateResult, AutoUpdateRecord, AutoUpdateStatus } from '$lib/types/auto-update.type';
+import type { AutoUpdateCheck, AutoUpdateResult } from '$lib/types/auto-update.type';
export class EnvironmentAPIService extends BaseAPIService {
private async getCurrentEnvironmentId(): Promise<string> {
- if (browser) {
- await environmentStore.ready;
- }
+ await environmentStore.ready;
+
const currentEnvironment = get(environmentStore.selected);
if (!currentEnvironment) {
return LOCAL_DOCKER_ENVIRONMENT_ID;
@@ -24,6 +21,8 @@ export class EnvironmentAPIService extends BaseAPIService {
return currentEnvironment.id;
}
+ // Container Api Calls
+
async getContainers(options?: SearchPaginationSortRequest): Promise<Paginated<ContainerSummaryDto>> {
const envId = await this.getCurrentEnvironmentId();
@@ -78,10 +77,9 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.delete(`/environments/${envId}/containers/${containerId}`, { params }));
}
- async pullContainerImage(containerId: string): Promise<Project> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/pull`));
- }
+ // End Container Api Calls
+
+ // Image Api Calls
async getImages(options?: SearchPaginationSortRequest): Promise<Paginated<ImageSummaryDto>> {
const envId = await this.getCurrentEnvironmentId();
@@ -118,10 +116,9 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`, body));
}
- async inspectImage(imageId: string): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}/inspect`));
- }
+ // End Image Api Calls
+
+ // Network Api Calls
async getNetworks(options?: SearchPaginationSortRequest): Promise<Paginated<NetworkSummaryDto>> {
const envId = await this.getCurrentEnvironmentId();
@@ -152,6 +149,10 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));
}
+ // End Network Api Calls
+
+ // Volume Api Calls
+
async getVolumes(options?: SearchPaginationSortRequest): Promise<Paginated<VolumeSummaryDto>> {
const envId = await this.getCurrentEnvironmentId();
@@ -186,42 +187,9 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/${volumeName}`));
}
- async pruneVolumes(): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/volumes/prune`));
- }
-
- async getAllResources(): Promise<Record<string, any>> {
- const [containers, images, networks, volumes] = await Promise.all([
- this.getContainers(),
- this.getImages(),
- this.getNetworks(),
- this.getVolumes()
- ]);
-
- return {
- containers,
- images,
- networks,
- volumes
- };
- }
+ // End Volume Api Calls
- async syncResources(): Promise<void> {
- const envId = await this.getCurrentEnvironmentId();
- await this.handleResponse(this.api.post(`/environments/${envId}/sync`));
- }
-
- async executeDockerCommand(command: string, args: string[] = []): Promise<any> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/execute`, { command, args }));
- }
-
- async checkImageUpdate(imageRef: string): Promise<ImageUpdateInfoDto> {
- const envId = await this.getCurrentEnvironmentId();
- const res = await this.api.get(`/environments/${envId}/image-updates/check`, { params: { imageRef } });
- return this.handleResponse(res.data);
- }
+ // Image Updater Api Calls
async checkImageUpdateByID(imageId: string): Promise<ImageUpdateInfoDto> {
const envId = await this.getCurrentEnvironmentId();
@@ -233,42 +201,14 @@ export class EnvironmentAPIService extends BaseAPIService {
return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/check-all`));
}
- async getUpdateSummary(): Promise<ImageUpdateSummary> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/summary`));
- }
-
- async getImageVersions(imageRef: string, limit = 20): Promise<ImageVersions> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(
- this.api.get(`/environments/${envId}/image-updates/versions`, {
- params: { imageRef, limit }
- })
- );
- }
-
- async compareVersions(request: CompareVersionRequest): Promise<VersionComparison> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.post(`/environments/${envId}/image-updates/compare`, request));
- }
-
async runAutoUpdate(options?: AutoUpdateCheck): Promise<AutoUpdateResult> {
const envId = await this.getCurrentEnvironmentId();
return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));
}
- async getAutoUpdateStatus(): Promise<AutoUpdateStatus> {
- const envId = await this.getCurrentEnvironmentId();
- return this.handleResponse(this.api.get(`/environments/${envId}/updater/status`));
- }
-
- async getAutoUpdateHistory(limit?: number): Promise<AutoUpdateRecord[]> {
- const envId = await this.getCurrentEnvironmentId();
- const params = limit ? { limit } : undefined;
- return this.handleResponse(this.api.get(`/environments/${envId}/updater/history`, { params }));
- }
+ // End Image Updater Api Calls
- // New Project Api Handlers
+ // Project Api Calls
async getProjects(options?: SearchPaginationSortRequest): Promise<Paginated<Project>> {
const envId = await this.getCurrentEnvironmentId();
@@ -417,7 +357,7 @@ export class EnvironmentAPIService extends BaseAPIService {
);
}
- //End New Project Api Handlers
+ //End New Project Api Calls
}
export const environmentAPI = new EnvironmentAPIService();
diff --git a/frontend/src/lib/services/api/event-api-service.ts b/frontend/src/lib/services/api/event-api-service.ts
index 027b3c3f5..d33074ea2 100644
--- a/frontend/src/lib/services/api/event-api-service.ts
+++ b/frontend/src/lib/services/api/event-api-service.ts
@@ -1,73 +1,14 @@
import BaseAPIService from './api-service';
-import type {
- PaginationRequest,
- SortRequest,
- PaginatedApiResponse,
- SearchPaginationSortRequest,
- Paginated
-} from '$lib/types/pagination.type';
-import type { Event, CreateEvent } from '$lib/types/event.type';
+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';
+import type { Event } from '$lib/types/event.type';
export default class EventAPIService extends BaseAPIService {
- async list(filters?: Record<string, string>) {
- return this.handleResponse(this.api.get('/events', { params: { filters } }));
- }
-
async getEvents(options?: SearchPaginationSortRequest): Promise<Paginated<Event>> {
const res = await this.api.get('/events', { params: options });
return res.data;
}
- async listPaginated(
- pagination?: PaginationRequest,
- sort?: SortRequest,
- search?: string,
- filters?: Record<string, string>
- ): Promise<PaginatedApiResponse<Event>> {
- const params: any = {};
- if (pagination) {
- params['pagination[page]'] = pagination.page;
- params['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]) => {
- if (value !== undefined && value !== null && value !== '') params[key] = value;
- });
- }
- const res = await this.api.get('/events', { params });
- return res.data as PaginatedApiResponse<Event>;
- }
-
- async get(id: string): Promise<Event> {
- return this.handleResponse(this.api.get(`/events/${id}`));
- }
-
- async create(event: CreateEvent): Promise<Event> {
- return this.handleResponse(this.api.post('/events', event));
- }
-
async delete(id: string): Promise<void> {
return this.handleResponse(this.api.delete(`/events/${id}`));
}
-
- async deleteOldEvents(olderThanDays: number): Promise<void> {
- return this.handleResponse(
- this.api.delete('/events/cleanup', {
- params: { olderThanDays }
- })
- );
- }
-
- async getEventTypes(): Promise<string[]> {
- return this.handleResponse(this.api.get('/events/types'));
- }
-
- async getEventSeverities(): Promise<string[]> {
- return this.handleResponse(this.api.get('/events/severities'));
- }
}
diff --git a/frontend/src/lib/services/api/image-api-service.ts b/frontend/src/lib/services/api/image-api-service.ts
deleted file mode 100644
index 52b0369d9..000000000
--- a/frontend/src/lib/services/api/image-api-service.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import BaseAPIService from './api-service';
-import type { PaginationRequest, SortRequest, PaginatedApiResponse } from '$lib/types/pagination.type';
-
-export default class ImageAPIService extends BaseAPIService {
- async list(filters?: Record<string, string>) {
- return this.handleResponse(this.api.get('/images', { params: { filters } }));
- }
-
- async getTotalSize() {
- return this.handleResponse(this.api.get(`/images/total-size`));
- }
-
- async inspect(id: string) {
- return this.handleResponse(this.api.get(`/images/${id}/inspect`));
- }
-
- async search(term: string, limit?: number) {
- return this.handleResponse(
- this.api.get('/images/search', {
- params: { term, limit }
- })
- );
- }
-
- async pull(imageName: string, tag: string = 'latest', auth?: any) {
- return this.handleResponse(
- this.api.post('/images/pull', {
- imageName,
- tag,
- auth
- })
- );
- }
-
- async push(imageName: string, tag: string = 'latest', auth?: any) {
- return this.handleResponse(
- this.api.post('/images/push', {
- imageName,
- tag,
- auth
- })
- );
- }
-
- async remove(id: string, options?: { force?: boolean; noprune?: boolean }) {
- return this.handleResponse(
- this.api.delete(`/images/${id}`, {
- params: options
- })
- );
- }
-
- async tag(id: string, repo: string, tag: string) {
- return this.handleResponse(
- this.api.post(`/images/${id}/tag`, {
- repo,
- tag
- })
- );
- }
-
- async history(id: string) {
- return this.handleResponse(this.api.get(`/images/${id}/history`));
- }
-
- async prune(filters?: Record<string, string>) {
- return this.handleResponse(this.api.post('/images/prune', { filters }));
- }
-
- async build(
- context: FormData,
- options?: {
- dockerfile?: string;
- tags?: string[];
- buildArgs?: Record<string, string>;
- target?: string;
- networkMode?: string;
- platform?: string;
- }
- ) {
- return this.handleResponse(
- this.api.post('/images/build', context, {
- headers: {
- 'Content-Type': 'multipart/form-data'
- },
- params: options
- })
- );
- }
-
- async export(ids: string[]) {
- const response = await this.api.post(
- '/images/export',
- { ids },
- {
- responseType: 'blob'
- }
- );
- return response.data;
- }
-
- async import(source: File | string, repo?: string, tag?: string) {
- const formData = new FormData();
- if (source instanceof File) {
- formData.append('file', source);
- } else {
- formData.append('url', source);
- }
- if (repo) formData.append('repo', repo);
- if (tag) formData.append('tag', tag);
-
- return this.handleResponse(
- this.api.post('/images/import', formData, {
- headers: {
- 'Content-Type': 'multipart/form-data'
- }
- })
- );
- }
-
- async commit(
- containerId: string,
- options?: {
- repo?: string;
- tag?: string;
- comment?: string;
- author?: string;
- pause?: boolean;
- changes?: string[];
- }
- ) {
- return this.handleResponse(
- this.api.post('/images/commit', {
- containerId,
- ...options
- })
- );
- }
-
- async checkMaturity(imageId: string) {
- return this.handleResponse(this.api.get(`/images/maturity/${imageId}`));
- }
-
- async checkMaturityBatch(imageIds: string[]) {
- if (!imageIds || imageIds.length === 0) {
- throw new Error('No image IDs provided for batch check');
- }
-
- const firstId = imageIds[0];
- return this.handleResponse(this.api.post(`/images/${firstId}/maturity`, { imageIds }));
- }
-
- async updateMaturity(imageId: string, maturityData: any) {
- return this.handleResponse(this.api.put(`/images/maturity/${imageId}`, maturityData));
- }
-
- async getVulnerabilities(imageId: string) {
- return this.handleResponse(this.api.get(`/images/${imageId}/vulnerabilities`));
- }
-
- async scanImage(imageId: string) {
- return this.handleResponse(this.api.post(`/images/${imageId}/scan`));
- }
-}
diff --git a/frontend/src/lib/services/api/index.ts b/frontend/src/lib/services/api/index.ts
index 4b41505d8..512044727 100644
--- a/frontend/src/lib/services/api/index.ts
+++ b/frontend/src/lib/services/api/index.ts
@@ -1,9 +1,7 @@
-import ImageAPIService from './image-api-service';
import SystemAPIService from './system-api-service';
import TemplateAPIService from './template-api-service';
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 ConverterAPIService from './converter-api-service';
import ContainerRegistryAPIService from './container-registry-api-service';
@@ -11,12 +9,10 @@ import { EnvironmentAPIService } from './environment-api-service';
import EnvironmentManagementAPIService from './environment-management-api-service';
import EventAPIService from './event-api-service';
-export const imageAPI = new ImageAPIService();
export const systemAPI = new SystemAPIService();
export const templateAPI = new TemplateAPIService();
export const userAPI = new UserAPIService();
export const settingsAPI = new SettingsAPIService();
-export const templateRegistryAPI = new TemplateRegistryAPIService();
export const oidcAPI = new OidcAPIService();
export const converterAPI = new ConverterAPIService();
export const containerRegistryAPI = new ContainerRegistryAPIService();
@@ -25,12 +21,10 @@ export const environmentManagementAPI = new EnvironmentManagementAPIService();
export const eventAPI = new EventAPIService();
interface APIServices {
- image: ImageAPIService;
system: SystemAPIService;
template: TemplateAPIService;
user: UserAPIService;
settings: SettingsAPIService;
- templateRegistry: TemplateRegistryAPIService;
oidc: OidcAPIService;
converter: ConverterAPIService;
containerRegistry: ContainerRegistryAPIService;
@@ -40,12 +34,10 @@ interface APIServices {
}
const apiServices: APIServices = {
- image: imageAPI,
system: systemAPI,
template: templateAPI,
user: userAPI,
settings: settingsAPI,
- templateRegistry: templateRegistryAPI,
oidc: oidcAPI,
converter: converterAPI,
containerRegistry: containerRegistryAPI,
diff --git a/frontend/src/lib/services/api/oidc-api-service.ts b/frontend/src/lib/services/api/oidc-api-service.ts
index 836072e43..27bcaec42 100644
--- a/frontend/src/lib/services/api/oidc-api-service.ts
+++ b/frontend/src/lib/services/api/oidc-api-service.ts
@@ -13,11 +13,6 @@ export interface OidcUserInfo {
groups?: string[];
}
-// export interface OidcStatus {
-// envForced: boolean;
-// envConfigured: boolean;
-// }
-
export default class OidcAPIService extends BaseAPIService {
async getAuthUrl(redirectUri: string): Promise<string> {
const response = (await this.handleResponse(this.api.post('/oidc/url', { redirectUri }))) as {
@@ -41,13 +36,4 @@ export default class OidcAPIService extends BaseAPIService {
async getStatus(): Promise<OidcStatusInfo> {
return this.handleResponse(this.api.get('/oidc/status'));
}
-
- async getConfig(): Promise<OidcConfig & { redirectUri: string }> {
- return this.handleResponse(this.api.get('/oidc/config'));
- }
-
- async updateConfig(config: Partial<OidcConfig>): Promise<OidcConfig> {
- const { ...updatePayload } = config;
- return this.handleResponse(this.api.put('/oidc/config', updatePayload));
- }
}
diff --git a/frontend/src/lib/services/api/system-api-service.ts b/frontend/src/lib/services/api/system-api-service.ts
index 0cb6b4119..2b95d4cb0 100644
--- a/frontend/src/lib/services/api/system-api-service.ts
+++ b/frontend/src/lib/services/api/system-api-service.ts
@@ -14,10 +14,6 @@ export default class SystemAPIService extends BaseAPIService {
return this.handleResponse(this.api.post('/system/prune', options));
}
- async startAllContainers() {
- return this.handleResponse(this.api.post('/system/containers/start-all'));
- }
-
async startAllStoppedContainers() {
return this.handleResponse(this.api.post('/system/containers/start-stopped'));
}
@@ -29,13 +25,4 @@ export default class SystemAPIService extends BaseAPIService {
async getDockerInfo(): Promise<DockerInfo> {
return this.handleResponse(this.api.get('/system/docker/info'));
}
-
- async testConnection(host?: string) {
- const params = host ? { host } : {};
- return this.handleResponse(this.api.get('/system/docker/test', { params }));
- }
-
- async getSystemInfo(): Promise<DockerInfo> {
- return this.handleResponse(this.api.get('/system/info'));
- }
}
diff --git a/frontend/src/lib/services/api/template-api-service.ts b/frontend/src/lib/services/api/template-api-service.ts
index f4a82f7e6..6bc6659cb 100644
--- a/frontend/src/lib/services/api/template-api-service.ts
+++ b/frontend/src/lib/services/api/template-api-service.ts
@@ -7,11 +7,6 @@ export default class TemplateAPIService extends BaseAPIService {
return response.data?.data ?? [];
}
- async getById(id: string): Promise<Template> {
- const response = await this.api.get(`/templates/${encodeURIComponent(id)}`);
- return response.data?.data;
- }
-
async getTemplateContent(id: string): Promise<{
content: string;
envContent: string;
@@ -27,27 +22,6 @@ export default class TemplateAPIService extends BaseAPIService {
};
}
- async create(template: { name: string; description: string; content: string; envContent?: string }): Promise<Template> {
- const response = await this.api.post('/templates', template);
- return response.data?.data;
- }
-
- async update(
- id: string,
- template: {
- name: string;
- description: string;
- content: string;
- envContent?: string;
- }
- ): Promise<void> {
- await this.api.put(`/templates/${id}`, template);
- }
-
- async delete(id: string): Promise<void> {
- await this.api.delete(`/templates/${id}`);
- }
-
async download(id: string): Promise<Template> {
const response = await this.api.post(`/templates/${encodeURIComponent(id)}/download`);
return response.data?.data;
@@ -97,87 +71,4 @@ export default class TemplateAPIService extends BaseAPIService {
async deleteRegistry(id: string): Promise<void> {
await this.api.delete(`/templates/registries/${id}`);
}
-
- async getByName(name: string): Promise<Template> {
- const templates = await this.loadAll();
- const template = templates.find((t) => t.name === name);
- if (!template) {
- throw new Error(`Template with name "${name}" not found`);
- }
- return template;
- }
-
- async search(query: string, category?: string): Promise<Template[]> {
- const templates = await this.loadAll();
- return templates.filter(
- (template) =>
- template.name.toLowerCase().includes(query.toLowerCase()) ||
- template.description.toLowerCase().includes(query.toLowerCase())
- );
- }
-
- async getCategories(): Promise<string[]> {
- const templates = await this.loadAll();
- const categories = new Set<string>();
- templates.forEach((template) => {
- if (template.metadata?.tags) {
- const tags = Array.isArray(template.metadata.tags) ? template.metadata.tags : JSON.parse(template.metadata.tags || '[]');
- tags.forEach((tag: string) => categories.add(tag));
- }
- });
- return Array.from(categories);
- }
-
- async refresh(): Promise<{ updated: number; added: number; removed: number }> {
- await this.loadAll();
- return { updated: 0, added: 0, removed: 0 };
- }
-
- async validateTemplate(template: Partial<Template>): Promise<{
- valid: boolean;
- errors: string[];
- warnings: string[];
- }> {
- const errors: string[] = [];
- const warnings: string[] = [];
-
- if (!template.name) errors.push('Template name is required');
- if (!template.content) errors.push('Template content is required');
-
- return {
- valid: errors.length === 0,
- errors,
- warnings
- };
- }
-
- async getTemplateByRegistry(registryId: string): Promise<Template[]> {
- const templates = await this.loadAll();
- return templates.filter((template) => template.registryId === registryId);
- }
-
- async importFromUrl(url: string): Promise<Template> {
- throw new Error('Import from URL not yet implemented');
- }
-
- async exportTemplate(id: string): Promise<Blob> {
- const template = await this.getById(id);
- const content = JSON.stringify(template, null, 2);
- return new Blob([content], { type: 'application/json' });
- }
-
- async refreshRegistry(id: string): Promise<void> {
- await this.loadAll();
- }
-
- async getTemplates(registryId?: string): Promise<Template[]> {
- if (registryId) {
- return this.getTemplateByRegistry(registryId);
- }
- return this.loadAll();
- }
-
- async getTemplate(id: string): Promise<Template> {
- return this.getById(id);
- }
}
diff --git a/frontend/src/lib/services/api/template-registry-api-service.ts b/frontend/src/lib/services/api/template-registry-api-service.ts
deleted file mode 100644
index e4fa8633e..000000000
--- a/frontend/src/lib/services/api/template-registry-api-service.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import BaseAPIService from './api-service';
-import type { TemplateRegistry } from '$lib/types/template.type';
-
-export default class TemplateRegistryAPIService extends BaseAPIService {
- async list(): Promise<TemplateRegistry[]> {
- return this.handleResponse(this.api.get('/template-registries'));
- }
-
- async get(id: string): Promise<TemplateRegistry> {
- return this.handleResponse(this.api.get(`/template-registries/${id}`));
- }
-
- async create(registry: Omit<TemplateRegistry, 'id' | 'createdAt' | 'updatedAt'>): Promise<TemplateRegistry> {
- return this.handleResponse(this.api.post('/template-registries', registry));
- }
-
- async update(id: string, registry: Partial<TemplateRegistry>): Promise<TemplateRegistry> {
- return this.handleResponse(this.api.put(`/template-registries/${id}`, registry));
- }
-
- async delete(id: string): Promise<void> {
- return this.handleResponse(this.api.delete(`/template-registries/${id}`));
- }
-
- async enable(id: string): Promise<void> {
- return this.handleResponse(this.api.post(`/template-registries/${id}/enable`));
- }
-
- async disable(id: string): Promise<void> {
- return this.handleResponse(this.api.post(`/template-registries/${id}/disable`));
- }
-
- async sync(id: string): Promise<{ synced: number; errors: string[] }> {
- return this.handleResponse(this.api.post(`/template-registries/${id}/sync`));
- }
-
- async test(id: string): Promise<{ success: boolean; message: string }> {
- return this.handleResponse(this.api.post(`/template-registries/${id}/test`));
- }
-
- async getTemplates(id: string): Promise<any[]> {
- return this.handleResponse(this.api.get(`/template-registries/${id}/templates`));
- }
-
- async syncAll(): Promise<{ registries: number; templates: number; errors: string[] }> {
- return this.handleResponse(this.api.post('/template-registries/sync-all'));
- }
-}
diff --git a/frontend/src/lib/services/api/user-api-service.ts b/frontend/src/lib/services/api/user-api-service.ts
index f22ef7e42..77a513bbc 100644
--- a/frontend/src/lib/services/api/user-api-service.ts
+++ b/frontend/src/lib/services/api/user-api-service.ts
@@ -1,28 +1,8 @@
import BaseAPIService from './api-service';
import type { User, CreateUser } from '$lib/types/user.type';
-import type {
- PaginationRequest,
- SortRequest,
- PaginatedApiResponse,
- Paginated,
- SearchPaginationSortRequest
-} from '$lib/types/pagination.type';
-
-export interface Role {
- id: string;
- name: string;
- permissions: string[];
- description?: string;
-}
+import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';
export default class UserAPIService extends BaseAPIService {
- // async getVolumes(options?: SearchPaginationSortRequest): Promise<Paginated<VolumeSummaryDto>> {
- // const envId = await this.getCurrentEnvironmentId();
-
- // const res = await this.api.get(`/environments/${envId}/volumes`, { params: options });
- // return res.data;
- // }
-
async getUsers(options?: SearchPaginationSortRequest): Promise<Paginated<User>> {
const res = await this.api.get('/users', { params: options });
return res.data;
@@ -48,63 +28,7 @@ export default class UserAPIService extends BaseAPIService {
return this.handleResponse(this.api.delete(`/users/${id}`)) as Promise<void>;
}
- async logout(): Promise<void> {
- return this.handleResponse(this.api.post('/auth/logout')) as Promise<void>;
- }
-
async changePassword(data: { currentPassword: string; newPassword: string }): Promise<void> {
return this.handleResponse(this.api.post('/auth/password', data)) as Promise<void>;
}
-
- async resetPassword(userId: string, newPassword: string): Promise<void> {
- return this.handleResponse(
- this.api.post(`/users/${userId}/reset-password`, {
- newPassword
- })
- ) as Promise<void>;
- }
-
- async getByUsername(username: string): Promise<User> {
- return this.handleResponse(this.api.get(`/users/by-username/${encodeURIComponent(username)}`)) as Promise<User>;
- }
-
- async getByOidcSubjectId(oidcSubjectId: string): Promise<User> {
- return this.handleResponse(this.api.get(`/users/by-oidc-subject/${encodeURIComponent(oidcSubjectId)}`)) as Promise<User>;
- }
-
- async getRoles(): Promise<Role[]> {
- return this.handleResponse(this.api.get('/roles')) as Promise<Role[]>;
- }
-
- async getRole(id: string): Promise<Role> {
- return this.handleResponse(this.api.get(`/roles/${id}`)) as Promise<Role>;
- }
-
- async createRole(role: Omit<Role, 'id'>): Promise<Role> {
- return this.handleResponse(this.api.post('/roles', role)) as Promise<Role>;
- }
-
- async updateRole(id: string, role: Partial<Role>): Promise<Role> {
- return this.handleResponse(this.api.put(`/roles/${id}`, role)) as Promise<Role>;
- }
-
- async deleteRole(id: string): Promise<void> {
- return this.handleResponse(this.api.delete(`/roles/${id}`)) as Promise<void>;
- }
-
- async assignRole(userId: string, roleId: string): Promise<void> {
- return this.handleResponse(this.api.post(`/users/${userId}/roles`, { roleId })) as Promise<void>;
- }
-
- async removeRole(userId: string, roleId: string): Promise<void> {
- return this.handleResponse(this.api.delete(`/users/${userId}/roles/${roleId}`)) as Promise<void>;
- }
-
- async getUserRoles(userId: string): Promise<Role[]> {
- return this.handleResponse(this.api.get(`/users/${userId}/roles`)) as Promise<Role[]>;
- }
-
- async getPermissions(): Promise<string[]> {
- return this.handleResponse(this.api.get('/permissions')) as Promise<string[]>;
- }
}
diff --git a/frontend/src/lib/types/auto-update.type.ts b/frontend/src/lib/types/auto-update.type.ts
index 43bcca8f4..01524d659 100644
--- a/frontend/src/lib/types/auto-update.type.ts
+++ b/frontend/src/lib/types/auto-update.type.ts
@@ -29,26 +29,3 @@ export interface AutoUpdateResourceResult {
error?: string;
details?: Record<string, any>;
}
-
-export interface AutoUpdateRecord {
- id: string;
- resourceId: string;
- resourceType: string;
- resourceName: string;
- status: string;
- startTime: string;
- endTime?: string;
- updateAvailable: boolean;
- updateApplied: boolean;
- oldImageVersions?: Record<string, string>;
- newImageVersions?: Record<string, string>;
- error?: string;
- details?: Record<string, any>;
-}
-
-export interface AutoUpdateStatus {
- updatingContainers: number;
- updatingProjects: number;
- containerIds: string[];
- projectIds: string[];
-}
diff --git a/frontend/src/lib/types/container.type.ts b/frontend/src/lib/types/container.type.ts
index dac2c819f..553459103 100644
--- a/frontend/src/lib/types/container.type.ts
+++ b/frontend/src/lib/types/container.type.ts
@@ -1,3 +1,5 @@
+// Base Container Types
+
export interface BaseContainer {
id: string;
names: string[];
@@ -10,20 +12,30 @@ export interface BaseContainer {
status: string;
}
-export interface ContainerStatusCounts {
- runningContainers: number;
- stoppedContainers: number;
- totalContainers: number;
+export interface ContainerSummaryDto extends BaseContainer {
+ ports: ContainerPorts[];
+ hostConfig: ContainerHostConfig;
+ networkSettings: ContainerNetworkSettings;
+ mounts: ContainerMounts[];
}
-export interface PortDto {
+export interface ContainerPorts {
ip?: string;
privatePort: number;
publicPort?: number;
type: string;
}
-export interface MountDto {
+export interface ContainerHostConfig {
+ networkMode: string;
+ restartPolicy?: string;
+}
+
+export interface ContainerNetworkSettings {
+ networks: Record<string, ContainerNetwork>;
+}
+
+export interface ContainerMounts {
type: string;
name?: string;
source?: string;
@@ -34,7 +46,7 @@ export interface MountDto {
propagation?: string;
}
-export interface NetworkDto {
+export interface ContainerNetwork {
ipamConfig: any | null;
links: string[] | null;
aliases: string[] | null;
@@ -52,20 +64,12 @@ export interface NetworkDto {
dnsNames: string[] | null;
}
-export interface HostConfigDto {
- networkMode: string;
- restartPolicy?: string;
-}
-
-export interface NetworkSettingsDto {
- networks: Record<string, NetworkDto>;
-}
+// End Base Container Types
-export interface ContainerSummaryDto extends BaseContainer {
- ports: PortDto[];
- hostConfig: HostConfigDto;
- networkSettings: NetworkSettingsDto;
- mounts: MountDto[];
+export interface ContainerStatusCounts {
+ runningContainers: number;
+ stoppedContainers: number;
+ totalContainers: number;
}
export interface CreateContainerDto {
@@ -130,9 +134,9 @@ export interface ContainerDetailsDto {
created: string;
state: ContainerStateDto;
config: ContainerConfigDto;
- hostConfig: HostConfigDto;
- networkSettings: NetworkSettingsDto;
- ports: PortDto[];
- mounts: MountDto[];
+ hostConfig: ContainerHostConfig;
+ networkSettings: ContainerNetworkSettings;
+ ports: ContainerPorts[];
+ mounts: ContainerMounts[];
labels: Record<string, string>;
}
diff --git a/frontend/src/lib/types/environment.type.ts b/frontend/src/lib/types/environment.type.ts
index 3befc04f8..225e4fd3e 100644
--- a/frontend/src/lib/types/environment.type.ts
+++ b/frontend/src/lib/types/environment.type.ts
@@ -24,7 +24,3 @@ export interface UpdateEnvironmentDTO {
enabled?: boolean;
bootstrapToken?: string;
}
-
-export interface EnvironmentResponse {
- data: Environment;
-}
diff --git a/frontend/src/lib/types/event.type.ts b/frontend/src/lib/types/event.type.ts
index 4a7f69342..d288e9d2d 100644
--- a/frontend/src/lib/types/event.type.ts
+++ b/frontend/src/lib/types/event.type.ts
@@ -15,27 +15,3 @@ export interface Event {
createdAt: string;
updatedAt?: string;
}
-
-export interface CreateEvent {
- type: string;
- severity?: 'info' | 'warning' | 'error' | 'success';
- title: string;
- description?: string;
- resourceType?: string;
- resourceId?: string;
- resourceName?: string;
- userId?: string;
- username?: string;
- environmentId?: string;
- metadata?: Record<string, any>;
-}
-
-export interface EventListResponse {
- events: Event[];
- total: number;
- page: number;
- pageSize: number;
- totalPages: number;
- hasNext: boolean;
- hasPrevious: boolean;
-}
diff --git a/frontend/src/lib/types/image.type.ts b/frontend/src/lib/types/image.type.ts
index 090d0db58..730983f30 100644
--- a/frontend/src/lib/types/image.type.ts
+++ b/frontend/src/lib/types/image.type.ts
@@ -75,35 +75,9 @@ export interface ImageDetailSummaryDto {
export type ImageUpdateData = ImageUpdateInfoDto;
-export interface ImageUpdateSummary {
- totalImages: number;
- imagesWithUpdates: number;
- digestUpdates: number;
- tagUpdates: number;
- errorsCount: number;
-}
-
export interface ImageVersions {
imageRef: string;
current: string;
versions: string[];
latest?: string;
}
-
-export interface VersionComparison {
- currentVersion: string;
- targetVersion: string;
- isNewer: boolean;
- updateType: string;
- changeLevel: string;
-}
-
-export interface BatchImageUpdateRequest {
- imageRefs: string[];
-}
-
-export interface CompareVersionRequest {
- currentVersion: string;
- targetVersion: string;
- imageRef: string;
-}
diff --git a/frontend/src/lib/types/pagination.type.ts b/frontend/src/lib/types/pagination.type.ts
index 0aa646c65..eb7e2549f 100644
--- a/frontend/src/lib/types/pagination.type.ts
+++ b/frontend/src/lib/types/pagination.type.ts
@@ -30,29 +30,19 @@ export type Paginated<T> = {
pagination: PaginationResponse;
};
-export interface PaginatedApiResponse<T> {
- success: boolean;
- data: T[];
- pagination: PaginationResponse;
-}
-
-export interface SortedPaginationRequest {
- pagination: {
- page: number;
- limit: number;
- };
- sort: {
- column: string;
- direction: 'asc' | 'desc';
- };
-}
-
-export interface ExternalPagination {
- pageSize: number;
- currentPage: number;
- totalPages: number;
- totalItems: number;
-}
-
-export const DEFAULT_PAGE_SIZE = 20;
-export const MAX_PAGE_SIZE = 100;
+// export interface PaginatedApiResponse<T> {
+// success: boolean;
+// data: T[];
+// pagination: PaginationResponse;
+// }
+
+// export interface SortedPaginationRequest {
+// pagination: {
+// page: number;
+// limit: number;
+// };
+// sort: {
+// column: string;
+// direction: 'asc' | 'desc';
+// };
+// }
diff --git a/frontend/src/lib/types/project.type.ts b/frontend/src/lib/types/project.type.ts
index 616bf05c5..a125a2ea4 100644
--- a/frontend/src/lib/types/project.type.ts
+++ b/frontend/src/lib/types/project.type.ts
@@ -1,10 +1,3 @@
-export interface ProjectPort {
- PublicPort?: number;
- PrivatePort?: number;
- Type?: string;
- [key: string]: any;
-}
-
export interface NetworkSettings {
Networks: Record<
string,
diff --git a/frontend/src/lib/types/settings.type.ts b/frontend/src/lib/types/settings.type.ts
index f54565ac7..9f47dde0d 100644
--- a/frontend/src/lib/types/settings.type.ts
+++ b/frontend/src/lib/types/settings.type.ts
@@ -1,3 +1,5 @@
+import type { TemplateRegistryConfig } from './template.type';
+
export type SettingRawResponse = {
key: string;
type: string;
@@ -19,7 +21,6 @@ export type Settings = {
authOidcEnabled: boolean;
authSessionTimeout: number;
authPasswordPolicy: 'basic' | 'standard' | 'strong';
- authRbacEnabled: boolean;
authOidcConfig: string;
onboardingCompleted: boolean;
@@ -41,33 +42,11 @@ export interface RegistryCredential {
password: string;
}
-export interface TemplateRegistryConfig {
- url: string;
- name: string;
- enabled: boolean;
- lastUpdated?: number;
- cacheTtl?: number;
-}
-
-export interface AuthSettings {
- localAuthEnabled: boolean;
- oidcEnabled: boolean;
- sessionTimeout: number;
- passwordPolicy: string;
- rbacEnabled: boolean;
- oidc?: OidcConfig;
-}
-
export interface OidcConfig {
clientId: string;
clientSecret?: string;
issuerUrl: string;
scopes: string;
- // Optional OIDC discovery endpoints (from backend)
- authorizationEndpoint?: string;
- tokenEndpoint?: string;
- userinfoEndpoint?: string;
- jwksUri?: string;
adminClaim?: string; // e.g., "roles", "groups", "realm_access.roles", "admin"
adminValue?: string; // e.g., "admin" (comma-separated accepted values)
diff --git a/frontend/src/lib/types/template.type.ts b/frontend/src/lib/types/template.type.ts
index 638f887e4..d72ed756f 100644
--- a/frontend/src/lib/types/template.type.ts
+++ b/frontend/src/lib/types/template.type.ts
@@ -57,27 +57,4 @@ export interface TemplateRegistryConfig {
url: string;
name: string;
enabled: boolean;
- last_updated?: string;
- cache_ttl?: number;
-}
-
-export interface TemplateEnvVar {
- name: string;
- label?: string;
- description?: string;
- default?: string;
- preset?: boolean;
- select?: TemplateSelectOption[];
-}
-
-export interface TemplateSelectOption {
- text: string;
- value: string;
- default?: boolean;
-}
-
-export interface TemplateVolume {
- container: string;
- bind?: string;
- readonly?: boolean;
}
diff --git a/frontend/src/lib/types/user.type.ts b/frontend/src/lib/types/user.type.ts
index 4882abe21..dbc56e09f 100644
--- a/frontend/src/lib/types/user.type.ts
+++ b/frontend/src/lib/types/user.type.ts
@@ -14,38 +14,6 @@ export type User = {
locale?: Locale;
};
-export interface UserRole {
- id: string;
- name: string;
- description?: string;
- permissions: Permission[];
-}
-
-export interface Permission {
- id: string;
- name: string;
- resource: string;
- action: string;
- description?: string;
-}
-
-export interface UserDto {
- username: string;
- email?: string;
- password: string;
- displayName?: string;
- role: UserRole;
- permissions?: string[];
-}
-
-export interface UpdateUserDto {
- email?: string;
- displayName?: string;
- role?: UserRole;
- permissions?: string[];
- isActive?: boolean;
-}
-
export type CreateUser = Omit<
User,
'id' | 'createdAt' | 'updatedAt' | 'lastLogin' | 'oidcSubjectId' | 'passwordHash' | 'requirePasswordChange' | 'roles'
diff --git a/frontend/src/routes/auth/logout/+page.ts b/frontend/src/routes/auth/logout/+page.ts
index 59aefd7d2..bd1997881 100644
--- a/frontend/src/routes/auth/logout/+page.ts
+++ b/frontend/src/routes/auth/logout/+page.ts
@@ -3,15 +3,13 @@ import { browser } from '$app/environment';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({ fetch }) => {
- if (browser) {
- try {
- await fetch('/api/auth/logout', {
- method: 'POST',
- credentials: 'include'
- });
- } catch (error) {
- console.error('Logout error:', error);
- }
+ try {
+ await fetch('/api/auth/logout', {
+ method: 'POST',
+ credentials: 'include'
+ });
+ } catch (error) {
+ console.error('Logout error:', error);
}
throw redirect(302, '/auth/login');
diff --git a/frontend/src/routes/containers/[containerId]/+page.svelte b/frontend/src/routes/containers/[containerId]/+page.svelte
index 36a3c04fd..c8b82adf4 100644
--- a/frontend/src/routes/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/containers/[containerId]/+page.svelte
@@ -24,7 +24,7 @@
import { Progress } from '$lib/components/ui/progress/index.js';
import { browser } from '$app/environment';
import Separator from '$lib/components/ui/separator/separator.svelte';
- import type { ContainerDetailsDto, NetworkSettingsDto } from '$lib/types/container.type';
+ import type { ContainerDetailsDto, ContainerNetworkSettings } from '$lib/types/container.type';
import { m } from '$lib/paraglide/messages';
import PortBadges from '$lib/components/port-badges.svelte';
@@ -144,7 +144,7 @@
const memoryLimitFormatted = $derived(bytes.format(memoryLimitBytes));
const memoryUsagePercent = $derived(memoryLimitBytes > 0 ? (memoryUsageBytes / memoryLimitBytes) * 100 : 0);
- const getPrimaryIpAddress = (networkSettings: NetworkSettingsDto | undefined | null): string => {
+ const getPrimaryIpAddress = (networkSettings: ContainerNetworkSettings | undefined | null): string => {
if (!networkSettings?.networks) return 'N/A';
for (const networkName in networkSettings.networks) {
diff --git a/frontend/src/routes/events/event-table.svelte b/frontend/src/routes/events/event-table.svelte
index 64b1b3766..b731d611b 100644
--- a/frontend/src/routes/events/event-table.svelte
+++ b/frontend/src/routes/events/event-table.svelte
@@ -69,12 +69,7 @@
setLoadingState: (value) => (isLoading.removing = value),
onSuccess: async () => {
toast.success(m.events_delete_success({ title: safeTitle }));
- events = await eventAPI.listPaginated(
- requestOptions.pagination,
- requestOptions.sort,
- requestOptions.search,
- requestOptions.filters
- );
+ events = await eventAPI.getEvents(requestOptions);
}
});
}
@@ -189,8 +184,7 @@
items={events}
bind:requestOptions
bind:selectedIds
- onRefresh={async (options) =>
- (events = await eventAPI.listPaginated(options.pagination, options.sort, options.search, options.filters))}
+ onRefresh={async (options) => (events = await eventAPI.getEvents(options))}
{columns}
rowActions={RowActions}
/>
diff --git a/frontend/src/routes/volumes/[volumeName]/+page.ts b/frontend/src/routes/volumes/[volumeName]/+page.ts
index acbabec86..5bb4a6eab 100644
--- a/frontend/src/routes/volumes/[volumeName]/+page.ts
+++ b/frontend/src/routes/volumes/[volumeName]/+page.ts
@@ -16,7 +16,6 @@ export const load: PageLoad = async ({ params }) => {
const volume = {
...volumeBase,
- inUse: Boolean(usage?.inUse),
containers: Array.isArray(usage?.containers) ? usage.containers : []
};