Documentation
¶
Overview ¶
Package lifecycle 提供与产品、账号和传输协议无关的资源生命周期。
Run 在 child context 内打开资源、执行 use,并确保 Lease.Close 恰好调用一次; use 与 close 的错误都会保留。
包的组成:Lease 持有打开的资源与关闭函数,Attempt 记录一次可重放操作是否已 越过提交边界,Open 与 Use 是调用方注入的两个阶段,CloseState 逆序关闭一次 执行登记的资源。
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNilContext 表示调用方没有提供 context。 ErrNilContext = errors.New("lifecycle: context is nil") // ErrNilLease 表示打开函数成功但没有返回 Lease。 ErrNilLease = errors.New("lifecycle: open function returned a nil lease") )
Functions ¶
Types ¶
type Attempt ¶
type Attempt struct {
// contains filtered or unexported fields
}
Attempt 标记一次资源使用是否已经越过可重放边界。 state 只允许从 0 到 1,Commit 幂等且不会回退。
type CloseState ¶
type CloseState struct {
// contains filtered or unexported fields
}
CloseState 登记一次 CLI 执行的逆序关闭函数,不缓存服务或暴露依赖图。
契约:
- 所有权:谁打开资源,谁调用 Add 登记关闭函数;资源在登记前不得被其他人假定已可用。
- 关闭顺序:Close 按登记的**逆序**关闭(后打开的先关闭),符合依赖关系。
- 幂等:Close 只真正执行一次(sync.Once),重复调用返回同一结果。
- 错误聚合:关闭错误全部并入同一个 error,不因第一个失败而漏关其余资源。
- 生命周期:调用方须先停止资源生产者、完成所有 Add,再调用 Close;不得在关闭开始后再登记。
- 锁只保护登记表,不协调生产者退出;closer 在持锁期间执行,不能对同一 scope 调用 Add 或 Close。
func (*CloseState) Close ¶
func (s *CloseState) Close() error
Close 在生产者退出、登记完成后逆序关闭资源并返回聚合错误;它是幂等的。
type Lease ¶
type Lease[T any] struct { // contains filtered or unexported fields }
Lease 持有一个需要在使用后释放的资源。
Lease 只能通过 NewLease 创建;Close 可以被重复调用,底层释放函数最多 执行一次,所有调用都会得到同一个释放错误。