vcom/internal/ssh/conn/pool.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

328 lines
7.8 KiB
Go

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)
}
}