pool

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 24 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 pool 实现 XOps v2 彻底解耦的双通道纯内存 Actor Merkle 连接池(ADR-009 / Plan P2-T5)。

本包物理封锁在 core/internal/pool 下,严禁导入 core/internal/sshnet/**、core/osfs 与 core/internal/gate,仅依赖 core/ports、core/domain/**、core/events、core/conc 与 core/internal/foundation/{actor,trace}(生产拨号适配器由 core/engine 注入,DST 由 sim 注入)。

核心并发与安全不变量(ADR-009 / INV-C1..C3):

  • 双通道纯内存非阻塞 Actor:基于 actor.DualActor 的有界请求通道 acquireCh 与永不阻塞控制队列 controlCh(两段式 select 始终优先排空控制消息),Actor 主循环 100% 纯内存非阻塞, 所有网络拨号、保活探测与连接拆断均在 Actor 外部由 core/conc.Nursery 监督执行(0 裸 go);
  • 控制面与数据面彻底分离:租约 Lease 借出后,数据面操作(OpenSession/DialTCP/ListenTCP/ OpenRemoteFS)仅做无锁原子 Epoch 与失效哨兵校验,不触碰 Actor 循环;
  • 归还防挂起:所有 ReleaseLease 控制回传均通过 DualActor.SendControl 监听 actorDone, 在邮箱满载或连接池关闭后绝不挂起;
  • 全局单层非重入租约作用域:trace.LeaseScope 仅在即将进入用户回调 fn(scopedCtx, ...) 前注入, 绝不在池内多跳 DAG 拨号前注入,避免内部多跳解析误触 ErrReentrantLease;
  • 严格 Merkle 缓存键、父代 Epoch CAS 与 90ms 有界拆断:按 HopDigest 共享公共跳板前缀, 子跳发布强制核验父代实例与精确世代(拒绝陈旧拨号毒化池),连接拆断统一基于注入的 ports.Clock 执行 90ms 宽限期并在超时后以单赢者 CAS 升级拆断卡死根跳板;
  • 世代 SlotMap 与 GateHalted 熔断:通过封闭幻影类型 plan.ManagedHandle[K] 托管跨请求长会话, 接收来自 gate.OnHaltFunc 的 GateHalted 通知后立即原子吊销全部活跃租约与托管句柄、 触发有界拆断并使后续一切申请失败关闭。

Index

Constants

View Source
const (
	// DefaultAcquireBuffer 是 DualActor 有界请求通道 acquireCh 的默认容量。
	DefaultAcquireBuffer = 64
	// DefaultTeardownGrace 是连接拆断默认宽限时长(90ms,INV-C3 / ADR-009)。
	DefaultTeardownGrace = 90 * time.Millisecond
	// DefaultDomain 是未显式指定 LeaseScope 诊断归属标签时的默认域名。
	DefaultDomain = "pool"
)

Variables

View Source
var (
	// ErrPoolNotInitialized 表示在 nil 或零值未初始化的 Pool 实例上执行操作。
	ErrPoolNotInitialized = domi18n.Sentinel(domi18n.KeyPoolNotInitialized)
	// ErrInvalidPoolConfig 表示 NewPool 收到的配置项或依赖端口无效。
	ErrInvalidPoolConfig = domi18n.Sentinel(domi18n.KeyPoolInvalidConfig)
	// ErrPoolClosed 表示连接池已关闭,拒绝继续受理租约申请或句柄操作。
	ErrPoolClosed = domi18n.Sentinel(domi18n.KeyPoolClosed)
	// ErrGateHalted 表示能力门控已触发 Halted 熔断,连接池拒绝全部申请并吊销既有资源。
	ErrGateHalted = domi18n.Sentinel(domi18n.KeyPoolGateHalted)
	// ErrNilContext 表示传入的 context.Context 为 nil(拒绝隐式回退到 Background)。
	ErrNilContext = domi18n.Sentinel(domi18n.KeyPoolNilContext)
	// ErrNilCallback 表示作用域闭包回调 fn 为 nil。
	ErrNilCallback = domi18n.Sentinel(domi18n.KeyPoolNilCallback)
	// ErrInvalidPlan 表示传入的 SealedConnectionPlan 或摘要无效。
	ErrInvalidPlan = domi18n.Sentinel(domi18n.KeyPoolInvalidPlan)
	// ErrEmptyPlanList 表示 WithMultiLease 传入的计划列表为空。
	ErrEmptyPlanList = domi18n.Sentinel(domi18n.KeyPoolEmptyPlanList)
	// ErrPoolCapacityExceeded 表示活跃连接与在途拨号数已达 MaxConns 上限且无可驱逐空闲叶子连接。
	ErrPoolCapacityExceeded = domi18n.Sentinel(domi18n.KeyPoolCapacityExceeded)
	// ErrParentEpochChanged 表示多跳拨号完成时上游父跳板已被替换、退役或失活,父代 Epoch CAS 拒绝发布。
	ErrParentEpochChanged = domi18n.Sentinel(domi18n.KeyPoolParentEpochChanged)
	// ErrInvalidTransportConn 表示 DialerPort 返回了 nil、失活或摘要不匹配的 TransportConn。
	ErrInvalidTransportConn = domi18n.Sentinel(domi18n.KeyPoolInvalidTransportConn)
	// ErrLeaseInvalid 表示在 nil 或零值未初始化的 Lease 上执行操作。
	ErrLeaseInvalid = domi18n.Sentinel(domi18n.KeyPoolLeaseInvalid)
	// ErrLeaseExpired 表示作用域借用租约已在回调退出后失效(运行时借用失效哨兵)。
	ErrLeaseExpired = domi18n.Sentinel(domi18n.KeyPoolLeaseExpired)
	// ErrLeaseRevoked 表示租约绑定的底层传输连接已被驱逐、退役或拆断。
	ErrLeaseRevoked = domi18n.Sentinel(domi18n.KeyPoolLeaseRevoked)
	// ErrHopRetired 表示该跳传输连接已退役。
	ErrHopRetired = domi18n.Sentinel(domi18n.KeyPoolHopRetired)
	// ErrTeardownEscalated 表示子跳连接关闭超过 90ms 宽限期,已升级拆断上游根跳板连接。
	ErrTeardownEscalated = domi18n.Sentinel(domi18n.KeyPoolTeardownEscalated)
	// ErrInvalidResource 表示注册至世代 SlotMap 的托管资源为 nil 或无效。
	ErrInvalidResource = domi18n.Sentinel(domi18n.KeyPoolInvalidResource)
	// ErrInvalidHandle 表示传入的 ManagedHandle 为零值或字段不合法。
	ErrInvalidHandle = domi18n.Sentinel(domi18n.KeyPoolInvalidHandle)
	// ErrHandleNotFound 表示指定 HandleID 不存在于活跃 SlotMap 中(未登记或已被释放/回收)。
	ErrHandleNotFound = domi18n.Sentinel(domi18n.KeyPoolHandleNotFound)
	// ErrHandleRevoked 表示托管句柄在借用上下文存活期间或进入回调前被吊销(见 context.Cause(scopedCtx) 与回调前置门控);
	// 槽位摘除后的后续查找将返回 ErrHandleNotFound(池关闭/熔断时返回 ErrPoolClosed / ErrGateHalted)。
	ErrHandleRevoked = domi18n.Sentinel(domi18n.KeyPoolHandleRevoked)
	// ErrHandleGenerationMismatch 表示句柄携带的世代号与当前槽位世代不匹配(拒绝陈旧句柄复用)。
	ErrHandleGenerationMismatch = domi18n.Sentinel(domi18n.KeyPoolHandleGenMismatch)
	// ErrHandleBindingMismatch 表示句柄的类别、PlanDigest 或 OperationBinding 与登记槽位不一致。
	ErrHandleBindingMismatch = domi18n.Sentinel(domi18n.KeyPoolHandleBindMismatch)
	// ErrHandleTypeMismatch 表示槽位内托管资源的实际类型与调用方期望类型 R 不匹配。
	ErrHandleTypeMismatch = domi18n.Sentinel(domi18n.KeyPoolHandleTypeMismatch)
	// ErrHandleLimitExceeded 表示活跃托管句柄数已达 MaxHandles 上限。
	ErrHandleLimitExceeded = domi18n.Sentinel(domi18n.KeyPoolHandleLimitExceeded)
)

本包导出的不可变哨兵错误,供用例服务、引擎、仿真测试与调用方通过 errors.Is 精确匹配。

Functions

func RegisterHandle

func RegisterHandle[K plan.HandleKind, R ComparableManagedResource](p *Pool, planDigest plan.PlanDigest, binding security.OperationBinding, resource R) (plan.ManagedHandle[K], error)

RegisterHandle 在连接池世代 SlotMap 中登记类别为 K 的托管资源;若当前 planDigest 存在活跃实例则自动钉选。

func RegisterLeaseHandle

func RegisterLeaseHandle[K plan.HandleKind, R ComparableManagedResource](p *Pool, lease *Lease, binding security.OperationBinding, resource R) (plan.ManagedHandle[K], error)

RegisterLeaseHandle 在当前有效租约 lease 锁定的底层跳板世代上登记托管句柄并严格钉选该跳板实例: 租约无效/过期/跳板已退役或熔断时失败关闭;存活期间底层跳板及其祖先绝不被空闲/LRU 驱逐,断连时同步撤销句柄。

func RegisterLeaseHandleWith

func RegisterLeaseHandleWith[K plan.HandleKind, R ComparableManagedResource](p *Pool, lease *Lease, binding security.OperationBinding, start func(revokeCtx context.Context, conn ports.TransportConn) (R, error)) (plan.ManagedHandle[K], error)

RegisterLeaseHandleWith 在当前有效租约 lease 锁定的底层跳板世代上先钉选跳板并预分配世代槽位, 再同步调用 start(revokeCtx, conn) 构造长生命周期托管资源 R:

  • 传入的 conn 为池钉选可撤销 ports.TransportConn(严禁标注 //xops:borrowed),租约退出后仍持续有效;
  • 在 ReleaseHandle、RetireHop/RetirePlan、GateHalted 或 Pool.Close 后,conn 立即拒绝后续数据面打开;
  • 若 start 失败、返回无效资源、发生 panic 或期间被并发吊销,均原子回滚槽位与跳板钉选并有界关闭资源。

func ReleaseHandle

func ReleaseHandle[K plan.HandleKind](p *Pool, handle plan.ManagedHandle[K]) error

ReleaseHandle 显式释放指定世代句柄、非阻塞解除底层跳板钉选,并在 90ms 有界预算内关闭底层资源。

func WithManagedHandle

func WithManagedHandle[K plan.HandleKind, R ComparableManagedResource](
	ctx context.Context, p *Pool, handle plan.ManagedHandle[K], fn func(ctx context.Context, res R) error,
) error

WithManagedHandle 凭世代句柄在同步闭包内借用类型为 R 的托管资源,绝不在回调期间持有 SlotMap 锁。

Types

type ComparableManagedResource

type ComparableManagedResource interface {
	ManagedResource
	comparable
}

ComparableManagedResource 约束可登记与借用的可比较托管资源类型,零 reflect 拦截 nil/typed-nil/零值。

type HandleStatus

type HandleStatus struct {
	// contains filtered or unexported fields
}

HandleStatus 表示世代 SlotMap 中某个托管句柄的不可变只读状态快照;零值恒无效并失败关闭。

func InspectHandle

func InspectHandle[K plan.HandleKind](p *Pool, handle plan.ManagedHandle[K]) (HandleStatus, error)

InspectHandle 只读查询指定世代句柄当前是否有效活跃(不暴露底层资源指针)。

func (HandleStatus) Active

func (s HandleStatus) Active() bool

func (HandleStatus) Binding

func (HandleStatus) Generation

func (s HandleStatus) Generation() uint64

func (HandleStatus) ID

func (s HandleStatus) ID() plan.HandleID

func (HandleStatus) IsValid

func (s HandleStatus) IsValid() bool

HandleStatus 只读访问器(全字段失败关闭,无效零值返回零值或 false)。

func (HandleStatus) IsZero

func (s HandleStatus) IsZero() bool

func (HandleStatus) Kind

func (s HandleStatus) Kind() plan.HandleKindCode

func (HandleStatus) PlanDigest

func (s HandleStatus) PlanDigest() plan.PlanDigest

type Lease

type Lease struct {
	// contains filtered or unexported fields
}

Lease 表示由 Pool.WithLease 或 Pool.WithMultiLease 在同步作用域闭包内借出的连接租约(ADR-009 / ADR-011)。 零值恒无效;回调退出即置 active=false;全部数据面方法仅做无锁原子 Epoch 校验,绝不触碰 DualActor 循环。

func (*Lease) DialStreamLocal

func (l *Lease) DialStreamLocal(ctx context.Context, remoteSocket pathalg.RemotePath) (net.Conn, error)

func (*Lease) DialTCP

func (l *Lease) DialTCP(ctx context.Context, target netaddr.HostPort) (net.Conn, error)

func (*Lease) Endpoint

func (l *Lease) Endpoint() netaddr.Endpoint

func (*Lease) Epoch

func (l *Lease) Epoch() uint64

func (*Lease) HopDigest

func (l *Lease) HopDigest() plan.HopDigest

func (*Lease) IsAlive

func (l *Lease) IsAlive() bool

func (*Lease) IsValid

func (l *Lease) IsValid() bool

IsValid 报告租约当前是否处于有效作用域内且底层连接世代未被吊销或熔断。

func (*Lease) IsZero

func (l *Lease) IsZero() bool

func (*Lease) LeaseID

func (l *Lease) LeaseID() string

func (*Lease) ListenStreamLocal

func (l *Lease) ListenStreamLocal(ctx context.Context, remoteSocket pathalg.RemotePath) (net.Listener, error)

func (*Lease) ListenTCP

func (l *Lease) ListenTCP(ctx context.Context, bindAddr string) (net.Listener, error)

func (*Lease) OpenRemoteFS

func (l *Lease) OpenRemoteFS(ctx context.Context) (ports.RemoteFSPort, error)

func (*Lease) OpenSession

func (l *Lease) OpenSession(ctx context.Context) (ports.RemoteSession, error)

以下方法在无锁数据面路径上直接委派底层 ports.TransportConn 执行会话、SFTP 与各类隧道转发。

func (*Lease) OpenTUN

func (l *Lease) OpenTUN(ctx context.Context, spec ports.TUNSpec) (io.ReadWriteCloser, error)

func (*Lease) PlanDigest

func (l *Lease) PlanDigest() plan.PlanDigest

func (*Lease) Retire

func (l *Lease) Retire()

Retire 通知连接池退役本租约绑定的精确世代连接实例(带世代防 ABA,绝不误杀已重连的新世代)。

type ManagedResource

type ManagedResource interface {
	IsValid() bool
	Close() error
}

ManagedResource 表示可托管于连接池世代 SlotMap 的跨请求长生命周期资源契约 (如持久 PTY、隧道转发器、可恢复文件传输会话或 ControlMaster 守护句柄,ADR-009)。

type Pool

type Pool struct {
	// contains filtered or unexported fields
}

Pool 是完全解耦于具体 SSH 实现的双通道纯内存 Actor Merkle 连接池(ADR-009 / Plan P2-T5)。

零值恒未初始化且所有方法均严格失败关闭;通过 NewPool 创建后,由 workNursery 监督 DualActor 主循环、在途拨号与保活任务,由独立 teardownNursery 执行 90ms 有界拆断,确保调用 Close 时 按严格顺序收敛所有后台协程并满足 goleak 0 泄漏。

func NewPool

func NewPool(ctx context.Context, cfg PoolConfig) (*Pool, error)

NewPool 校验配置与出站依赖端口,初始化 DualActor、双 Nursery 与世代 SlotMap,并启动 Actor 主循环。 调用方须在生命周期结束时配对调用 Close() 以优雅排空所有后台协程与底层传输连接。

func (*Pool) Close

func (p *Pool) Close() error

Close 幂等关闭连接池:吊销全部托管句柄、停止 DualActor 并排空所有请求与工作协程、 对残余连接执行 90ms 有界拆断并等待全部拆断协程退出,保证零连接与零协程泄漏。

func (*Pool) EvictIdle

func (p *Pool) EvictIdle() int

EvictIdle 立即驱逐池内所有无活跃租约、无钉选托管句柄且无活跃子跳的空闲连接(自底向上级联驱逐),返回驱逐数量。

func (*Pool) GateHalted

func (p *Pool) GateHalted(reason error)

GateHalted 响应能力门控触发的 Halted 熔断(可直接接线至 gate.OnHaltFunc,ADR-008 / ADR-009): 原子置位熔断态、取消 haltCtx 并吊销全部活跃托管句柄、经控制通道同步摘除全部连接并有界拆断。

func (*Pool) IsClosed

func (p *Pool) IsClosed() bool

func (*Pool) IsHalted

func (p *Pool) IsHalted() bool

IsHalted / IsClosed 报告连接池熔断或关闭状态(nil 或未初始化零值失败关闭返回 true)。

func (*Pool) RetireHop

func (p *Pool) RetireHop(digest plan.HopDigest) error

RetireHop 主动退役指定 HopDigest 的当前活跃连接及其全部下游子跳,取消关联租约并在 90ms 宽限内拆断。

func (*Pool) RetirePlan

func (p *Pool) RetirePlan(planDigest plan.PlanDigest) error

RetirePlan 主动退役指定顶层 PlanDigest 对应的末跳连接(不误伤健康共享的上游堡垒机跳板)。

func (*Pool) RevokeHandlesByPlan

func (p *Pool) RevokeHandlesByPlan(planDigest plan.PlanDigest) int

RevokeHandlesByPlan 吊销并回收全部绑定到指定 PlanDigest 的活跃托管句柄,非阻塞解钉并返回吊销数量。

func (*Pool) Stats

func (p *Pool) Stats() PoolStats

Stats 返回连接池当前的无锁并发安全运行期统计快照。

func (*Pool) WaitPendingTeardowns

func (p *Pool) WaitPendingTeardowns(ctx context.Context) error

WaitPendingTeardowns 阻塞等待当前已派发的有界拆断协调任务全部结束(或 ctx 取消),供测试零 time.Sleep 同步。

func (*Pool) WithLease

func (p *Pool) WithLease(ctx context.Context, connPlan plan.SealedConnectionPlan, fn func(ctx context.Context, lease *Lease) error) error

WithLease 按不可变 Merkle 连接计划申请单条同步借用连接租约,在即将进入用户回调 fn 前注入 全局单层不可重入 trace.LeaseScope(绝不在池内多跳 DAG 拨号前注入,防止内部多跳误触 ErrReentrantLease)。 回调返回(含错误与 panic)时无条件使借用哨兵失效,并通过监听 actorDone 的控制通道归还租约。

func (*Pool) WithMultiLease

func (p *Pool) WithMultiLease(ctx context.Context, plans []plan.SealedConnectionPlan, fn func(ctx context.Context, leases []*Lease) error) error

WithMultiLease 按规范拓扑深度优先 + PlanDigest 全序一次性申请多个连接计划的同步借用租约, 从根源消除并发反序申请的锁序/容量死锁(ADR-009),并在即将进入用户回调 fn 前注入单一 全局不可重入 trace.LeaseScope。回调收到的 leases 切片严格保持调用方传入 plans 的原始顺序。

type PoolConfig

type PoolConfig struct {
	Dialer                   ports.DialerPort  // 协议无关 SSH 单跳/多跳拨号端口(必需)
	Clock                    ports.Clock       // 时钟与定时器端口(驱动 90ms 拆断、保活与空闲回收,必需)
	Entropy                  ports.Entropy     // 并发安全显式熵源(必需)
	Bus                      *events.SystemBus // 可选系统诊断事件总线
	Domain                   string            // trace.LeaseScope 诊断归属标签(默认 "pool")
	AcquireBuffer            int               // DualActor 有界请求通道容量(0 取 DefaultAcquireBuffer)
	MaxConns                 int               // 活跃连接与在途拨号总数上限(0 不限,负值非法)
	MaxHandles               int               // 世代 SlotMap 活跃托管句柄上限(0 不限,负值非法)
	TeardownGrace            time.Duration     // 连接拆断宽限时长(0 取 DefaultTeardownGrace=90ms)
	IdleTTL                  time.Duration     // 空闲叶子连接过期回收时长(0 禁用后台扫描)
	DefaultKeepaliveInterval time.Duration     // HopSpec 未指定 ServerAliveInterval 时的保活回退间隔
}

PoolConfig 定义连接池 Pool 的运行期初始化配置(纯内存构造参数,非持久化 DTO)。 Dialer、Clock 与 Entropy 为必需依赖;Clock 与 Entropy 经接口注入确保确定性仿真。

type PoolStats

type PoolStats struct {
	ActiveConns, DialingConns, ActiveHandles int
	ActiveLeases                             int64
	TotalDials, DialErrors, CacheHits        uint64
	ParentCASRejections                      uint64
	TeardownCompleted, TeardownEscalations   uint64
	Halted, Closed                           bool
}

PoolStats 提供连接池当前的无锁并发安全运行期统计快照。

Jump to

Keyboard shortcuts

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