vcom/internal/transfer/prepare.go
vrubelroman edf196a149 fix(transfer): clean up temp files left by a dead connection
A failed write whose temp file cannot be removed (the connection is gone)
is remembered by the executor and removed again on Retry (typically after
the pool reconnected inside OnError) and at the end of Execute; whatever
still cannot be removed is named in Report.Warnings. Prepare now always
lists ToDir once (instead of a Lstat per root), so leftovers next to a
single top-level file are reported too. TestOverwriteThenDrop checks this
strictly, TestOverwriteThenDropRetryLeavesNoTemp covers the retry path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 04:15:40 +03:00

218 lines
5.8 KiB
Go

package transfer
import (
"context"
"errors"
"fmt"
"strings"
"vcom/internal/vfs"
)
// partPrefix names temp files of WriteAtomic: <dir>/.vcom-part-<8hex>-<name>.
const partPrefix = ".vcom-part-"
// Prepare validates req and builds the plan (design §4.2): the target is
// writable and a directory; no root is the same file as its target and no
// directory is copied into itself (SameFile/Within, through symlinks); the
// source is walked once; every target directory that already exists is
// listed once (not one call per file) to find Existing and the Conflicts;
// totals are exact. progress, if non-nil, receives Scanning snapshots.
func Prepare(ctx context.Context, req Request, progress func(Progress)) (*Plan, error) {
if req.To == nil || req.From == nil {
return nil, errors.New("transfer: incomplete request")
}
if req.Op == Move {
req.Opts.Symlinks = CopyLinks // a move never follows links
}
if req.To.Caps().ReadOnly {
return nil, fmt.Errorf("%w: %s", ErrReadOnly, req.To.Label())
}
toOps := req.To.Paths()
req.ToDir = toOps.Clean(req.ToDir)
if fi, err := req.To.Stat(ctx, req.ToDir); err != nil {
return nil, err
} else if !fi.IsDir() {
return nil, fmt.Errorf("%w: %s", ErrTargetNotDir, req.ToDir)
}
if _, ok := req.From.(FSBacked); !ok && req.Op == Move {
return nil, errors.New("transfer: move needs a file-system source")
}
if fb, ok := req.From.(FSBacked); ok {
if req.Op == Move && fb.FS().Caps().ReadOnly {
return nil, fmt.Errorf("%w: cannot move from %s", ErrReadOnly, fb.FS().Label())
}
if err := checkRoots(ctx, fb, req); err != nil {
return nil, err
}
if fs, ok := fb.(*fsSource); ok && fs.sym != req.Opts.Symlinks {
cp := *fs
cp.sym = req.Opts.Symlinks
req.From = &cp
}
}
plan := &Plan{Req: req}
report := func() {
if progress != nil {
progress(Progress{Phase: Scanning, FilesTotal: plan.TotalFiles, BytesTotal: plan.TotalBytes})
}
}
err := req.From.Walk(ctx, func(it Item) error {
if it.Warning != "" {
plan.Warnings = append(plan.Warnings, it.Rel+": "+it.Warning)
}
switch it.Kind {
case File:
plan.TotalFiles++
plan.TotalBytes += it.Size
case Symlink:
plan.TotalFiles++
case Special:
plan.Warnings = append(plan.Warnings, it.Rel+": special file skipped")
}
plan.Items = append(plan.Items, it)
if len(plan.Items)%256 == 0 {
report()
}
return nil
})
if err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
seen := map[string]bool{}
for _, it := range plan.Items {
if !strings.Contains(it.Rel, "/") {
if seen[it.Rel] {
return nil, fmt.Errorf("%w: %s", ErrDuplicateName, it.Rel)
}
seen[it.Rel] = true
}
}
if err := findExisting(ctx, plan); err != nil {
return nil, err
}
report()
if fb, ok := req.From.(FSBacked); ok {
a, b := fb.FS(), req.To
plan.SameConn = (a.Kind() == vfs.KindLocal && b.Kind() == vfs.KindLocal) ||
(a == b && a.Volume() == b.Volume())
}
return plan, nil
}
// checkRoots refuses roots that are their own target or contain ToDir.
func checkRoots(ctx context.Context, fb FSBacked, req Request) error {
src := fb.FS()
for _, root := range fb.Roots() {
dst := req.To.Paths().Join(req.ToDir, src.Paths().Base(root))
same, err := vfs.SameFile(ctx, src, root, req.To, dst)
if err != nil {
return err
}
if same {
return fmt.Errorf("%w: %s", ErrSameFile, root)
}
if src.Volume() != req.To.Volume() {
continue
}
fi, err := src.Lstat(ctx, root)
if err != nil {
return err
}
isDir := fi.IsDir() || (req.Opts.Symlinks == FollowLinks && fi.NavigableDir())
if !isDir {
continue
}
in, err := vfs.Within(ctx, req.To, req.ToDir, root)
if err != nil {
return err
}
if in {
return fmt.Errorf("%w: %s → %s", ErrIntoItself, root, req.ToDir)
}
}
return nil
}
// dstPath maps an item's Rel onto the target FS.
func dstPath(to vfs.FS, toDir, rel string) string {
return to.Paths().Join(append([]string{toDir}, strings.Split(rel, "/")...)...)
}
func splitRel(rel string) (parent, name string) {
i := strings.LastIndexByte(rel, '/')
if i < 0 {
return "", rel
}
return rel[:i], rel[i+1:]
}
// findExisting fills Existing and Conflicts. ToDir and the target
// directories a source directory merges into are listed — one ReadDir per
// directory, never a stat per file (N-P2-4/5).
func findExisting(ctx context.Context, plan *Plan) error {
to, toDir := plan.Req.To, plan.Req.ToDir
listings := map[string]map[string]vfs.FileInfo{}
list := func(rel, p string) error {
ents, err := to.ReadDir(ctx, p)
if err != nil {
return err
}
m := make(map[string]vfs.FileInfo, len(ents))
for _, e := range ents {
m[e.Name] = e
if strings.HasPrefix(e.Name, partPrefix) {
plan.Warnings = append(plan.Warnings, fmt.Sprintf("%s: leftover of an interrupted transfer",
to.Paths().Join(p, e.Name)))
}
}
listings[rel] = m
return nil
}
// ToDir is always listed once: it gives Existing for every root without
// a stat per root and reveals temp files left by an interrupted transfer
// (a dead connection cannot remove them).
if err := list("", toDir); err != nil {
return err
}
for i := range plan.Items {
if i%256 == 0 {
if err := ctx.Err(); err != nil {
return err
}
}
it := &plan.Items[i]
parent, name := splitRel(it.Rel)
var existing *vfs.FileInfo
if l, ok := listings[parent]; ok {
if fi, ok := l[name]; ok {
existing = &fi
}
}
it.Existing = existing
if existing == nil {
continue
}
switch {
case it.Kind == Dir && existing.IsDir():
if err := list(it.Rel, dstPath(to, toDir, it.Rel)); err != nil {
return err
}
case it.Kind == Dir || existing.IsDir():
plan.Conflicts = append(plan.Conflicts, Conflict{Item: *it, Kind: TypeMismatch})
case it.Kind == Special:
default:
plan.Conflicts = append(plan.Conflicts, Conflict{Item: *it, Kind: FileFile})
}
}
return nil
}