connpool

package
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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

View Source
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 NewAssetCache

func NewAssetCache() *AssetCache

NewAssetCache returns an empty cache.

func (*AssetCache) Get

func (c *AssetCache) Get(key string, now time.Time) (assets.Info, bool)

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.

func (*AssetCache) Put

func (c *AssetCache) Put(key string, info assets.Info, now time.Time)

Put stores a resolution.

type Event added in v0.1.1

type Event struct {
	Kind     EventKind
	Server   string
	Asset    string
	Account  string
	Protocol string
	// Idle is how long the terminal sat unused, for evict and reap.
	Idle time.Duration
	// Reason is a short cause, for evict.
	Reason string
}

Event is one pool lifecycle transition.

It carries what the pool knows about its own key and nothing about the audit schema, so this package stays independent of the observability layer.

type EventKind added in v0.1.1

type EventKind string

EventKind names one pool lifecycle transition.

const (
	// KindCold reports a terminal that had to be built.
	KindCold EventKind = "cold"
	// KindHit reports a command that reused a pooled terminal.
	KindHit EventKind = "hit"
	// KindEvict reports a terminal dropped because its stream was in an
	// unknown state, or because a caller asked for it.
	KindEvict EventKind = "evict"
	// KindReap reports an idle terminal closed by the reaper.
	KindReap EventKind = "reap"
	// KindLogin reports a login the session pool performed.
	KindLogin EventKind = "login"
	// KindRelogin reports a login that replaced a session dropped by
	// Invalidate.
	KindRelogin EventKind = "relogin"
)

Lifecycle events. These are the pool's own vocabulary; the CLI is what translates them into audit kinds (DESIGN.md「审计日志」).

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 {

	// Notify, when set, receives one event per login the pool performs. It
	// is called with no pool lock held.
	Notify func(Event)
	// 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 NewSessionPool

func NewSessionPool() *SessionPool

NewSessionPool returns an empty pool.

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「代理策略」).

A cached session is only reused when it is bound to the requested address. The pool key is the alias, but the address is what the session actually talks to: a long-lived host (the MCP server) re-runs the failover policy on every call, and when that policy moves to another address the cached session is stale by definition — every KoKo connection derived from it would keep dialing the address the policy just abandoned. That was a real failure: the MCP server kept opening WebSockets to an internal address that had started answering 302, while the CLI, whose pool is a fresh process every time, worked. A mismatched address therefore re-logs in rather than being handed back (DESIGN.md「端点故障转移」第 1 点).

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 Stats

type Stats struct {
	Terminals int
	Hits      int
	Cold      int
}

Stats reports the pool's current shape, for `jms_pool_status`.

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)

	// Notify, when set, receives every lifecycle transition: a cold start, a
	// hit, an eviction and a reap. It is called with no pool or terminal
	// lock held, so a slow observer cannot stall the pool.
	Notify func(Event)
	// 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

func (p *TerminalPool) Reap(now time.Time, ttl time.Duration) int

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) RunReaper added in v0.1.1

func (p *TerminalPool) RunReaper(ctx context.Context, interval time.Duration, ttl time.Duration)

RunReaper reaps idle terminals every interval until ctx is cancelled.

It is the production caller Reap never had: the pool only knows how to close an idle terminal, and a long-lived process needs something to keep asking it to. Without this, a terminal stayed in the pool until its process exited (DESIGN.md「连接池」3.2: 空闲回收).

The loop is meant to be started with `go` by a long-lived host. It returns when ctx is done, so the goroutine does not outlive the host. A nil pool or a non-positive interval makes it return immediately rather than spin.

The ttl is passed on every pass instead of being read once, so a caller that tunes it later is not silently ignored.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL