lifecycle

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 4 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 lifecycle 提供与产品、账号和传输协议无关的资源生命周期。

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilContext 表示调用方没有提供 context。
	ErrNilContext = errors.New("lifecycle: context is nil")
	// ErrNilOpen 表示调用方没有提供资源打开函数。
	ErrNilOpen = errors.New("lifecycle: open function is nil")
	// ErrNilUse 表示调用方没有提供资源使用函数。
	ErrNilUse = errors.New("lifecycle: use function is nil")
	// ErrNilLease 表示打开函数成功但没有返回 Lease。
	ErrNilLease = errors.New("lifecycle: open function returned a nil lease")
)

Functions

func Run

func Run[T any](ctx context.Context, open Open[T], use Use[T]) (err error)

Run 执行一次完整生命周期:创建 child context 和 Attempt,打开资源, 使用资源,再恰好调用一次 Lease.Close;use 与 close 的错误都会保留。 即使 use 发生 panic,也会先关闭 Lease,再继续传播 panic。

Types

type Attempt

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

Attempt 标记一次资源使用是否已经越过可重放边界。 state 只允许从 0 到 1,Commit 幂等且不会回退。

func (*Attempt) Commit

func (a *Attempt) Commit()

Commit 标记本次尝试已经提交给调用方或产生外部副作用。

func (*Attempt) Committed

func (a *Attempt) Committed() bool

Committed 返回本次尝试是否已经越过可重放边界。

type Lease

type Lease[T any] struct {
	// contains filtered or unexported fields
}

Lease 持有一个需要在使用后释放的资源。

Lease 只能通过 NewLease 创建;Close 可以被重复调用,底层释放函数最多 执行一次,所有调用都会得到同一个释放错误。

func NewLease

func NewLease[T any](value T, closeFn func() error) *Lease[T]

NewLease 创建一个资源 Lease。closeFn 为 nil 时使用无操作释放函数。

func (*Lease[T]) Close

func (l *Lease[T]) Close() error

Close 释放 Lease 持有的资源。

释放函数在并发或重复调用下最多执行一次;首次调用产生的错误会被后续 调用复用。

func (*Lease[T]) Value

func (l *Lease[T]) Value() (zero T)

Value 返回 Lease 持有的资源。nil Lease 返回 T 的零值。

type Open

type Open[T any] func(context.Context) (*Lease[T], error)

Open 打开一次资源。若打开失败但仍返回非 nil Lease,Run 仍会负责关闭它。

type Use

type Use[T any] func(context.Context, T, *Attempt) error

Use 使用一次已经打开的资源。Attempt 是可重放边界的唯一状态。

Jump to

Keyboard shortcuts

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