Skip to content

Modern Docker Management, Designed for Everyone

feat: chunked upload sessions for large-file endpoints (#3595)

Kyle Mendell380fe2e19880
diff --git a/backend/api/api.go b/backend/api/api.go
index a31a62a6f..c0b6e2679 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -51,6 +51,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/system"
"github.com/getarcaneapp/arcane/backend/v2/internal/updater"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/internal/volume"
"github.com/getarcaneapp/arcane/backend/v2/internal/webhook"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
@@ -253,6 +254,7 @@ type HandlerDeps struct {
Dashboard *dashboard.Module
Role *role.Module
Variable *variable.Module
+ Upload *upload.Module
}
// SetupAPI creates and configures the Huma API attached to the Echo router.
@@ -413,7 +415,8 @@ func registerHandlersInternal(api huma.API, deps HandlerDeps, handlerAppCtx hand
deps.Template.RegisterRoutes(api)
deps.Variable.RegisterRoutes(api, cfg)
deps.Image.RegisterRoutes(api, handlerAppCtx)
- build.RegisterBuildWorkspaces(api, deps.BuildWorkspace)
+ deps.Upload.RegisterRoutes(api)
+ build.RegisterBuildWorkspaces(api, deps.BuildWorkspace, deps.Upload.Service())
deps.ImageUpdate.RegisterRoutes(api, handlerAppCtx)
deps.Settings.RegisterRoutes(api)
deps.JobSchedule.RegisterRoutes(api)
diff --git a/backend/api/api_test.go b/backend/api/api_test.go
index ad199c786..c64ea223c 100644
--- a/backend/api/api_test.go
+++ b/backend/api/api_test.go
@@ -410,6 +410,13 @@ func TestEnvScopedOperationsDeclarePermission(t *testing.T) {
if !strings.HasPrefix(path, "/environments/{id}/") {
continue
}
+ // Upload-session routes derive their permission from the {kind} path
+ // segment at request time (authz.UploadKindPermission); both the local
+ // handlers and the proxy's uploadSessionKindInternal special case
+ // enforce it, so no static mapping exists to declare here.
+ if strings.HasPrefix(path, "/environments/{id}/uploads/{kind}") {
+ continue
+ }
for method, op := range envScopedTestOperationsInternal(item) {
if op == nil {
continue
diff --git a/backend/go.mod b/backend/go.mod
index fb59d7b4b..8dce5830f 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -56,7 +56,7 @@ require (
github.com/stretchr/testify v1.11.1
github.com/subosito/gotenv v1.6.0
github.com/wneessen/go-mail v0.8.1
- go.getarcane.app/acfs v0.3.0
+ go.getarcane.app/acfs v0.4.0
go.getarcane.app/builds v0.3.0
go.getarcane.app/docker/convert v0.1.0
go.getarcane.app/streams v0.3.1
diff --git a/backend/go.sum b/backend/go.sum
index 6c5e66347..94cea4da4 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -758,6 +758,8 @@ github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
go.getarcane.app/acfs v0.3.0 h1:UsYo1tbjU6wjv1vpIwPpz4+wyXCmL+v3maUwJz2MlpU=
go.getarcane.app/acfs v0.3.0/go.mod h1:sU3t21KctTsQM3OW10+RNB0Z6lR+YfaSr5Nxubq3cpI=
+go.getarcane.app/acfs v0.4.0 h1:vJo+NbVYGk2hJimejFRHhkHUdQ3ob0wzuPLXG4XXW+o=
+go.getarcane.app/acfs v0.4.0/go.mod h1:sU3t21KctTsQM3OW10+RNB0Z6lR+YfaSr5Nxubq3cpI=
go.getarcane.app/builds v0.3.0 h1:6fCgHy6PaEr3LpCtiF1iCdT4nuV3D3xvUHnV+E/0cqk=
go.getarcane.app/builds v0.3.0/go.mod h1:yZJDSh9XX/sgZlwx7lghHEucgZeQ74Gr/Fx+XdR2bdk=
go.getarcane.app/docker/convert v0.1.0 h1:prlIOs6dMx6CdnetsJFZ6ak0vcistM3DcH5lrZiFHBU=
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 4e2113da9..2fb328a90 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -90,6 +90,7 @@ type registerJobsParams struct {
VulnerabilityScan *scheduler.VulnerabilityScanJob
AutoHeal *scheduler.AutoHealJob
ActivitySweep *scheduler.ActivitySweepJob
+ UploadSessionsCleanup *scheduler.UploadSessionsCleanupJob
}
func registerJobs(params registerJobsParams) error {
@@ -130,6 +131,7 @@ func registerJobs(params registerJobsParams) error {
params.VulnerabilityScan,
params.AutoHeal,
params.ActivitySweep,
+ params.UploadSessionsCleanup,
} {
if err := params.Scheduler.RegisterJob(job); err != nil {
return err
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index 9bee21641..e0eca1d12 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -56,6 +56,8 @@ var loggerSkipPatterns = []string{
// Static branding / PWA assets — browsers re-request these frequently
// and the logs add no signal.
"GET /api/app-images/*",
+ // Chunked uploads: a large file logs one line per chunk otherwise.
+ "PUT /api/environments/*/uploads/*/*/chunks/*",
}
func shouldLogRequestInternal(c *echo.Context, _ error) bool {
diff --git a/backend/internal/build/workspace_handler.go b/backend/internal/build/workspace_handler.go
index 1f6c3a9c1..af8b4e373 100644
--- a/backend/internal/build/workspace_handler.go
+++ b/backend/internal/build/workspace_handler.go
@@ -3,25 +3,27 @@ package build
import (
"context"
"io"
- "mime/multipart"
"path"
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
"github.com/getarcaneapp/arcane/types/v2/base"
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"
)
// BuildWorkspaceHandler provides file browsing endpoints for manual build workspaces.
type BuildWorkspaceHandler struct {
- service *BuildWorkspaceService
+ service *BuildWorkspaceService
+ uploadService *upload.UploadService
}
// RegisterBuildWorkspaces registers build workspace file browser routes.
-func RegisterBuildWorkspaces(api huma.API, workspaceService *BuildWorkspaceService) {
- h := &BuildWorkspaceHandler{service: workspaceService}
+func RegisterBuildWorkspaces(api huma.API, workspaceService *BuildWorkspaceService, uploadService *upload.UploadService) {
+ h := &BuildWorkspaceHandler{service: workspaceService, uploadService: uploadService}
middleware.RegisterWithPermission(api, huma.Operation{
OperationID: "builds-browse",
@@ -58,26 +60,10 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *BuildWorkspaceServi
Method: "POST",
Path: "/environments/{id}/builds/browse/upload",
Summary: "Upload build workspace file",
- Description: "Upload a file into the builds workspace root",
+ Description: "Copy a complete chunked upload session into the builds workspace root. multipart/form-data bodies are still accepted for backward compatibility; that form is deprecated and will be removed in a future release.",
Tags: []string{"Builds"},
Security: handlerutil.DefaultOperationSecurity(),
- RequestBody: &huma.RequestBody{
- Content: map[string]*huma.MediaType{
- "multipart/form-data": {
- Schema: &huma.Schema{
- Type: "object",
- Properties: map[string]*huma.Schema{
- "file": {
- Type: "string",
- Format: "binary",
- Description: "File to upload",
- },
- },
- Required: []string{"file"},
- },
- },
- },
- },
+ Middlewares: upload.LegacyMultipartMiddleware(api, uploadService, uploadtypes.KindBuildWorkspace),
}, authz.PermBuildWorkspacesManage, h.UploadFile)
middleware.RegisterWithPermission(api, huma.Operation{
@@ -138,9 +124,9 @@ type DownloadBuildFileOutput struct {
}
type UploadBuildFileInput struct {
- EnvironmentID string `path:"id" doc:"Environment ID"`
- Path string `query:"path" default:"/" doc:"Destination path"`
- RawBody multipart.Form `contentType:"multipart/form-data"`
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Path string `query:"path" default:"/" doc:"Destination path"`
+ Body uploadtypes.ConsumeRequest
}
type CreateBuildDirectoryInput struct {
@@ -186,13 +172,16 @@ func (h *BuildWorkspaceHandler) DownloadFile(ctx context.Context, input *Downloa
}
func (h *BuildWorkspaceHandler) UploadFile(ctx context.Context, input *UploadBuildFileInput) (*base.ApiResponse[base.MessageResponse], error) {
- file, fileHeader, err := handlerutil.OpenUploadedFile(input.RawBody)
+ file, session, cleanup, err := h.uploadService.Consume(ctx, uploadtypes.KindBuildWorkspace, input.Body.UploadID)
if err != nil {
- return nil, err
+ if httpErr := upload.SessionHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
+ return nil, huma.Error500InternalServerError(err.Error())
}
- defer func() { _ = file.Close() }()
+ defer cleanup()
- if err := h.service.UploadFile(ctx, input.Path, file, fileHeader.Filename, fileHeader.Size); err != nil {
+ if err := h.service.UploadFile(ctx, input.Path, file, session.Filename, session.Size); err != nil {
return nil, huma.Error500InternalServerError(err.Error())
}
return &base.ApiResponse[base.MessageResponse]{
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 4da5be656..4dde67cd2 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -106,4 +106,9 @@ var (
ErrInvalidNotificationPayloadTemplate = Classify(ErrValidation, errors.Sentinel("invalid generic webhook payload template"))
ErrRedeployAfterSyncFailed = errors.Sentinel("redeploy failed")
ErrGitOpsSyncProjectBindingBroken = errors.Sentinel("GitOps sync project binding broken")
+ ErrUploadSessionNotFound = Classify(ErrNotFound, errors.Sentinel("Upload session not found"))
+ ErrUploadSessionIncomplete = Classify(ErrConflict, errors.Sentinel("Upload session is incomplete"))
+ ErrUploadKindMismatch = Classify(ErrBadRequest, errors.Sentinel("Upload session kind does not match this endpoint"))
+ ErrUploadChunkInvalid = Classify(ErrValidation, errors.Sentinel("Invalid upload chunk"))
+ ErrUploadSessionInvalid = Classify(ErrValidation, errors.Sentinel("Invalid upload session request"))
)
diff --git a/backend/internal/di/di.go b/backend/internal/di/di.go
index 5b81170b2..84e8dfeab 100644
--- a/backend/internal/di/di.go
+++ b/backend/internal/di/di.go
@@ -22,6 +22,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/session"
"github.com/getarcaneapp/arcane/backend/v2/internal/swarm"
"github.com/getarcaneapp/arcane/backend/v2/internal/system"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/internal/variable"
"github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"
"github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler"
@@ -92,6 +93,8 @@ var ServiceOptions = fx.Options(
provideWebhookModuleInternal,
variable.NewVariableService,
variable.New,
+ upload.NewUploadService,
+ upload.New,
// Adapters for scalar config fields, unexported parameters, builders, and lifecycle hooks.
provideVersionServiceInternal,
@@ -128,5 +131,6 @@ var JobOptions = fx.Options(
scheduler.NewVulnerabilityScanJob,
scheduler.NewAutoHealJob,
scheduler.NewActivitySweepJob,
+ scheduler.NewUploadSessionsCleanupJob,
),
)
diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.go
index da551fae6..a4a081b7f 100644
--- a/backend/internal/di/providers.go
+++ b/backend/internal/di/providers.go
@@ -44,6 +44,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/system"
"github.com/getarcaneapp/arcane/backend/v2/internal/updater"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/internal/volume"
"github.com/getarcaneapp/arcane/backend/v2/internal/webhook"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"
@@ -106,13 +107,14 @@ func provideImageUpdateModuleInternal(service *imageupdate.ImageUpdateService, i
})
}
-func provideImageModuleInternal(service *image.ImageService, dockerService *docker.DockerClientService, imageUpdate *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, buildService *build.BuildService, activityService *activity.ActivityService) *image.Module {
+func provideImageModuleInternal(service *image.ImageService, dockerService *docker.DockerClientService, imageUpdate *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, buildService *build.BuildService, activityService *activity.ActivityService, uploadService *upload.UploadService) *image.Module {
return image.New(service, image.Dependencies{
Docker: dockerService,
ImageUpdate: imageUpdate,
Settings: settingsService,
Build: buildService,
Activity: activityService,
+ Upload: uploadService,
})
}
@@ -210,7 +212,7 @@ func provideGitRepositoryServiceInternal(module *gitrepo.Module) *gitrepo.GitRep
return module.Service()
}
-func provideVolumeModuleInternal(lc fx.Lifecycle, db *database.DB, docker *docker.DockerClientService, event *event.EventService, settings *settings.SettingsService, image *image.ImageService, activity *activity.ActivityService, cfg *config.Config) *volume.Module {
+func provideVolumeModuleInternal(lc fx.Lifecycle, db *database.DB, docker *docker.DockerClientService, event *event.EventService, settings *settings.SettingsService, image *image.ImageService, activity *activity.ActivityService, cfg *config.Config, uploadService *upload.UploadService) *volume.Module {
module := volume.New(volume.Dependencies{
DB: db,
Docker: docker,
@@ -219,6 +221,7 @@ func provideVolumeModuleInternal(lc fx.Lifecycle, db *database.DB, docker *docke
Image: image,
Activity: activity,
Config: cfg,
+ Upload: uploadService,
})
lc.Append(fx.Hook{
OnStop: func(ctx context.Context) error {
diff --git a/backend/internal/image/handler.go b/backend/internal/image/handler.go
index e4ea47112..7f658d939 100644
--- a/backend/internal/image/handler.go
+++ b/backend/internal/image/handler.go
@@ -5,7 +5,6 @@ import (
stderrors "errors"
"fmt"
"io"
- "mime/multipart"
"net/http"
"net/url"
"strings"
@@ -20,6 +19,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
@@ -28,6 +28,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/image"
"github.com/getarcaneapp/arcane/types/v2/system"
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
buildtypes "go.getarcane.app/builds/types"
"gorm.io/gorm"
)
@@ -40,6 +41,7 @@ type ImageHandler struct {
settingsService *settings.SettingsService
buildService *build.BuildService
activityService *activity.ActivityService
+ uploadService *upload.UploadService
appCtx context.Context
}
@@ -182,8 +184,8 @@ type GetImageUsageCountsOutput struct {
}
type UploadImageInput struct {
- EnvironmentID string `path:"id" doc:"Environment ID"`
- RawBody multipart.Form `contentType:"multipart/form-data"`
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body uploadtypes.ConsumeRequest
}
type UploadImageOutput struct {
@@ -191,7 +193,7 @@ type UploadImageOutput struct {
}
// RegisterImages registers image management routes using Huma.
-func RegisterImages(api huma.API, dockerService *docker.DockerClientService, imageService *ImageService, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, buildService *build.BuildService, activityService *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
+func RegisterImages(api huma.API, dockerService *docker.DockerClientService, imageService *ImageService, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, buildService *build.BuildService, activityService *activity.ActivityService, uploadService *upload.UploadService, appCtx handlerutil.ActivityAppContext) {
h := &ImageHandler{
dockerService: dockerService,
imageService: imageService,
@@ -199,6 +201,7 @@ func RegisterImages(api huma.API, dockerService *docker.DockerClientService, ima
settingsService: settingsService,
buildService: buildService,
activityService: activityService,
+ uploadService: uploadService,
appCtx: appCtx.Context(),
}
@@ -347,26 +350,10 @@ func RegisterImages(api huma.API, dockerService *docker.DockerClientService, ima
Method: http.MethodPost,
Path: "/environments/{id}/images/upload",
Summary: "Upload an image",
- Description: "Upload a Docker image from a tar archive",
+ Description: "Load a Docker image tar archive from a complete chunked upload session. multipart/form-data bodies are still accepted for backward compatibility; that form is deprecated and will be removed in a future release.",
Tags: []string{"Images"},
Security: handlerutil.DefaultOperationSecurity(),
- RequestBody: &huma.RequestBody{
- Content: map[string]*huma.MediaType{
- "multipart/form-data": {
- Schema: &huma.Schema{
- Type: "object",
- Properties: map[string]*huma.Schema{
- "file": {
- Type: "string",
- Format: "binary",
- Description: "Docker image tar archive",
- },
- },
- Required: []string{"file"},
- },
- },
- },
- },
+ Middlewares: upload.LegacyMultipartMiddleware(api, h.uploadService, uploadtypes.KindImage),
}, authz.PermImagesUpload, h.UploadImage)
}
@@ -883,39 +870,19 @@ func (h *ImageHandler) UploadImage(ctx context.Context, input *UploadImageInput)
return nil, err
}
- // Get file from multipart form
- files := input.RawBody.File["file"]
- if len(files) == 0 {
- return nil, huma.Error400BadRequest("No file uploaded")
- }
-
- fileHeader := files[0]
- fileName := fileHeader.Filename
-
- // Validate file extension
- lowerName := strings.ToLower(fileName)
- if !strings.HasSuffix(lowerName, ".tar") && !strings.HasSuffix(lowerName, ".tar.gz") && !strings.HasSuffix(lowerName, ".tgz") && !strings.HasSuffix(lowerName, ".tar.xz") {
- return nil, huma.Error400BadRequest("Invalid file format. Only Docker image tar archives are allowed (.tar, .tar.gz, .tgz, .tar.xz)")
+ file, session, cleanup, err := h.uploadService.Consume(ctx, uploadtypes.KindImage, input.Body.UploadID)
+ if err != nil {
+ if httpErr := upload.SessionHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to open upload").Error())
}
+ defer cleanup()
- // Get max upload size from settings
maxSizeMB := h.settingsService.GetIntSetting(ctx, "maxImageUploadSize", 500)
maxSizeBytes := int64(maxSizeMB) * 1024 * 1024
- // Check file size
- if fileHeader.Size > maxSizeBytes {
- return nil, huma.NewError(http.StatusRequestEntityTooLarge, fmt.Sprintf("file size exceeds maximum allowed size of %d MB", maxSizeMB))
- }
-
- // Open the file
- file, err := fileHeader.Open()
- if err != nil {
- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to read upload").Error())
- }
- defer func() { _ = file.Close() }()
-
- // Load the image
- result, err := h.imageService.LoadImageFromReader(ctx, file, fileName, *user, maxSizeBytes)
+ result, err := h.imageService.LoadImageFromReader(ctx, file, session.Filename, *user, maxSizeBytes)
if err != nil {
return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to load image").Error())
}
diff --git a/backend/internal/image/module.go b/backend/internal/image/module.go
index 93b50efe0..abc081dca 100644
--- a/backend/internal/image/module.go
+++ b/backend/internal/image/module.go
@@ -9,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/docker"
"github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"
"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
)
@@ -18,6 +19,7 @@ type Dependencies struct {
Settings *settings.SettingsService
Build *build.BuildService
Activity *activity.ActivityService
+ Upload *upload.UploadService
}
type Module struct {
@@ -38,8 +40,8 @@ func (m *Module) Service() *ImageService {
func (m *Module) RegisterRoutes(api huma.API, appCtx handlerutil.ActivityAppContext) {
if m == nil {
- RegisterImages(api, nil, nil, nil, nil, nil, nil, appCtx)
+ RegisterImages(api, nil, nil, nil, nil, nil, nil, nil, appCtx)
return
}
- RegisterImages(api, m.deps.Docker, m.service, m.deps.ImageUpdate, m.deps.Settings, m.deps.Build, m.deps.Activity, appCtx)
+ RegisterImages(api, m.deps.Docker, m.service, m.deps.ImageUpdate, m.deps.Settings, m.deps.Build, m.deps.Activity, m.deps.Upload, appCtx)
}
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index 73209dcdb..ee3b5bd9e 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -225,6 +225,18 @@ func (m *EnvironmentMiddleware) proxyPermissionDenied(c *echo.Context, ps *authz
method := c.Request().Method
suffix := m.buildResourceSuffix(c.Request().URL.Path, envID)
+ if kind, ok := uploadSessionKindInternal(method, suffix); ok {
+ // Upload-session routes derive their permission from the {kind} path
+ // segment, so they carry no static mapping in the matcher; resolve the
+ // kind here and fail closed on unknown kinds.
+ perm, known := authz.UploadKindPermission(kind)
+ if !known || !ps.Allows(perm, envID) {
+ slog.DebugContext(c.Request().Context(), "Denying proxied upload session request: permission denied",
+ "method", method, "path", suffix, "kind", kind, "environment_id", envID)
+ return true
+ }
+ return false
+ }
perm, ok := m.matcher.Lookup(method, suffix).Get()
if !ok {
slog.WarnContext(c.Request().Context(), "Denying proxied request with no known permission mapping",
@@ -264,6 +276,25 @@ func (m *EnvironmentMiddleware) proxyPermissionDenied(c *echo.Context, ps *authz
return false
}
+// uploadSessionKindInternal extracts the upload kind from the exact
+// upload-session route shapes: POST /uploads/{kind}, GET or DELETE
+// /uploads/{kind}/{uploadId}, and PUT /uploads/{kind}/{uploadId}/chunks/{n}.
+func uploadSessionKindInternal(method, suffix string) (string, bool) {
+ segments := strings.Split(strings.Trim(suffix, "/"), "/")
+ if len(segments) < 2 || segments[0] != "uploads" || segments[1] == "" {
+ return "", false
+ }
+ switch {
+ case len(segments) == 2 && method == http.MethodPost:
+ return segments[1], true
+ case len(segments) == 3 && (method == http.MethodGet || method == http.MethodDelete):
+ return segments[1], true
+ case len(segments) == 5 && method == http.MethodPut && segments[3] == "chunks":
+ return segments[1], true
+ }
+ return "", false
+}
+
func isVolumeWorkspaceUpdateRequestInternal(method, suffix string) bool {
if method != http.MethodPut {
return false
diff --git a/backend/internal/upload/handler.go b/backend/internal/upload/handler.go
new file mode 100644
index 000000000..5de15dc0e
--- /dev/null
+++ b/backend/internal/upload/handler.go
@@ -0,0 +1,280 @@
+package upload
+
+import (
+ "bytes"
+ "context"
+ "encoding/json/v2"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "strings"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"
+ "github.com/getarcaneapp/arcane/types/v2/base"
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
+)
+
+// UploadHandler provides the Huma-based chunked upload-session endpoints.
+type UploadHandler struct {
+ uploadService *UploadService
+}
+
+// --- Huma Input/Output Wrappers ---
+
+type CreateUploadSessionInput struct {
+ EnvironmentID string `path:"id"`
+ Kind string `path:"kind" enum:"image,volume-backup,build-workspace"`
+ Body uploadtypes.CreateSessionRequest
+}
+
+type UploadChunkInput struct {
+ EnvironmentID string `path:"id"`
+ Kind string `path:"kind" enum:"image,volume-backup,build-workspace"`
+ UploadID string `path:"uploadId"`
+ Index int `path:"index"`
+ RawBody []byte `contentType:"application/octet-stream"`
+}
+
+type GetUploadSessionInput struct {
+ EnvironmentID string `path:"id"`
+ Kind string `path:"kind" enum:"image,volume-backup,build-workspace"`
+ UploadID string `path:"uploadId"`
+}
+
+type DeleteUploadSessionInput struct {
+ EnvironmentID string `path:"id"`
+ Kind string `path:"kind" enum:"image,volume-backup,build-workspace"`
+ UploadID string `path:"uploadId"`
+}
+
+type UploadSessionOutput struct {
+ Body base.ApiResponse[uploadtypes.Session]
+}
+
+type DeleteUploadSessionOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// SessionHTTPError maps upload-session errors to HTTP errors for this package
+// and the domain endpoints that consume sessions. It returns nil for errors
+// that are not upload-session errors.
+func SessionHTTPError(err error) error {
+ switch {
+ case errors.Is(err, common.ErrUploadSessionNotFound):
+ return huma.Error404NotFound(err.Error())
+ case errors.Is(err, common.ErrUploadSessionIncomplete):
+ return huma.Error409Conflict(err.Error())
+ case errors.Is(err, common.ErrUploadKindMismatch):
+ return huma.Error400BadRequest(err.Error())
+ case errors.Is(err, common.ErrUploadChunkInvalid), errors.Is(err, common.ErrUploadSessionInvalid):
+ return huma.Error422UnprocessableEntity(err.Error())
+ }
+ return nil
+}
+
+// requireUploadPermissionInternal enforces the kind-derived permission for the
+// target environment. Registration cannot use middleware.RegisterWithPermission
+// because the required permission depends on the {kind} path parameter; the
+// manager-side proxy applies the same mapping for remote environments.
+func requireUploadPermissionInternal(ctx context.Context, kind, environmentID string) error {
+ perm, known := authz.UploadKindPermission(kind)
+ if !known {
+ return huma.Error403Forbidden("permission denied: unknown upload kind " + kind)
+ }
+ ps, _ := middleware.PermissionsFromContext(ctx)
+ if !ps.Allows(perm, environmentID) {
+ return huma.Error403Forbidden("permission denied: " + perm)
+ }
+ return nil
+}
+
+func sessionResponseInternal(session *uploadtypes.Session) *UploadSessionOutput {
+ return &UploadSessionOutput{
+ Body: base.ApiResponse[uploadtypes.Session]{
+ Success: true,
+ Data: *session,
+ },
+ }
+}
+
+func (h *UploadHandler) CreateSession(ctx context.Context, input *CreateUploadSessionInput) (*UploadSessionOutput, error) {
+ if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
+ return nil, err
+ }
+ session, err := h.uploadService.CreateSession(ctx, input.Kind, input.Body)
+ if err != nil {
+ if httpErr := SessionHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ return sessionResponseInternal(session), nil
+}
+
+func (h *UploadHandler) UploadChunk(ctx context.Context, input *UploadChunkInput) (*UploadSessionOutput, error) {
+ if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
+ return nil, err
+ }
+ session, err := h.uploadService.WriteChunk(ctx, input.Kind, input.UploadID, input.Index, input.RawBody)
+ if err != nil {
+ if httpErr := SessionHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ return sessionResponseInternal(session), nil
+}
+
+func (h *UploadHandler) GetSession(ctx context.Context, input *GetUploadSessionInput) (*UploadSessionOutput, error) {
+ if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
+ return nil, err
+ }
+ session, err := h.uploadService.GetSession(ctx, input.Kind, input.UploadID)
+ if err != nil {
+ if httpErr := SessionHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ return sessionResponseInternal(session), nil
+}
+
+func (h *UploadHandler) DeleteSession(ctx context.Context, input *DeleteUploadSessionInput) (*DeleteUploadSessionOutput, error) {
+ if err := requireUploadPermissionInternal(ctx, input.Kind, input.EnvironmentID); err != nil {
+ return nil, err
+ }
+ if err := h.uploadService.DeleteSession(ctx, input.Kind, input.UploadID); err != nil {
+ if httpErr := SessionHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+ return &DeleteUploadSessionOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{Message: "Upload session deleted"},
+ },
+ }, nil
+}
+
+// LegacyMultipartMiddleware converts a deprecated multipart/form-data request
+// into a complete upload session and rewrites the request into the JSON
+// {"uploadId"} form, so clients predating chunked uploads keep working. It
+// runs after authentication (a huma global middleware) but before the
+// operation's permission middleware, so it enforces the kind permission
+// itself to avoid staging files for unauthorized callers.
+//
+// This compatibility path is deprecated for API consumers; delete this
+// middleware when multipart upload support is removed.
+func LegacyMultipartMiddleware(api huma.API, service *UploadService, kind string) huma.Middlewares {
+ return huma.Middlewares{func(ctx huma.Context, next func(huma.Context)) {
+ if !strings.HasPrefix(ctx.Header("Content-Type"), "multipart/form-data") {
+ next(ctx)
+ return
+ }
+ writeErr := func(status int, message string) {
+ if err := huma.WriteErr(api, ctx, status, message); err != nil {
+ slog.WarnContext(ctx.Context(), "failed to write legacy upload error response", "error", err)
+ }
+ }
+ if err := requireUploadPermissionInternal(ctx.Context(), kind, authz.EnvIDFromPath(ctx.URL().Path)); err != nil {
+ writeErr(http.StatusForbidden, "permission denied")
+ return
+ }
+
+ request := humaecho.Unwrap(ctx).Request()
+ if err := request.ParseMultipartForm(32 << 10); err != nil {
+ writeErr(http.StatusBadRequest, "Invalid multipart form: "+err.Error())
+ return
+ }
+ defer func() { _ = request.MultipartForm.RemoveAll() }()
+ file, header, err := request.FormFile("file")
+ if err != nil {
+ writeErr(http.StatusBadRequest, "No file uploaded")
+ return
+ }
+ defer func() { _ = file.Close() }()
+
+ slog.WarnContext(ctx.Context(), "Deprecated multipart upload used; migrate to chunked upload sessions",
+ "kind", kind, "path", ctx.URL().Path, "filename", header.Filename, "size", header.Size)
+
+ session, err := service.IngestSession(ctx.Context(), kind, header.Filename, header.Size, file)
+ if err != nil {
+ if httpErr := SessionHTTPError(err); httpErr != nil {
+ var statusErr huma.StatusError
+ if errors.As(httpErr, &statusErr) {
+ writeErr(statusErr.GetStatus(), statusErr.Error())
+ return
+ }
+ }
+ writeErr(http.StatusInternalServerError, err.Error())
+ return
+ }
+
+ payload, err := json.Marshal(uploadtypes.ConsumeRequest{UploadID: session.ID})
+ if err != nil {
+ writeErr(http.StatusInternalServerError, err.Error())
+ return
+ }
+ request.Body = io.NopCloser(bytes.NewReader(payload))
+ request.ContentLength = int64(len(payload))
+ request.Header.Set("Content-Type", "application/json")
+ next(ctx)
+ }}
+}
+
+// RegisterUploads registers the upload-session routes. The required permission
+// depends on the {kind} path parameter, so the operations carry no static
+// permission metadata; enforcement happens in-handler and, for remote
+// environments, in the proxy's upload special case.
+func RegisterUploads(api huma.API, service *UploadService) {
+ h := &UploadHandler{uploadService: service}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "create-upload-session",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/uploads/{kind}",
+ Summary: "Create an upload session",
+ Description: "Start a chunked upload session; the file arrives as independently retryable chunks",
+ Tags: []string{"Uploads"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.CreateSession)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "upload-chunk",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/uploads/{kind}/{uploadId}/chunks/{index}",
+ Summary: "Upload a chunk",
+ Description: "Upload one chunk of an upload session; re-sending a chunk is idempotent",
+ Tags: []string{"Uploads"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ MaxBodyBytes: uploadtypes.MaxChunkSize,
+ }, h.UploadChunk)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-upload-session",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/uploads/{kind}/{uploadId}",
+ Summary: "Get an upload session",
+ Description: "Inspect an upload session to resume by re-sending only the missing chunks",
+ Tags: []string{"Uploads"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.GetSession)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "delete-upload-session",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/uploads/{kind}/{uploadId}",
+ Summary: "Delete an upload session",
+ Description: "Abort an upload session and discard its received chunks",
+ Tags: []string{"Uploads"},
+ Security: handlerutil.DefaultOperationSecurity(),
+ }, h.DeleteSession)
+}
diff --git a/backend/internal/upload/module.go b/backend/internal/upload/module.go
new file mode 100644
index 000000000..6d530adf9
--- /dev/null
+++ b/backend/internal/upload/module.go
@@ -0,0 +1,33 @@
+package upload
+
+import "github.com/danielgtaylor/huma/v2"
+
+// Module wires the upload domain and mounts its routes.
+type Module struct {
+ service *UploadService
+}
+
+// New builds the upload module around its session service.
+func New(service *UploadService) *Module {
+ return &Module{service: service}
+}
+
+// Service exposes the upload session service to the domain endpoints that
+// consume completed sessions.
+func (m *Module) Service() *UploadService {
+ if m == nil {
+ return nil
+ }
+ return m.service
+}
+
+// RegisterRoutes mounts the upload-session endpoints. A nil module still
+// registers, so OpenAPI spec generation can discover the routes without a
+// service graph.
+func (m *Module) RegisterRoutes(api huma.API) {
+ if m == nil {
+ RegisterUploads(api, nil)
+ return
+ }
+ RegisterUploads(api, m.service)
+}
diff --git a/backend/internal/upload/service_test.go b/backend/internal/upload/service_test.go
new file mode 100644
index 000000000..b0f828799
--- /dev/null
+++ b/backend/internal/upload/service_test.go
@@ -0,0 +1,155 @@
+package upload
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+)
+
+func TestSessionChunkRoundTrip(t *testing.T) {
+ service := &UploadService{root: filepath.Join(t.TempDir(), "uploads")}
+ ctx := t.Context()
+
+ chunkSize := uploadtypes.MinChunkSize
+ payload := bytes.Repeat([]byte("a"), int(chunkSize))
+ payload = append(payload, bytes.Repeat([]byte("b"), int(chunkSize))...)
+ payload = append(payload, []byte("short-tail")...)
+
+ session, err := service.CreateSession(ctx, uploadtypes.KindBuildWorkspace, uploadtypes.CreateSessionRequest{
+ Filename: "artifact.bin",
+ Size: int64(len(payload)),
+ ChunkSize: chunkSize,
+ })
+ if err != nil {
+ t.Fatalf("CreateSession: %v", err)
+ }
+ if session.TotalChunks != 3 {
+ t.Fatalf("TotalChunks = %d, want 3", session.TotalChunks)
+ }
+
+ if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 3, payload[:chunkSize]); !errors.Is(err, common.ErrUploadChunkInvalid) {
+ t.Fatalf("out-of-range chunk error = %v, want ErrUploadChunkInvalid", err)
+ }
+ if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 2, payload[:chunkSize]); !errors.Is(err, common.ErrUploadChunkInvalid) {
+ t.Fatalf("wrong-length chunk error = %v, want ErrUploadChunkInvalid", err)
+ }
+
+ // Chunks arrive out of order; the session stays resumable in between.
+ if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 2, payload[2*chunkSize:]); err != nil {
+ t.Fatalf("WriteChunk(2): %v", err)
+ }
+ updated, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 0, payload[:chunkSize])
+ if err != nil {
+ t.Fatalf("WriteChunk(0): %v", err)
+ }
+ if got := updated.ReceivedChunks; len(got) != 2 || got[0] != 0 || got[1] != 2 || updated.Complete {
+ t.Fatalf("session after partial upload = %+v", updated)
+ }
+ if _, _, _, err := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID); !errors.Is(err, common.ErrUploadSessionIncomplete) {
+ t.Fatalf("incomplete Consume error = %v, want ErrUploadSessionIncomplete", err)
+ }
+
+ if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 1, payload[chunkSize:2*chunkSize]); err != nil {
+ t.Fatalf("WriteChunk(1): %v", err)
+ }
+ if _, _, _, err := service.Consume(ctx, uploadtypes.KindImage, session.ID); !errors.Is(err, common.ErrUploadKindMismatch) {
+ t.Fatalf("wrong-kind Consume error = %v, want ErrUploadKindMismatch", err)
+ }
+
+ file, consumed, cleanup, err := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID)
+ if err != nil {
+ t.Fatalf("Consume: %v", err)
+ }
+ if !consumed.Complete || consumed.Filename != "artifact.bin" {
+ t.Fatalf("consumed session = %+v", consumed)
+ }
+ // Sessions are single-use: a concurrent second consumer must not see it.
+ if _, _, _, err := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID); !errors.Is(err, common.ErrUploadSessionNotFound) {
+ t.Fatalf("second Consume error = %v, want ErrUploadSessionNotFound", err)
+ }
+ assembled, err := io.ReadAll(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(assembled, payload) {
+ t.Fatalf("assembled file differs from input (%d vs %d bytes)", len(assembled), len(payload))
+ }
+ cleanup()
+ if _, err := os.Stat(filepath.Join(service.root, session.ID)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("session dir still present after cleanup: %v", err)
+ }
+}
+
+func TestIngestSessionCreatesCompleteSession(t *testing.T) {
+ service := &UploadService{root: filepath.Join(t.TempDir(), "uploads")}
+ ctx := t.Context()
+ payload := []byte("legacy-multipart-body")
+
+ session, err := service.IngestSession(ctx, uploadtypes.KindBuildWorkspace, "legacy.bin", int64(len(payload)), bytes.NewReader(payload))
+ if err != nil {
+ t.Fatalf("IngestSession: %v", err)
+ }
+ if !session.Complete {
+ t.Fatalf("ingested session not complete: %+v", session)
+ }
+
+ file, _, cleanup, err := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID)
+ if err != nil {
+ t.Fatalf("Consume: %v", err)
+ }
+ defer cleanup()
+ assembled, err := io.ReadAll(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(assembled, payload) {
+ t.Fatalf("assembled = %q, want %q", assembled, payload)
+ }
+
+ if _, err := service.IngestSession(ctx, uploadtypes.KindBuildWorkspace, "short.bin", 10, bytes.NewReader([]byte("abc"))); err == nil {
+ t.Fatal("IngestSession with short source unexpectedly succeeded")
+ }
+}
+
+func TestPurgeExpiredSessionsRemovesOnlyStaleSessions(t *testing.T) {
+ service := &UploadService{root: filepath.Join(t.TempDir(), "uploads")}
+ ctx := t.Context()
+
+ stale, err := service.CreateSession(ctx, uploadtypes.KindBuildWorkspace, uploadtypes.CreateSessionRequest{Filename: "stale.bin", Size: 1})
+ if err != nil {
+ t.Fatalf("CreateSession(stale): %v", err)
+ }
+ // Expiry is idle-based: backdate every mtime the purge inspects.
+ idle := time.Now().Add(-48 * time.Hour)
+ for _, name := range []string{"", "meta.json", "data"} {
+ if err := os.Chtimes(filepath.Join(service.root, stale.ID, name), idle, idle); err != nil {
+ t.Fatalf("backdate stale session: %v", err)
+ }
+ }
+ fresh, err := service.CreateSession(ctx, uploadtypes.KindBuildWorkspace, uploadtypes.CreateSessionRequest{Filename: "fresh.bin", Size: 1})
+ if err != nil {
+ t.Fatalf("CreateSession(fresh): %v", err)
+ }
+
+ removed, err := service.PurgeExpiredSessions(ctx, 24*time.Hour)
+ if err != nil {
+ t.Fatalf("PurgeExpiredSessions: %v", err)
+ }
+ if removed != 1 {
+ t.Fatalf("removed = %d, want 1", removed)
+ }
+ if _, err := service.GetSession(ctx, uploadtypes.KindBuildWorkspace, stale.ID); !errors.Is(err, common.ErrUploadSessionNotFound) {
+ t.Fatalf("stale session error = %v, want ErrUploadSessionNotFound", err)
+ }
+ if _, err := service.GetSession(ctx, uploadtypes.KindBuildWorkspace, fresh.ID); err != nil {
+ t.Fatalf("fresh session should survive purge: %v", err)
+ }
+}
diff --git a/backend/internal/upload/upload.go b/backend/internal/upload/upload.go
new file mode 100644
index 000000000..3559df4d3
--- /dev/null
+++ b/backend/internal/upload/upload.go
@@ -0,0 +1,321 @@
+// Package upload owns chunked upload sessions: filesystem-backed staging for
+// large files that arrive as independently retryable chunks, consumed by the
+// image, volume-backup, and build-workspace endpoints.
+package upload
+
+import (
+ "context"
+ "encoding/json/v2"
+ "fmt"
+ "io"
+ "os"
+ "path"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "time"
+
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
+ "go.getarcane.app/acfs"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
+)
+
+const (
+ sessionMetaFilename = "meta.json"
+ sessionDataFilename = "data"
+)
+
+// uploadIDPattern matches the random hex component acfs.MkdirTemp generates
+// for session directories; anything else is rejected before touching disk.
+var uploadIDPattern = regexp.MustCompile(`^[0-9a-f]{16}$`)
+
+// UploadService stages chunked upload sessions on local disk. Sessions are
+// node-local by design: chunks and the consuming request must reach the same
+// instance, which holds for Arcane's single-instance-per-node deployment (for
+// remote environments the session lives on that environment's agent).
+type UploadService struct {
+ settingsService *settings.SettingsService
+ root string
+ locks utils.KeyedMutex
+}
+
+// NewUploadService builds the session service rooted in the system temp
+// directory; the root is created lazily on first session.
+func NewUploadService(settingsService *settings.SettingsService) *UploadService {
+ return &UploadService{
+ settingsService: settingsService,
+ root: filepath.Join(os.TempDir(), "arcane-uploads"),
+ }
+}
+
+func validFilenameForKindInternal(kind, filename string) bool {
+ lower := strings.ToLower(filename)
+ switch kind {
+ case uploadtypes.KindImage:
+ return strings.HasSuffix(lower, ".tar") || strings.HasSuffix(lower, ".tar.gz") ||
+ strings.HasSuffix(lower, ".tgz") || strings.HasSuffix(lower, ".tar.xz")
+ case uploadtypes.KindVolumeBackup:
+ return strings.HasSuffix(lower, ".tar.gz") || strings.HasSuffix(lower, ".tgz")
+ case uploadtypes.KindBuildWorkspace:
+ return true
+ }
+ return false
+}
+
+// CreateSession validates the request against the kind's filename and size
+// rules and stages a new empty session on disk.
+func (s *UploadService) CreateSession(ctx context.Context, kind string, request uploadtypes.CreateSessionRequest) (*uploadtypes.Session, error) {
+ filename := path.Base(strings.ReplaceAll(request.Filename, "\\", "/"))
+ if filename == "" || filename == "." || filename == "/" {
+ return nil, fmt.Errorf("%w: a filename is required", common.ErrUploadSessionInvalid)
+ }
+ if !validFilenameForKindInternal(kind, filename) {
+ return nil, fmt.Errorf("%w: file type not allowed for %s uploads", common.ErrUploadSessionInvalid, kind)
+ }
+ if request.Size <= 0 {
+ return nil, fmt.Errorf("%w: size must be positive", common.ErrUploadSessionInvalid)
+ }
+ if kind == uploadtypes.KindImage {
+ maxSizeMB := s.settingsService.GetIntSetting(ctx, "maxImageUploadSize", 500)
+ if maxSizeBytes := int64(maxSizeMB) * 1024 * 1024; request.Size > maxSizeBytes {
+ return nil, fmt.Errorf("%w: file size exceeds maximum allowed size of %d MB", common.ErrUploadSessionInvalid, maxSizeMB)
+ }
+ }
+ chunkSize := request.ChunkSize
+ if chunkSize == 0 {
+ chunkSize = uploadtypes.DefaultChunkSize
+ }
+ if chunkSize < uploadtypes.MinChunkSize || chunkSize > uploadtypes.MaxChunkSize {
+ return nil, fmt.Errorf("%w: chunk size must be between %d and %d bytes", common.ErrUploadSessionInvalid, uploadtypes.MinChunkSize, uploadtypes.MaxChunkSize)
+ }
+
+ if err := os.MkdirAll(s.root, 0o700); err != nil {
+ return nil, fmt.Errorf("create upload root: %w", err)
+ }
+ sessionDir, err := acfs.MkdirTemp(ctx, s.root, "/", "*")
+ if err != nil {
+ return nil, fmt.Errorf("create upload session directory: %w", err)
+ }
+ session := &uploadtypes.Session{
+ ID: path.Base(sessionDir),
+ Kind: kind,
+ Filename: filename,
+ Size: request.Size,
+ ChunkSize: chunkSize,
+ TotalChunks: int((request.Size + chunkSize - 1) / chunkSize),
+ ReceivedChunks: []int{},
+ CreatedAt: time.Now().UTC(),
+ }
+ if err := acfs.WriteFile(ctx, s.root, path.Join(sessionDir, sessionDataFilename), nil, 0o600); err != nil {
+ _ = acfs.RemoveAll(ctx, s.root, sessionDir)
+ return nil, fmt.Errorf("create upload session data file: %w", err)
+ }
+ if err := s.writeMetaInternal(ctx, session); err != nil {
+ _ = acfs.RemoveAll(ctx, s.root, sessionDir)
+ return nil, err
+ }
+ return session, nil
+}
+
+func (s *UploadService) sessionPathInternal(uploadID, filename string) (string, error) {
+ if !uploadIDPattern.MatchString(uploadID) {
+ return "", fmt.Errorf("%w: invalid upload ID", common.ErrUploadSessionNotFound)
+ }
+ return path.Join("/", uploadID, filename), nil
+}
+
+func (s *UploadService) loadMetaInternal(ctx context.Context, kind, uploadID string) (*uploadtypes.Session, error) {
+ metaPath, err := s.sessionPathInternal(uploadID, sessionMetaFilename)
+ if err != nil {
+ return nil, err
+ }
+ payload, err := acfs.ReadFile(ctx, s.root, metaPath)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %s", common.ErrUploadSessionNotFound, uploadID)
+ }
+ var session uploadtypes.Session
+ if err := json.Unmarshal(payload, &session); err != nil {
+ return nil, fmt.Errorf("%w: corrupt session metadata", common.ErrUploadSessionNotFound)
+ }
+ if session.Kind != kind {
+ return nil, fmt.Errorf("%w: session is for %s uploads", common.ErrUploadKindMismatch, session.Kind)
+ }
+ session.Complete = len(session.ReceivedChunks) == session.TotalChunks
+ return &session, nil
+}
+
+func (s *UploadService) writeMetaInternal(ctx context.Context, session *uploadtypes.Session) error {
+ session.Complete = len(session.ReceivedChunks) == session.TotalChunks
+ payload, err := json.Marshal(session)
+ if err != nil {
+ return fmt.Errorf("encode upload session metadata: %w", err)
+ }
+ if err := acfs.WriteFile(ctx, s.root, path.Join("/", session.ID, sessionMetaFilename), payload, 0o600); err != nil {
+ return fmt.Errorf("write upload session metadata: %w", err)
+ }
+ return nil
+}
+
+// WriteChunk stores one chunk at its final offset and records it as received.
+// Re-sending an already-received chunk is an idempotent overwrite.
+func (s *UploadService) WriteChunk(ctx context.Context, kind, uploadID string, index int, data []byte) (*uploadtypes.Session, error) {
+ defer s.locks.Lock(uploadID)()
+
+ session, err := s.loadMetaInternal(ctx, kind, uploadID)
+ if err != nil {
+ return nil, err
+ }
+ if index < 0 || index >= session.TotalChunks {
+ return nil, fmt.Errorf("%w: chunk index %d out of range [0,%d)", common.ErrUploadChunkInvalid, index, session.TotalChunks)
+ }
+ expected := session.ChunkSize
+ if index == session.TotalChunks-1 {
+ expected = session.Size - int64(index)*session.ChunkSize
+ }
+ if int64(len(data)) != expected {
+ return nil, fmt.Errorf("%w: chunk %d is %d bytes, expected %d", common.ErrUploadChunkInvalid, index, len(data), expected)
+ }
+
+ dataPath, err := s.sessionPathInternal(uploadID, sessionDataFilename)
+ if err != nil {
+ return nil, err
+ }
+ if err := acfs.WriteAt(ctx, s.root, dataPath, int64(index)*session.ChunkSize, data); err != nil {
+ return nil, fmt.Errorf("write chunk %d: %w", index, err)
+ }
+ if position, found := slices.BinarySearch(session.ReceivedChunks, index); !found {
+ session.ReceivedChunks = slices.Insert(session.ReceivedChunks, position, index)
+ if err := s.writeMetaInternal(ctx, session); err != nil {
+ return nil, err
+ }
+ }
+ return session, nil
+}
+
+// GetSession reports the session state, including which chunks have been
+// received so clients can resume.
+func (s *UploadService) GetSession(ctx context.Context, kind, uploadID string) (*uploadtypes.Session, error) {
+ defer s.locks.RLock(uploadID)()
+ return s.loadMetaInternal(ctx, kind, uploadID)
+}
+
+// DeleteSession aborts a session and discards its received chunks.
+func (s *UploadService) DeleteSession(ctx context.Context, kind, uploadID string) error {
+ defer s.locks.Lock(uploadID)()
+
+ if _, err := s.loadMetaInternal(ctx, kind, uploadID); err != nil {
+ return err
+ }
+ if err := acfs.RemoveAll(ctx, s.root, path.Join("/", uploadID)); err != nil {
+ return fmt.Errorf("delete upload session: %w", err)
+ }
+ return nil
+}
+
+// IngestSession creates a session already containing the complete file. It
+// backs the deprecated single-request multipart compatibility path, applying
+// the same per-kind validation as chunked sessions.
+func (s *UploadService) IngestSession(ctx context.Context, kind, filename string, size int64, source io.Reader) (*uploadtypes.Session, error) {
+ session, err := s.CreateSession(ctx, kind, uploadtypes.CreateSessionRequest{Filename: filename, Size: size})
+ if err != nil {
+ return nil, err
+ }
+ if _, err := acfs.WriteFrom(ctx, s.root, path.Join("/", session.ID, sessionDataFilename), source, size, 0o600); err != nil {
+ _ = acfs.RemoveAll(ctx, s.root, path.Join("/", session.ID))
+ return nil, fmt.Errorf("write uploaded file: %w", err)
+ }
+ for index := range session.TotalChunks {
+ session.ReceivedChunks = append(session.ReceivedChunks, index)
+ }
+ if err := s.writeMetaInternal(ctx, session); err != nil {
+ _ = acfs.RemoveAll(ctx, s.root, path.Join("/", session.ID))
+ return nil, err
+ }
+ return session, nil
+}
+
+// Consume validates that the session matches kind and is complete, then opens
+// the assembled file for reading. The session metadata is removed under the
+// session lock before returning, so a session can be consumed at most once
+// even by concurrent requests; the returned cleanup closes the file and
+// deletes the remaining session data.
+func (s *UploadService) Consume(ctx context.Context, kind, uploadID string) (io.ReadSeekCloser, *uploadtypes.Session, func(), error) {
+ defer s.locks.Lock(uploadID)()
+
+ session, err := s.loadMetaInternal(ctx, kind, uploadID)
+ if err != nil {
+ return nil, nil, nil, err
+ }
+ if !session.Complete {
+ return nil, nil, nil, fmt.Errorf("%w: %d of %d chunks received", common.ErrUploadSessionIncomplete, len(session.ReceivedChunks), session.TotalChunks)
+ }
+ dataPath, err := s.sessionPathInternal(uploadID, sessionDataFilename)
+ if err != nil {
+ return nil, nil, nil, err
+ }
+ file, size, err := acfs.OpenReadSeek(ctx, s.root, dataPath)
+ if err != nil {
+ return nil, nil, nil, fmt.Errorf("open upload session data: %w", err)
+ }
+ if size != session.Size {
+ _ = file.Close()
+ return nil, nil, nil, fmt.Errorf("%w: assembled size %d does not match declared size %d", common.ErrUploadSessionIncomplete, size, session.Size)
+ }
+ if err := acfs.Remove(ctx, s.root, path.Join("/", uploadID, sessionMetaFilename)); err != nil {
+ _ = file.Close()
+ return nil, nil, nil, fmt.Errorf("mark upload session consumed: %w", err)
+ }
+ cleanup := func() {
+ _ = file.Close()
+ // context.WithoutCancel: the session must be removed even when the
+ // consuming request was cancelled mid-restore.
+ _ = acfs.RemoveAll(context.WithoutCancel(ctx), s.root, path.Join("/", uploadID))
+ }
+ return file, session, cleanup, nil
+}
+
+// PurgeExpiredSessions removes sessions that have been idle for longer than
+// maxAge. Idleness is judged by the newest modification time among the
+// session's files — the data file advances on every chunk write and the
+// metadata on every chunk recorded — so a slow but active upload is never
+// swept, and the check runs under the session lock so an in-flight chunk
+// write cannot race the removal.
+func (s *UploadService) PurgeExpiredSessions(ctx context.Context, maxAge time.Duration) (int, error) {
+ if _, err := os.Stat(s.root); os.IsNotExist(err) {
+ return 0, nil
+ }
+ entries, err := acfs.List(ctx, s.root, "/")
+ if err != nil {
+ return 0, fmt.Errorf("list upload sessions: %w", err)
+ }
+ cutoff := time.Now().Add(-maxAge)
+ removed := 0
+ for _, entry := range entries {
+ if !entry.IsDirectory {
+ continue
+ }
+ unlock := s.locks.Lock(entry.Name)
+ lastActivity := entry.ModTime
+ for _, filename := range []string{sessionDataFilename, sessionMetaFilename} {
+ if info, statErr := acfs.Stat(ctx, s.root, path.Join("/", entry.Name, filename), true); statErr == nil && info.ModTime.After(lastActivity) {
+ lastActivity = info.ModTime
+ }
+ }
+ var removeErr error
+ if lastActivity.Before(cutoff) {
+ removeErr = acfs.RemoveAll(ctx, s.root, path.Join("/", entry.Name))
+ }
+ unlock()
+ if removeErr != nil {
+ return removed, fmt.Errorf("remove expired upload session %s: %w", entry.Name, removeErr)
+ }
+ if lastActivity.Before(cutoff) {
+ removed++
+ }
+ }
+ return removed, nil
+}
diff --git a/backend/internal/volume/backup.go b/backend/internal/volume/backup.go
index 38b0e91ad..bde9e48de 100644
--- a/backend/internal/volume/backup.go
+++ b/backend/internal/volume/backup.go
@@ -7,7 +7,6 @@ import (
"fmt"
"io"
"log/slog"
- "os"
"path"
"strconv"
"strings"
@@ -864,25 +863,10 @@ func (s *VolumeService) DownloadBackup(ctx context.Context, backupID string, use
return reader, size, nil
}
-func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string, archive io.Reader, filename string, user models.User) error {
+func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string, archive io.ReadSeeker, filename string, user models.User) error {
slog.DebugContext(ctx, "volume service: upload and restore", "volume", volumeName, "filename", filename, "user", user.ID)
- // System temp scratch for the upload buffer: no acfs root exists for it.
- tmpFile, err := os.CreateTemp("", "arcane-restore-*.tar.gz")
- if err != nil {
- return errors.WrapIf(err, "failed to buffer upload")
- }
- defer func() {
- _ = tmpFile.Close()
- _ = os.Remove(tmpFile.Name())
- }()
- if _, err := io.Copy(tmpFile, archive); err != nil {
- return errors.WrapIf(err, "failed to buffer upload")
- }
- if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
- return errors.WrapIf(err, "failed to read buffered upload")
- }
- gzr, err := gzip.NewReader(tmpFile)
+ gzr, err := gzip.NewReader(archive)
if err != nil {
return errors.WrapIf(err, "invalid archive")
}
@@ -923,12 +907,12 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,
slog.DebugContext(ctx, "volume service: restore temp dir stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))
}
- if _, err := tmpFile.Seek(0, io.SeekStart); err != nil {
- return errors.WrapIf(err, "failed to read buffered upload")
+ if _, err := archive.Seek(0, io.SeekStart); err != nil {
+ return errors.WrapIf(err, "failed to read uploaded archive")
}
_, err = dockerClient.CopyToContainer(ctx, containerID, client.CopyToContainerOptions{
DestinationPath: tmpDir,
- Content: tmpFile,
+ Content: archive,
})
if err != nil {
return errors.WrapIf(err, "failed to restore from uploaded archive")
diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.go
index e2eedd509..92dcac7bd 100644
--- a/backend/internal/volume/handler.go
+++ b/backend/internal/volume/handler.go
@@ -3,7 +3,6 @@ package volume
import (
"context"
"io"
- "mime/multipart"
"net/http"
"strconv"
"strings"
@@ -15,12 +14,14 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
"github.com/getarcaneapp/arcane/types/v2/base"
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/moby/moby/client"
"github.com/samber/mo"
@@ -31,6 +32,7 @@ type VolumeHandler struct {
volumeService *VolumeService
dockerService *docker.DockerClientService
activityService *activity.ActivityService
+ uploadService *upload.UploadService
appCtx context.Context
}
@@ -235,9 +237,9 @@ type DownloadBackupInput struct {
}
type UploadAndRestoreInput struct {
- EnvironmentID string `path:"id" doc:"Environment ID"`
- VolumeName string `path:"volumeName" doc:"Volume name"`
- RawBody multipart.Form `contentType:"multipart/form-data"`
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ VolumeName string `path:"volumeName" doc:"Volume name"`
+ Body uploadtypes.ConsumeRequest
}
type UploadAndRestoreOutput struct {
@@ -245,11 +247,12 @@ type UploadAndRestoreOutput struct {
}
// RegisterVolumes registers volume management routes using Huma.
-func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, volumeService *VolumeService, activityService *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
+func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, volumeService *VolumeService, activityService *activity.ActivityService, uploadService *upload.UploadService, appCtx handlerutil.ActivityAppContext) {
h := &VolumeHandler{
volumeService: volumeService,
dockerService: dockerService,
activityService: activityService,
+ uploadService: uploadService,
appCtx: appCtx.Context(),
}
@@ -416,25 +419,10 @@ func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, vo
Method: http.MethodPost,
Path: "/environments/{id}/volumes/{volumeName}/backups/upload",
Summary: "Upload and restore volume backup",
+ Description: "Restore a volume from a complete chunked upload session containing a tar.gz backup archive. multipart/form-data bodies are still accepted for backward compatibility; that form is deprecated and will be removed in a future release.",
Tags: []string{"Volume Backup"},
Security: handlerutil.DefaultOperationSecurity(),
- RequestBody: &huma.RequestBody{
- Content: map[string]*huma.MediaType{
- "multipart/form-data": {
- Schema: &huma.Schema{
- Type: "object",
- Properties: map[string]*huma.Schema{
- "file": {
- Type: "string",
- Format: "binary",
- Description: "Backup archive (tar.gz)",
- },
- },
- Required: []string{"file"},
- },
- },
- },
- },
+ Middlewares: upload.LegacyMultipartMiddleware(api, h.uploadService, uploadtypes.KindVolumeBackup),
}, authz.PermVolumesUpload, h.UploadAndRestore)
}
@@ -915,11 +903,14 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRe
return nil, err
}
- file, fileHeader, err := handlerutil.OpenUploadedFile(input.RawBody)
+ file, session, cleanup, err := h.uploadService.Consume(ctx, uploadtypes.KindVolumeBackup, input.Body.UploadID)
if err != nil {
- return nil, err
+ if httpErr := upload.SessionHTTPError(err); httpErr != nil {
+ return nil, httpErr
+ }
+ return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to open upload").Error())
}
- defer func() { _ = file.Close() }()
+ defer cleanup()
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
@@ -934,10 +925,10 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndRe
SuccessMessage: "Backup uploaded and restored successfully",
Metadata: models.JSON{
"action": "upload_restore_volume_backup",
- "filename": fileHeader.Filename,
+ "filename": session.Filename,
},
}, func(runtimeCtx context.Context) error {
- return h.volumeService.UploadAndRestore(runtimeCtx, input.VolumeName, file, fileHeader.Filename, *user)
+ return h.volumeService.UploadAndRestore(runtimeCtx, input.VolumeName, file, session.Filename, *user)
})
if err != nil {
return nil, huma.Error500InternalServerError(err.Error())
diff --git a/backend/internal/volume/module.go b/backend/internal/volume/module.go
index c58ae25c6..8cbec5492 100644
--- a/backend/internal/volume/module.go
+++ b/backend/internal/volume/module.go
@@ -12,6 +12,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/event"
"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
)
@@ -24,6 +25,7 @@ type Dependencies struct {
Image *image.ImageService
Activity *activity.ActivityService
Config *config.Config
+ Upload *upload.UploadService
}
// Module wires the volume domain and mounts its routes.
@@ -53,8 +55,8 @@ func (m *Module) Service() *VolumeService {
// OpenAPI spec generation can discover the routes without a service graph.
func (m *Module) RegisterRoutes(api huma.API, appCtx handlerutil.ActivityAppContext) {
if m == nil {
- RegisterVolumes(api, nil, nil, nil, appCtx)
+ RegisterVolumes(api, nil, nil, nil, nil, appCtx)
return
}
- RegisterVolumes(api, m.deps.Docker, m.service, m.deps.Activity, appCtx)
+ RegisterVolumes(api, m.deps.Docker, m.service, m.deps.Activity, m.deps.Upload, appCtx)
}
diff --git a/backend/internal/volume/workspace_handler_test.go b/backend/internal/volume/workspace_handler_test.go
index e5781aaa1..c47fa786b 100644
--- a/backend/internal/volume/workspace_handler_test.go
+++ b/backend/internal/volume/workspace_handler_test.go
@@ -9,8 +9,10 @@ import (
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -22,22 +24,22 @@ func volumeWorkspacePermissionContextInternal(environmentID string, permissions
return context.WithValue(context.Background(), middleware.ContextKeyUserPermissions, permissionSet)
}
-func TestUploadAndRestoreReturnsBadRequestWhenNoFileProvided(t *testing.T) {
- h := &VolumeHandler{volumeService: &VolumeService{}}
+func TestUploadAndRestoreReturnsNotFoundForUnknownSession(t *testing.T) {
+ h := &VolumeHandler{volumeService: &VolumeService{}, uploadService: upload.NewUploadService(nil)}
ctx := context.WithValue(context.Background(), models.CurrentUserContextKey{}, &models.User{BaseModel: models.BaseModel{ID: "u-1"}})
_, err := h.UploadAndRestore(ctx, &UploadAndRestoreInput{
EnvironmentID: "0",
VolumeName: "vol-1",
- RawBody: multipart.Form{},
+ Body: uploadtypes.ConsumeRequest{UploadID: "missing"},
})
require.Error(t, err)
var statusErr huma.StatusError
require.ErrorAs(t, err, &statusErr)
- assert.Equal(t, http.StatusBadRequest, statusErr.GetStatus())
+ assert.Equal(t, http.StatusNotFound, statusErr.GetStatus())
}
func TestParseVolumeWorkspaceManifestInternal(t *testing.T) {
diff --git a/backend/pkg/authz/upload.go b/backend/pkg/authz/upload.go
new file mode 100644
index 000000000..244fab7f6
--- /dev/null
+++ b/backend/pkg/authz/upload.go
@@ -0,0 +1,18 @@
+package authz
+
+import uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
+
+// UploadKindPermission maps an upload-session kind to the permission required
+// to create, write to, inspect, or delete sessions of that kind. The boolean
+// is false for unknown kinds so callers (and remote proxies) fail closed.
+func UploadKindPermission(kind string) (string, bool) {
+ switch kind {
+ case uploadtypes.KindImage:
+ return PermImagesUpload, true
+ case uploadtypes.KindVolumeBackup:
+ return PermVolumesUpload, true
+ case uploadtypes.KindBuildWorkspace:
+ return PermBuildWorkspacesManage, true
+ }
+ return "", false
+}
diff --git a/backend/pkg/libarcane/edge/commands.go b/backend/pkg/libarcane/edge/commands.go
index 9e55ede08..a7afc0c9d 100644
--- a/backend/pkg/libarcane/edge/commands.go
+++ b/backend/pkg/libarcane/edge/commands.go
@@ -40,6 +40,11 @@ var commandRoutes = []commandRoute{
{Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/prune", CommandName: "image.prune"},
{Method: http.MethodPost, PathPattern: "/api/environments/{id}/images/upload", CommandName: "image.upload"},
+ {Method: http.MethodPost, PathPattern: "/api/environments/{id}/uploads/{kind}", CommandName: "upload.session.create"},
+ {Method: http.MethodGet, PathPattern: "/api/environments/{id}/uploads/{kind}/{uploadId}", CommandName: "upload.session.get"},
+ {Method: http.MethodDelete, PathPattern: "/api/environments/{id}/uploads/{kind}/{uploadId}", CommandName: "upload.session.delete"},
+ {Method: http.MethodPut, PathPattern: "/api/environments/{id}/uploads/{kind}/{uploadId}/chunks/{index}", CommandName: "upload.session.chunk"},
+
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/image-updates/check", CommandName: "image_update.check"},
{Method: http.MethodGet, PathPattern: "/api/environments/{id}/image-updates/check/{imageId}", CommandName: "image_update.check_one"},
{Method: http.MethodPost, PathPattern: "/api/environments/{id}/image-updates/check/{imageId}", CommandName: "image_update.check_one"},
diff --git a/backend/pkg/scheduler/upload_sessions_cleanup_job.go b/backend/pkg/scheduler/upload_sessions_cleanup_job.go
new file mode 100644
index 000000000..f1ecf4bff
--- /dev/null
+++ b/backend/pkg/scheduler/upload_sessions_cleanup_job.go
@@ -0,0 +1,50 @@
+package scheduler
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/upload"
+)
+
+// UploadSessionsCleanupJobName identifies the hourly purge of idle chunked
+// upload sessions.
+const UploadSessionsCleanupJobName = "upload-sessions-cleanup"
+
+const uploadSessionMaxAge = 24 * time.Hour
+
+// UploadSessionsCleanupJob purges upload sessions that have been idle for
+// longer than uploadSessionMaxAge. It runs on managers and agents alike,
+// since sessions live on whichever node serves the environment.
+type UploadSessionsCleanupJob struct {
+ uploadService *upload.UploadService
+}
+
+// NewUploadSessionsCleanupJob builds the cleanup job for the scheduler.
+func NewUploadSessionsCleanupJob(uploadService *upload.UploadService) *UploadSessionsCleanupJob {
+ return &UploadSessionsCleanupJob{uploadService: uploadService}
+}
+
+func (j *UploadSessionsCleanupJob) Name() string {
+ return UploadSessionsCleanupJobName
+}
+
+func (j *UploadSessionsCleanupJob) Schedule(ctx context.Context) string {
+ return "0 0 * * * *"
+}
+
+func (j *UploadSessionsCleanupJob) Run(ctx context.Context) {
+ removed, err := j.uploadService.PurgeExpiredSessions(ctx, uploadSessionMaxAge)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to purge expired upload sessions", "jobName", UploadSessionsCleanupJobName, "removed", removed, "error", err)
+ return
+ }
+ if removed > 0 {
+ slog.InfoContext(ctx, "Purged expired upload sessions", "jobName", UploadSessionsCleanupJobName, "removed", removed)
+ }
+}
+
+func (j *UploadSessionsCleanupJob) Reschedule(ctx context.Context) error {
+ return nil
+}
diff --git a/backend/pkg/utils/handlerutil/handlerutil.go b/backend/pkg/utils/handlerutil/handlerutil.go
index 6fc9886af..0392d2c57 100644
--- a/backend/pkg/utils/handlerutil/handlerutil.go
+++ b/backend/pkg/utils/handlerutil/handlerutil.go
@@ -8,8 +8,6 @@ import (
"mime/multipart"
"strings"
- "emperror.dev/errors"
-
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/v2/internal/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
@@ -79,21 +77,6 @@ func RequireUser(ctx context.Context) (*models.User, error) {
return user, nil
}
-func OpenUploadedFile(form multipart.Form) (multipart.File, *multipart.FileHeader, error) {
- files := form.File["file"]
- if len(files) == 0 {
- return nil, nil, huma.Error400BadRequest("No file uploaded")
- }
-
- fileHeader := files[0]
- file, err := fileHeader.Open()
- if err != nil {
- return nil, nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to read upload").Error())
- }
-
- return file, fileHeader, nil
-}
-
// ParseMultipartJSONPart decodes one required JSON-valued multipart field.
func ParseMultipartJSONPart[T any](form multipart.Form, partName string) (T, error) {
var result T
diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go
index f65764a73..45013d6c1 100644
--- a/cli/internal/types/endpoints.go
+++ b/cli/internal/types/endpoints.go
@@ -66,6 +66,11 @@ type ArcaneApiEndpoints struct {
ImagesCountsEndpoint string
ImagesUploadEndpoint string
+ // Upload sessions
+ UploadSessionsEndpoint string
+ UploadSessionEndpoint string
+ UploadSessionChunkEndpoint string
+
// Image Updates
ImageUpdatesCheckEndpoint string
ImageUpdatesCheckAllEndpoint string
@@ -236,6 +241,11 @@ var Endpoints = ArcaneApiEndpoints{ //nolint:gosec // static endpoint paths; aut
ImagesCountsEndpoint: "/api/environments/%s/images/counts",
ImagesUploadEndpoint: "/api/environments/%s/images/upload",
+ // Upload sessions
+ UploadSessionsEndpoint: "/api/environments/%s/uploads/%s",
+ UploadSessionEndpoint: "/api/environments/%s/uploads/%s/%s",
+ UploadSessionChunkEndpoint: "/api/environments/%s/uploads/%s/%s/chunks/%d",
+
// Image Updates
ImageUpdatesCheckEndpoint: "/api/environments/%s/image-updates/check",
ImageUpdatesCheckAllEndpoint: "/api/environments/%s/image-updates/check-all",
@@ -462,6 +472,20 @@ func (e ArcaneApiEndpoints) ImagesUpload(envID string) string {
return fmt.Sprintf(e.ImagesUploadEndpoint, envID)
}
+// Upload session endpoints
+
+func (e ArcaneApiEndpoints) UploadSessions(envID, kind string) string {
+ return fmt.Sprintf(e.UploadSessionsEndpoint, envID, kind)
+}
+
+func (e ArcaneApiEndpoints) UploadSession(envID, kind, uploadID string) string {
+ return fmt.Sprintf(e.UploadSessionEndpoint, envID, kind, uploadID)
+}
+
+func (e ArcaneApiEndpoints) UploadSessionChunk(envID, kind, uploadID string, index int) string {
+ return fmt.Sprintf(e.UploadSessionChunkEndpoint, envID, kind, uploadID, index)
+}
+
// Image Update endpoints
func (e ArcaneApiEndpoints) ImageUpdatesCheck(envID, imageRef string) string {
diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.go
index bfd6f43a8..82db84157 100644
--- a/cli/pkg/images/cmd.go
+++ b/cli/pkg/images/cmd.go
@@ -31,11 +31,11 @@
package images
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
"io"
- "mime/multipart"
"net/http"
"net/url"
"os"
@@ -55,6 +55,7 @@ import (
"github.com/getarcaneapp/arcane/cli/v2/pkg/images/updates"
"github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/image"
+ uploadtypes "github.com/getarcaneapp/arcane/types/v2/upload"
"github.com/spf13/cobra"
)
@@ -617,9 +618,6 @@ var imagesUploadCmd = &cobra.Command{
c.SetTimeout(30 * time.Minute)
filePath := args[0]
- path := types.Endpoints.ImagesUpload(c.EnvID())
-
- log.Debugf("Uploading image from file: %s to %s", filePath, path)
// Open the file
file, err := os.Open(filePath)
@@ -632,58 +630,78 @@ var imagesUploadCmd = &cobra.Command{
return errors.WrapIf(err, "failed to stat file")
}
- pr, pw := io.Pipe()
- writer := multipart.NewWriter(pw)
+ // Create the chunked upload session; the file is sent as independently
+ // retried chunks so reverse-proxy body limits never see the full size.
+ var created struct {
+ Success bool `json:"success"`
+ Data uploadtypes.Session `json:"data"`
+ }
+ createPath := types.Endpoints.UploadSessions(c.EnvID(), uploadtypes.KindImage)
+ if err := c.DoJSON(cmd.Context(), http.MethodPost, createPath, uploadtypes.CreateSessionRequest{
+ Filename: filepath.Base(filePath),
+ Size: fileInfo.Size(),
+ }, &created); err != nil {
+ return errors.WrapIf(err, "failed to create upload session")
+ }
+ session := created.Data
+ log.Debugf("Uploading image %s as %d chunks of %d bytes (session %s)", filePath, session.TotalChunks, session.ChunkSize, session.ID)
output.Info("Uploading image: %s", filePath)
- var requestBody io.Reader = pr
-
jsonOutput := cmdutil.JSONOutputEnabled(cmd)
var progressUI *output.Progress
if !jsonOutput {
progressUI = output.StartProgress("Uploading", fileInfo.Size())
- requestBody = output.NewProgressReader(pr, progressUI)
defer progressUI.Stop()
}
- go func() {
- part, err := writer.CreateFormFile("file", filepath.Base(filePath))
- if err != nil {
- _ = pw.CloseWithError(errors.WrapIf(err, "failed to create form file"))
- return
+ deleteSession := func() {
+ if resp, deleteErr := c.Delete(context.WithoutCancel(cmd.Context()), types.Endpoints.UploadSession(c.EnvID(), uploadtypes.KindImage, session.ID)); deleteErr == nil {
+ _ = resp.Body.Close()
}
- if _, err := io.Copy(part, file); err != nil {
- _ = pw.CloseWithError(errors.WrapIf(err, "failed to copy file"))
- return
+ }
+
+ buf := make([]byte, session.ChunkSize)
+ for index := range session.TotalChunks {
+ expected := session.ChunkSize
+ if index == session.TotalChunks-1 {
+ expected = session.Size - int64(index)*session.ChunkSize
}
- if err := writer.Close(); err != nil {
- _ = pw.CloseWithError(errors.WrapIf(err, "failed to close multipart writer"))
- return
+ if _, err := io.ReadFull(file, buf[:expected]); err != nil {
+ deleteSession()
+ return errors.WrapIf(err, "failed to read file")
}
- _ = pw.Close()
- }()
- // Use client.RequestRaw to make the multipart request with correct headers
- headers := map[string]string{
- "Content-Type": writer.FormDataContentType(),
+ chunkPath := types.Endpoints.UploadSessionChunk(c.EnvID(), uploadtypes.KindImage, session.ID, index)
+ for attempt := 1; ; attempt++ {
+ resp, chunkErr := c.RequestRaw(cmd.Context(), http.MethodPut, chunkPath, bytes.NewReader(buf[:expected]), map[string]string{"Content-Type": "application/octet-stream"})
+ if chunkErr == nil {
+ ok := resp.StatusCode >= 200 && resp.StatusCode < 300
+ if !ok {
+ errorBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
+ chunkErr = errors.Errorf("chunk %d failed (status %d): %s", index, resp.StatusCode, strings.TrimSpace(string(errorBody)))
+ }
+ _ = resp.Body.Close()
+ if ok {
+ break
+ }
+ }
+ if attempt >= 3 {
+ deleteSession()
+ return errors.WrapIf(chunkErr, "failed to upload image")
+ }
+ log.Debugf("Retrying chunk %d after error: %v", index, chunkErr)
+ }
+ if progressUI != nil {
+ progressUI.Add(expected)
+ }
}
- resp, err := c.RequestRaw(cmd.Context(), http.MethodPost, path, requestBody, headers)
+ respBody, err := c.DoRaw(cmd.Context(), http.MethodPost, types.Endpoints.ImagesUpload(c.EnvID()), uploadtypes.ConsumeRequest{UploadID: session.ID})
if err != nil {
+ deleteSession()
return errors.WrapIf(err, "failed to upload image")
}
- defer func() { _ = resp.Body.Close() }()
-
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- errorBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
- return errors.Errorf("failed to upload image (status %d): %s", resp.StatusCode, strings.TrimSpace(string(errorBody)))
- }
-
- respBody, err := io.ReadAll(resp.Body)
- if err != nil {
- return errors.WrapIf(err, "failed to read response")
- }
log.Debugf("Response body: %s", string(respBody))
diff --git a/frontend/src/lib/components/file-browser/FileUploadDialog.svelte b/frontend/src/lib/components/file-browser/FileUploadDialog.svelte
index b17c94972..a25ae8b21 100644
--- a/frontend/src/lib/components/file-browser/FileUploadDialog.svelte
+++ b/frontend/src/lib/components/file-browser/FileUploadDialog.svelte
@@ -6,6 +6,8 @@
import * as m from '#lib/paraglide/messages.js';
import { CloseIcon } from '#lib/icons';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast';
+ import { Progress } from '#lib/components/ui/progress/index.js';
+ import type { ChunkedUploadProgress, UploadProgressCallback } from '#lib/services/upload-service';
let {
open = $bindable(false),
@@ -14,11 +16,13 @@
}: {
open: boolean;
currentPath: string;
- onUpload: (file: File) => Promise<unknown>;
+ onUpload: (file: File, onProgress?: UploadProgressCallback) => Promise<unknown>;
} = $props();
let files = $state<File[]>([]);
let uploading = $state(false);
+ let uploadingFile = $state<string | null>(null);
+ let uploadProgress = $state<ChunkedUploadProgress | null>(null);
const onUpload: FileDropZoneProps['onUpload'] = async (newFiles) => {
files = [...files, ...newFiles];
@@ -38,7 +42,9 @@
try {
let lastResult: unknown;
for (const file of files) {
- lastResult = await onUploadAction(file);
+ uploadingFile = file.name;
+ uploadProgress = null;
+ lastResult = await onUploadAction(file, (progress) => (uploadProgress = progress));
}
toast.success(m.common_success(), activityToastOptions(extractActivityId(lastResult)));
open = false;
@@ -47,6 +53,8 @@
toast.error(e.message || m.common_failed());
} finally {
uploading = false;
+ uploadingFile = null;
+ uploadProgress = null;
}
}
</script>
@@ -71,20 +79,25 @@
{#if files.length > 0}
<div class="flex max-h-[200px] flex-col gap-2 overflow-y-auto pr-1">
{#each files as file, i (file.name + i)}
- <div class="flex items-center justify-between gap-2 rounded-lg border border-border bg-muted/50 p-2">
- <div class="flex flex-col overflow-hidden">
- <span class="truncate text-xs font-medium">{file.name}</span>
- <span class="text-[10px] text-muted-foreground">{displaySize(file.size)}</span>
+ <div class="flex flex-col gap-1.5 rounded-lg border border-border bg-muted/50 p-2">
+ <div class="flex items-center justify-between gap-2">
+ <div class="flex flex-col overflow-hidden">
+ <span class="truncate text-xs font-medium">{file.name}</span>
+ <span class="text-[10px] text-muted-foreground">{displaySize(file.size)}</span>
+ </div>
+ <ArcaneButton
+ action="base"
+ tone="ghost"
+ size="icon"
+ class="h-6 w-6"
+ onclick={() => removeFile(i)}
+ icon={CloseIcon}
+ disabled={uploading}
+ />
</div>
- <ArcaneButton
- action="base"
- tone="ghost"
- size="icon"
- class="h-6 w-6"
- onclick={() => removeFile(i)}
- icon={CloseIcon}
- disabled={uploading}
- />
+ {#if uploadingFile === file.name && uploadProgress}
+ <Progress value={(uploadProgress.bytesDone / uploadProgress.totalBytes) * 100} class="h-1 rounded-full" />
+ {/if}
</div>
{/each}
</div>
diff --git a/frontend/src/lib/components/file-browser/file-provider.ts b/frontend/src/lib/components/file-browser/file-provider.ts
index 6b885edff..62494156a 100644
--- a/frontend/src/lib/components/file-browser/file-provider.ts
+++ b/frontend/src/lib/components/file-browser/file-provider.ts
@@ -1,9 +1,10 @@
import type { FileEntry } from '#lib/types/shared';
+import type { UploadProgressCallback } from '#lib/services/upload-service';
export interface FileProvider {
list: (path: string) => Promise<FileEntry[]>;
mkdir: (path: string) => Promise<unknown>;
- upload: (path: string, file: File) => Promise<unknown>;
+ upload: (path: string, file: File, onProgress?: UploadProgressCallback) => Promise<unknown>;
delete: (path: string) => Promise<unknown>;
download: (path: string) => Promise<void>;
getContent: (path: string) => Promise<{ content: string }>;
diff --git a/frontend/src/lib/services/api-service.ts b/frontend/src/lib/services/api-service.ts
index 2a87c01a7..cc99778c6 100644
--- a/frontend/src/lib/services/api-service.ts
+++ b/frontend/src/lib/services/api-service.ts
@@ -450,12 +450,6 @@ abstract class BaseAPIService {
upgradeInProgressInternal = value;
}
- protected postFile<T = any>(url: string, file: File, params?: SearchParamsOption): Promise<T> {
- const formData = new FormData();
- formData.append('file', file);
- return this.handleResponse<T>(this.api.post(url, formData, params !== undefined ? { params } : undefined));
- }
-
protected async handleResponse<T>(promise: Promise<APIResponse>): Promise<T> {
const response = await promise;
const payload = response.data;
diff --git a/frontend/src/lib/services/build-workspace-service.ts b/frontend/src/lib/services/build-workspace-service.ts
index 2ab0b83c2..c34e20e1c 100644
--- a/frontend/src/lib/services/build-workspace-service.ts
+++ b/frontend/src/lib/services/build-workspace-service.ts
@@ -1,4 +1,5 @@
import BaseAPIService from './api-service';
+import { uploadService, type UploadProgressCallback } from './upload-service';
import { environmentStore } from '#lib/stores/environment.store.svelte';
import type { FileEntry, FileContentResponse } from '#lib/types/shared';
import { downloadBlob, filenameFromPath } from '#lib/utils/browser-download';
@@ -30,14 +31,17 @@ class BuildWorkspaceService extends BaseAPIService {
downloadBlob(res.data, filenameFromPath(path));
}
- async uploadFile(path: string, file: File): Promise<void> {
+ async uploadFile(path: string, file: File, onProgress?: UploadProgressCallback): Promise<void> {
const envId = await environmentStore.getCurrentEnvironmentId();
- const formData = new FormData();
- formData.append('file', file);
+ const uploadId = await uploadService.uploadFile(envId, 'build-workspace', file, onProgress);
return this.handleResponse(
- this.api.post(`/environments/${envId}/builds/browse/upload`, formData, {
- params: { path }
- })
+ this.api.post(
+ `/environments/${envId}/builds/browse/upload`,
+ { uploadId },
+ {
+ params: { path }
+ }
+ )
);
}
diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.ts
index e417cf6d1..7b2a3600f 100644
--- a/frontend/src/lib/services/image-service.ts
+++ b/frontend/src/lib/services/image-service.ts
@@ -1,4 +1,5 @@
import BaseAPIService from './api-service';
+import { uploadService, type UploadProgressCallback } from './upload-service';
import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '#lib/stores/environment.store.svelte';
import type {
ImageSummaryDto,
@@ -191,11 +192,10 @@ class ImageService extends BaseAPIService {
return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));
}
- async uploadImage(file: File, environmentId?: string): Promise<any> {
+ async uploadImage(file: File, environmentId?: string, onProgress?: UploadProgressCallback): Promise<any> {
const envId = await this.resolveEnvironmentId(environmentId);
- const formData = new FormData();
- formData.append('file', file);
- return this.handleResponse(this.api.post(`/environments/${envId}/images/upload`, formData));
+ const uploadId = await uploadService.uploadFile(envId, 'image', file, onProgress);
+ return this.handleResponse(this.api.post(`/environments/${envId}/images/upload`, { uploadId }));
}
async getImageBuilds(options?: SearchPaginationSortRequest): Promise<Paginated<ImageBuildRecord>> {
diff --git a/frontend/src/lib/services/upload-service.ts b/frontend/src/lib/services/upload-service.ts
new file mode 100644
index 000000000..cc260e171
--- /dev/null
+++ b/frontend/src/lib/services/upload-service.ts
@@ -0,0 +1,98 @@
+import BaseAPIService from './api-service';
+
+export type UploadKind = 'image' | 'volume-backup' | 'build-workspace';
+
+export interface UploadSession {
+ id: string;
+ kind: UploadKind;
+ filename: string;
+ size: number;
+ chunkSize: number;
+ totalChunks: number;
+ receivedChunks: number[];
+ complete: boolean;
+ createdAt: string;
+}
+
+export interface ChunkedUploadProgress {
+ chunksDone: number;
+ totalChunks: number;
+ bytesDone: number;
+ totalBytes: number;
+}
+
+export type UploadProgressCallback = (progress: ChunkedUploadProgress) => void;
+
+const chunkRetryAttempts = 3;
+const chunkRetryDelayMs = 1000;
+
+class UploadService extends BaseAPIService {
+ async createSession(envId: string, kind: UploadKind, file: File): Promise<UploadSession> {
+ return this.handleResponse(this.api.post(`/environments/${envId}/uploads/${kind}`, { filename: file.name, size: file.size }));
+ }
+
+ async putChunk(envId: string, kind: UploadKind, uploadId: string, index: number, chunk: Blob): Promise<UploadSession> {
+ return this.handleResponse(
+ this.api.put(`/environments/${envId}/uploads/${kind}/${uploadId}/chunks/${index}`, chunk, {
+ headers: { 'Content-Type': 'application/octet-stream' }
+ })
+ );
+ }
+
+ async getSession(envId: string, kind: UploadKind, uploadId: string): Promise<UploadSession> {
+ return this.handleResponse(this.api.get(`/environments/${envId}/uploads/${kind}/${uploadId}`));
+ }
+
+ async deleteSession(envId: string, kind: UploadKind, uploadId: string): Promise<void> {
+ await this.api.delete(`/environments/${envId}/uploads/${kind}/${uploadId}`);
+ }
+
+ // Uploads a file as sequential chunks with per-chunk retry, so it passes
+ // reverse proxies that reject large request bodies. Returns the uploadId of
+ // the complete session for the caller to pass to the consuming endpoint.
+ async uploadFile(envId: string, kind: UploadKind, file: File, onProgress?: UploadProgressCallback): Promise<string> {
+ const session = await this.createSession(envId, kind, file);
+ let received = new Set(session.receivedChunks);
+
+ const chunkBytes = (index: number) =>
+ index === session.totalChunks - 1 ? file.size - index * session.chunkSize : session.chunkSize;
+ const report = () => {
+ if (!onProgress) return;
+ let bytesDone = 0;
+ for (const index of received) bytesDone += chunkBytes(index);
+ onProgress({ chunksDone: received.size, totalChunks: session.totalChunks, bytesDone, totalBytes: file.size });
+ };
+ report();
+
+ for (let index = 0; index < session.totalChunks; index++) {
+ if (received.has(index)) continue;
+ const start = index * session.chunkSize;
+ const chunk = file.slice(start, Math.min(start + session.chunkSize, file.size));
+
+ for (let attempt = 1; ; attempt++) {
+ try {
+ const updated = await this.putChunk(envId, kind, session.id, index, chunk);
+ received = new Set(updated.receivedChunks);
+ break;
+ } catch (error) {
+ if (attempt >= chunkRetryAttempts) {
+ await this.deleteSession(envId, kind, session.id).catch(() => {});
+ throw error;
+ }
+ await new Promise((resolve) => setTimeout(resolve, chunkRetryDelayMs * attempt));
+ // Resume: skip anything the server already has.
+ try {
+ received = new Set((await this.getSession(envId, kind, session.id)).receivedChunks);
+ if (received.has(index)) break;
+ } catch {
+ // The status check is best-effort; keep retrying the chunk.
+ }
+ }
+ }
+ report();
+ }
+ return session.id;
+ }
+}
+
+export const uploadService = new UploadService();
diff --git a/frontend/src/lib/services/volume-backup-service.ts b/frontend/src/lib/services/volume-backup-service.ts
index c71a05b6f..9413e9c11 100644
--- a/frontend/src/lib/services/volume-backup-service.ts
+++ b/frontend/src/lib/services/volume-backup-service.ts
@@ -1,4 +1,5 @@
import BaseAPIService from './api-service';
+import { uploadService, type UploadProgressCallback } from './upload-service';
import { environmentStore } from '#lib/stores/environment.store.svelte';
import type { BackupEntry } from '#lib/types/shared';
import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared';
@@ -68,9 +69,10 @@ class VolumeBackupService extends BaseAPIService {
link.remove();
}
- async uploadAndRestore(volumeName: string, file: File): Promise<any> {
+ async uploadAndRestore(volumeName: string, file: File, onProgress?: UploadProgressCallback): Promise<any> {
const envId = await environmentStore.getCurrentEnvironmentId();
- return this.postFile(`/environments/${envId}/volumes/${volumeName}/backups/upload`, file);
+ const uploadId = await uploadService.uploadFile(envId, 'volume-backup', file, onProgress);
+ return this.handleResponse(this.api.post(`/environments/${envId}/volumes/${volumeName}/backups/upload`, { uploadId }));
}
}
diff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelte
index 23d00df0a..219c94853 100644
--- a/frontend/src/routes/(app)/images/+page.svelte
+++ b/frontend/src/routes/(app)/images/+page.svelte
@@ -9,7 +9,9 @@
import { displaySize, FileDropZone, MEGABYTE, type FileDropZoneProps } from '#lib/components/ui/file-drop-zone';
import ImageTable from './image-table.svelte';
import { m } from '#lib/paraglide/messages';
+ import { Progress } from '#lib/components/ui/progress/index.js';
import { imageService } from '#lib/services/image-service';
+ import type { ChunkedUploadProgress } from '#lib/services/upload-service';
import { environmentStore } from '#lib/stores/environment.store.svelte';
import { hasPermission } from '#lib/utils/auth';
import { queryKeys } from '#lib/query/query-keys';
@@ -35,6 +37,7 @@
let isConfirmPruneDialogOpen = $state(false);
let isRefreshing = $state(false);
let uploadedFiles = $state<File[]>([]);
+ let uploadProgress = $state<ChunkedUploadProgress | null>(null);
let imagePruneMode = $state<'dangling' | 'all' | 'olderThan'>('dangling');
let imagePruneUntil = $state('');
const envId = $derived(environmentStore.selected?.id || '0');
@@ -114,10 +117,12 @@
mutationFn: async ({ files, requestedEnvId }: { files: File[]; requestedEnvId: string }) => {
for (const file of files) {
try {
- await imageService.uploadImage(file, requestedEnvId);
+ await imageService.uploadImage(file, requestedEnvId, (progress) => (uploadProgress = progress));
toast.success(m.images_upload_success());
} catch {
toast.error(m.images_upload_failed());
+ } finally {
+ uploadProgress = null;
}
}
},
@@ -390,8 +395,18 @@
</div>
{/if}
{#if isUploading}
- <div class="flex items-center gap-2 text-sm text-muted-foreground">
- <Spinner class="size-4" />{m.images_uploading()}
+ <div class="flex flex-col gap-2">
+ <div class="flex items-center gap-2 text-sm text-muted-foreground">
+ <Spinner class="size-4" />{m.images_uploading()}
+ {#if uploadProgress}
+ <span class="ml-auto tabular-nums"
+ >{Math.round((uploadProgress.bytesDone / uploadProgress.totalBytes) * 100)}%</span
+ >
+ {/if}
+ </div>
+ {#if uploadProgress}
+ <Progress value={(uploadProgress.bytesDone / uploadProgress.totalBytes) * 100} class="h-1.5 rounded-full" />
+ {/if}
</div>
{/if}
</div>
diff --git a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
index 5ef64b05f..379b0d63a 100644
--- a/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
+++ b/frontend/src/routes/(app)/images/builds/build-workspace-browser.svelte
@@ -18,6 +18,7 @@
import { queryKeys } from '#lib/query/query-keys';
import type { FileEntry } from '#lib/types/shared';
import { sortFileEntries, type FileProvider } from '#lib/components/file-browser';
+ import type { UploadProgressCallback } from '#lib/services/upload-service';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
let {
@@ -103,7 +104,8 @@
const uploadMutation = createMutation(() => ({
mutationKey: ['build-workspace', 'upload', envId],
- mutationFn: ({ path, file }: { path: string; file: File }) => provider.upload(path, file),
+ mutationFn: ({ path, file, onProgress }: { path: string; file: File; onProgress?: UploadProgressCallback }) =>
+ provider.upload(path, file, onProgress),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: queryKeys.buildWorkspace.listPrefix(envId) });
}
@@ -277,8 +279,8 @@
<FileUploadDialog
bind:open={showUpload}
{currentPath}
- onUpload={async (file) => {
- await uploadMutation.mutateAsync({ path: currentPath, file });
+ onUpload={async (file, onProgress) => {
+ await uploadMutation.mutateAsync({ path: currentPath, file, onProgress });
await filesQuery.refetch();
}}
/>
diff --git a/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte b/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte
index 507f61417..115b52b7a 100644
--- a/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte
+++ b/frontend/src/routes/(app)/images/builds/components/build-workspace-panel.svelte
@@ -30,7 +30,7 @@
const provider: FileProvider = {
list: (path: string) => buildWorkspaceService.listDirectory(path),
mkdir: (path: string) => buildWorkspaceService.createDirectory(path),
- upload: (path: string, file: File) => buildWorkspaceService.uploadFile(path, file),
+ upload: (path: string, file: File, onProgress) => buildWorkspaceService.uploadFile(path, file, onProgress),
delete: (path: string) => buildWorkspaceService.deleteFile(path),
download: (path: string) => buildWorkspaceService.downloadFile(path),
getContent: (path: string) => buildWorkspaceService.getFileContent(path)
diff --git a/types/upload/upload.go b/types/upload/upload.go
new file mode 100644
index 000000000..6581c98a8
--- /dev/null
+++ b/types/upload/upload.go
@@ -0,0 +1,47 @@
+// Package upload defines the chunked upload-session wire types shared by the
+// backend, frontend contract, and CLI.
+package upload
+
+import "time"
+
+// Session kinds tie an upload session to the domain endpoint allowed to
+// consume it.
+const (
+ KindImage = "image"
+ KindVolumeBackup = "volume-backup"
+ KindBuildWorkspace = "build-workspace"
+)
+
+// Chunk size bounds keep every chunk request safely under common reverse-proxy
+// and WAF body limits (~100 MB).
+const (
+ DefaultChunkSize int64 = 10 * 1024 * 1024
+ MinChunkSize int64 = 1 * 1024 * 1024
+ MaxChunkSize int64 = 50 * 1024 * 1024
+)
+
+// CreateSessionRequest starts a chunked upload session.
+type CreateSessionRequest struct {
+ Filename string `json:"filename" required:"true" doc:"Original filename; validated per kind"`
+ Size int64 `json:"size" required:"true" minimum:"1" doc:"Total file size in bytes"`
+ ChunkSize int64 `json:"chunkSize,omitempty" doc:"Chunk size in bytes; server default and bounds apply"`
+}
+
+// Session describes a chunked upload session, including which chunks have been
+// received so clients can resume by re-sending only the missing ones.
+type Session struct {
+ CreatedAt time.Time `json:"createdAt"`
+ ID string `json:"id"`
+ Kind string `json:"kind"`
+ Filename string `json:"filename"`
+ ReceivedChunks []int `json:"receivedChunks"`
+ Size int64 `json:"size"`
+ ChunkSize int64 `json:"chunkSize"`
+ TotalChunks int `json:"totalChunks"`
+ Complete bool `json:"complete"`
+}
+
+// ConsumeRequest references a complete upload session from a domain endpoint.
+type ConsumeRequest struct {
+ UploadID string `json:"uploadId" required:"true" doc:"ID of a complete upload session"`
+}