vcom/internal/ssh/conn/pool_test.go
vrubelroman c328fff867 feat(ssh): add refcounted connection Pool and Lease (2B.4)
Panels, jobs and previews hold Leases; only the pool closes a
connection, after IdleClose without leases or on Close, so concurrent
use and release cannot race (N-P0-8) and a mirror keeps its connection
when the other panel leaves (N-P1-12). Concurrent Acquires of one
user@host:port share a single dial (N-P2-8); Reconnect retries with
backoff.

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

339 lines
8.9 KiB
Go

package conn
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
"vcom/internal/testutil/sshtest"
)
func (e *env) pool(o PoolOptions) *Pool {
e.t.Helper()
if o.Home == "" {
o.Home = e.home
}
if o.AgentSocket == "" {
o.AgentSocket = "-"
}
if o.KnownHostsFiles == nil {
o.KnownHostsFiles = []string{e.kh}
}
p := NewPool(o)
e.t.Cleanup(func() { p.Close() })
return p
}
func (p *Pool) entryCount() int {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.entries)
}
func mustAcquire(t *testing.T, p *Pool, ep Endpoint) *Lease {
t.Helper()
l, err := p.Acquire(context.Background(), ep)
if err != nil {
t.Fatalf("Acquire: %v", err)
}
return l
}
// Ported from TestCloseRace (B5), N-P0-8: Close raced with running calls
// and could call a method on a nil *sftp.Client. Leases are used, released,
// re-acquired and the pool closed concurrently under -race.
func TestLeaseReleaseRace(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
p := e.pool(PoolOptions{IdleClose: 10 * time.Millisecond})
ep := endpointFor(srv.Addr, srv.Password)
base := mustAcquire(t, p, ep)
dir := t.TempDir()
var wg sync.WaitGroup
panicked := make(chan any, 8)
worker := func(fn func(i int)) {
wg.Add(1)
go func() {
defer wg.Done()
defer func() {
if r := recover(); r != nil {
panicked <- r
}
}()
for i := 0; i < 300; i++ {
fn(i)
}
}()
}
for w := 0; w < 3; w++ {
worker(func(int) {
l := base.Acquire()
defer l.Release()
defer l.Release() // idempotent
if sc, err := l.Client(); err == nil {
_, err := sc.ReadDir(dir)
if err != nil && !errors.Is(l.Conn().MapErr(err), ErrClosed) && !errors.Is(l.Conn().MapErr(err), ErrConnLost) {
t.Errorf("ReadDir: %v", err)
}
}
})
}
worker(func(int) {
if l, err := p.Acquire(context.Background(), ep); err == nil {
l.Conn().State()
l.Release()
}
})
worker(func(i int) {
switch i {
case 0:
time.Sleep(50 * time.Millisecond) // let the readers get going
case 1:
p.Close()
}
})
wg.Wait()
close(panicked)
for r := range panicked {
t.Fatalf("panic: %v", r)
}
if _, err := base.Client(); !errors.Is(err, ErrClosed) {
t.Errorf("Client after pool Close: %v", err)
}
if _, err := p.Acquire(context.Background(), ep); !errors.Is(err, ErrPoolClosed) {
t.Errorf("Acquire after Close: %v", err)
}
base.Release()
})
}
// N-P2-8: a double Enter made two connections.
func TestAcquireSingleflight(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
px.SetDelay(20 * time.Millisecond) // keep the dial in flight while all callers arrive
p := e.pool(PoolOptions{})
ep := endpointFor(px.Addr, srv.Password)
const n = 10
leases := make([]*Lease, n)
errs := make([]error, n)
var wg sync.WaitGroup
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
defer wg.Done()
leases[i], errs[i] = p.Acquire(context.Background(), ep)
}()
}
wg.Wait()
for i := 0; i < n; i++ {
if errs[i] != nil {
t.Fatal(errs[i])
}
if leases[i].Conn() != leases[0].Conn() {
t.Error("leases on different connections")
}
}
if d := p.d.dials.Load(); d != 1 {
t.Errorf("dials = %d, want 1", d)
}
// Same user@host:port through another alias shares the connection.
ep2 := ep
ep2.Alias = "other-alias"
l := mustAcquire(t, p, ep2)
if l.Conn() != leases[0].Conn() || p.d.dials.Load() != 1 {
t.Error("alias with the same key did not share the connection")
}
}
// Every caller gave up: the dial is cancelled and nothing stays open.
func TestAcquireAllWaitersGone(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
px.Freeze(true)
p := e.pool(PoolOptions{})
ep := endpointFor(px.Addr, srv.Password)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
start := time.Now()
if _, err := p.Acquire(ctx, ep); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err = %v", err)
}
if el := time.Since(start); el > time.Second {
t.Errorf("Acquire returned after %v", el)
}
waitFor(t, 2*time.Second, "in-flight dial gone", func() bool {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.inflight) == 0 && len(p.entries) == 0
})
px.Freeze(false)
})
}
func TestIdleClose(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
var ev events
p := e.pool(PoolOptions{IdleClose: 150 * time.Millisecond, OnEvent: ev.add})
ep := endpointFor(srv.Addr, srv.Password)
l := mustAcquire(t, p, ep)
c := l.Conn()
l.Release()
l = mustAcquire(t, p, ep) // within IdleClose: reused
if l.Conn() != c || p.d.dials.Load() != 1 {
t.Fatal("connection not reused within IdleClose")
}
time.Sleep(300 * time.Millisecond)
if c.State() != Ready {
t.Fatal("connection with a live lease was closed")
}
l.Release()
waitFor(t, 2*time.Second, "idle close", func() bool { return ev.has(Closed) && p.entryCount() == 0 })
if c.State() != Closed {
t.Errorf("state = %v", c.State())
}
l = mustAcquire(t, p, ep)
if l.Conn() == c || p.d.dials.Load() != 2 {
t.Error("expected a fresh connection after idle close")
}
l.Release()
}
// N-P1-12: mirror shared one client and a second mirror closed it.
func TestMirrorLeaseSurvivesRelease(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
p := e.pool(PoolOptions{IdleClose: -1})
left := mustAcquire(t, p, endpointFor(srv.Addr, srv.Password))
right := left.Acquire() // mirror
left.Release()
left.Release()
left.Release() // over-release must not steal right's reference
sc, err := right.Client()
if err != nil {
t.Fatalf("mirror lease broken: %v", err)
}
if _, err := sc.ReadDir(t.TempDir()); err != nil {
t.Fatalf("ReadDir on mirror: %v", err)
}
c := right.Conn()
right.Release()
waitFor(t, 2*time.Second, "close after last release", func() bool { return c.State() == Closed })
}
func TestAcquireReconnectsLost(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
p := e.pool(PoolOptions{})
ep := endpointFor(px.Addr, srv.Password)
l := mustAcquire(t, p, ep)
defer l.Release()
px.KillAll()
waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost })
l2 := mustAcquire(t, p, ep)
defer l2.Release()
if l2.Conn() != l.Conn() || l.Conn().State() != Ready || l.Conn().Gen() != 2 {
t.Errorf("state %v gen %d", l.Conn().State(), l.Conn().Gen())
}
if _, err := l.Client(); err != nil {
t.Errorf("old lease after reconnect: %v", err)
}
}
func TestPoolReconnectBackoff(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
var mu sync.Mutex
connecting := 0
p := e.pool(PoolOptions{
ReconnectBackoff: []time.Duration{10 * time.Millisecond, 10 * time.Millisecond},
OnEvent: func(ev Event) {
if ev.State == Connecting {
mu.Lock()
connecting++
mu.Unlock()
}
},
})
ep := endpointFor(px.Addr, srv.Password)
l := mustAcquire(t, p, ep)
defer l.Release()
px.Freeze(true)
px.KillAll()
waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost })
p.d.opts.HandshakeTimeout = 100 * time.Millisecond
if err := p.Reconnect(context.Background(), ep.Key()); err == nil {
t.Fatal("reconnect through a frozen link succeeded")
}
mu.Lock()
if connecting != 3 {
t.Errorf("attempts = %d, want 3", connecting)
}
mu.Unlock()
px.Freeze(false)
if err := p.Reconnect(context.Background(), ep.Key()); err != nil {
t.Fatalf("reconnect after recovery: %v", err)
}
if l.Conn().State() != Ready {
t.Errorf("state = %v", l.Conn().State())
}
if err := p.Reconnect(context.Background(), "nobody@nowhere:22"); !errors.Is(err, ErrClosed) {
t.Errorf("unknown key: %v", err)
}
}
func TestPoolCloseCancelsDial(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
px.Freeze(true)
p := e.pool(PoolOptions{})
res := make(chan error, 1)
go func() {
_, err := p.Acquire(context.Background(), endpointFor(px.Addr, srv.Password))
res <- err
}()
waitFor(t, time.Second, "dial in flight", func() bool { return p.d.dials.Load() == 1 })
start := time.Now()
p.Close()
select {
case err := <-res:
if err == nil {
t.Fatal("Acquire succeeded on a closed pool")
}
case <-time.After(2 * time.Second):
t.Fatal("Acquire still blocked after Close")
}
if el := time.Since(start); el > time.Second {
t.Errorf("Close took %v", el)
}
px.Freeze(false)
})
}
func TestPoolDifferentUsersSeparate(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
p := e.pool(PoolOptions{})
a := endpointFor(srv.Addr, srv.Password)
b := a
b.User = "other"
la, lb := mustAcquire(t, p, a), mustAcquire(t, p, b)
defer la.Release()
defer lb.Release()
if la.Conn() == lb.Conn() {
t.Error(fmt.Sprintf("users %s and %s share a connection", a.User, b.User))
}
}