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>
This commit is contained in:
vrubelroman 2026-11-01 03:51:51 +03:00
parent 351970078f
commit c328fff867
4 changed files with 694 additions and 3 deletions

View file

@ -34,6 +34,12 @@ func (e *events) has(s State) bool {
return false
}
func (e *events) snapshot() []Event {
e.mu.Lock()
defer e.mu.Unlock()
return append([]Event(nil), e.ev...)
}
func (e *events) last() Event {
e.mu.Lock()
defer e.mu.Unlock()
@ -100,8 +106,9 @@ func TestFreezeDetectedAsLost(t *testing.T) {
case <-time.After(time.Second):
t.Fatal("hung ReadDir did not return after Lost")
}
if !ev.has(Lost) || ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) {
t.Errorf("events = %+v", ev.ev)
waitFor(t, time.Second, "Lost event", func() bool { return ev.has(Lost) })
if ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) {
t.Errorf("events = %+v", ev.snapshot())
}
if _, err := c.Client(); !errors.Is(err, ErrConnLost) {
t.Errorf("Client() after Lost: %v", err)
@ -153,7 +160,7 @@ func TestReconnectAfterCut(t *testing.T) {
t.Errorf("Reconnect on a Ready conn must be a no-op: %v", err)
}
if !ev.has(Connecting) || ev.last().State != Ready {
t.Errorf("events = %+v", ev.ev)
t.Errorf("events = %+v", ev.snapshot())
}
c.close()
if err := c.Reconnect(context.Background()); !errors.Is(err, ErrClosed) {

328
internal/ssh/conn/pool.go Normal file
View file

@ -0,0 +1,328 @@
package conn
import (
"context"
"errors"
"sync"
"sync/atomic"
"time"
"github.com/pkg/sftp"
)
// ErrPoolClosed is returned by Acquire after Pool.Close.
var ErrPoolClosed = errors.New("connection pool closed")
// DefaultIdleClose is how long a connection without leases stays open.
const DefaultIdleClose = 60 * time.Second
// DefaultReconnectBackoff: delays between Pool.Reconnect attempts (5 tries).
var DefaultReconnectBackoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second}
// PoolOptions configure a Pool.
type PoolOptions struct {
DialOptions // Prompter, HandshakeTimeout, known_hosts, agent, ...
KeepaliveInterval time.Duration // 15s (or ServerAliveInterval)
KeepaliveTimeout time.Duration // 10s
KeepaliveMaxMiss int // 2 (or ServerAliveCountMax)
// IdleClose closes a connection this long after its last lease is
// released. Default 60s; negative closes immediately.
IdleClose time.Duration
// ReconnectBackoff are the delays between Reconnect attempts; attempts
// = len+1. nil means DefaultReconnectBackoff (1,2,4,8s).
ReconnectBackoff []time.Duration
// OnEvent receives connection state changes (main forwards them with
// program.Send). Called from pool goroutines; must not block.
OnEvent func(Event)
}
// Pool shares one connection per Endpoint.Key() among panels, jobs,
// previews and size counters. Each user holds a Lease; the pool alone
// closes connections: when the last lease has been released for IdleClose,
// or on Close (N-P0-8, N-P1-12). It is safe for concurrent use.
type Pool struct {
d *dialer
opts PoolOptions
mu sync.Mutex
closed bool
entries map[string]*entry
inflight map[string]*call
wg sync.WaitGroup // dial goroutines and idle closes
}
type entry struct {
key string
conn *Conn
refs int
idle *time.Timer
seq uint64 // invalidates stale idle timers
}
// call is one in-flight dial shared by every concurrent Acquire of a key.
type call struct {
done chan struct{}
waiters int
cancel context.CancelFunc
e *entry
err error
}
// NewPool creates a pool.
func NewPool(o PoolOptions) *Pool {
if o.IdleClose == 0 {
o.IdleClose = DefaultIdleClose
}
if o.ReconnectBackoff == nil {
o.ReconnectBackoff = DefaultReconnectBackoff
}
return &Pool{
d: newDialer(o.DialOptions),
opts: o,
entries: map[string]*entry{},
inflight: map[string]*call{},
}
}
func (p *Pool) connOptions() ConnOptions {
return ConnOptions{
KeepaliveInterval: p.opts.KeepaliveInterval,
KeepaliveTimeout: p.opts.KeepaliveTimeout,
KeepaliveMaxMiss: p.opts.KeepaliveMaxMiss,
OnEvent: p.opts.OnEvent,
}
}
// Acquire returns a lease on the connection for ep, dialing it if needed.
// Concurrent Acquires of the same key share one dial (N-P2-8: a double
// Enter makes one connection). A Lost connection gets one reconnect
// attempt. If every waiter gives up (ctx), the dial is cancelled; a dial
// that still completes is parked idle and closed after IdleClose.
func (p *Pool) Acquire(ctx context.Context, ep Endpoint) (*Lease, error) {
key := ep.Key()
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return nil, ErrPoolClosed
}
if e := p.entries[key]; e != nil {
l := p.lease(e)
p.mu.Unlock()
if e.conn.State() == Lost {
if err := e.conn.Reconnect(ctx); err != nil {
l.Release()
return nil, err
}
}
return l, nil
}
c := p.inflight[key]
if c == nil {
dctx, cancel := context.WithCancel(context.Background())
c = &call{done: make(chan struct{}), cancel: cancel}
p.inflight[key] = c
p.wg.Add(1)
go p.dial(dctx, key, ep, c)
}
c.waiters++
p.mu.Unlock()
select {
case <-c.done:
case <-ctx.Done():
p.mu.Lock()
c.waiters--
select {
case <-c.done:
// Finished concurrently: the entry may now have no users.
if c.e != nil && c.e.refs == 0 {
p.startIdle(c.e)
}
default:
if c.waiters == 0 {
c.cancel()
}
}
p.mu.Unlock()
return nil, ctx.Err()
}
if c.err != nil {
return nil, c.err
}
p.mu.Lock()
defer p.mu.Unlock()
if p.closed || p.entries[key] != c.e {
return nil, ErrPoolClosed
}
return p.lease(c.e), nil
}
func (p *Pool) dial(ctx context.Context, key string, ep Endpoint, c *call) {
defer p.wg.Done()
conn, err := p.d.connect(ctx, ep, p.connOptions())
c.cancel()
p.mu.Lock()
delete(p.inflight, key)
if err == nil && p.closed {
err = ErrPoolClosed
p.mu.Unlock()
conn.close()
p.mu.Lock()
}
c.err = err
if err == nil {
c.e = &entry{key: key, conn: conn}
p.entries[key] = c.e
if c.waiters == 0 {
p.startIdle(c.e) // everyone gave up; keep briefly, then close
}
}
close(c.done)
p.mu.Unlock()
}
// lease takes a reference on e; p.mu is held.
func (p *Pool) lease(e *entry) *Lease {
e.refs++
e.seq++
if e.idle != nil {
e.idle.Stop()
e.idle = nil
}
return &Lease{p: p, e: e}
}
// startIdle schedules e to close after IdleClose; p.mu is held.
func (p *Pool) startIdle(e *entry) {
e.seq++
seq := e.seq
if e.idle != nil {
e.idle.Stop()
}
fire := func() {
p.mu.Lock()
if e.seq != seq || e.refs != 0 || p.entries[e.key] != e {
p.mu.Unlock()
return
}
delete(p.entries, e.key)
// The entry was still registered, so Close has not started waiting:
// this Add cannot race with p.wg.Wait.
p.wg.Add(1)
p.mu.Unlock()
defer p.wg.Done()
e.conn.close()
}
if p.opts.IdleClose < 0 {
e.idle = nil
go fire()
return
}
e.idle = time.AfterFunc(p.opts.IdleClose, fire)
}
func (p *Pool) release(e *entry) {
p.mu.Lock()
defer p.mu.Unlock()
e.refs--
if e.refs == 0 && !p.closed && p.entries[e.key] == e {
p.startIdle(e)
}
}
// Reconnect re-dials a Lost connection with backoff (1,2,4,8s between at
// most 5 attempts by default). A Ready connection is left alone. Host key
// problems and ctx cancellation stop the retries.
func (p *Pool) Reconnect(ctx context.Context, key string) error {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return ErrPoolClosed
}
e := p.entries[key]
p.mu.Unlock()
if e == nil {
return ErrClosed
}
var err error
for i := 0; ; i++ {
if err = e.conn.Reconnect(ctx); err == nil {
return nil
}
if errors.Is(err, ErrClosed) || errors.Is(err, ErrHostKeyChanged) ||
errors.Is(err, ErrHostKeyRejected) || errors.Is(err, ErrIdentityChanged) || ctx.Err() != nil {
return err
}
if i >= len(p.opts.ReconnectBackoff) {
return err
}
t := time.NewTimer(p.opts.ReconnectBackoff[i])
select {
case <-t.C:
case <-ctx.Done():
t.Stop()
return ctx.Err()
}
}
}
// Close closes every connection, cancels pending dials and waits for them.
// Leases stay safe to use: their calls fail with ErrClosed.
func (p *Pool) Close() error {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return nil
}
p.closed = true
var conns []*Conn
for k, e := range p.entries {
if e.idle != nil {
e.idle.Stop()
}
e.seq++
conns = append(conns, e.conn)
delete(p.entries, k)
}
for _, c := range p.inflight {
c.cancel()
}
p.mu.Unlock()
for _, c := range conns {
c.close()
}
p.wg.Wait()
p.d.close()
return nil
}
// Lease is one user's reference to a pooled connection. Release it when
// done; it is idempotent. A lease stays safe to use after the connection
// died or the pool closed: calls return errors, never panic.
type Lease struct {
p *Pool
e *entry
released atomic.Bool
}
// Conn returns the leased connection.
func (l *Lease) Conn() *Conn { return l.e.conn }
// Client is shorthand for Conn().Client().
func (l *Lease) Client() (*sftp.Client, error) { return l.e.conn.Client() }
// Acquire takes another reference to the same connection (mirror panel,
// background job). Release each lease separately.
func (l *Lease) Acquire() *Lease {
l.p.mu.Lock()
defer l.p.mu.Unlock()
return l.p.lease(l.e)
}
// Release drops this reference; the second and later calls do nothing.
func (l *Lease) Release() {
if l.released.CompareAndSwap(false, true) {
l.p.release(l.e)
}
}

