test(transfer): remote acceptance on the SSH stand (3.7)

Run the key transfer scenarios over sftpfs: overwrite cut mid-file keeps
the old file (N-P0-4), the same file through two aliases is refused and
never truncated (N-P0-5), broken symlinks up and down (N-P1-8), mode and
mtime (N-P1-9), remote to remote between users (N-P1-10), retry after a
lost connection (N-P1-2), cancel and freeze in the middle of a file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-11-01 04:11:54 +03:00
parent f08467d63b
commit aa6be396c7
2 changed files with 476 additions and 0 deletions

View file

@ -0,0 +1,456 @@
package transfer
// Stage 3.7: the key transfer scenarios over SFTP on the in-process stand
// (internal/testutil/sshtest). The stand serves the real file system, so
// remote paths are local temp paths and results are checked with os.*.
import (
"bytes"
"context"
"errors"
"net"
"os"
"path/filepath"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/crypto/ssh/knownhosts"
"vcom/internal/ssh/conn"
"vcom/internal/testutil/sshtest"
"vcom/internal/vfs"
"vcom/internal/vfs/sftpfs"
)
// rstand is a server, its keys in an isolated known_hosts and a pool with
// fast keepalive (a frozen link is Lost within ~0.4 s).
type rstand struct {
t *testing.T
srv *sshtest.Server
pool *conn.Pool
kh string
}
func newRStand(t *testing.T) *rstand {
t.Helper()
home := sshtest.IsolatedHome(t)
s := &rstand{t: t, srv: sshtest.Start(t, sshtest.Options{}), kh: filepath.Join(home, ".ssh", "known_hosts")}
s.trust(s.srv.Addr)
s.pool = conn.NewPool(conn.PoolOptions{
DialOptions: conn.DialOptions{Home: home, AgentSocket: "-", KnownHostsFiles: []string{s.kh}},
KeepaliveInterval: 100 * time.Millisecond,
KeepaliveTimeout: 100 * time.Millisecond,
KeepaliveMaxMiss: 2,
ReconnectBackoff: []time.Duration{50 * time.Millisecond, 100 * time.Millisecond},
})
t.Cleanup(func() { s.pool.Close() })
return s
}
func (s *rstand) trust(addr string) {
s.t.Helper()
f, err := os.OpenFile(s.kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
s.t.Fatal(err)
}
defer f.Close()
for _, k := range s.srv.HostKeys {
if _, err := f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(addr)}, k.PublicKey()) + "\n"); err != nil {
s.t.Fatal(err)
}
}
}
func (s *rstand) proxy() *sshtest.Proxy {
px := sshtest.NewProxy(s.t, s.srv.Addr)
s.trust(px.Addr)
return px
}
// fs connects as user ("" = "u") to addr ("" = the server itself).
func (s *rstand) fs(addr, user string) *sftpfs.FS {
s.t.Helper()
if addr == "" {
addr = s.srv.Addr
}
if user == "" {
user = "u"
}
host, port, _ := net.SplitHostPort(addr)
p, _ := strconv.Atoi(port)
l, err := s.pool.Acquire(context.Background(), conn.Endpoint{
Alias: "alias-" + port, User: user, Host: host, Port: p, Password: s.srv.Password,
})
if err != nil {
s.t.Fatalf("acquire: %v", err)
}
f := sftpfs.New(l)
s.t.Cleanup(f.Release)
return f
}
func prepare(t *testing.T, r Request) *Plan {
t.Helper()
plan, err := Prepare(bg, r, nil)
if err != nil {
t.Fatalf("Prepare: %v", err)
}
return plan
}
// partFiles lists .vcom-part-* / .vcom-old-* names directly in dir.
func partFiles(t *testing.T, dir string) []string {
t.Helper()
ents, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
var out []string
for _, e := range ents {
if n := e.Name(); len(n) > len(partPrefix) && (n[:len(partPrefix)] == partPrefix || n[:len(oldPrefix)] == oldPrefix) {
out = append(out, n)
}
}
return out
}
// Ported from the testbed (B8), N-P0-4: the connection is cut in the middle
// of overwriting a remote file. The old file must survive, and nothing
// partial may sit under its name.
func TestOverwriteThenDrop(t *testing.T) {
s := newRStand(t)
px := s.proxy()
remote := s.fs(px.Addr, "")
dir := t.TempDir()
dst := filepath.Join(dir, "important.db")
old := sshtest.WriteRandom(t, dst, 2<<20, 0o644)
srcDir := t.TempDir()
sshtest.WriteRandom(t, filepath.Join(srcDir, "important.db"), 8<<20, 0o644)
plan := prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite))
px.CutAfter(1 << 20)
rep := Execute(bg, plan, Hooks{})
if rep.Failed != 1 || rep.Done != 0 {
t.Fatalf("report = %+v", rep)
}
if !errors.Is(rep.Errors[0].Err, vfs.ErrConnLost) {
t.Errorf("item error = %v, want ErrConnLost", rep.Errors[0].Err)
}
now, err := os.ReadFile(dst)
if err != nil || !bytes.Equal(now, old) {
t.Fatalf("old destination damaged: %d bytes, err %v", len(now), err)
}
// The temp file cannot be removed over a dead connection: a hidden
// .vcom-part-* may stay (see 04-dev-log-B.md, 3.7). It never replaces the
// target, and a retry after reconnect writes a fresh temp file.
if parts := partFiles(t, dir); len(parts) > 0 {
t.Logf("temp left after the cut: %v", parts)
}
if err := s.pool.Reconnect(bg, remote.Conn().Key()); err != nil {
t.Fatal(err)
}
rep = Execute(bg, prepare(t, req(Copy, local, join(srcDir, "important.db"), remote, dir, overwrite)), Hooks{})
if rep.Done != 1 {
t.Fatalf("copy after reconnect: %+v", rep)
}
if now, _ := os.ReadFile(dst); len(now) != 8<<20 {
t.Errorf("after retry: %d bytes", len(now))
}
}
// Ported from TestSameFileViaAliasTruncates (B4), N-P0-5: the same file
// through two aliases of one server was truncated to zero.
func TestSameFileViaAliasRejected(t *testing.T) {
s := newRStand(t)
a := s.fs("", "")
b := s.fs(s.proxy().Addr, "")
if a.Conn() == b.Conn() {
t.Fatal("test needs two connections")
}
dir := t.TempDir()
f := filepath.Join(dir, "data.bin")
data := sshtest.WriteRandom(t, f, 1<<20, 0o644)
_, err := Prepare(bg, req(Copy, a, []string{f}, b, dir, overwrite), nil)
if !errors.Is(err, ErrSameFile) {
t.Fatalf("Prepare = %v, want ErrSameFile", err)
}
// Even if the check is bypassed, the write goes to a temp file and the
// rename replaces the file only with complete content.
other := t.TempDir()
plan := prepare(t, req(Copy, a, []string{f}, b, other, overwrite))
plan.Req.ToDir = dir
fi, err := b.Lstat(bg, f)
if err != nil {
t.Fatal(err)
}
plan.Items[0].Existing = &fi
rep := Execute(bg, plan, Hooks{})
if rep.Done != 1 {
t.Fatalf("report = %+v", rep)
}
if now, _ := os.ReadFile(f); !bytes.Equal(now, data) {
t.Fatalf("file damaged: %d bytes", len(now))
}
noLeftovers(t, dir)
}
func brokenLinkTree(t *testing.T, root string) {
t.Helper()
sshtest.WriteRandom(t, filepath.Join(root, "a.txt"), 10, 0o644)
sshtest.WriteRandom(t, filepath.Join(root, "z_after.txt"), 10, 0o644)
if err := os.Symlink("/nonexistent/zzz", filepath.Join(root, "broken")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(".", filepath.Join(root, "loopdir")); err != nil {
t.Fatal(err)
}
}
func checkBrokenLinkCopy(t *testing.T, rep Report, dst string) {
t.Helper()
if rep.Failed != 0 || rep.Err != nil || rep.Done != 4 {
t.Fatalf("report = %+v", rep)
}
for _, n := range []string{"a.txt", "z_after.txt"} {
if _, err := os.Stat(filepath.Join(dst, n)); err != nil {
t.Errorf("%s missing: %v", n, err)
}
}
for n, want := range map[string]string{"broken": "/nonexistent/zzz", "loopdir": "."} {
if got, err := os.Readlink(filepath.Join(dst, n)); err != nil || got != want {
t.Errorf("%s -> %q (%v), want link to %q", n, got, err, want)
}
}
noLeftovers(t, dst)
}
// Ported (B2), N-P1-8: a broken symlink aborted a directory upload.
func TestUploadDirWithBrokenSymlink(t *testing.T) {
s := newRStand(t)
remote := s.fs("", "")
src := filepath.Join(t.TempDir(), "src")
brokenLinkTree(t, src)
dst := t.TempDir()
rep := Execute(bg, prepare(t, req(Copy, local, []string{src}, remote, dst)), Hooks{})
checkBrokenLinkCopy(t, rep, filepath.Join(dst, "src"))
}
func TestDownloadDirWithBrokenSymlink(t *testing.T) {
s := newRStand(t)
remote := s.fs("", "")
src := filepath.Join(t.TempDir(), "src")
brokenLinkTree(t, src)
dst := t.TempDir()
rep := Execute(bg, prepare(t, req(Copy, remote, []string{src}, local, dst)), Hooks{})
checkBrokenLinkCopy(t, rep, filepath.Join(dst, "src"))
}
// Ported from TestPermsMtimeLost (B3), N-P1-9.
func TestRemotePermsMtimePreserved(t *testing.T) {
s := newRStand(t)
remote := s.fs("", "")
dir := t.TempDir()
src := filepath.Join(dir, "run.sh")
sshtest.WriteRandom(t, src, 100, 0o755)
mt := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)
if err := os.Chtimes(src, mt, mt); err != nil {
t.Fatal(err)
}
up, down := t.TempDir(), t.TempDir()
if rep := Execute(bg, prepare(t, req(Copy, local, []string{src}, remote, up)), Hooks{}); rep.Done != 1 {
t.Fatalf("upload: %+v", rep)
}
if rep := Execute(bg, prepare(t, req(Copy, remote, []string{src}, local, down)), Hooks{}); rep.Done != 1 {
t.Fatalf("download: %+v", rep)
}
for _, p := range []string{filepath.Join(up, "run.sh"), filepath.Join(down, "run.sh")} {
st, err := os.Stat(p)
if err != nil {
t.Fatal(err)
}
if st.Mode().Perm() != 0o755 || !st.ModTime().Equal(mt) {
t.Errorf("%s: mode %v mtime %v", p, st.Mode().Perm(), st.ModTime())
}
}
}
// N-P1-10 / N-P2-3: two users on one host are different connections; a
// remote→remote copy between them merges into an existing directory (no
// dst/proj/proj) and a move is copy+delete, not a server-side rename.
func TestRemoteToRemoteDifferentUsersNotSameConn(t *testing.T) {
s := newRStand(t)
alice := s.fs("", "alice")
bob := s.fs("", "bob")
if alice.Conn() == bob.Conn() {
t.Fatal("different users share a connection")
}
base := t.TempDir()
src := filepath.Join(base, "src", "proj")
sshtest.WriteRandom(t, filepath.Join(src, "new.txt"), 100, 0o644)
sshtest.WriteRandom(t, filepath.Join(src, "sub", "deep.txt"), 100, 0o644)
dst := filepath.Join(base, "dst")
sshtest.WriteRandom(t, filepath.Join(dst, "proj", "keep.txt"), 10, 0o644)
plan := prepare(t, req(Copy, alice, []string{src}, bob, dst))
if plan.SameConn {
t.Error("plan.SameConn for different users")
}
rep := Execute(bg, plan, Hooks{})
if rep.Failed != 0 || rep.Done != 2 {
t.Fatalf("report = %+v", rep)
}
for _, p := range []string{"proj/new.txt", "proj/sub/deep.txt", "proj/keep.txt"} {
if _, err := os.Stat(filepath.Join(dst, p)); err != nil {
t.Errorf("%s: %v", p, err)
}
}
if _, err := os.Stat(filepath.Join(dst, "proj", "proj")); err == nil {
t.Error("copy nested proj/proj")
}
mv := filepath.Join(base, "dst2")
if err := os.Mkdir(mv, 0o755); err != nil {
t.Fatal(err)
}
rep = Execute(bg, prepare(t, req(Move, alice, []string{src}, bob, mv)), Hooks{})
if rep.Failed != 0 || rep.Done != 2 {
t.Fatalf("move report = %+v", rep)
}
if _, err := os.Lstat(src); !os.IsNotExist(err) {
t.Errorf("move left the source: %v", err)
}
if _, err := os.Stat(filepath.Join(mv, "proj", "sub", "deep.txt")); err != nil {
t.Errorf("moved content missing: %v", err)
}
}
// N-P1-2: a cut connection surfaces as ErrConnLost; the caller reconnects
// and retries, and the copy completes.
func TestConnLostAsksRetry(t *testing.T) {
s := newRStand(t)
px := s.proxy()
remote := s.fs(px.Addr, "")
srcDir := t.TempDir()
data := sshtest.WriteRandom(t, filepath.Join(srcDir, "big.bin"), 4<<20, 0o644)
dst := t.TempDir()
plan := prepare(t, req(Copy, local, join(srcDir, "big.bin"), remote, dst))
px.CutAfter(512 << 10)
var asked atomic.Int32
rep := Execute(bg, plan, Hooks{OnError: func(ctx context.Context, e ItemError) (ErrorAction, error) {
asked.Add(1)
if !errors.Is(e.Err, vfs.ErrConnLost) {
t.Errorf("OnError got %v, want ErrConnLost", e.Err)
return ErrorStop, nil
}
if err := s.pool.Reconnect(ctx, remote.Conn().Key()); err != nil {
t.Errorf("reconnect: %v", err)
return ErrorStop, nil
}
return ErrorRetry, nil
}})
if rep.Done != 1 || rep.Failed != 0 || asked.Load() != 1 {
t.Fatalf("report = %+v, asked %d", rep, asked.Load())
}
if got, _ := os.ReadFile(filepath.Join(dst, "big.bin")); !bytes.Equal(got, data) {
t.Fatal("content mismatch after retry")
}
if remote.Conn().Gen() != 2 {
t.Errorf("gen = %d", remote.Conn().Gen())
}
}
// Cancelling in the middle of an upload over a live link returns promptly,
// keeps the old target and removes the temp file (N-P1-7).
func TestRemoteCancelMidFile(t *testing.T) {
s := newRStand(t)
px := s.proxy()
px.SetDelay(5 * time.Millisecond)
remote := s.fs(px.Addr, "")
dir := t.TempDir()
old := sshtest.WriteRandom(t, filepath.Join(dir, "f.bin"), 1<<20, 0o644)
srcDir := t.TempDir()
sshtest.WriteRandom(t, filepath.Join(srcDir, "f.bin"), 32<<20, 0o644)
plan := prepare(t, req(Copy, local, join(srcDir, "f.bin"), remote, dir, overwrite))
ctx, cancel := context.WithCancel(bg)
defer cancel()
var once sync.Once
var cancelled time.Time
rep := Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
if p.CurrentDone > 2<<20 {
once.Do(func() { cancelled = time.Now(); cancel() })
}
}})
if cancelled.IsZero() {
t.Fatal("never cancelled")
}
if el := time.Since(cancelled); el > time.Second {
t.Errorf("Execute returned %v after cancel", el)
}
if !rep.Cancelled || rep.Done != 0 {
t.Errorf("report = %+v", rep)
}
if now, _ := os.ReadFile(filepath.Join(dir, "f.bin")); !bytes.Equal(now, old) {
t.Fatal("old target damaged")
}
noLeftovers(t, dir)
}
// A link that freezes in the middle of a file (Wi-Fi gone): cancelling
// returns once the pool notices the dead link (fast keepalive here), with
// the old target intact.
func TestRemoteFreezeMidFileThenCancel(t *testing.T) {
s := newRStand(t)
px := s.proxy()
remote := s.fs(px.Addr, "")
dir := t.TempDir()
old := sshtest.WriteRandom(t, filepath.Join(dir, "f.bin"), 1<<20, 0o644)
srcDir := t.TempDir()
sshtest.WriteRandom(t, filepath.Join(srcDir, "f.bin"), 16<<20, 0o644)
plan := prepare(t, req(Copy, local, join(srcDir, "f.bin"), remote, dir, overwrite))
ctx, cancel := context.WithCancel(bg)
defer cancel()
var once sync.Once
var cancelled time.Time
var mu sync.Mutex
done := make(chan Report, 1)
go func() {
done <- Execute(ctx, plan, Hooks{ProgressInterval: time.Millisecond, Progress: func(p Progress) {
if p.CurrentDone > 1<<20 {
once.Do(func() {
px.Freeze(true)
time.AfterFunc(50*time.Millisecond, func() {
mu.Lock()
cancelled = time.Now()
mu.Unlock()
cancel()
})
})
}
}})
}()
var rep Report
select {
case rep = <-done:
case <-time.After(5 * time.Second):
t.Fatal("Execute hung on a frozen link after cancel")
}
px.Freeze(false)
mu.Lock()
el := time.Since(cancelled)
mu.Unlock()
t.Logf("returned %v after cancel", el)
if el > 2*time.Second {
t.Errorf("returned %v after cancel", el)
}
if rep.Done != 0 || !(rep.Cancelled || rep.Failed == 1) {
t.Errorf("report = %+v", rep)
}
if now, _ := os.ReadFile(filepath.Join(dir, "f.bin")); !bytes.Equal(now, old) {
t.Fatal("old target damaged")
}
}

