Skip to content

Modern Docker Management, Designed for Everyone

refactor: modernize backend code (#1793)

Kyle Mendellab845f7a6892
diff --git a/backend/cli/generate/secret_test.go b/backend/cli/generate/secret_test.go
index dd7eaa038..a00e57d76 100644
--- a/backend/cli/generate/secret_test.go
+++ b/backend/cli/generate/secret_test.go
@@ -56,12 +56,12 @@ func TestSecretDefaultBase64(t *testing.T) {
// find ENCRYPTION_KEY= and JWT_SECRET= lines and ensure they are valid base64
var encVal, jwtVal string
- for _, line := range strings.Split(out, "\n") {
- if strings.HasPrefix(line, "ENCRYPTION_KEY=") {
- encVal = strings.TrimPrefix(line, "ENCRYPTION_KEY=")
+ for line := range strings.SplitSeq(out, "\n") {
+ if after, ok := strings.CutPrefix(line, "ENCRYPTION_KEY="); ok {
+ encVal = after
}
- if strings.HasPrefix(line, "JWT_SECRET=") {
- jwtVal = strings.TrimPrefix(line, "JWT_SECRET=")
+ if after, ok := strings.CutPrefix(line, "JWT_SECRET="); ok {
+ jwtVal = after
}
}
if encVal == "" || jwtVal == "" {
@@ -110,17 +110,17 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
// verify hex values decode to 32 bytes
var hexEnc, hexJwt string
- for _, line := range strings.Split(out, "\n") {
- if strings.HasPrefix(line, "ENCRYPTION_KEY=") {
- v := strings.TrimPrefix(line, "ENCRYPTION_KEY=")
+ for line := range strings.SplitSeq(out, "\n") {
+ if after, ok := strings.CutPrefix(line, "ENCRYPTION_KEY="); ok {
+ v := after
// prefer hex if line length looks like hex (64 chars)
if len(v) >= 64 {
hexEnc = v
continue
}
}
- if strings.HasPrefix(line, "JWT_SECRET=") {
- v := strings.TrimPrefix(line, "JWT_SECRET=")
+ if after, ok := strings.CutPrefix(line, "JWT_SECRET="); ok {
+ v := after
if len(v) >= 64 {
hexJwt = v
continue
diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.go
index 25f6aefaa..690307dd2 100644
--- a/backend/cli/upgrade/upgrade.go
+++ b/backend/cli/upgrade/upgrade.go
@@ -261,8 +261,8 @@ func extractImageNameFromConfig(cont container.InspectResponse) string {
// stripDigest removes digest from image reference
func stripDigest(imageName string) string {
- if idx := strings.Index(imageName, "@"); idx != -1 {
- return imageName[:idx]
+ if before, _, ok := strings.Cut(imageName, "@"); ok {
+ return before
}
return imageName
}
diff --git a/backend/internal/api/ws_handler.go b/backend/internal/api/ws_handler.go
index 5e5a77230..056ae947a 100644
--- a/backend/internal/api/ws_handler.go
+++ b/backend/internal/api/ws_handler.go
@@ -511,7 +511,7 @@ func (h *WebSocketHandler) startContainerStatsHub(containerID string, onEmptyHoo
go hub.Run(ctx)
- statsChan := make(chan interface{}, 64)
+ statsChan := make(chan any, 64)
go func(ctx context.Context) {
defer close(statsChan)
_ = h.containerService.StreamStats(ctx, containerID, statsChan)
diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.go
index 21aa0d204..6e65c0792 100644
--- a/backend/internal/bootstrap/edge_bootstrap.go
+++ b/backend/internal/bootstrap/edge_bootstrap.go
@@ -40,7 +40,7 @@ func registerEdgeTunnelRoutes(ctx context.Context, apiGroup *gin.RouterGroup, ap
status = string(models.EnvironmentStatusOffline)
}
- updates := map[string]interface{}{
+ updates := map[string]any{
"status": status,
}
_, err := appServices.Environment.UpdateEnvironment(ctx, envID, updates, nil, nil)
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index b63906a1c..63348081f 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -43,9 +43,8 @@ func shouldLogRequest(c *gin.Context) bool {
if pat == mp {
return false
}
- if strings.HasSuffix(pat, "/*") {
- prefix := strings.TrimSuffix(pat, "/*")
- if strings.HasPrefix(mp, prefix) {
+ if before, ok := strings.CutSuffix(pat, "/*"); ok {
+ if strings.HasPrefix(mp, before) {
return false
}
}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 17fb09b09..f5e4afdc3 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -131,8 +131,8 @@ func applyOptions(cfg *Config) {
return
}
- options := strings.Split(optionsTag, ",")
- for _, option := range options {
+ options := strings.SplitSeq(optionsTag, ",")
+ for option := range options {
switch strings.TrimSpace(option) {
case "file":
resolveFileBasedEnvVariable(field, fieldType)
diff --git a/backend/internal/huma/handlers/auth.go b/backend/internal/huma/handlers/auth.go
index 0d36bf291..b539f53a7 100644
--- a/backend/internal/huma/handlers/auth.go
+++ b/backend/internal/huma/handlers/auth.go
@@ -154,10 +154,7 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpu
return nil, huma.Error500InternalServerError((&common.UserMappingError{Err: mapErr}).Error())
}
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
+ maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60
return &LoginOutput{
@@ -232,10 +229,7 @@ func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInput
}
}
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
+ maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60
return &RefreshTokenOutput{
diff --git a/backend/internal/huma/handlers/container_registries.go b/backend/internal/huma/handlers/container_registries.go
index 18657d92a..a52eaeca9 100644
--- a/backend/internal/huma/handlers/container_registries.go
+++ b/backend/internal/huma/handlers/container_registries.go
@@ -397,7 +397,7 @@ func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *Sy
// Helper Methods
// ============================================================================
-func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, registryModel *models.ContainerRegistry, decryptedToken string) (map[string]interface{}, error) {
+func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, registryModel *models.ContainerRegistry, decryptedToken string) (map[string]any, error) {
var creds *registry.Credentials
if registryModel.Username != "" && decryptedToken != "" {
creds = &registry.Credentials{
@@ -418,7 +418,7 @@ func (h *ContainerRegistryHandler) performRegistryTest(ctx context.Context, regi
return nil, fmt.Errorf("invalid credentials")
}
- return map[string]interface{}{
+ return map[string]any{
"message": "Authentication succeeded",
}, nil
}
diff --git a/backend/internal/huma/handlers/containers.go b/backend/internal/huma/handlers/containers.go
index 0590b8f0f..21c8b9624 100644
--- a/backend/internal/huma/handlers/containers.go
+++ b/backend/internal/huma/handlers/containers.go
@@ -2,6 +2,7 @@ package handlers
import (
"context"
+ "maps"
"net/http"
"strings"
@@ -319,9 +320,7 @@ func buildCreateLabels(body containertypes.Create) map[string]string {
labels := map[string]string{
"com.arcane.created": "true",
}
- for key, value := range body.Labels {
- labels[key] = value
- }
+ maps.Copy(labels, body.Labels)
return labels
}
diff --git a/backend/internal/huma/handlers/environments.go b/backend/internal/huma/handlers/environments.go
index 26424bbf7..aa90d8e8d 100644
--- a/backend/internal/huma/handlers/environments.go
+++ b/backend/internal/huma/handlers/environments.go
@@ -430,7 +430,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKey(ctx context.Context, en
encryptedKey := apiKeyDto.Key // Store the full key
// Link API key to environment and store encrypted key for manager use
- updates := map[string]interface{}{
+ updates := map[string]any{
"api_key_id": apiKeyDto.ID,
"access_token": encryptedKey,
}
@@ -885,7 +885,7 @@ func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnv
return nil, huma.Error400BadRequest("Environment is not in pending status")
}
- updates := map[string]interface{}{
+ updates := map[string]any{
"status": string(models.EnvironmentStatusOnline),
}
_, err = h.environmentService.UpdateEnvironment(ctx, *envID, updates, nil, nil)
diff --git a/backend/internal/huma/handlers/oidc.go b/backend/internal/huma/handlers/oidc.go
index 70576fc81..13af5714b 100644
--- a/backend/internal/huma/handlers/oidc.go
+++ b/backend/internal/huma/handlers/oidc.go
@@ -264,10 +264,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
}
// Calculate cookie max age
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
+ maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60 // Add 60 seconds buffer for clock skew
// Build cookies: session token + clear state cookie
@@ -351,10 +348,7 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDe
return nil, huma.Error500InternalServerError((&common.AuthFailedError{Err: err}).Error())
}
- maxAge := int(time.Until(tokenPair.ExpiresAt).Seconds())
- if maxAge < 0 {
- maxAge = 0
- }
+ maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60
tokenCookie := cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken)
diff --git a/backend/internal/huma/handlers/projects.go b/backend/internal/huma/handlers/projects.go
index 34045072d..4269a8d6b 100644
--- a/backend/internal/huma/handlers/projects.go
+++ b/backend/internal/huma/handlers/projects.go
@@ -153,7 +153,7 @@ type PullProgressEvent struct {
ProgressDetail struct {
Current int64 `json:"current,omitempty"`
Total int64 `json:"total,omitempty"`
- } `json:"progressDetail,omitempty"`
+ } `json:"progressDetail"`
Error string `json:"error,omitempty"`
}
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index afb600fcf..c268555d3 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -23,7 +23,7 @@ func customSchemaNamer(t reflect.Type, hint string) string {
pkgPath := t.PkgPath()
// For pointer types, get the element's package path
- if pkgPath == "" && t.Kind() == reflect.Ptr {
+ if pkgPath == "" && t.Kind() == reflect.Pointer {
pkgPath = t.Elem().PkgPath()
}
@@ -31,8 +31,8 @@ func customSchemaNamer(t reflect.Type, hint string) string {
// Format: "pkgname.TypeName" - we extract the pkgname part
typeStr := t.String()
var shortPkg string
- if dotIdx := strings.Index(typeStr, "."); dotIdx != -1 {
- shortPkg = typeStr[:dotIdx]
+ if before, _, ok := strings.Cut(typeStr, "."); ok {
+ shortPkg = before
}
// For types from our types package, prefix with the package name
@@ -94,12 +94,12 @@ func customSchemaNamer(t reflect.Type, hint string) string {
// "base.ApiResponse[github.com/getarcaneapp/arcane/types/volume.UsageCounts]"
if strings.Contains(typeName, "[") && strings.Contains(typeName, "github.com/getarcaneapp/arcane/types/") {
// Extract the inner package name
- start := strings.Index(typeName, "github.com/getarcaneapp/arcane/types/")
- if start != -1 {
- rest := typeName[start+len("github.com/getarcaneapp/arcane/types/"):]
- end := strings.Index(rest, ".")
- if end != -1 {
- innerPkg := rest[:end]
+ _, after, ok := strings.Cut(typeName, "github.com/getarcaneapp/arcane/types/")
+ if ok {
+ rest := after
+ before, _, ok := strings.Cut(rest, ".")
+ if ok {
+ innerPkg := before
innerPkg = strings.ToUpper(innerPkg[:1]) + innerPkg[1:]
// Insert the package name into the schema name
// BaseApiResponseUsageCounts -> BaseApiResponseVolumeUsageCounts
diff --git a/backend/internal/huma/middleware/auth.go b/backend/internal/huma/middleware/auth.go
index 60e3aff83..c0917af5e 100644
--- a/backend/internal/huma/middleware/auth.go
+++ b/backend/internal/huma/middleware/auth.go
@@ -9,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
+ pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"
)
const (
@@ -217,14 +218,14 @@ func extractBearerToken(ctx huma.Context) string {
// extractTokenFromCookieHeader parses the token cookie from a Cookie header string.
func extractTokenFromCookieHeader(cookieHeader string) string {
- cookies := strings.Split(cookieHeader, ";")
- for _, c := range cookies {
+ cookies := strings.SplitSeq(cookieHeader, ";")
+ for c := range cookies {
c = strings.TrimSpace(c)
- if strings.HasPrefix(c, "token=") {
- return strings.TrimPrefix(c, "token=")
+ if after, ok := strings.CutPrefix(c, "token="); ok {
+ return after
}
- if strings.HasPrefix(c, "__Host-token=") {
- return strings.TrimPrefix(c, "__Host-token=")
+ if after, ok := strings.CutPrefix(c, "__Host-token="); ok {
+ return after
}
}
return ""
@@ -234,15 +235,6 @@ func extractTokenFromCookieHeader(cookieHeader string) string {
func setUserInContext(ctx context.Context, user *models.User) context.Context {
ctx = context.WithValue(ctx, ContextKeyUserID, user.ID)
ctx = context.WithValue(ctx, ContextKeyCurrentUser, user)
- ctx = context.WithValue(ctx, ContextKeyUserIsAdmin, userHasRole(user, "admin"))
+ ctx = context.WithValue(ctx, ContextKeyUserIsAdmin, pkgutils.UserHasRole(user.Roles, "admin"))
return ctx
}
-
-func userHasRole(user *models.User, role string) bool {
- for _, r := range user.Roles {
- if r == role {
- return true
- }
- }
- return false
-}
diff --git a/backend/internal/middleware/auth_middleware.go b/backend/internal/middleware/auth_middleware.go
index c0029f9ca..91ef04160 100644
--- a/backend/internal/middleware/auth_middleware.go
+++ b/backend/internal/middleware/auth_middleware.go
@@ -11,6 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
"github.com/getarcaneapp/arcane/backend/internal/utils/cookie"
+ pkgutils "github.com/getarcaneapp/arcane/backend/pkg/utils"
"github.com/gin-gonic/gin"
)
@@ -111,7 +112,7 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c *gin.Context) {
if apiKey := c.GetHeader(headerApiKey); apiKey != "" && m.apiKeyValidator != nil {
user, err := m.apiKeyValidator.ValidateApiKey(ctx, apiKey)
if err == nil && user != nil {
- isAdmin := userHasRole(user, "admin")
+ isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
if m.options.AdminRequired && !isAdmin {
c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
@@ -174,7 +175,7 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c *gin.Context) {
return
}
- isAdmin := userHasRole(user, "admin")
+ isAdmin := pkgutils.UserHasRole(user.Roles, "admin")
if m.options.AdminRequired && !isAdmin {
c.JSON(http.StatusForbidden, models.APIError{
Code: "FORBIDDEN",
@@ -209,20 +210,11 @@ func agentSudo(c *gin.Context) {
func extractBearerOrCookieToken(c *gin.Context) string {
authHeader := c.GetHeader("Authorization")
- if strings.HasPrefix(authHeader, "Bearer ") {
- return strings.TrimPrefix(authHeader, "Bearer ")
+ if after, ok := strings.CutPrefix(authHeader, "Bearer "); ok {
+ return after
}
if tok, err := cookie.GetTokenCookie(c); err == nil && tok != "" {
return tok
}
return ""
}
-
-func userHasRole(user *models.User, role string) bool {
- for _, r := range user.Roles {
- if r == role {
- return true
- }
- }
- return false
-}
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index c4ec07638..40d4aaf8b 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -22,17 +22,6 @@ const (
apiEnvironmentsPrefix = "/api/environments/"
environmentsPathMarker = "/environments/"
- managementEndpointTest = "/test"
- managementEndpointHeartbeat = "/heartbeat"
- managementEndpointSyncRegistries = "/sync-registries"
- managementEndpointSync = "/sync"
- managementEndpointDeployment = "/deployment"
- managementEndpointAgentPair = "/agent/pair"
- managementEndpointVersion = "/version"
- managementEndpointSettings = "/settings"
- managementEndpointJobSchedules = "/job-schedules"
- managementEndpointJobs = "/jobs"
-
errEnvironmentNotFound = "Environment not found"
errEnvironmentDisabled = "Environment is disabled"
errFailedCreateProxyRequest = "Failed to create proxy request"
@@ -44,6 +33,20 @@ const (
proxyTimeout = 30 * time.Minute
)
+// managementEndpointSet contains paths handled locally and never proxied to remote environments.
+var managementEndpointSet = map[string]struct{}{
+ "/test": {},
+ "/heartbeat": {},
+ "/sync-registries": {},
+ "/sync": {},
+ "/deployment": {},
+ "/agent/pair": {},
+ "/version": {},
+ "/settings": {},
+ "/job-schedules": {},
+ "/jobs": {},
+}
+
// EnvResolver resolves an environment ID to its connection details.
// Returns: apiURL, accessToken, enabled, error
type EnvResolver func(ctx context.Context, id string) (string, *string, bool, error)
@@ -166,44 +169,16 @@ func (m *EnvironmentMiddleware) Handle(c *gin.Context) {
}
}
-// hasResourcePath checks if the request has additional path segments after the environment ID.
-// Returns true for paths like /api/environments/{id}/containers (should be proxied)
-// Returns false for paths like /api/environments/{id} or management endpoints (should be handled locally)
+// hasResourcePath reports whether the request targets a proxiable resource path.
+// Returns true for paths like /api/environments/{id}/containers (should be proxied).
+// Returns false for /api/environments/{id} exactly or any management endpoint.
func (m *EnvironmentMiddleware) hasResourcePath(c *gin.Context, envID string) bool {
- path := c.Request.URL.Path
- prefix := apiEnvironmentsPrefix + envID
-
- // If there's content after the environment ID path, check if it's a management endpoint
- suffix := strings.TrimPrefix(path, prefix)
-
- // No suffix means it's exactly /api/environments/{id} - management endpoint
- if len(suffix) <= 1 || !strings.HasPrefix(suffix, "/") {
+ suffix, ok := strings.CutPrefix(c.Request.URL.Path, apiEnvironmentsPrefix+envID)
+ if !ok || len(suffix) <= 1 || suffix[0] != '/' {
return false
}
-
- // Check if it's a management endpoint that should NOT be proxied
- // These are environment management operations handled by the manager
- managementEndpoints := []string{
- managementEndpointTest,
- managementEndpointHeartbeat,
- managementEndpointSyncRegistries,
- managementEndpointSync,
- managementEndpointDeployment,
- managementEndpointAgentPair,
- managementEndpointVersion,
- managementEndpointSettings,
- managementEndpointJobSchedules,
- managementEndpointJobs,
- }
-
- for _, endpoint := range managementEndpoints {
- if suffix == endpoint {
- return false
- }
- }
-
- // It's a resource operation (e.g., "/containers", "/images") - should be proxied
- return true
+ _, isManagement := managementEndpointSet[suffix]
+ return !isManagement
}
// extractEnvironmentID gets the environment ID from the request.
@@ -222,46 +197,38 @@ func (m *EnvironmentMiddleware) extractEnvironmentID(c *gin.Context) string {
}
// Fall back to parsing the URL path
- if idx := strings.Index(requestPath, environmentsPathMarker); idx >= 0 {
- rest := requestPath[idx+len(environmentsPathMarker):]
- if parts := strings.SplitN(rest, "/", 2); len(parts) > 0 && parts[0] != "" {
- return parts[0]
+ if _, rest, ok := strings.Cut(requestPath, environmentsPathMarker); ok {
+ if envID, _, _ := strings.Cut(rest, "/"); envID != "" {
+ return envID
}
}
return ""
}
-// buildTargetURL constructs the proxy target URL.
-func (m *EnvironmentMiddleware) buildTargetURL(c *gin.Context, envID, apiURL string) string {
- // Remove the environment prefix from the path
- prefix := apiEnvironmentsPrefix + envID
- suffix := strings.TrimPrefix(c.Request.URL.Path, prefix)
- if suffix != "" && !strings.HasPrefix(suffix, "/") {
+// buildResourceSuffix extracts the resource path after stripping the environment ID prefix.
+func (m *EnvironmentMiddleware) buildResourceSuffix(requestPath, envID string) string {
+ suffix, _ := strings.CutPrefix(requestPath, apiEnvironmentsPrefix+envID)
+ if suffix != "" && suffix[0] != '/' {
suffix = "/" + suffix
}
+ return suffix
+}
- // Build target: apiURL + /api/environments/{localID} + suffix
+// buildTargetURL constructs the full proxy target URL for a remote environment.
+func (m *EnvironmentMiddleware) buildTargetURL(c *gin.Context, envID, apiURL string) string {
+ suffix := m.buildResourceSuffix(c.Request.URL.Path, envID)
target := strings.TrimRight(apiURL, "/") + path.Join(apiEnvironmentsPrefix, m.localID) + suffix
-
- // Append query string if present
if qs := c.Request.URL.RawQuery; qs != "" {
target += "?" + qs
}
-
return target
}
-// buildProxyPath constructs the path to send through the edge tunnel.
-// This includes the /api/environments/{localID} prefix so the agent can route it properly.
+// buildProxyPath constructs the path sent through the edge tunnel.
+// Includes the /api/environments/{localID} prefix so the agent can route it properly.
func (m *EnvironmentMiddleware) buildProxyPath(c *gin.Context, envID string) string {
- prefix := apiEnvironmentsPrefix + envID
- suffix := strings.TrimPrefix(c.Request.URL.Path, prefix)
- if suffix != "" && !strings.HasPrefix(suffix, "/") {
- suffix = "/" + suffix
- }
- // Build path: /api/environments/{localID} + suffix
- return path.Join(apiEnvironmentsPrefix, m.localID) + suffix
+ return path.Join(apiEnvironmentsPrefix, m.localID) + m.buildResourceSuffix(c.Request.URL.Path, envID)
}
// isWebSocketUpgrade checks if this is a WebSocket upgrade request.
@@ -310,21 +277,25 @@ func (m *EnvironmentMiddleware) proxyHTTP(c *gin.Context, target string, accessT
// createProxyRequest builds the HTTP request to forward to the remote environment.
func (m *EnvironmentMiddleware) createProxyRequest(c *gin.Context, target string, accessToken *string) (*http.Request, error) {
- // Read the body to log it and then restore it for forwarding
var bodyBytes []byte
- var err error
if c.Request.Body != nil {
+ var err error
bodyBytes, err = io.ReadAll(c.Request.Body)
+ _ = c.Request.Body.Close()
if err != nil {
return nil, fmt.Errorf("failed to read request body: %w", err)
}
- // Restore the body for forwarding
- c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
}
slog.DebugContext(c.Request.Context(), "Creating proxy request", "method", c.Request.Method, "target", target, "contentLength", c.Request.ContentLength, "contentType", c.GetHeader("Content-Type"), "bodyLength", len(bodyBytes), "body", string(bodyBytes))
- req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, target, bytes.NewBuffer(bodyBytes))
+ // bytes.NewReader is preferred over bytes.NewBuffer: it implements io.ReadSeeker
+ // and avoids the internal grow-buffer logic that NewBuffer carries.
+ var body io.Reader
+ if len(bodyBytes) > 0 {
+ body = bytes.NewReader(bodyBytes)
+ }
+ req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, target, body)
if err != nil {
return nil, err
}
diff --git a/backend/internal/models/base.go b/backend/internal/models/base.go
index 68b292bbe..a9dd5351c 100644
--- a/backend/internal/models/base.go
+++ b/backend/internal/models/base.go
@@ -32,7 +32,7 @@ func (m *BaseModel) BeforeUpdate(_ *gorm.DB) (err error) {
}
// nolint:recvcheck
-type JSON map[string]interface{}
+type JSON map[string]any
func (j JSON) Value() (driver.Value, error) {
if j == nil {
@@ -41,7 +41,7 @@ func (j JSON) Value() (driver.Value, error) {
return json.Marshal(j)
}
-func (j *JSON) Scan(value interface{}) error {
+func (j *JSON) Scan(value any) error {
if value == nil {
*j = nil
return nil
@@ -66,7 +66,7 @@ func (s StringSlice) Value() (driver.Value, error) {
return json.Marshal(s)
}
-func (s *StringSlice) Scan(value interface{}) error {
+func (s *StringSlice) Scan(value any) error {
if value == nil {
*s = nil
return nil
diff --git a/backend/internal/models/errors.go b/backend/internal/models/errors.go
index be72b6baa..5e2ebf0e1 100644
--- a/backend/internal/models/errors.go
+++ b/backend/internal/models/errors.go
@@ -23,20 +23,20 @@ type APIErrorResponse struct {
Success bool `json:"success"`
Error string `json:"error"`
Code APIErrorCode `json:"code"`
- Details interface{} `json:"details,omitempty"`
+ Details any `json:"details,omitempty"`
}
type APISuccessResponse struct {
- Success bool `json:"success"`
- Data interface{} `json:"data,omitempty"`
- Message string `json:"message,omitempty"`
+ Success bool `json:"success"`
+ Data any `json:"data,omitempty"`
+ Message string `json:"message,omitempty"`
}
type APIError struct {
Message string `json:"message"`
Code APIErrorCode `json:"code"`
StatusCode int `json:"statusCode"`
- Details interface{} `json:"details,omitempty"`
+ Details any `json:"details,omitempty"`
}
func (e *APIError) Error() string {
@@ -59,7 +59,7 @@ func NewAPIError(message string, code APIErrorCode, statusCode int) *APIError {
}
}
-func NewAPIErrorWithDetails(message string, code APIErrorCode, statusCode int, details interface{}) *APIError {
+func NewAPIErrorWithDetails(message string, code APIErrorCode, statusCode int, details any) *APIError {
return &APIError{
Message: message,
Code: code,
@@ -80,7 +80,7 @@ func NewInternalServerError(message string) *APIError {
return NewAPIError(message, APIErrorCodeInternalServerError, http.StatusInternalServerError)
}
-func NewValidationError(message string, details interface{}) *APIError {
+func NewValidationError(message string, details any) *APIError {
return NewAPIErrorWithDetails(message, APIErrorCodeValidationError, http.StatusBadRequest, details)
}
@@ -103,7 +103,7 @@ func (e *ConflictError) Error() string {
type DockerAPIError struct {
Message string
StatusCode int
- Details interface{}
+ Details any
}
func (e *DockerAPIError) Error() string {
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index 9fcff2515..360577ed4 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -189,10 +189,10 @@ func (s *Settings) FieldByKey(key string) (defaultValue string, isPublic bool, i
}
func (s *Settings) IsLocalSetting(key string) bool {
- rt := reflect.TypeOf(s).Elem()
+ rt := reflect.TypeFor[Settings]()
- for i := 0; i < rt.NumField(); i++ {
- tagValue := strings.Split(rt.Field(i).Tag.Get("key"), ",")
+ for field := range rt.Fields() {
+ tagValue := strings.Split(field.Tag.Get("key"), ",")
keyFromTag := tagValue[0]
if keyFromTag == key {
diff --git a/backend/internal/services/apprise_service.go b/backend/internal/services/apprise_service.go
index 325ddee8f..dce38e852 100644
--- a/backend/internal/services/apprise_service.go
+++ b/backend/internal/services/apprise_service.go
@@ -9,6 +9,7 @@ import (
"io"
"log/slog"
"net/http"
+ "strings"
"time"
"github.com/getarcaneapp/arcane/backend/internal/config"
@@ -197,10 +198,11 @@ func (s *AppriseService) SendBatchImageUpdateNotification(ctx context.Context, u
}
title := fmt.Sprintf("%d Container Image Update(s) Available", len(updatesWithChanges))
- body := "The following images have updates available:\n\n"
+ var body strings.Builder
+ body.WriteString("The following images have updates available:\n\n")
for imageRef, update := range updatesWithChanges {
- body += fmt.Sprintf("• %s\n Type: %s\n Current: %s\n Latest: %s\n\n",
+ fmt.Fprintf(&body, "• %s\n Type: %s\n Current: %s\n Latest: %s\n\n",
imageRef,
update.UpdateType,
update.CurrentDigest,
@@ -208,7 +210,7 @@ func (s *AppriseService) SendBatchImageUpdateNotification(ctx context.Context, u
)
}
- return s.SendNotification(ctx, title, body, "text", models.NotificationEventImageUpdate)
+ return s.SendNotification(ctx, title, body.String(), "text", models.NotificationEventImageUpdate)
}
func (s *AppriseService) TestNotification(ctx context.Context, testType string) error {
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index 94c098d0f..588ea9bf3 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -522,8 +522,8 @@ func (s *AuthService) getAdminClaimConfig(ctx context.Context) (claim string, va
if raw == "" {
return claim, nil
}
- parts := strings.Split(raw, ",")
- for _, p := range parts {
+ parts := strings.SplitSeq(raw, ",")
+ for p := range parts {
v := strings.TrimSpace(p)
if v != "" {
values = append(values, v)
@@ -549,7 +549,7 @@ func (s *AuthService) persistOidcTokens(user *models.User, tokenResp *auth.OidcT
func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string) (*TokenPair, error) {
token, err := jwt.ParseWithClaims(refreshToken, &jwt.RegisteredClaims{},
- func(t *jwt.Token) (interface{}, error) {
+ func(t *jwt.Token) (any, error) {
return s.jwtSecret, nil
})
@@ -590,7 +590,7 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string) (*T
func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*models.User, error) {
token, err := jwt.ParseWithClaims(accessToken, &UserClaims{},
- func(t *jwt.Token) (interface{}, error) {
+ func(t *jwt.Token) (any, error) {
return s.jwtSecret, nil
})
diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.go
index 8a03276fc..1bf3dfc69 100644
--- a/backend/internal/services/container_service.go
+++ b/backend/internal/services/container_service.go
@@ -258,7 +258,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe
return &containerJSON, nil
}
-func (s *ContainerService) StreamStats(ctx context.Context, containerID string, statsChan chan<- interface{}) error {
+func (s *ContainerService) StreamStats(ctx context.Context, containerID string, statsChan chan<- any) error {
dockerClient, err := s.dockerService.GetClient()
if err != nil {
return fmt.Errorf("failed to connect to Docker: %w", err)
@@ -277,7 +277,7 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,
return err
}
- var statsData interface{}
+ var statsData any
if err := decoder.Decode(&statsData); err != nil {
if ctx.Err() != nil {
return ctx.Err()
@@ -410,8 +410,8 @@ func (s *ContainerService) readAllLogs(logs io.ReadCloser, logsChan chan<- strin
// Send stdout lines
if stdoutBuf.Len() > 0 {
- lines := strings.Split(strings.TrimRight(stdoutBuf.String(), "\n"), "\n")
- for _, line := range lines {
+ lines := strings.SplitSeq(strings.TrimRight(stdoutBuf.String(), "\n"), "\n")
+ for line := range lines {
if line != "" {
logsChan <- line
}
@@ -420,8 +420,8 @@ func (s *ContainerService) readAllLogs(logs io.ReadCloser, logsChan chan<- strin
// Send stderr lines with prefix
if stderrBuf.Len() > 0 {
- lines := strings.Split(strings.TrimRight(stderrBuf.String(), "\n"), "\n")
- for _, line := range lines {
+ lines := strings.SplitSeq(strings.TrimRight(stderrBuf.String(), "\n"), "\n")
+ for line := range lines {
if line != "" {
logsChan <- "[STDERR] " + line
}
diff --git a/backend/internal/services/customize_search_service.go b/backend/internal/services/customize_search_service.go
index c33ea9391..275bba45d 100644
--- a/backend/internal/services/customize_search_service.go
+++ b/backend/internal/services/customize_search_service.go
@@ -43,9 +43,8 @@ func (s *CustomizeSearchService) buildCategoriesFromModel() []category.Category
categories := map[string][]meta.Metadata{}
categoryOrder := []string{} // Track order from first appearance in struct
- rt := reflect.TypeOf(models.CustomizeItem{})
- for i := 0; i < rt.NumField(); i++ {
- field := rt.Field(i)
+ rt := reflect.TypeFor[models.CustomizeItem]()
+ for field := range rt.Fields() {
keyTag := field.Tag.Get("key")
key, _, _ := strings.Cut(keyTag, ",")
if key == "" {
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index 2e0c72c03..85a410546 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -164,7 +164,7 @@ func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]mode
return envs, nil
}
-func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]interface{}, userID, username *string) (*models.Environment, error) {
+func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]any, userID, username *string) (*models.Environment, error) {
now := time.Now()
updates["updated_at"] = &now
@@ -316,7 +316,7 @@ func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context
}
now := time.Now()
- updates := map[string]interface{}{
+ updates := map[string]any{
"status": status,
"last_seen": &now,
"updated_at": &now,
@@ -362,7 +362,7 @@ func (s *EnvironmentService) createEnvironmentEvent(ctx context.Context, envID,
func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, envID string, newApiKeyID string, encryptedKey string, userID, username string, envName string) error {
// Update environment with new API key and set to pending status
- updates := map[string]interface{}{
+ updates := map[string]any{
"api_key_id": newApiKeyID,
"access_token": encryptedKey,
"status": string(models.EnvironmentStatusPending),
diff --git a/backend/internal/services/event_service.go b/backend/internal/services/event_service.go
index d05781fa6..23d54ae15 100644
--- a/backend/internal/services/event_service.go
+++ b/backend/internal/services/event_service.go
@@ -415,9 +415,9 @@ var eventDefinitions = map[models.EventType]struct {
}
func (s *EventService) toEventDto(e *models.Event) *event.Event {
- var metadata map[string]interface{}
+ var metadata map[string]any
if e.Metadata != nil {
- metadata = map[string]interface{}(e.Metadata)
+ metadata = map[string]any(e.Metadata)
}
return &event.Event{
diff --git a/backend/internal/services/git_repository_service.go b/backend/internal/services/git_repository_service.go
index 397664aac..9cbd485d1 100644
--- a/backend/internal/services/git_repository_service.go
+++ b/backend/internal/services/git_repository_service.go
@@ -145,7 +145,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
return nil, err
}
- updates := make(map[string]interface{})
+ updates := make(map[string]any)
if req.Name != nil {
updates["name"] = *req.Name
diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.go
index f1d8ba9c2..b0c45f7c5 100644
--- a/backend/internal/services/gitops_sync_service.go
+++ b/backend/internal/services/gitops_sync_service.go
@@ -217,7 +217,7 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id st
return nil, err
}
- updates := make(map[string]interface{})
+ updates := make(map[string]any)
if req.Name != nil {
updates["name"] = *req.Name
@@ -406,7 +406,7 @@ func (s *GitOpsSyncService) PerformSync(ctx context.Context, environmentID, id s
func (s *GitOpsSyncService) updateSyncStatus(ctx context.Context, id, status, errorMsg, commitHash string) {
now := time.Now()
- updates := map[string]interface{}{
+ updates := map[string]any{
"last_sync_at": now,
"last_sync_status": status,
}
@@ -593,7 +593,7 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sy
}
// Update sync with project ID
- if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("id = ?", id).Updates(map[string]interface{}{
+ if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("id = ?", id).Updates(map[string]any{
"project_id": project.ID,
}).Error; err != nil {
return nil, s.failSync(ctx, id, result, sync, "Failed to update sync with project ID", err.Error())
diff --git a/backend/internal/services/image_service.go b/backend/internal/services/image_service.go
index 1bfc49222..37a6c8c81 100644
--- a/backend/internal/services/image_service.go
+++ b/backend/internal/services/image_service.go
@@ -549,11 +549,11 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatio
return result.Items, paginationResp, nil
}
-func convertLabels(labels map[string]string) map[string]interface{} {
+func convertLabels(labels map[string]string) map[string]any {
if labels == nil {
return nil
}
- result := make(map[string]interface{}, len(labels))
+ result := make(map[string]any, len(labels))
for k, v := range labels {
result[k] = v
}
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index 62f14c580..108340d5a 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log/slog"
+ "maps"
"strings"
"sync"
"time"
@@ -942,9 +943,7 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefs
rc := registry.NewClient()
regRepos, initialResults, images := s.parseAndGroupImages(imageRefs)
- for k, v := range initialResults {
- results[k] = v
- }
+ maps.Copy(results, initialResults)
credMap, enabledRegs := s.buildCredentialMap(ctx, externalCreds)
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index 77292e6d6..a299f52bb 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -201,12 +201,12 @@ func (s *NotificationService) isEventEnabled(config models.JSON, eventType model
return true // Default to enabled if we can't parse
}
- var configMap map[string]interface{}
+ var configMap map[string]any
if err := json.Unmarshal(configBytes, &configMap); err != nil {
return true // Default to enabled if we can't parse
}
- events, ok := configMap["events"].(map[string]interface{})
+ events, ok := configMap["events"].(map[string]any)
if !ok {
return true // If no events config, default to enabled
}
@@ -618,7 +618,7 @@ func (s *NotificationService) sendEmailNotification(ctx context.Context, imageRe
func (s *NotificationService) renderEmailTemplate(imageRef string, updateInfo *imageupdate.Response) (string, string, error) {
appURL := s.config.GetAppURL()
logoURL := appURL + logoURLPath
- data := map[string]interface{}{
+ data := map[string]any{
"LogoURL": logoURL,
"AppURL": appURL,
"Environment": "Local Docker",
@@ -811,7 +811,7 @@ func (s *NotificationService) sendEmailContainerUpdateNotification(ctx context.C
func (s *NotificationService) renderContainerUpdateEmailTemplate(containerName, imageRef, oldDigest, newDigest string) (string, string, error) {
appURL := s.config.GetAppURL()
logoURL := appURL + logoURLPath
- data := map[string]interface{}{
+ data := map[string]any{
"LogoURL": logoURL,
"AppURL": appURL,
"Environment": "Local Docker",
@@ -1089,7 +1089,7 @@ func (s *NotificationService) sendTestEmail(ctx context.Context, config models.J
func (s *NotificationService) renderTestEmailTemplate() (string, string, error) {
appURL := s.config.GetAppURL()
logoURL := appURL + logoURLPath
- data := map[string]interface{}{
+ data := map[string]any{
"LogoURL": logoURL,
"AppURL": appURL,
}
@@ -1255,10 +1255,11 @@ func (s *NotificationService) sendBatchDiscordNotification(ctx context.Context,
description = "1 container image has an update available."
}
- message := fmt.Sprintf("**%s**\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "**%s**\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("**%s**\n"+
+ fmt.Fprintf(&message, "**%s**\n"+
"• **Type:** %s\n"+
"• **Current:** `%s`\n"+
"• **Latest:** `%s`\n\n",
@@ -1269,7 +1270,7 @@ func (s *NotificationService) sendBatchDiscordNotification(ctx context.Context,
)
}
- if err := notifications.SendDiscord(ctx, discordConfig, message); err != nil {
+ if err := notifications.SendDiscord(ctx, discordConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Discord notification: %w", err)
}
@@ -1298,10 +1299,11 @@ func (s *NotificationService) sendBatchTelegramNotification(ctx context.Context,
description = "1 container image has an update available."
}
- message := fmt.Sprintf("<b>%s</b>\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "<b>%s</b>\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("<b>%s</b>\n"+
+ fmt.Fprintf(&message, "<b>%s</b>\n"+
"• <b>Type:</b> %s\n"+
"• <b>Current:</b> <code>%s</code>\n"+
"• <b>Latest:</b> <code>%s</code>\n\n",
@@ -1317,7 +1319,7 @@ func (s *NotificationService) sendBatchTelegramNotification(ctx context.Context,
telegramConfig.ParseMode = "HTML"
}
- if err := notifications.SendTelegram(ctx, telegramConfig, message); err != nil {
+ if err := notifications.SendTelegram(ctx, telegramConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Telegram notification: %w", err)
}
@@ -1386,7 +1388,7 @@ func (s *NotificationService) renderBatchEmailTemplate(updates map[string]*image
appURL := s.config.GetAppURL()
logoURL := appURL + logoURLPath
- data := map[string]interface{}{
+ data := map[string]any{
"LogoURL": logoURL,
"AppURL": appURL,
"UpdateCount": len(updates),
@@ -1612,10 +1614,11 @@ func (s *NotificationService) sendBatchSignalNotification(ctx context.Context, u
description = "1 container image has an update available."
}
- message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "%s\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("%s\n"+
+ fmt.Fprintf(&message, "%s\n"+
"• Type: %s\n"+
"• Current: %s\n"+
"• Latest: %s\n\n",
@@ -1626,7 +1629,7 @@ func (s *NotificationService) sendBatchSignalNotification(ctx context.Context, u
)
}
- if err := notifications.SendSignal(ctx, signalConfig, message); err != nil {
+ if err := notifications.SendSignal(ctx, signalConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Signal notification: %w", err)
}
@@ -1749,10 +1752,11 @@ func (s *NotificationService) sendBatchSlackNotification(ctx context.Context, up
description = "1 container image has an update available."
}
- message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "%s\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("*%s*\n"+
+ fmt.Fprintf(&message, "*%s*\n"+
"• *Type:* %s\n"+
"• *Current:* `%s`\n"+
"• *Latest:* `%s`\n\n",
@@ -1763,7 +1767,7 @@ func (s *NotificationService) sendBatchSlackNotification(ctx context.Context, up
)
}
- if err := notifications.SendSlack(ctx, slackConfig, message); err != nil {
+ if err := notifications.SendSlack(ctx, slackConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Slack notification: %w", err)
}
@@ -1888,10 +1892,11 @@ func (s *NotificationService) sendBatchNtfyNotification(ctx context.Context, upd
description = "1 container image has an update available."
}
- message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "%s\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("%s\n"+
+ fmt.Fprintf(&message, "%s\n"+
"• Type: %s\n"+
"• Current: %s\n"+
"• Latest: %s\n\n",
@@ -1902,7 +1907,7 @@ func (s *NotificationService) sendBatchNtfyNotification(ctx context.Context, upd
)
}
- if err := notifications.SendNtfy(ctx, ntfyConfig, message); err != nil {
+ if err := notifications.SendNtfy(ctx, ntfyConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Ntfy notification: %w", err)
}
@@ -2028,10 +2033,11 @@ func (s *NotificationService) sendBatchPushoverNotification(ctx context.Context,
description = "1 container image has an update available."
}
- message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "%s\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("%s\n"+
+ fmt.Fprintf(&message, "%s\n"+
"• Type: %s\n"+
"• Current: %s\n"+
"• Latest: %s\n\n",
@@ -2042,7 +2048,7 @@ func (s *NotificationService) sendBatchPushoverNotification(ctx context.Context,
)
}
- if err := notifications.SendPushover(ctx, pushoverConfig, message); err != nil {
+ if err := notifications.SendPushover(ctx, pushoverConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Pushover notification: %w", err)
}
@@ -2132,7 +2138,7 @@ func (s *NotificationService) sendGenericContainerUpdateNotification(ctx context
func (s *NotificationService) renderVulnerabilitySummaryEmailTemplate(payload VulnerabilityNotificationPayload) (string, string, error) {
appURL := s.config.GetAppURL()
logoURL := appURL + logoURLPath
- data := map[string]interface{}{
+ data := map[string]any{
"LogoURL": logoURL,
"AppURL": appURL,
"SummaryLabel": payload.CVEID,
@@ -2445,10 +2451,11 @@ func (s *NotificationService) sendBatchGenericNotification(ctx context.Context,
description = "1 container image has an update available."
}
- message := fmt.Sprintf("%s\n\n", description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "%s\n\n", description)
for imageRef, update := range updates {
- message += fmt.Sprintf("%s\n"+
+ fmt.Fprintf(&message, "%s\n"+
"• Type: %s\n"+
"• Current: %s\n"+
"• Latest: %s\n\n",
@@ -2459,7 +2466,7 @@ func (s *NotificationService) sendBatchGenericNotification(ctx context.Context,
)
}
- if err := notifications.SendGenericWithTitle(ctx, genericConfig, title, message); err != nil {
+ if err := notifications.SendGenericWithTitle(ctx, genericConfig, title, message.String()); err != nil {
return fmt.Errorf("failed to send batch Generic webhook notification: %w", err)
}
@@ -2571,10 +2578,11 @@ func (s *NotificationService) sendBatchGotifyNotification(ctx context.Context, u
description = "1 container image has an update available."
}
- message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "%s\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("%s\n"+
+ fmt.Fprintf(&message, "%s\n"+
"• Type: %s\n"+
"• Current: %s\n"+
"• Latest: %s\n\n",
@@ -2585,7 +2593,7 @@ func (s *NotificationService) sendBatchGotifyNotification(ctx context.Context, u
)
}
- if err := notifications.SendGotify(ctx, gotifyConfig, message); err != nil {
+ if err := notifications.SendGotify(ctx, gotifyConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Gotify notification: %w", err)
}
@@ -2693,10 +2701,11 @@ func (s *NotificationService) sendBatchMatrixNotification(ctx context.Context, u
description = "1 container image has an update available."
}
- message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+ var message strings.Builder
+ fmt.Fprintf(&message, "%s\n\n%s\n\n", title, description)
for imageRef, update := range updates {
- message += fmt.Sprintf("%s\n"+
+ fmt.Fprintf(&message, "%s\n"+
"• Type: %s\n"+
"• Current: %s\n"+
"• Latest: %s\n\n",
@@ -2707,7 +2716,7 @@ func (s *NotificationService) sendBatchMatrixNotification(ctx context.Context, u
)
}
- if err := notifications.SendMatrix(ctx, matrixConfig, message); err != nil {
+ if err := notifications.SendMatrix(ctx, matrixConfig, message.String()); err != nil {
return fmt.Errorf("failed to send batch Matrix notification: %w", err)
}
@@ -3010,7 +3019,7 @@ func (s *NotificationService) sendEmailPruneNotification(ctx context.Context, re
func (s *NotificationService) renderPruneReportEmailTemplate(result *system.PruneAllResult) (string, string, error) {
appURL := s.config.GetAppURL()
logoURL := appURL + logoURLPath
- data := map[string]interface{}{
+ data := map[string]any{
"LogoURL": logoURL,
"AppURL": appURL,
"TotalSpaceReclaimed": s.formatBytesInternal(result.SpaceReclaimed),
@@ -3185,7 +3194,7 @@ func (s *NotificationService) sendGenericPruneNotification(ctx context.Context,
}
// Helper methods to reduce code duplication
-func (s *NotificationService) unmarshalConfigInternal(config models.JSON, dest interface{}) error {
+func (s *NotificationService) unmarshalConfigInternal(config models.JSON, dest any) error {
configBytes, err := json.Marshal(config)
if err != nil {
return fmt.Errorf("failed to marshal config: %w", err)
@@ -3230,7 +3239,7 @@ func (s *NotificationService) decryptEmailPasswordInternal(config *models.EmailC
}
}
-func (s *NotificationService) renderTemplatesInternal(name string, data interface{}) (string, string, error) {
+func (s *NotificationService) renderTemplatesInternal(name string, data any) (string, string, error) {
htmlContent, err := resources.FS.ReadFile(fmt.Sprintf("email-templates/%s_html.tmpl", name))
if err != nil {
return "", "", fmt.Errorf("failed to read HTML template: %w", err)
diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.go
index 804bd9a44..d0f4657ae 100644
--- a/backend/internal/services/notification_service_test.go
+++ b/backend/internal/services/notification_service_test.go
@@ -38,7 +38,7 @@ func TestNotificationService_MigrateDiscordWebhookUrlToFields(t *testing.T) {
svc := NewNotificationService(db, cfg)
// Create legacy Discord config with webhookUrl
- legacyConfig := map[string]interface{}{
+ legacyConfig := map[string]any{
"webhookUrl": "https://discord.com/api/webhooks/123456789/abcdef123456",
"username": "Arcane Bot",
"avatarUrl": "https://example.com/avatar.png",
@@ -182,7 +182,7 @@ func TestNotificationService_MigrateDiscordWebhookUrlToFields_InvalidWebhookUrl(
// Clean up before each sub-test
db.Exec("DELETE FROM notification_settings")
- legacyConfig := map[string]interface{}{
+ legacyConfig := map[string]any{
"webhookUrl": tc.webhookUrl,
}
@@ -207,7 +207,7 @@ func TestNotificationService_MigrateDiscordWebhookUrlToFields_InvalidWebhookUrl(
var unchangedSetting models.NotificationSettings
require.NoError(t, db.Where("provider = ?", models.NotificationProviderDiscord).First(&unchangedSetting).Error)
- var resultConfig map[string]interface{}
+ var resultConfig map[string]any
configBytes, err = json.Marshal(unchangedSetting.Config)
require.NoError(t, err)
require.NoError(t, json.Unmarshal(configBytes, &resultConfig))
@@ -251,7 +251,7 @@ func TestNotificationService_MigrateDiscordWebhookUrlToFields_PreservesAllFields
svc := NewNotificationService(db, cfg)
// Create legacy config with all optional fields
- legacyConfig := map[string]interface{}{
+ legacyConfig := map[string]any{
"webhookUrl": "https://discord.com/api/webhooks/111222333/token444555",
"username": "Custom Bot Name",
"avatarUrl": "https://cdn.example.com/bot-avatar.jpg",
diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.go
index a1889d4ea..c4178831b 100644
--- a/backend/internal/services/oidc_service.go
+++ b/backend/internal/services/oidc_service.go
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "slices"
"strings"
"sync"
"time"
@@ -132,13 +133,7 @@ func (s *OidcService) getInsecureHttpClient() *http.Client {
}
func (s *OidcService) ensureOpenIDScope(scopes []string) []string {
- hasOpenID := false
- for _, scope := range scopes {
- if scope == oidc.ScopeOpenID {
- hasOpenID = true
- break
- }
- }
+ hasOpenID := slices.Contains(scopes, oidc.ScopeOpenID)
if !hasOpenID {
scopes = append([]string{oidc.ScopeOpenID}, scopes...)
}
@@ -251,7 +246,7 @@ func (s *OidcService) getOrDiscoverProvider(ctx context.Context, cfg *models.Oid
// Use singleflight to prevent thundering herd. Include skipTls in key to handle toggling.
sfKey := fmt.Sprintf("%s|%v", issuer, skipTls)
- v, err, _ := s.sfGroup.Do(sfKey, func() (interface{}, error) {
+ v, err, _ := s.sfGroup.Do(sfKey, func() (any, error) {
// Double check inside the lock/singleflight
s.providerMutex.RLock()
if s.providerCache != nil && s.cachedIssuer == issuer && s.cachedSkipTls == skipTls {
@@ -583,10 +578,7 @@ func (s *OidcService) buildUserInfo(ctx context.Context, provider *oidc.Provider
IDToken: rawIDToken,
}
if !token.Expiry.IsZero() {
- expiresIn := int(time.Until(token.Expiry).Seconds())
- if expiresIn < 0 {
- expiresIn = 0
- }
+ expiresIn := max(int(time.Until(token.Expiry).Seconds()), 0)
tokenResp.ExpiresIn = expiresIn
}
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index ecf7d9640..8a8c4ab76 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -159,7 +159,7 @@ func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Contex
serviceCount, runningCount := s.getServiceCounts(services)
- if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", projectID).Updates(map[string]interface{}{
+ if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", projectID).Updates(map[string]any{
"status": status,
"service_count": serviceCount,
"running_count": runningCount,
@@ -173,7 +173,7 @@ func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Contex
func (s *ProjectService) updateProjectStatusInternal(ctx context.Context, id string, status models.ProjectStatus) error {
now := time.Now()
- res := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", id).Updates(map[string]interface{}{
+ res := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", id).Updates(map[string]any{
"status": status,
"updated_at": now,
})
@@ -476,7 +476,7 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPa
return fmt.Errorf("query existing project for %q failed: %w", dirPath, err)
}
- updates := map[string]interface{}{}
+ updates := map[string]any{}
if existing.Path != dirPath {
updates["path"] = dirPath
}
diff --git a/backend/internal/services/settings_search_service.go b/backend/internal/services/settings_search_service.go
index 691fdc3c1..1fa4b309f 100644
--- a/backend/internal/services/settings_search_service.go
+++ b/backend/internal/services/settings_search_service.go
@@ -43,9 +43,8 @@ func (s *SettingsSearchService) buildCategoriesFromModel() []category.Category {
categories := map[string][]meta.Metadata{}
categoryOrder := []string{} // Track order from first appearance in struct
- rt := reflect.TypeOf(models.Settings{})
- for i := 0; i < rt.NumField(); i++ {
- field := rt.Field(i)
+ rt := reflect.TypeFor[models.Settings]()
+ for field := range rt.Fields() {
keyTag := field.Tag.Get("key")
key, _, _ := strings.Cut(keyTag, ",")
if key == "" {
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 9ed7aa25a..4c4ac12b3 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -207,13 +207,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *dat
tagParts := strings.Split(field.Tag.Get("key"), ",")
key := tagParts[0]
- isInternal := false
- for _, attr := range tagParts[1:] {
- if attr == "internal" {
- isInternal = true
- break
- }
- }
+ isInternal := slices.Contains(tagParts[1:], "internal")
if isInternal {
if val, ok := settingsMap[key]; ok {
@@ -270,13 +264,7 @@ func (s *SettingsService) applyEnvOverrides(ctx context.Context, dest *models.Se
// Parse tag attributes (e.g., "dockerHost,public,envOverride")
parts := strings.Split(tagValue, ",")
key := parts[0]
- hasEnvOverride := false
- for _, attr := range parts[1:] {
- if attr == "envOverride" {
- hasEnvOverride = true
- break
- }
- }
+ hasEnvOverride := slices.Contains(parts[1:], "envOverride")
if !hasEnvOverride {
continue
@@ -294,9 +282,8 @@ func (s *SettingsService) applyEnvOverrides(ctx context.Context, dest *models.Se
// isEnvOverrideActiveInternal returns true when the given setting key has an envOverride tag
// and its corresponding environment variable is currently set to a non-empty value.
func (s *SettingsService) isEnvOverrideActiveInternal(key string) bool {
- rt := reflect.TypeOf(models.Settings{})
- for i := 0; i < rt.NumField(); i++ {
- field := rt.Field(i)
+ rt := reflect.TypeFor[models.Settings]()
+ for field := range rt.Fields() {
tagValue := field.Tag.Get("key")
if tagValue == "" {
continue
@@ -529,7 +516,7 @@ var timeoutSettingKeys = []string{
}
func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defaultCfg *models.Settings) ([]models.SettingVariable, bool, bool, bool, bool, map[string]string, error) {
- rt := reflect.TypeOf(updates)
+ rt := reflect.TypeFor[settings.Update]()
rv := reflect.ValueOf(updates)
valuesToUpdate := make([]models.SettingVariable, 0)
@@ -543,13 +530,13 @@ func (s *SettingsService) prepareUpdateValues(updates settings.Update, cfg, defa
field := rt.Field(i)
fieldValue := rv.Field(i)
- if fieldValue.Kind() == reflect.Ptr && fieldValue.IsNil() {
+ if fieldValue.Kind() == reflect.Pointer && fieldValue.IsNil() {
continue
}
key, _, _ := strings.Cut(field.Tag.Get("json"), ",")
var value string
- if fieldValue.Kind() == reflect.Ptr {
+ if fieldValue.Kind() == reflect.Pointer {
value = fieldValue.Elem().String()
}
@@ -721,13 +708,12 @@ func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {
}
func (s *SettingsService) PersistEnvSettingsIfMissing(ctx context.Context) error {
- rt := reflect.TypeOf(models.Settings{})
+ rt := reflect.TypeFor[models.Settings]()
appCfg := config.Load()
isEnvOnlyMode := appCfg.AgentMode || appCfg.UIConfigurationDisabled
if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- for i := 0; i < rt.NumField(); i++ {
- field := rt.Field(i)
+ for field := range rt.Fields() {
if err := s.processEnvField(ctx, tx, field, isEnvOnlyMode); err != nil {
return err
}
@@ -744,9 +730,9 @@ func (s *SettingsService) PersistEnvSettingsIfMissing(ctx context.Context) error
func allowedSettingKeys() map[string]struct{} {
allowed := make(map[string]struct{})
- settingsType := reflect.TypeOf(models.Settings{})
- for i := 0; i < settingsType.NumField(); i++ {
- key, _, _ := strings.Cut(settingsType.Field(i).Tag.Get("key"), ",")
+ settingsType := reflect.TypeFor[models.Settings]()
+ for field := range settingsType.Fields() {
+ key, _, _ := strings.Cut(field.Tag.Get("key"), ",")
if key == "" {
continue
}
@@ -820,17 +806,16 @@ func (s *SettingsService) ListSettings(all bool) []models.SettingVariable {
// GetSettingType returns the type from the setting metadata
func (s *SettingsService) GetSettingType(key string) string {
- rt := reflect.TypeOf(models.Settings{})
- for i := 0; i < rt.NumField(); i++ {
- field := rt.Field(i)
+ rt := reflect.TypeFor[models.Settings]()
+ for field := range rt.Fields() {
keyTag := field.Tag.Get("key")
fieldKey, _, _ := strings.Cut(keyTag, ",")
if fieldKey == key {
metaTag := field.Tag.Get("meta")
- parts := strings.Split(metaTag, ";")
- for _, part := range parts {
- if strings.HasPrefix(part, "type=") {
- return strings.TrimPrefix(part, "type=")
+ parts := strings.SplitSeq(metaTag, ";")
+ for part := range parts {
+ if after, ok := strings.CutPrefix(part, "type="); ok {
+ return after
}
}
return "text" // default type
diff --git a/backend/internal/services/updater_service.go b/backend/internal/services/updater_service.go
index 5aeb13833..397a59870 100644
--- a/backend/internal/services/updater_service.go
+++ b/backend/internal/services/updater_service.go
@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"log/slog"
+ "slices"
"strings"
"time"
@@ -766,8 +767,8 @@ func (s *UpdaterService) normalizeRef(ref string) string {
}
func (s *UpdaterService) stripDigest(ref string) string {
- if i := strings.Index(ref, "@"); i != -1 {
- return ref[:i]
+ if before, _, ok := strings.Cut(ref, "@"); ok {
+ return before
}
return ref
}
@@ -969,8 +970,8 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldID
excludedSetting := s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", "")
excludedContainers := make(map[string]bool)
if excludedSetting != "" {
- parts := strings.Split(excludedSetting, ",")
- for _, p := range parts {
+ parts := strings.SplitSeq(excludedSetting, ",")
+ for p := range parts {
excludedContainers[strings.TrimSpace(p)] = true
}
}
@@ -1062,14 +1063,11 @@ func (s *UpdaterService) restartContainersUsingOldIDs(ctx context.Context, oldID
targetImageIDs[newRef] = tids
}
- for _, tid := range tids {
- if tid == inspect.Image {
- // Already on target image
- slog.InfoContext(ctx, "restartContainersUsingOldIDs: container already on target image; skipping restart",
- "containerId", c.ID, "containerName", dep.Name, "imageID", inspect.Image, "newRef", newRef)
- newRef = ""
- break
- }
+ if slices.Contains(tids, inspect.Image) {
+ // Already on target image
+ slog.InfoContext(ctx, "restartContainersUsingOldIDs: container already on target image; skipping restart",
+ "containerId", c.ID, "containerName", dep.Name, "imageID", inspect.Image, "newRef", newRef)
+ newRef = ""
}
}
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index 8aedfd57a..ebbe57d7c 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -1251,7 +1251,7 @@ func (s *VolumeService) BackupHasPath(ctx context.Context, backupID string, file
return false, fmt.Errorf("failed to list backup contents: %s", strings.TrimSpace(stderr))
}
- for _, line := range strings.Split(stdout, "\n") {
+ for line := range strings.SplitSeq(stdout, "\n") {
entry := strings.TrimSpace(line)
if entry == "" {
continue
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
index ac753f6e2..cf83d4344 100644
--- a/backend/internal/services/vulnerability_service.go
+++ b/backend/internal/services/vulnerability_service.go
@@ -518,7 +518,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
Key: "imageName",
Fn: func(item vulnerability.VulnerabilityWithImage, value string) bool {
itemLower := strings.ToLower(item.ImageName)
- for _, part := range strings.Split(value, ",") {
+ for part := range strings.SplitSeq(value, ",") {
if part = strings.TrimSpace(part); part != "" && strings.Contains(itemLower, strings.ToLower(part)) {
return true
}
@@ -1145,10 +1145,10 @@ func parseTrivyVersion(output string) string {
if output == "" {
return ""
}
- lines := strings.Split(output, "\n")
- for _, line := range lines {
- if strings.HasPrefix(line, "Version:") {
- return strings.TrimSpace(strings.TrimPrefix(line, "Version:"))
+ lines := strings.SplitSeq(output, "\n")
+ for line := range lines {
+ if after, ok := strings.CutPrefix(line, "Version:"); ok {
+ return strings.TrimSpace(after)
}
}
return strings.TrimSpace(output)
@@ -2089,7 +2089,7 @@ func applyIgnoredVulnerabilitiesSort(query *gorm.DB, sort string) *gorm.DB {
return query.Order("created_at DESC")
}
- for _, part := range strings.Split(sort, ",") {
+ for part := range strings.SplitSeq(sort, ",") {
part = strings.TrimSpace(part)
if part == "" {
continue
diff --git a/backend/internal/services/vulnerability_service_test.go b/backend/internal/services/vulnerability_service_test.go
index 806ad1e76..2689596c6 100644
--- a/backend/internal/services/vulnerability_service_test.go
+++ b/backend/internal/services/vulnerability_service_test.go
@@ -51,7 +51,7 @@ func TestDecodeTrivyReportFromFileInternal_LargePayload(t *testing.T) {
const vulnCount = 4000
vulns := make([]vulnerability.TrivyVulnerability, 0, vulnCount)
- for i := 0; i < vulnCount; i++ {
+ for i := range vulnCount {
vulns = append(vulns, vulnerability.TrivyVulnerability{
VulnerabilityID: fmt.Sprintf("CVE-2026-%04d", i),
PkgName: fmt.Sprintf("pkg-%d", i),
diff --git a/backend/internal/utils/arcaneupdater/sorter.go b/backend/internal/utils/arcaneupdater/sorter.go
index db110e24b..6dd27645e 100644
--- a/backend/internal/utils/arcaneupdater/sorter.go
+++ b/backend/internal/utils/arcaneupdater/sorter.go
@@ -145,7 +145,7 @@ func ExtractContainerDeps(ctx context.Context, dcli *client.Client, cnt containe
// Extract explicit depends-on from label
if inspect.Config != nil && inspect.Config.Labels != nil {
if deps, ok := inspect.Config.Labels[LabelDependsOn]; ok {
- for _, dep := range strings.Split(deps, ",") {
+ for dep := range strings.SplitSeq(deps, ",") {
dep = strings.TrimSpace(dep)
if dep != "" {
c.DependsOn = append(c.DependsOn, dep)
diff --git a/backend/internal/utils/bootstrap_util.go b/backend/internal/utils/bootstrap_util.go
index 4b32f85ca..304a57025 100644
--- a/backend/internal/utils/bootstrap_util.go
+++ b/backend/internal/utils/bootstrap_util.go
@@ -387,10 +387,7 @@ func tryConvertSecondStep(sec, min, hour, day, month, weekday string) (int, bool
}
if min == "*" && hour == "*" && day == "*" && month == "*" && weekday == "*" {
- minutes := (step + 59) / 60
- if minutes < 1 {
- minutes = 1
- }
+ minutes := max((step+59)/60, 1)
warn := ""
if step%60 != 0 {
warn = "scheduler interval rounded up to minutes"
diff --git a/backend/internal/utils/converter/converter_util.go b/backend/internal/utils/converter/converter_util.go
index d2b6d1b93..f90fd2dac 100644
--- a/backend/internal/utils/converter/converter_util.go
+++ b/backend/internal/utils/converter/converter_util.go
@@ -130,8 +130,8 @@ func parseUnknownFlag(token string, tokens []string, index int, result *models.D
}
func parseCombinedFlags(token string, result *models.DockerRunCommand) {
- flags := strings.Split(token[1:], "")
- for _, flag := range flags {
+ flags := strings.SplitSeq(token[1:], "")
+ for flag := range flags {
switch flag {
case "d":
result.Detached = true
diff --git a/backend/internal/utils/docker/cgroup_utils.go b/backend/internal/utils/docker/cgroup_utils.go
index b86c5120b..b2051e1c1 100644
--- a/backend/internal/utils/docker/cgroup_utils.go
+++ b/backend/internal/utils/docker/cgroup_utils.go
@@ -117,10 +117,7 @@ func detectCgroupV2Limits(limits *CgroupLimits) (*CgroupLimits, error) {
}
if limits.CPUQuota > 0 && limits.CPUPeriod > 0 {
- limits.CPUCount = int((limits.CPUQuota + limits.CPUPeriod - 1) / limits.CPUPeriod)
- if limits.CPUCount < 1 {
- limits.CPUCount = 1
- }
+ limits.CPUCount = max(int((limits.CPUQuota+limits.CPUPeriod-1)/limits.CPUPeriod), 1)
}
return limits, nil
@@ -153,10 +150,7 @@ func detectCgroupV1Limits(limits *CgroupLimits) (*CgroupLimits, error) {
}
if limits.CPUQuota > 0 && limits.CPUPeriod > 0 {
- limits.CPUCount = int((limits.CPUQuota + limits.CPUPeriod - 1) / limits.CPUPeriod)
- if limits.CPUCount < 1 {
- limits.CPUCount = 1
- }
+ limits.CPUCount = max(int((limits.CPUQuota+limits.CPUPeriod-1)/limits.CPUPeriod), 1)
}
return limits, nil
@@ -332,9 +326,9 @@ func getContainerIDFromMountinfo() (string, error) {
}
content := string(data)
- lines := strings.Split(content, "\n")
+ lines := strings.SplitSeq(content, "\n")
- for _, line := range lines {
+ for line := range lines {
// Look for Docker container paths in mountinfo
if strings.Contains(line, "/docker/containers/") {
parts := strings.Split(line, "/docker/containers/")
diff --git a/backend/internal/utils/edge/client_test.go b/backend/internal/utils/edge/client_test.go
index 9f865cd14..1f2653881 100644
--- a/backend/internal/utils/edge/client_test.go
+++ b/backend/internal/utils/edge/client_test.go
@@ -1,7 +1,6 @@
package edge
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -67,8 +66,7 @@ func TestTunnelClient_HandleRequest(t *testing.T) {
client := NewTunnelClient(cfg, localHandler)
client.managerURL = "ws" + strings.TrimPrefix(managerServer.URL, "http")
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
// Run client in background
go client.StartWithErrorChan(ctx, nil)
@@ -145,8 +143,7 @@ func TestTunnelClient_WebSocketProxy(t *testing.T) {
client := NewTunnelClient(cfg, http.NotFoundHandler()) // Handler ignored for WS
client.managerURL = "ws" + strings.TrimPrefix(managerServer.URL, "http")
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go client.StartWithErrorChan(ctx, nil)
time.Sleep(100 * time.Millisecond)
@@ -195,8 +192,7 @@ func TestTunnelClient_HandleRequest_Errors(t *testing.T) {
client := NewTunnelClient(cfg, http.NotFoundHandler())
client.managerURL = "ws" + strings.TrimPrefix(managerServer.URL, "http")
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go client.StartWithErrorChan(ctx, nil)
time.Sleep(100 * time.Millisecond)
diff --git a/backend/internal/utils/fs/watcher.go b/backend/internal/utils/fs/watcher.go
index 9c8f4c96a..d820a883a 100644
--- a/backend/internal/utils/fs/watcher.go
+++ b/backend/internal/utils/fs/watcher.go
@@ -10,6 +10,7 @@ import (
"time"
"github.com/fsnotify/fsnotify"
+ "github.com/getarcaneapp/arcane/backend/pkg/projects"
)
type Watcher struct {
@@ -170,7 +171,7 @@ func (fw *Watcher) shouldHandleEvent(event fsnotify.Event) bool {
// Watch for new directories, compose files, .env being manipulated.
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove) {
- if info, err := os.Stat(event.Name); err == nil && info.IsDir() || IsProjectFile(name) {
+ if info, err := os.Stat(event.Name); err == nil && info.IsDir() || projects.IsProjectFile(name) {
return true
}
}
@@ -210,26 +211,6 @@ func (fw *Watcher) addExistingDirectories(root string) error {
})
}
-// IsProjectFile checks if a filename is a common Docker Compose or environment file
-func IsProjectFile(filename string) bool {
- composeFiles := []string{
- "compose.yaml",
- "compose.yml",
- "docker-compose.yaml",
- "docker-compose.yml",
- "podman-compose.yaml",
- "podman-compose.yml",
- ".env",
- }
-
- for _, cf := range composeFiles {
- if filename == cf {
- return true
- }
- }
- return false
-}
-
func (fw *Watcher) dirDepth(path string) int {
cleanRoot := fw.watchedPath
cleanPath := filepath.Clean(path)
diff --git a/backend/internal/utils/pagination/filters.go b/backend/internal/utils/pagination/filters.go
index 69868d1bf..399667bf6 100644
--- a/backend/internal/utils/pagination/filters.go
+++ b/backend/internal/utils/pagination/filters.go
@@ -75,8 +75,8 @@ func getAccessor[T any](key string, accessors []FilterAccessor[T]) *FilterAccess
func matchValue[T any](item T, value string, accessor *FilterAccessor[T]) bool {
if strings.Contains(value, ",") {
- values := strings.Split(value, ",")
- for _, v := range values {
+ values := strings.SplitSeq(value, ",")
+ for v := range values {
v = strings.TrimSpace(v)
if accessor.Fn(item, v) {
return true
diff --git a/backend/internal/utils/pagination/reflect.go b/backend/internal/utils/pagination/reflect.go
index 631a859df..b47366df2 100644
--- a/backend/internal/utils/pagination/reflect.go
+++ b/backend/internal/utils/pagination/reflect.go
@@ -9,7 +9,7 @@ import (
"gorm.io/gorm/clause"
)
-func PaginateAndSortDB(params QueryParams, query *gorm.DB, result interface{}) (Response, error) {
+func PaginateAndSortDB(params QueryParams, query *gorm.DB, result any) (Response, error) {
sortColumn := params.Sort
sortDirection := string(params.Order)
@@ -52,7 +52,7 @@ func PaginateAndSortDB(params QueryParams, query *gorm.DB, result interface{}) (
}
// paginateDBAll returns all results without pagination limits
-func paginateDBAll(query *gorm.DB, result interface{}) (Response, error) {
+func paginateDBAll(query *gorm.DB, result any) (Response, error) {
var totalItems int64
if err := query.Count(&totalItems).Error; err != nil {
return Response{}, err
@@ -70,7 +70,7 @@ func paginateDBAll(query *gorm.DB, result interface{}) (Response, error) {
}, nil
}
-func paginateDB(page int, pageSize int, query *gorm.DB, result interface{}) (Response, error) {
+func paginateDB(page int, pageSize int, query *gorm.DB, result any) (Response, error) {
if page < 1 {
page = 1
}
diff --git a/backend/internal/utils/reflection.go b/backend/internal/utils/reflection.go
index ba6710af0..e937ac88c 100644
--- a/backend/internal/utils/reflection.go
+++ b/backend/internal/utils/reflection.go
@@ -2,6 +2,7 @@ package utils
import (
"reflect"
+ "slices"
"strings"
)
@@ -12,8 +13,8 @@ func ParseMetaTag(tag string) map[string]string {
if tag == "" {
return res
}
- parts := strings.Split(tag, ";")
- for _, p := range parts {
+ parts := strings.SplitSeq(tag, ";")
+ for p := range parts {
if p == "" {
continue
}
@@ -29,7 +30,7 @@ func ParseMetaTag(tag string) map[string]string {
func ParseKeywords(keywordsStr string) []string {
keywords := []string{}
if k := strings.TrimSpace(keywordsStr); k != "" {
- for _, kk := range strings.Split(k, ",") {
+ for kk := range strings.SplitSeq(k, ",") {
if t := strings.TrimSpace(kk); t != "" {
keywords = append(keywords, t)
}
@@ -40,13 +41,12 @@ func ParseKeywords(keywordsStr string) []string {
// ExtractCategoryMetadata extracts category metadata from struct fields with catmeta tags
// Returns a map of category ID to category metadata in field order
-func ExtractCategoryMetadata(model interface{}, categoryIDsInOrder []string) map[string]map[string]string {
+func ExtractCategoryMetadata(model any, categoryIDsInOrder []string) map[string]map[string]string {
result := make(map[string]map[string]string)
seenCategories := make(map[string]bool)
rt := reflect.TypeOf(model)
- for i := 0; i < rt.NumField(); i++ {
- field := rt.Field(i)
+ for field := range rt.Fields() {
catmetaTag := field.Tag.Get("catmeta")
if catmetaTag == "" {
continue
@@ -67,10 +67,5 @@ func ExtractCategoryMetadata(model interface{}, categoryIDsInOrder []string) map
// Contains checks if a string slice contains an item
func Contains(slice []string, item string) bool {
- for _, v := range slice {
- if v == item {
- return true
- }
- }
- return false
+ return slices.Contains(slice, item)
}
diff --git a/backend/internal/utils/registry/auth.go b/backend/internal/utils/registry/auth.go
index 27dafe054..08b754059 100644
--- a/backend/internal/utils/registry/auth.go
+++ b/backend/internal/utils/registry/auth.go
@@ -49,11 +49,11 @@ func (c *Client) ParseAuthChallenge(header string) (string, string) {
if !strings.HasPrefix(lower, "bearer ") {
return "", ""
}
- idx := strings.Index(header, " ")
- if idx == -1 {
+ _, after, ok := strings.Cut(header, " ")
+ if !ok {
return "", ""
}
- raw := header[idx+1:]
+ raw := after
parts := strings.Split(raw, ",")
var realm, service string
for _, p := range parts {
diff --git a/backend/internal/utils/remenv/remenv.go b/backend/internal/utils/remenv/remenv.go
index 6a8da5cbb..9408f1e9a 100644
--- a/backend/internal/utils/remenv/remenv.go
+++ b/backend/internal/utils/remenv/remenv.go
@@ -142,7 +142,7 @@ func BuildHopByHopHeaders(respHeader http.Header) map[string]struct{} {
hop := GetHopByHopHeaders()
for _, connVal := range respHeader.Values("Connection") {
- for _, token := range strings.Split(connVal, ",") {
+ for token := range strings.SplitSeq(connVal, ",") {
if t := strings.TrimSpace(token); t != "" {
hop[http.CanonicalHeaderKey(t)] = struct{}{}
}
diff --git a/backend/internal/utils/update_value_util.go b/backend/internal/utils/update_value_util.go
index 62612e7f1..1559d3e79 100644
--- a/backend/internal/utils/update_value_util.go
+++ b/backend/internal/utils/update_value_util.go
@@ -5,7 +5,7 @@ package utils
// Supported types: *string, *bool, **string.
// For *string and *bool targets, if the value is a pointer of the same type,
// the update only happens if the value pointer is not nil.
-func UpdateIfChanged(target interface{}, value interface{}) bool {
+func UpdateIfChanged(target any, value any) bool {
switch t := target.(type) {
case *string:
if v, ok := value.(string); ok {
diff --git a/backend/internal/utils/ws/benchmark_test.go b/backend/internal/utils/ws/benchmark_test.go
index 757fdc190..e7f4fa380 100644
--- a/backend/internal/utils/ws/benchmark_test.go
+++ b/backend/internal/utils/ws/benchmark_test.go
@@ -293,8 +293,7 @@ func BenchmarkHub_MemoryPerClient(b *testing.B) {
for _, sendBuf := range []int{16, 64, 256} {
b.Run(fmt.Sprintf("sendBuffer_%d", sendBuf), func(b *testing.B) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := b.Context()
go h.Run(ctx)
wsURL, serverCleanup := benchWSServer(b)
diff --git a/backend/internal/utils/ws/bridge_test.go b/backend/internal/utils/ws/bridge_test.go
index 519694fef..a325bbeaa 100644
--- a/backend/internal/utils/ws/bridge_test.go
+++ b/backend/internal/utils/ws/bridge_test.go
@@ -45,8 +45,7 @@ func drainClient(t *testing.T, c *Client, count int, timeout time.Duration) [][]
func TestForwardLines(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
// Register collector BEFORE starting forwarder
@@ -68,8 +67,7 @@ func TestForwardLines(t *testing.T) {
func TestForwardLines_ContextCancellation(t *testing.T) {
h := NewHub(100)
- hubCtx, hubCancel := context.WithCancel(context.Background())
- defer hubCancel()
+ hubCtx := t.Context()
go h.Run(hubCtx)
lines := make(chan string)
@@ -93,8 +91,7 @@ func TestForwardLines_ContextCancellation(t *testing.T) {
func TestForwardLogJSON(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
c := registerCollector(t, h, 256)
@@ -120,8 +117,7 @@ func TestForwardLogJSON(t *testing.T) {
func TestForwardLogJSON_FillsEmptyTimestamp(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
c := registerCollector(t, h, 256)
@@ -144,8 +140,7 @@ func TestForwardLogJSON_FillsEmptyTimestamp(t *testing.T) {
func TestForwardLogJSONBatched(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
c := registerCollector(t, h, 256)
@@ -171,8 +166,7 @@ func TestForwardLogJSONBatched(t *testing.T) {
func TestForwardLogJSONBatched_FlushesOnInterval(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
c := registerCollector(t, h, 256)
@@ -192,8 +186,7 @@ func TestForwardLogJSONBatched_FlushesOnInterval(t *testing.T) {
func TestForwardLogJSONBatched_MultipleBatches(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
c := registerCollector(t, h, 256)
@@ -221,8 +214,7 @@ func TestForwardLogJSONBatched_MultipleBatches(t *testing.T) {
func TestForwardLogJSONBatched_DelegatesToUnbatchedWhenMaxBatchOne(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
c := registerCollector(t, h, 256)
@@ -244,8 +236,7 @@ func TestForwardLogJSONBatched_DelegatesToUnbatchedWhenMaxBatchOne(t *testing.T)
func TestForwardLogJSONBatched_FlushesOnChannelClose(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
c := registerCollector(t, h, 256)
@@ -269,8 +260,7 @@ func TestForwardLogJSONBatched_FlushesOnChannelClose(t *testing.T) {
func TestForwardLogJSONBatched_FlushesOnContextCancel(t *testing.T) {
h := NewHub(100)
- hubCtx, hubCancel := context.WithCancel(context.Background())
- defer hubCancel()
+ hubCtx := t.Context()
go h.Run(hubCtx)
c := registerCollector(t, h, 256)
diff --git a/backend/internal/utils/ws/client_test.go b/backend/internal/utils/ws/client_test.go
index 7a1bdfb53..72ce4d5aa 100644
--- a/backend/internal/utils/ws/client_test.go
+++ b/backend/internal/utils/ws/client_test.go
@@ -27,8 +27,7 @@ func TestNewClient(t *testing.T) {
func TestServeClient_ReceivesBroadcast(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
// Set up a test WS server that upgrades and serves the client
@@ -71,8 +70,7 @@ func TestServeClient_ReceivesBroadcast(t *testing.T) {
func TestServeClient_ClientDisconnect(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
upgrader := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}
@@ -107,8 +105,7 @@ func TestServeClient_ClientDisconnect(t *testing.T) {
func TestServeClient_ContextCancellation(t *testing.T) {
h := NewHub(10)
- hubCtx, hubCancel := context.WithCancel(context.Background())
- defer hubCancel()
+ hubCtx := t.Context()
go h.Run(hubCtx)
clientCtx, clientCancel := context.WithCancel(context.Background())
@@ -207,8 +204,7 @@ func TestIsExpectedCloseError(t *testing.T) {
func TestServeClient_MultipleMessages(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
serverReady := make(chan struct{})
diff --git a/backend/internal/utils/ws/cpu_regression_test.go b/backend/internal/utils/ws/cpu_regression_test.go
index 1906d7b3f..c5467c409 100644
--- a/backend/internal/utils/ws/cpu_regression_test.go
+++ b/backend/internal/utils/ws/cpu_regression_test.go
@@ -18,7 +18,7 @@ import (
// startStatsHubPipeline starts the stats producer and JSON broadcaster goroutines
// for benchmarks/tests that need a container-stats-style hub. Caller must run hub.Run and ServeClient.
func startStatsHubPipeline(ctx context.Context, hub *Hub) {
- statsChan := make(chan interface{}, 64)
+ statsChan := make(chan any, 64)
go func() {
defer close(statsChan)
ticker := time.NewTicker(100 * time.Millisecond)
diff --git a/backend/internal/utils/ws/goroutine_leak_test.go b/backend/internal/utils/ws/goroutine_leak_test.go
index c957620fc..8ad0f61fa 100644
--- a/backend/internal/utils/ws/goroutine_leak_test.go
+++ b/backend/internal/utils/ws/goroutine_leak_test.go
@@ -35,8 +35,8 @@ func countWsWorkerGoroutines() int {
n := runtime.Stack(buf, true)
s := string(buf[:n])
count := 0
- blocks := strings.Split(s, "\n\n")
- for _, block := range blocks {
+ blocks := strings.SplitSeq(s, "\n\n")
+ for block := range blocks {
if block == "" || !strings.Contains(block, pkgPath) {
continue
}
@@ -425,7 +425,7 @@ func TestLeak_HubWithForwardLogJSONBatchedLifecycle(t *testing.T) {
// startStatsHubForTest starts Hub.Run plus stats producer and JSON broadcaster;
// caller must call ServeClient(ctx, hub, conn). Used by container-stats leak tests.
func startStatsHubForTest(ctx context.Context, hub *Hub) {
- statsChan := make(chan interface{}, 64)
+ statsChan := make(chan any, 64)
go func() {
defer close(statsChan)
ticker := time.NewTicker(100 * time.Millisecond)
@@ -438,7 +438,7 @@ func startStatsHubForTest(ctx context.Context, hub *Hub) {
select {
case <-ctx.Done():
return
- case statsChan <- map[string]interface{}{"cpu_percent": 12.5, "memory": 1024000}:
+ case statsChan <- map[string]any{"cpu_percent": 12.5, "memory": 1024000}:
default:
}
}
@@ -463,7 +463,7 @@ func startStatsHubForTest(ctx context.Context, hub *Hub) {
// startStatsHubRepeatedTest starts stats producer + broadcaster with 50ms ticker (for repeated cycles test).
func startStatsHubRepeatedTest(ctx context.Context, hub *Hub) {
- statsChan := make(chan interface{}, 64)
+ statsChan := make(chan any, 64)
go func() {
defer close(statsChan)
ticker := time.NewTicker(50 * time.Millisecond)
@@ -528,7 +528,7 @@ func TestLeak_ContainerStatsHubPattern(t *testing.T) {
_ = clientConn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, raw, err := clientConn.ReadMessage()
require.NoError(t, err)
- var stats map[string]interface{}
+ var stats map[string]any
require.NoError(t, json.Unmarshal(raw, &stats))
clientConn.Close()
diff --git a/backend/internal/utils/ws/hub_test.go b/backend/internal/utils/ws/hub_test.go
index 4f4732fcd..0d1132240 100644
--- a/backend/internal/utils/ws/hub_test.go
+++ b/backend/internal/utils/ws/hub_test.go
@@ -53,8 +53,7 @@ func TestNewHub(t *testing.T) {
func TestHub_RegisterAndClientCount(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
_, serverConn, cleanup := newTestWSPair(t)
@@ -71,8 +70,7 @@ func TestHub_RegisterAndClientCount(t *testing.T) {
func TestHub_UnregisterClient(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
_, serverConn, cleanup := newTestWSPair(t)
@@ -94,8 +92,7 @@ func TestHub_UnregisterClient(t *testing.T) {
func TestHub_Broadcast(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
_, serverConn, cleanup := newTestWSPair(t)
@@ -122,8 +119,7 @@ func TestHub_Broadcast(t *testing.T) {
func TestHub_BroadcastToMultipleClients(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
const numClients = 5
@@ -161,8 +157,7 @@ func TestHub_BroadcastToMultipleClients(t *testing.T) {
func TestHub_BackpressureDropsSlowClient(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
// Create a client with a tiny send buffer so it fills up fast
@@ -189,8 +184,7 @@ func TestHub_BackpressureDropsSlowClient(t *testing.T) {
func TestHub_OnEmptyCallback(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
var called atomic.Bool
@@ -215,8 +209,7 @@ func TestHub_OnEmptyCallback(t *testing.T) {
func TestHub_OnEmptyCalledOnlyOnce(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
var callCount atomic.Int32
@@ -291,8 +284,7 @@ func TestHub_ContextCancellation(t *testing.T) {
func TestHub_BroadcastBufferFull(t *testing.T) {
// Hub with a buffer of 1
h := NewHub(1)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
// Don't run the hub — the broadcast channel will fill up
h.broadcast <- []byte("fill")
@@ -306,8 +298,7 @@ func TestHub_BroadcastBufferFull(t *testing.T) {
func TestHub_ConcurrentOperations(t *testing.T) {
h := NewHub(100)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
const goroutines = 10
@@ -348,8 +339,7 @@ func TestHub_ConcurrentOperations(t *testing.T) {
func TestHub_DoubleUnregister(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
+ ctx := t.Context()
go h.Run(ctx)
_, serverConn, cleanup := newTestWSPair(t)
diff --git a/backend/pkg/projects/custom_labels.go b/backend/pkg/projects/custom_labels.go
index e20cdb4ee..bc7b93797 100644
--- a/backend/pkg/projects/custom_labels.go
+++ b/backend/pkg/projects/custom_labels.go
@@ -4,6 +4,7 @@ package projects
import (
"context"
"fmt"
+ "maps"
"os"
"path/filepath"
"strings"
@@ -196,9 +197,7 @@ func loadComposeEnvironment(workdir string) map[string]string {
func mergeEnvFromDotEnv(envMap map[string]string, workdir string) map[string]string {
merged := make(map[string]string, len(envMap)+1)
- for k, v := range envMap {
- merged[k] = v
- }
+ maps.Copy(merged, envMap)
if workdir == "" {
return merged
}
@@ -245,7 +244,7 @@ func parseIncludePaths(composeFilePath string) ([]string, error) {
return nil, fmt.Errorf("read compose file: %w", err)
}
- composeData := map[string]interface{}{}
+ composeData := map[string]any{}
if err := yaml.Unmarshal(content, &composeData); err != nil {
return nil, fmt.Errorf("parse compose file: %w", err)
}
@@ -274,7 +273,7 @@ func parseIncludePaths(composeFilePath string) ([]string, error) {
switch v := item.(type) {
case string:
paths = append(paths, v)
- case map[string]interface{}:
+ case map[string]any:
if p, ok := v["path"]; ok {
switch pathValue := p.(type) {
case string:
diff --git a/backend/pkg/projects/includes.go b/backend/pkg/projects/includes.go
index b5846126e..2f1373076 100644
--- a/backend/pkg/projects/includes.go
+++ b/backend/pkg/projects/includes.go
@@ -30,7 +30,7 @@ func ParseIncludes(composeFilePath string) ([]IncludeFile, error) {
return nil, fmt.Errorf("failed to read compose file: %w", err)
}
- var composeData map[string]interface{}
+ var composeData map[string]any
if err := yaml.Unmarshal(content, &composeData); err != nil {
return nil, fmt.Errorf("failed to parse compose file: %w", err)
}
@@ -45,7 +45,7 @@ func ParseIncludes(composeFilePath string) ([]IncludeFile, error) {
var includeFiles []IncludeFile
switch v := includes.(type) {
- case []interface{}:
+ case []any:
for _, item := range v {
if include, err := parseIncludeItem(item, composeDir); err == nil {
includeFiles = append(includeFiles, include)
@@ -60,13 +60,13 @@ func ParseIncludes(composeFilePath string) ([]IncludeFile, error) {
return includeFiles, nil
}
-func parseIncludeItem(item interface{}, baseDir string) (IncludeFile, error) {
+func parseIncludeItem(item any, baseDir string) (IncludeFile, error) {
var includePath string
switch v := item.(type) {
case string:
includePath = v
- case map[string]interface{}:
+ case map[string]any:
if path, ok := v["path"].(string); ok {
includePath = path
}
diff --git a/backend/pkg/projects/load.go b/backend/pkg/projects/load.go
index ffbb7511e..7c2cd84d6 100644
--- a/backend/pkg/projects/load.go
+++ b/backend/pkg/projects/load.go
@@ -4,8 +4,10 @@ import (
"context"
"fmt"
"log/slog"
+ "maps"
"os"
"path/filepath"
+ "slices"
"github.com/compose-spec/compose-go/v2/loader"
composetypes "github.com/compose-spec/compose-go/v2/types"
@@ -13,17 +15,26 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/utils/pathmapper"
)
-var ComposeFileCandidates = []string{
+var ProjectFileCandidates = []string{
"compose.yaml",
"compose.yml",
"docker-compose.yaml",
"docker-compose.yml",
"podman-compose.yaml",
"podman-compose.yml",
+ ".env",
+}
+
+// IsProjectFile reports whether filename is a Compose file or an environment file.
+func IsProjectFile(filename string) bool {
+ return slices.Contains(ProjectFileCandidates, filename)
}
func locateComposeFile(dir string) string {
- for _, filename := range ComposeFileCandidates {
+ for _, filename := range ProjectFileCandidates {
+ if filename == ".env" {
+ continue
+ }
fullPath := filepath.Join(dir, filename)
if info, err := os.Stat(fullPath); err == nil && !info.IsDir() {
return fullPath
@@ -69,9 +80,7 @@ func loadComposeProjectInternal(
slog.WarnContext(ctx, "Failed to load environment", "error", err)
}
- for k, v := range envOverride {
- fullEnvMap[k] = v
- }
+ maps.Copy(fullEnvMap, envOverride)
// Set PWD
if absWorkdir, absErr := filepath.Abs(workdir); absErr == nil {
diff --git a/backend/pkg/scheduler/scheduler_test.go b/backend/pkg/scheduler/scheduler_test.go
index cb3d1b069..1b40232dd 100644
--- a/backend/pkg/scheduler/scheduler_test.go
+++ b/backend/pkg/scheduler/scheduler_test.go
@@ -30,8 +30,7 @@ func TestJobScheduler_RescheduleJob_UsesProvidedContext(t *testing.T) {
var once sync.Once
runErrCh := make(chan error, 1)
- runCtx, cancelRunCtx := context.WithCancel(context.Background())
- defer cancelRunCtx()
+ runCtx := t.Context()
job := &testSchedulerJob{
name: "test-reschedule-provided-context",
diff --git a/backend/pkg/utils/auth.go b/backend/pkg/utils/auth.go
new file mode 100644
index 000000000..e82a69c96
--- /dev/null
+++ b/backend/pkg/utils/auth.go
@@ -0,0 +1,8 @@
+package utils
+
+import "slices"
+
+// UserHasRole reports whether the user's roles contains the given role.
+func UserHasRole(roles []string, role string) bool {
+ return slices.Contains(roles, role)
+}