View file

@ -0,0 +1,339 @@
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))
}
}

View file

@ -83,3 +83,20 @@
этого `ExecSupported(ctx)` — проба `true`, кэшируется только определённый ответ.
- Тест-сервер `sshtest` не обрабатывает `signal`; отмена проверяется по клиенту (возврат < 1 с, соединение живо),
процесс `sleep` на стороне стенда добивается при остановке сервера.
## 2B.4 `ssh/conn` Pool + Lease
- **`NewPool(PoolOptions)`** вместо `NewPool(resolver, opts)`: `Acquire` получает уже разрешённый `Endpoint`,
резолвер пулу не нужен (UI вызывает `resolver.Resolve(alias)`, затем `pool.Acquire`). `PoolOptions` встраивает
`DialOptions` и добавляет `ReconnectBackoff []time.Duration` (по умолчанию 1,2,4,8 с между ≤ 5 попытками; в
тестах — миллисекунды).
- **`Lease.FS()` нет** — `conn` не может импортировать `vfs`/`sftpfs` (цикл `sftpfs → conn`). В 2B.5 будет
`sftpfs.New(lease)`. Вместо этого у Lease есть `Conn()` и сокращение `Client()`.
- **Singleflight с отменой:** dial идёт в контексте пула; каждый ждущий `Acquire` уходит по своему ctx; когда ушли
все — dial отменяется. Если dial всё же завершился без ждущих, соединение паркуется и закрывается через
`IdleClose` (не утекает). `Pool.Close` отменяет текущие dial и ждёт их goroutine.
- **`Acquire` на `Lost`-соединении** делает одну попытку `Reconnect` с ctx вызывающего (повторный Enter на хост
после сна ноутбука). Ошибки host key (`ErrHostKeyChanged/Rejected`, `ErrIdentityChanged`) прекращают backoff.
- `IdleClose < 0` — закрыть сразу после последнего `Release`. `Release` идемпотентен на уровне каждой аренды:
лишние вызовы не отбирают чужие ссылки. После `Pool.Close` аренды безопасны: `Client()` → `ErrClosed`,
`Acquire` → `ErrPoolClosed`.