Skip to content

Modern Docker Management, Designed for Everyone

fix: false 409 workspace conflict when saving files in imported projects (#3560)

Kyle Mendell10c9a269f8e8
diff --git a/backend/internal/volume/workspace.go b/backend/internal/volume/workspace.go
index d3ddf86c1..04829e067 100644
--- a/backend/internal/volume/workspace.go
+++ b/backend/internal/volume/workspace.go
@@ -562,7 +562,7 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName st
}
uploadReferences := make([]workspacepkg.UploadReference, 0, len(manifest.FileChanges))
for _, change := range manifest.FileChanges {
- uploadReferences = append(uploadReferences, workspacepkg.UploadReference{Operation: change.Operation, UploadIndex: change.UploadIndex})
+ uploadReferences = append(uploadReferences, workspacepkg.UploadReference{Operation: change.Operation, UploadIndex: change.UploadIndex, BaselineIndex: change.BaselineIndex})
if err := validateVolumeWorkspaceFileChangeInternal(change); err != nil {
return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, err)
}
diff --git a/backend/pkg/projects/workspace.go b/backend/pkg/projects/workspace.go
index 0ffc128fd..6b85176f6 100644
--- a/backend/pkg/projects/workspace.go
+++ b/backend/pkg/projects/workspace.go
@@ -176,7 +176,12 @@ func (w *projectWorkspaceTreeWalkerInternal) visit(rel string, entry fs.DirEntry
case !info.Mode().IsRegular():
kind = "special"
}
- pkgutils.WriteFileTreeRevisionEntry(w.revisionHash, rel, kind, info.Size(), info.ModTime().UnixNano(), info.Mode().String(), false)
+ // The revision is structural (path + kind only): running containers write
+ // into their own project directory continuously (logs, certs, app state),
+ // so keying on mtime/size would invalidate every workspace draft for a
+ // live project and make saves 409 forever (#3199). Structural changes —
+ // files appearing, disappearing, or changing kind — still conflict.
+ pkgutils.WriteFileTreeRevisionEntry(w.revisionHash, rel, kind, 0, 0, "", false)
w.entryCount++
size := info.Size()
@@ -222,13 +227,18 @@ func classifyProjectWorkspaceFileInternal(filePath string, size, maxFileSizeByte
return true, ""
}
+// ApplyProjectWorkspaceChanges applies changes in order without internal
+// rollback: on any error, earlier changes remain on disk. Callers own
+// atomicity — ProjectService.UpdateProjectWorkspace wraps every save in
+// BackupProjectUpdateScope / RestoreProjectUpdateBackup, and project creation
+// removes the whole directory on failure.
func ApplyProjectWorkspaceChanges(projectPath string, changes []project.WorkspaceFileChange, uploads map[int][]byte, opts ProjectWorkspaceApplyOptions) error {
if opts.MaxFileSizeBytes <= 0 {
opts.MaxFileSizeBytes = workspacepkg.MaxFileSizeBytes(workspacepkg.DefaultMaxFileSizeMB)
}
uploadReferences := make([]workspacepkg.UploadReference, 0, len(changes))
for _, change := range changes {
- uploadReferences = append(uploadReferences, workspacepkg.UploadReference{Operation: change.Operation, UploadIndex: change.UploadIndex})
+ uploadReferences = append(uploadReferences, workspacepkg.UploadReference{Operation: change.Operation, UploadIndex: change.UploadIndex, BaselineIndex: change.BaselineIndex})
}
if err := workspacepkg.ValidateUploadIndices(uploadReferences, len(uploads), project.FileOpCreateFile, project.FileOpUpdateFile); err != nil {
return err
@@ -293,7 +303,11 @@ func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool,
case project.FileOpCreateFolder:
return createProjectWorkspaceFolderInternal(root, protected, rel)
case project.FileOpUpdateFile:
- return updateProjectWorkspaceFileInternal(root, protected, rel, uploads[*change.UploadIndex], maxFileSizeBytes)
+ var baseline []byte
+ if change.BaselineIndex != nil {
+ baseline = uploads[*change.BaselineIndex]
+ }
+ return updateProjectWorkspaceFileInternal(root, protected, rel, uploads[*change.UploadIndex], baseline, change.BaselineIndex != nil, maxFileSizeBytes)
case project.FileOpRename:
newName, err := pkgutils.ValidateFileName(change.NewName)
if err != nil {
@@ -362,7 +376,7 @@ func createProjectWorkspaceFolderInternal(root *os.Root, protected map[string]bo
return nil
}
-func updateProjectWorkspaceFileInternal(root *os.Root, protected map[string]bool, rel string, content []byte, maxFileSizeBytes int64) error {
+func updateProjectWorkspaceFileInternal(root *os.Root, protected map[string]bool, rel string, content, baseline []byte, baselineSet bool, maxFileSizeBytes int64) error {
if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
return err
}
@@ -387,12 +401,38 @@ func updateProjectWorkspaceFileInternal(root *os.Root, protected map[string]bool
return errors.WrapIf(ErrProjectWorkspaceSymlinkPath, "symlink files are not supported")
}
+ // The workspace revision is structural only, so an external edit to this
+ // same file would otherwise be silently overwritten. The client uploads
+ // the content its draft was based on; a mismatch with the current on-disk
+ // content is a real per-file conflict. Checked here, in apply order, so an
+ // earlier rename/move in the same manifest has already landed and the
+ // comparison targets the right path. The read is capped just past the
+ // baseline length: a longer on-disk file differs by definition.
+ if baselineSet {
+ current, err := readProjectWorkspaceFileLimitedInternal(root, rel, int64(len(baseline))+1)
+ if err != nil {
+ return errors.WrapIf(err, "read project workspace file")
+ }
+ if !bytes.Equal(current, baseline) {
+ return errors.WrapIf(ErrProjectWorkspaceRevisionConflict, "file content changed since it was loaded")
+ }
+ }
+
if err := root.WriteFile(rel, content, pkgutils.FilePerm); err != nil {
return errors.WrapIf(err, "update project workspace file")
}
return nil
}
+func readProjectWorkspaceFileLimitedInternal(root *os.Root, rel string, maxBytes int64) ([]byte, error) {
+ f, err := root.Open(rel)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = f.Close() }()
+ return io.ReadAll(io.LimitReader(f, maxBytes))
+}
+
func renameProjectWorkspacePathInternal(root *os.Root, protected map[string]bool, rel, newName string) error {
if err := ensureWritableProjectRelPathInternal(protected, rel); err != nil {
return err
diff --git a/backend/pkg/projects/workspace_test.go b/backend/pkg/projects/workspace_test.go
index bad5ae9f6..3edac4ae8 100644
--- a/backend/pkg/projects/workspace_test.go
+++ b/backend/pkg/projects/workspace_test.go
@@ -391,3 +391,58 @@ func TestProtectedProjectFilePaths_IncludesComposeOverrideCandidates(t *testing.
assert.Truef(t, protected[candidate], "expected %q to be protected", candidate)
}
}
+
+func TestApplyProjectWorkspaceChanges_ContentChurnDoesNotConflict(t *testing.T) {
+ projectDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "app.log"), []byte("line1\n"), 0o644))
+
+ _, revision, _, err := ReadProjectWorkspace(projectDir, 3, "", "compose.yaml", 0, 0)
+ require.NoError(t, err)
+
+ // A running container appending to files in its own project directory
+ // (changed size + mtime) must not invalidate the workspace draft (#3199).
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "app.log"), []byte("line1\nline2\n"), 0o644))
+
+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{
+ {Operation: project.FileOpCreateFile, RelativePath: "notes.txt", UploadIndex: new(0)},
+ }, map[int][]byte{0: []byte("hello")}, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml", ExpectedRevision: revision, MaxDepth: 3})
+ require.NoError(t, err)
+ require.FileExists(t, filepath.Join(projectDir, "notes.txt"))
+
+ // Structural drift (notes.txt now exists) does conflict against the old revision.
+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{
+ {Operation: project.FileOpDelete, RelativePath: "app.log"},
+ }, nil, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml", ExpectedRevision: revision, MaxDepth: 3})
+ require.ErrorIs(t, err, ErrProjectWorkspaceRevisionConflict)
+}
+
+func TestApplyProjectWorkspaceChanges_BaselineGuardsConcurrentEdit(t *testing.T) {
+ projectDir := t.TempDir()
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services: {}\n"), 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config.txt"), []byte("original\n"), 0o644))
+
+ _, revision, _, err := ReadProjectWorkspace(projectDir, 3, "", "compose.yaml", 0, 0)
+ require.NoError(t, err)
+
+ // The structural revision still matches after an external content edit,
+ // but the uploaded baseline no longer matches the on-disk content: the
+ // stale draft must conflict instead of silently overwriting the newer file.
+ require.NoError(t, os.WriteFile(filepath.Join(projectDir, "config.txt"), []byte("external newer edit\n"), 0o644))
+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{
+ {Operation: project.FileOpUpdateFile, RelativePath: "config.txt", UploadIndex: new(0), BaselineIndex: new(1)},
+ }, map[int][]byte{0: []byte("stale draft\n"), 1: []byte("original\n")}, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml", ExpectedRevision: revision, MaxDepth: 3})
+ require.ErrorIs(t, err, ErrProjectWorkspaceRevisionConflict)
+ content, err := os.ReadFile(filepath.Join(projectDir, "config.txt"))
+ require.NoError(t, err)
+ require.Equal(t, "external newer edit\n", string(content))
+
+ // A baseline matching the current on-disk content saves normally.
+ err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{
+ {Operation: project.FileOpUpdateFile, RelativePath: "config.txt", UploadIndex: new(0), BaselineIndex: new(1)},
+ }, map[int][]byte{0: []byte("fresh draft\n"), 1: []byte("external newer edit\n")}, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml", ExpectedRevision: revision, MaxDepth: 3})
+ require.NoError(t, err)
+ content, err = os.ReadFile(filepath.Join(projectDir, "config.txt"))
+ require.NoError(t, err)
+ require.Equal(t, "fresh draft\n", string(content))
+}
diff --git a/backend/pkg/workspace/workspace.go b/backend/pkg/workspace/workspace.go
index c7cec7ab8..4ae35b4d6 100644
--- a/backend/pkg/workspace/workspace.go
+++ b/backend/pkg/workspace/workspace.go
@@ -11,8 +11,9 @@ import (
const DefaultMaxFileSizeMB = 10
type UploadReference struct {
- Operation string
- UploadIndex *int
+ Operation string
+ UploadIndex *int
+ BaselineIndex *int
}
func EffectiveMaxFileSizeMB(configured int) int {
@@ -75,6 +76,22 @@ func ValidateUploadIndices(changes []UploadReference, uploadCount int, createFil
}
used[index] = struct{}{}
}
+ for _, change := range changes {
+ if change.BaselineIndex == nil {
+ continue
+ }
+ if change.Operation != updateFileOperation {
+ return errors.Errorf("baselineIndex is not allowed for %s", change.Operation)
+ }
+ index := *change.BaselineIndex
+ if index < 0 || index >= uploadCount {
+ return errors.Errorf("baselineIndex %d is out of range", index)
+ }
+ if _, exists := used[index]; exists {
+ return errors.Errorf("baselineIndex %d is duplicated", index)
+ }
+ used[index] = struct{}{}
+ }
if len(used) != uploadCount {
return errors.New("one or more uploaded files are unused")
}
diff --git a/frontend/src/lib/types/workspace.ts b/frontend/src/lib/types/workspace.ts
index 43d766ad2..f103bcbf9 100644
--- a/frontend/src/lib/types/workspace.ts
+++ b/frontend/src/lib/types/workspace.ts
@@ -40,6 +40,7 @@ export interface WorkspaceFileChange {
newName?: string;
newParentPath?: string;
uploadIndex?: number;
+ baselineIndex?: number;
recursive?: boolean;
}
diff --git a/frontend/src/lib/utils/workspace-files.ts b/frontend/src/lib/utils/workspace-files.ts
index 728aaf571..e14e416b4 100644
--- a/frontend/src/lib/utils/workspace-files.ts
+++ b/frontend/src/lib/utils/workspace-files.ts
@@ -28,7 +28,9 @@ export function buildWorkspaceMultipartUpdate<T extends WorkspaceDisplayFileChan
fileContents: Record<string, string>,
loadedFileContents: Record<string, string>
): { fileChanges: T[]; files: File[] } {
- const fileChanges = draftChanges.map(({ uploadIndex: _uploadIndex, ...change }) => ({ ...change }) as T);
+ const fileChanges = draftChanges.map(
+ ({ uploadIndex: _uploadIndex, baselineIndex: _baselineIndex, ...change }) => ({ ...change }) as T
+ );
const files: File[] = [];
const changedPaths = Object.keys(fileContents).filter(
(relativePath) => fileContents[relativePath] !== loadedFileContents[relativePath]
@@ -61,6 +63,17 @@ export function buildWorkspaceMultipartUpdate<T extends WorkspaceDisplayFileChan
if (change.uploadIndex === undefined) stageText(change, fileContents[relativePath] ?? '');
}
+ // Every update also carries the content the draft was based on, so the
+ // backend can reject a save that would overwrite a concurrent external
+ // edit to the same file.
+ for (const change of fileChanges) {
+ if (change.operation !== 'update_file') continue;
+ const baseline = loadedFileContents[change.relativePath];
+ if (baseline === undefined) continue;
+ change.baselineIndex = files.length;
+ files.push(new File([baseline], workspaceFileBasename(change.relativePath), { type: 'text/plain' }));
+ }
+
return { fileChanges, files };
}
diff --git a/types/volume/workspace.go b/types/volume/workspace.go
index 075c1bcdf..43f598d85 100644
--- a/types/volume/workspace.go
+++ b/types/volume/workspace.go
@@ -18,6 +18,11 @@ type WorkspaceFileChange struct {
NewName string `json:"newName,omitempty"`
NewParentPath string `json:"newParentPath,omitempty"`
UploadIndex *int `json:"uploadIndex,omitempty" minimum:"0"`
+ // BaselineIndex references an uploaded copy of the content an update_file
+ // change was drafted against. The volume workspace revision is already
+ // content-aware, so the baseline is accepted for API symmetry with
+ // project workspaces but not separately compared.
+ BaselineIndex *int `json:"baselineIndex,omitempty" minimum:"0"`
BackupID string `json:"backupId,omitempty"`
Recursive bool `json:"recursive,omitempty"`
}
diff --git a/types/workspace/workspace.go b/types/workspace/workspace.go
index ea8124101..7f0aa0679 100644
--- a/types/workspace/workspace.go
+++ b/types/workspace/workspace.go
@@ -38,7 +38,14 @@ type FileChange struct {
NewName string `json:"newName,omitempty"`
NewParentPath string `json:"newParentPath,omitempty"`
UploadIndex *int `json:"uploadIndex,omitempty" minimum:"0"`
- Recursive bool `json:"recursive,omitempty"`
+ // BaselineIndex references an uploaded copy of the content this
+ // update_file change was drafted against. When set, the apply conflicts
+ // if the on-disk content no longer matches it, so a concurrent edit to
+ // the same file is not silently overwritten. Deliberately optional:
+ // imperative clients like the CLI overwrite without ever reading the
+ // file (last-write-wins), while the web editor always sends it.
+ BaselineIndex *int `json:"baselineIndex,omitempty" minimum:"0"`
+ Recursive bool `json:"recursive,omitempty"`
}
type Workspace struct {