View file

@ -154,3 +154,23 @@
- **Shutdown(ctx):** отменяет очередь (holds освобождаются сразу) и работающие джобы, ждёт их возврата и доставки
всех событий; по дедлайну возвращает `ctx.Err()`. `Start` после Shutdown сразу даёт Cancelled с `ErrShutdown`
(holds освобождаются).
## 3.7 Remote-приёмка transfer на стенде
- Файл `internal/transfer/remote_test.go` (код `transfer` не менялся). Стенд: `sshtest` + `conn.Pool` с быстрым
keepalive (100 мс × 2 + 100 мс) + `sftpfs`. Тесты: `TestOverwriteThenDrop` (N-P0-4), `TestSameFileViaAliasRejected`
(N-P0-5; и с обходом Prepare файл цел), `TestUploadDirWithBrokenSymlink`/`TestDownloadDirWithBrokenSymlink`
(N-P1-8), `TestRemotePermsMtimePreserved` (N-P1-9), `TestRemoteToRemoteDifferentUsersNotSameConn` (N-P1-10/N-P2-3:
слияние без `proj/proj`, move = copy+delete), `TestConnLostAsksRetry` (N-P1-2: cut → `OnError(ErrConnLost)` →
`Pool.Reconnect` → Retry → файл цел), плюс `TestRemoteCancelMidFile` (возврат ≈ 0,2 с, temp удалён) и
`TestRemoteFreezeMidFileThenCancel`.
- **Заморозка + отмена:** `File.Close` в pkg/sftp ждёт тот же mutex, что и идущий `ReadFrom`, а запрос CLOSE по
замороженному каналу не получает ответа, поэтому `AfterFunc(Close)` сам по себе висящую запись не освобождает.
Execute возвращается, когда пул признаёт соединение мёртвым (keepalive / `ssh.Client.Wait`): в тесте ≈ 0,2–0,4 с,
с умолчаниями (15 с × 2 + 10 с) — до ~40 с. Цель при этом цела. Ускорять можно только агрессивнее keepalive
во время передачи — оставил как есть (поведение по §3.4).
- **Находка для A (не исправлял, код transfer не мой):** после обрыва temp-файл `.vcom-part-*` остаётся на сервере
(удалить по мёртвому соединению нельзя), а `Prepare` предупреждает об остатках только в каталогах, которые он
листает (слияние каталогов); для одиночного файла в корне `ToDir` (≤ 4 корня → Lstat вместо ReadDir) остаток не
замечается. Варианты: после Retry с новым поколением соединения удалять temp прошлой попытки (executor знает его
имя), или листать `ToDir` при наличии `partPrefix`-подозрений. Тест `TestOverwriteThenDrop` это только логирует.