Documentation
¶
Overview ¶
Package connpool keeps authenticated sessions and live terminals alive across calls, which is the rewrite's central difference from the Python implementation.
The Python MCP server performed a full login -> resolve -> connect -> teardown cycle for every tool call. Here a session is logged in once and reused, and a terminal is opened once and kept until it goes idle or breaks (DESIGN.md「连接池」).
Index ¶
- Constants
- Variables
- type AssetCache
- type ExecOptions
- type SessionPool
- func (p *SessionPool) Close() error
- func (p *SessionPool) Get(ctx context.Context, srv *config.ServerConfig, baseURL string, ...) (*auth.Session, error)
- func (p *SessionPool) GetWithProxy(ctx context.Context, srv *config.ServerConfig, baseURL string, ...) (*auth.Session, error)
- func (p *SessionPool) Invalidate(alias string)
- type Stats
- type TerminalPool
- func (p *TerminalPool) Close() error
- func (p *TerminalPool) Evict(srv, assetName, account, protocol string)
- func (p *TerminalPool) Exec(ctx context.Context, srv *config.ServerConfig, sess *auth.Session, ...) (transport.Result, error)
- func (p *TerminalPool) Reap(now time.Time, ttl time.Duration) int
- func (p *TerminalPool) Stats() Stats
Constants ¶
const ( // IdleTTL is how long a terminal may sit unused before the reaper // closes it. IdleTTL = 10 * time.Minute // ResolveTTL caches an asset resolution. ResolveTTL = 5 * time.Minute // ReapInterval is the reaper's scan period. ReapInterval = 60 * time.Second )
Defaults from DESIGN.md「数值基线」
Variables ¶
var ErrClosed = errors.New("pool is closed")
ErrClosed reports use of a pool after Close.
Functions ¶
This section is empty.
Types ¶
type AssetCache ¶
type AssetCache struct {
// contains filtered or unexported fields
}
AssetCache caches asset resolutions for ResolveTTL.
func (*AssetCache) Get ¶
Get returns a cached resolution when it is still fresh.
Freshness is measured against the injected now, and an entry expires at exactly ResolveTTL: answering a lookup the caller asked to re-check would hide a renamed asset (DESIGN.md「冷/热路径」).
func (*AssetCache) Invalidate ¶
func (c *AssetCache) Invalidate(key string)
Invalidate drops one entry.
type ExecOptions ¶
type ExecOptions struct {
Account string
Protocol string
// Backend selects the transport when the terminal is built. A terminal
// already in the pool keeps the backend it was built with, because the
// key does not include it.
Backend transport.BackendType
Timeout time.Duration
// OnBackend, when set, is called with the backend the terminal actually
// uses, once the terminal is in hand. It lets a caller record backend
// memory (DESIGN.md「端点故障转移」第 4 点) without probing the terminal afterwards.
OnBackend func(transport.BackendType)
}
ExecOptions tunes one pooled execution.
type SessionPool ¶
type SessionPool struct {
// contains filtered or unexported fields
}
SessionPool caches authenticated sessions, keyed by server alias.
Health is verified lazily: there is no periodic probe. A call that hits an api.AuthError re-logs in once and retries the operation, which avoids idle probe traffic while still recovering from an expired token (DESIGN.md 「SessionPool」).
The pool's half of that retry-once policy is Invalidate: the caller that sees an api.AuthError drops the alias and re-issues the operation once, and the drop makes the retry perform a real login instead of handing back the session that just failed.
func (*SessionPool) Close ¶
func (p *SessionPool) Close() error
Close drops every cached session.
A session owns no closable handle — its HTTP keep-alive connections are reaped by the transport — so dropping the references is the whole teardown. Close is idempotent, and a nil pool behaves as a closed one.
func (*SessionPool) Get ¶
func (p *SessionPool) Get(ctx context.Context, srv *config.ServerConfig, baseURL string, creds auth.Credentials, otpPrompt func() (string, error)) (*auth.Session, error)
Get returns a session for srv, logging in when necessary.
creds supplies the password and TOTP secret; otpPrompt is consulted when the server demands MFA and no secret is stored.
The key is the server alias: one alias means one endpoint, and a session is bound to the address it logged in against (DESIGN.md「端点故障转移」第 1 点). The alias is deliberately part of the key even though baseURL identifies the endpoint, because the alias is what Invalidate is given and what the CLI and MCP surfaces name.
func (*SessionPool) GetWithProxy ¶
func (p *SessionPool) GetWithProxy(ctx context.Context, srv *config.ServerConfig, baseURL string, creds auth.Credentials, otpPrompt func() (string, error), px netproxy.Proxy) (*auth.Session, error)
GetWithProxy is Get with an explicit proxy policy.
The policy is recorded on the session so the KoKo WebSocket, SSH and SFTP connections derived from it reach the same network the login did (DESIGN.md「代理策略」).
func (*SessionPool) Invalidate ¶
func (p *SessionPool) Invalidate(alias string)
Invalidate drops the cached session for an alias so the next Get logs in again. It is called when a call hits an authentication error.
A login already in flight is not cancelled: it finishes and caches its result, which is harmless because that login is newer than the session being dropped.
type TerminalPool ¶
type TerminalPool struct {
// Connect and Resolve are seams so tests can drive the pool without a
// network.
Connect func(ctx context.Context, sess *auth.Session, asset assets.Info, opts transport.ConnectOptions) (transport.Terminal, error)
Resolve func(ctx context.Context, sess *auth.Session, name, account, protocol string) (assets.Info, error)
// contains filtered or unexported fields
}
TerminalPool keeps live terminals keyed by server, asset, account and protocol, and serializes execution per terminal.
func NewTerminalPool ¶
func NewTerminalPool() *TerminalPool
NewTerminalPool returns an empty terminal pool.
The Connect and Resolve seams are left nil so the caller wires them; the CLI sets them to the real transport functions, and tests set fakes.
func (*TerminalPool) Close ¶
func (p *TerminalPool) Close() error
Close closes every terminal.
It is idempotent and safe on a nil pool. Each terminal is closed under its own lock, so a command in flight finishes before its connection goes away.
func (*TerminalPool) Evict ¶
func (p *TerminalPool) Evict(srv, assetName, account, protocol string)
Evict closes and removes one terminal.
It is idempotent and safe for an unknown key; both are what the retry-once policy needs, since the caller may evict a terminal another call already replaced.
func (*TerminalPool) Exec ¶
func (p *TerminalPool) Exec(ctx context.Context, srv *config.ServerConfig, sess *auth.Session, assetName string, cmd string, opts ExecOptions) (transport.Result, error)
Exec runs one command on a pooled terminal, opening it when necessary.
The same asset always uses the same terminal, and execution is serialized on that terminal: a shared PTY cannot interleave two commands, and ordering keeps output attribution unambiguous (DESIGN.md「TerminalPool」第 1 点). Different assets use different terminals and run in parallel.
Draining the previous command's residual output is the transport's job — transport.Terminal.Execute drains before it sends, because only the backend knows where its stream ended (DESIGN.md「TerminalPool」第 3 点); the lock this pool holds is what makes that drain meaningful.
A failure that happened before the command produced any output evicts the terminal and replays the command once on a connection built from scratch. A command that already emitted output is never replayed: the remote host has seen it, and rm/reboot are not idempotent (DESIGN.md「TerminalPool」第 5 点、 「端点故障转移」第 3 点). Output that arrived before the failure is returned with the error.
func (*TerminalPool) Reap ¶
Reap closes terminals idle for longer than ttl and reports how many.
now is injected so the caller (a ticker, or a test) owns the clock. A terminal that is running a command is skipped rather than waited for: the reaper must not stall behind a long command, and the command's own completion refreshes lastUse before it releases the lock, so a busy terminal is re-examined on the next pass.
func (*TerminalPool) Stats ¶
func (p *TerminalPool) Stats() Stats
Stats returns the current counters.
Hits and Cold are cumulative for the pool's lifetime: a reaped terminal must not make the savings disappear from the report.