Every file is written to .vcom-part-<rand>-<name>, closed (a Close error fails the item: N-P2-6), chmod/chtimes'ed and only then renamed over the target, so a failed or cancelled overwrite keeps the old file (N-P0-4) and leaves no temp. Without atomic replace the old file is renamed aside and restored on failure. Directories are merged, never replaced (N-P0-7), and get their real mode/mtime post-order (N-P1-17); symlinks are copied as links, broken ones too (N-P1-8); mode and mtime are preserved (N-P1-9); FIFOs and devices are skipped with a warning. The copy loop goes through a ctx-aware reader with Size() and throttled byte progress. Conflict and error policies are wired in here; their tests follow in 3.3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
185 lines
5 KiB
Go
185 lines
5 KiB
Go
package transfer
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"time"
|
|
"unicode/utf8"
|
|
|
|
"vcom/internal/vfs"
|
|
)
|
|
|
|
// oldPrefix names the aside copy of a replaced file on FSes without atomic
|
|
// replace: <dir>/.vcom-old-<8hex>-<name>.
|
|
const oldPrefix = ".vcom-old-"
|
|
|
|
// maxName is NAME_MAX on Linux and OpenSSH servers.
|
|
const maxName = 255
|
|
|
|
// WriteOptions control WriteAtomic.
|
|
type WriteOptions struct {
|
|
Perm fs.FileMode // final mode (0 → 0644); the temp file is 0600 while being written
|
|
ModTime time.Time // zero → leave as written
|
|
Replace bool // replace an existing target (else ErrExist if it exists)
|
|
Fsync bool // fsync before the rename (if the FS supports it)
|
|
}
|
|
|
|
// WriteAtomic is the only way the engine (and archive.Create, remote edit)
|
|
// writes a file: fill writes into <dir>/.vcom-part-<8hex>-<name>, which is
|
|
// then closed, chmod'ed, chtimes'ed and renamed over path. On any error or
|
|
// cancellation the temp file is removed and an existing target is untouched:
|
|
// it is replaced only by the final rename (N-P0-4). A Close error is an
|
|
// error (N-P2-6).
|
|
func WriteAtomic(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fill func(w io.Writer) error) error {
|
|
tmp, err := writeTemp(ctx, fsys, path, o, fill)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := commit(ctx, fsys, tmp, path, o.Replace); err != nil {
|
|
removeQuiet(ctx, fsys, tmp)
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// tempName returns <dir>/<prefix><8hex>-<name>, truncating name so the result
|
|
// fits NAME_MAX.
|
|
func tempName(fsys vfs.FS, path, prefix string) string {
|
|
ops := fsys.Paths()
|
|
var b [4]byte
|
|
_, _ = rand.Read(b[:])
|
|
head := prefix + hex.EncodeToString(b[:]) + "-"
|
|
name := ops.Base(path)
|
|
if len(head)+len(name) > maxName {
|
|
name = name[:maxName-len(head)]
|
|
for len(name) > 0 && !utf8.ValidString(name) {
|
|
name = name[:len(name)-1]
|
|
}
|
|
}
|
|
return ops.Join(ops.Dir(path), head+name)
|
|
}
|
|
|
|
// writeTemp writes the content into a fresh temp file next to path and
|
|
// returns its name; on error nothing is left behind.
|
|
func writeTemp(ctx context.Context, fsys vfs.FS, path string, o WriteOptions, fill func(w io.Writer) error) (string, error) {
|
|
if err := ctx.Err(); err != nil {
|
|
return "", err
|
|
}
|
|
var (
|
|
tmp string
|
|
f vfs.File
|
|
err error
|
|
)
|
|
for range 8 {
|
|
tmp = tempName(fsys, path, partPrefix)
|
|
f, err = fsys.Create(ctx, tmp, 0o600, vfs.CreateExcl)
|
|
if !errors.Is(err, vfs.ErrExist) {
|
|
break
|
|
}
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
// A hung network write is released by closing the file on cancel.
|
|
stop := context.AfterFunc(ctx, func() { _ = f.Close() })
|
|
err = fill(&ctxWriter{ctx: ctx, f: f})
|
|
if err == nil && o.Fsync && fsys.Caps().Fsync {
|
|
err = f.Sync()
|
|
}
|
|
var cerr error
|
|
if stop() {
|
|
cerr = f.Close()
|
|
}
|
|
if ctx.Err() != nil {
|
|
err = ctx.Err()
|
|
}
|
|
if err == nil && cerr != nil {
|
|
err = fmt.Errorf("close: %w", cerr)
|
|
}
|
|
if err == nil {
|
|
err = finishMeta(ctx, fsys, tmp, o)
|
|
}
|
|
if err != nil {
|
|
removeQuiet(ctx, fsys, tmp)
|
|
return "", err
|
|
}
|
|
return tmp, nil
|
|
}
|
|
|
|
func finishMeta(ctx context.Context, fsys vfs.FS, p string, o WriteOptions) error {
|
|
caps := fsys.Caps()
|
|
perm := o.Perm
|
|
if perm == 0 {
|
|
perm = 0o644
|
|
}
|
|
if caps.Chmod {
|
|
if err := fsys.Chmod(ctx, p, perm); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if caps.Chtimes && !o.ModTime.IsZero() {
|
|
if err := fsys.Chtimes(ctx, p, o.ModTime, o.ModTime); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// commit renames tmp to path. Without replace it fails with ErrExist when
|
|
// path exists. With replace on an FS without atomic replace it renames the
|
|
// old target aside first and restores it if the second rename fails.
|
|
func commit(ctx context.Context, fsys vfs.FS, tmp, path string, replace bool) error {
|
|
if !replace {
|
|
return fsys.Rename(ctx, tmp, path, vfs.NoReplace)
|
|
}
|
|
if fsys.Caps().AtomicReplace {
|
|
return fsys.Rename(ctx, tmp, path, vfs.Replace)
|
|
}
|
|
err := fsys.Rename(ctx, tmp, path, vfs.NoReplace)
|
|
if !errors.Is(err, vfs.ErrExist) {
|
|
return err
|
|
}
|
|
old := tempName(fsys, path, oldPrefix)
|
|
if err := fsys.Rename(ctx, path, old, vfs.NoReplace); err != nil {
|
|
return err
|
|
}
|
|
if err := fsys.Rename(ctx, tmp, path, vfs.NoReplace); err != nil {
|
|
if rerr := fsys.Rename(context.WithoutCancel(ctx), old, path, vfs.NoReplace); rerr != nil {
|
|
return fmt.Errorf("%w (and restoring the old file from %s failed: %v)", err, old, rerr)
|
|
}
|
|
return err
|
|
}
|
|
removeQuiet(ctx, fsys, old)
|
|
return nil
|
|
}
|
|
|
|
// removeQuiet deletes a temp file even when ctx is already cancelled.
|
|
func removeQuiet(ctx context.Context, fsys vfs.FS, p string) {
|
|
_ = fsys.Remove(context.WithoutCancel(ctx), p)
|
|
}
|
|
|
|
// ctxWriter stops writing once ctx is done and keeps the File's ReadFrom
|
|
// (pkg/sftp uses it for concurrent writes; N-P1-6).
|
|
type ctxWriter struct {
|
|
ctx context.Context
|
|
f vfs.File
|
|
}
|
|
|
|
func (w *ctxWriter) Write(p []byte) (int, error) {
|
|
if err := w.ctx.Err(); err != nil {
|
|
return 0, err
|
|
}
|
|
return w.f.Write(p)
|
|
}
|
|
|
|
func (w *ctxWriter) ReadFrom(r io.Reader) (int64, error) {
|
|
if rf, ok := w.f.(io.ReaderFrom); ok {
|
|
return rf.ReadFrom(r)
|
|
}
|
|
return io.Copy(struct{ io.Writer }{w}, r)
|
|
}
|