events

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 11 Imported by: 6 modules, 7 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.

README

Events

要求 Go 1.23 或更高版本。

一、这是什么

Storage Lock底层的事件机制,分布式锁算法的大多数操作都会触发事件,通过监听事件可以实现锁的可观测性等等功能,这里只是进行事件机制的基础定义,具体事件触发是在Storage Lock的分布式锁的各个步骤里。

二、安装依赖

go get github.com/storage-lock/go-events@latest

三、组件介绍

Event

用于封装每个被触发的事件:

// Event 表示一个事件
type Event struct {

	// 事件的唯一ID
	ID string `json:"id"`

	// 此事件树的树根ID,用于对事件进行聚合分组
	RootID string `json:"root_id"`

	// 如果此事件拥有父事件,则保留一个指向父事件的引用
	ParentID string `json:"parent_id"`
	Parent   *Event `json:"-"`

	// 事件可以绑定到一个锁
	LockId string `json:"lock_id"`

	// 当前的事件是由谁产生的
	OwnerId string `json:"owner_id"`

	// 事件可以绑定到一个Storage
	StorageName string `json:"storage_name"`

	// 事件拥有开始时间和结束时间,可以通过这个来借助事件进行一些性能统计之类的
	StartTime *time.Time `json:"start_time"`
	EndTime   *time.Time `json:"end_time"`

	// 事件的类型
	EventType EventType `json:"event_type"`

	// 事件持续过程中的一些行为记录
	Actions []*Action `json:"actions"`

	// 事件可以绑定一个WatchDog
	WatchDogId string `json:"watch_dog_id"`

	// 事件可以绑定到锁信息
	LockInformation *storage.LockInformation `json:"lock_information"`

	// 如果有事件级别的错误,则可以放在这里,不过还是推荐优先使用Action级别的错误对Action进行精准绑定
	Err error `json:"err"`

	// 订阅了此时间的Listener都有哪些
	Listeners []Listener `json:"-"`
}

Action

一个事件可能会携带多个Action:

// Action 一个事件可以添加若干个Action,每个Action都会有一些时间、名称、上下文之类的
type Action struct {

	// Action被创建的时间
	StartTime *time.Time `json:"start_time"`

	// Action结束的时间,有时候会用不到
	EndTime *time.Time `json:"end_time"`

	// Action的名字
	Name string `json:"name"`

	// 执行此Action时发生的错误
	Err error `json:"err"`

	// action可以携带一些自己单独的上下文信息之类的
	PayloadMap map[string]any `json:"payload_map"`
}

JSON 序列化

Event.ToJsonStringE() 会返回编码错误,适合需要可靠处理序列化失败的场景;ToJsonString() 为兼容便利方法,编码失败时返回空字符串。EventFromJsonStringE() 会返回格式错误。错误字段只持久化 Error() 文本,错误的具体类型、包装链和 errors.Is 关系不会跨 JSON 保留。旧版本将 error interface 编码成 {} 的记录仍可读取,但历史错误文本本身无法恢复。

EventType

Event.EventType 用于标识事件类别,可通过 EventType.String() 获取稳定的可读名称:

常量 值 String() 含义
EventTypeUnknown 0 unknown 未指定类型
EventTypeCreateLock 1 create 创建锁
EventTypeLock 2 lock 获取锁流程
EventTypeUnlock 3 unlock 释放锁流程
EventTypeWatchDog 4 watchdog 看门狗活动
EventTypeExpired 5 expired 锁租约过期或过期记录被接管
EventTypeBusy 6 busy 锁正被占用,竞争者等待重试
EventTypeRenewed 7 renewed 锁租约续期成功
EventTypeLost 8 lost 原持有者确认失去锁所有权
EventTypeWaitChanged 9 wait_changed 锁的等待队列发生变化

事件类型在 JSON 中以整数保存。已分配的整数值是兼容性契约,后续类型只会追加,不应重排或复用;遇到未知数值时 String() 返回 unknown。消费者应为未知类型保留兜底处理。Event.Err 和 Action.Err 在 JSON 中保存为错误消息字符串,反序列化后可读取消息,但原错误类型及 errors.Is 关系无法恢复;旧版本产生的空对象错误字段会按无错误处理。

按类型过滤事件的示例:

listener := events.NewListenerWrapper("lock-events", func(ctx context.Context, e *events.Event) {
    switch e.EventType {
    case events.EventTypeBusy:
        // 记录锁竞争
    case events.EventTypeLost:
        // 处理持有权丢失
    }
})

Listener

实现Listener在创建锁的时候设置上则可以实现对锁事件的监听:

// Listener 事件监听器,当有任何事件的时候都会触发此监听器把事件传给它处理
type Listener interface {

	// Name 当有多个事件监听器的时候用于区分彼此
	Name() string

	// On 每次事件被触发的时候此函数被执行一次
	On(ctx context.Context, e *Event)
}

四、实现示例

基于事件机制,你可以实现很多有意思的功能,这里是一些基于事件机制实现的示例:

Documentation

Index

Constants

View Source
const EventIDPrefix = "storage-lock-event-"

EventIDPrefix 事件的ID的前缀,用于方便区分是否是事件的ID

Variables

This section is empty.

Functions

This section is empty.

Types

type Action

type Action struct {

	// Action被创建的时间
	StartTime *time.Time `json:"start_time"`

	// Action结束的时间,有时候会用不到
	EndTime *time.Time `json:"end_time"`

	// Action的名字
	Name string `json:"name"`

	// 执行此Action时发生的错误
	Err error `json:"err"`

	// action可以携带一些自己单独的上下文信息之类的
	PayloadMap map[string]any `json:"payload_map"`
}

Action 一个事件可以添加若干个Action,每个Action都会有一些时间、名称、上下文之类的

func NewAction

func NewAction(name string) *Action

func (*Action) AddPayload

func (x *Action) AddPayload(key string, value any) *Action

AddPayload 往action上增加payload

func (*Action) ClearErr

func (x *Action) ClearErr() *Action

ClearErr 清空action绑定的错误

func (*Action) ClearPayloadMap

func (x *Action) ClearPayloadMap() *Action

ClearPayloadMap 清空payloadMap

func (*Action) Cost

func (x *Action) Cost() time.Duration

Cost 计算此Action花费的时间,必须startTime和endTime同时存在的时候才有效

func (*Action) End

func (x *Action) End() *Action

End 用于标记action结束了,更新其结束时间

func (*Action) ErrorIs

func (x *Action) ErrorIs(err error) bool

ErrorIs 判断action绑定的错误是否是给定类型

func (*Action) GetErrMsg

func (x *Action) GetErrMsg() string

GetErrMsg 获取action绑定的错误的信息,如果没有绑定错误的话返回空字符串

func (*Action) GetPayload

func (x *Action) GetPayload(key string) (any, bool)

GetPayload 从payloadMap中获取value

func (*Action) GetPayloadAsInt

func (x *Action) GetPayloadAsInt(key string) int

GetPayloadAsInt 获取payload作为int返回。 支持整数类型和可解析的十进制数字字符串;缺少key、溢出或类型不支持时返回0。

func (*Action) GetPayloadAsString

func (x *Action) GetPayloadAsString(key string) string

GetPayloadAsString 从payloadMap中获取value并以string返回。 对于序列化后常见的字符串、数字和布尔值会转换为其文本表示; 缺少key或值类型不支持时返回空字符串。

func (*Action) GetPayloadMap

func (x *Action) GetPayloadMap() map[string]any

func (*Action) MarshalJSON added in v0.0.5

func (x *Action) MarshalJSON() ([]byte, error)

func (*Action) SetErr

func (x *Action) SetErr(err error) *Action

SetErr 设置action绑定的错误

func (*Action) SetName

func (x *Action) SetName(name string) *Action

SetName 设置action的名字

func (*Action) SetPayloadMap

func (x *Action) SetPayloadMap(payloadMap map[string]any) *Action

SetPayloadMap 设置action的payload map

func (*Action) UnmarshalJSON added in v0.0.5

func (x *Action) UnmarshalJSON(data []byte) error

type Event

type Event struct {

	// 事件的唯一ID
	ID string `json:"id"`

	// 此事件树的树根ID,用于对事件进行聚合分组
	RootID string `json:"root_id"`

	// 如果此事件拥有父事件,则保留一个指向父事件的引用
	ParentID string `json:"parent_id"`
	Parent   *Event `json:"-"`

	// 事件可以绑定到一个锁
	LockId string `json:"lock_id"`

	// 当前的事件是由谁产生的
	OwnerId string `json:"owner_id"`

	// 事件可以绑定到一个Storage
	StorageName string `json:"storage_name"`

	// 事件拥有开始时间和结束时间,可以通过这个来借助事件进行一些性能统计之类的
	StartTime *time.Time `json:"start_time"`
	EndTime   *time.Time `json:"end_time"`

	// 事件的类型
	EventType EventType `json:"event_type"`

	// 事件持续过程中的一些行为记录
	Actions []*Action `json:"actions"`

	// 事件可以绑定一个WatchDog
	WatchDogId string `json:"watch_dog_id"`

	// 事件可以绑定到锁信息
	LockInformation *storage.LockInformation `json:"lock_information"`

	// 如果有事件级别的错误,则可以放在这里,不过还是推荐优先使用Action级别的错误对Action进行精准绑定
	Err error `json:"err"`

	// 订阅了此时间的Listener都有哪些
	Listeners []Listener `json:"-"`
}

Event 表示一个事件

func EventFromJsonStringE

func EventFromJsonStringE(eventJsonString string) (*Event, error)

func NewEvent

func NewEvent(lockId string) *Event

func (*Event) AddAction

func (x *Event) AddAction(action *Action) *Event

AddAction 往事件中追加一个action

func (*Event) AddActionByName

func (x *Event) AddActionByName(actionName string) *Event

AddActionByName 添加Action名,一般用于只需要记录名称和时间不需要记录其它字段的时候

func (*Event) AddListeners

func (x *Event) AddListeners(listener Listener) *Event

func (*Event) ClearListeners

func (x *Event) ClearListeners() *Event

func (*Event) End

func (x *Event) End() *Event

End 用于设置事件的完成时间为当前

func (*Event) Fork

func (x *Event) Fork() *Event

Fork 从当前事件创建一个子事件,子事件会继承父事件的一些属性

func (*Event) GetParentID

func (x *Event) GetParentID() string

func (*Event) IsRootEvent

func (x *Event) IsRootEvent() bool

IsRootEvent 此事件是否是最底层的事件,整个事件的fork关系可以看做是一颗树

func (*Event) MarshalJSON added in v0.0.5

func (x *Event) MarshalJSON() ([]byte, error)

func (*Event) Publish

func (x *Event) Publish(ctx context.Context, listeners ...Listener)

Publish 把当前的事件发布到多个Listener上

func (*Event) SetErr

func (x *Event) SetErr(err error) *Event

func (*Event) SetListeners

func (x *Event) SetListeners(listeners []Listener) *Event

func (*Event) SetLockId

func (x *Event) SetLockId(lockId string) *Event

func (*Event) SetLockInformation

func (x *Event) SetLockInformation(lockInformation *storage.LockInformation) *Event

func (*Event) SetOwnerId

func (x *Event) SetOwnerId(ownerId string) *Event

func (*Event) SetParent

func (x *Event) SetParent(event *Event) *Event

func (*Event) SetRootID

func (x *Event) SetRootID(rootID string) *Event

func (*Event) SetStorageName

func (x *Event) SetStorageName(storageName string) *Event

func (*Event) SetType

func (x *Event) SetType(eventType EventType) *Event

func (*Event) SetWatchDogId

func (x *Event) SetWatchDogId(watchDogId string) *Event

func (*Event) ToJsonString

func (x *Event) ToJsonString() string

func (*Event) ToJsonStringE

func (x *Event) ToJsonStringE() (string, error)

func (*Event) UnmarshalJSON added in v0.0.5

func (x *Event) UnmarshalJSON(data []byte) error

type EventType

type EventType int
const (

	// EventTypeUnknown 未设置事件类型
	EventTypeUnknown EventType = iota

	// EventTypeCreateLock 创建锁的过程中产生的事件
	EventTypeCreateLock

	// EventTypeLock 获取锁的过程中产生的事件
	EventTypeLock

	// EventTypeUnlock 释放锁的过程中产生的事件
	EventTypeUnlock

	// EventTypeWatchDog 看门狗产生的事件
	EventTypeWatchDog

	// EventTypeExpired 锁因租约过期被抢占(记录是墓碑或超时后他人接管)。见 ActionLockExpired。
	EventTypeExpired

	// EventTypeBusy 竞争锁时发现锁被他人持有而等待重试。见 ActionLockBusy。
	EventTypeBusy

	// EventTypeRenewed 锁租约被看门狗或主动 Renew 成功续期。见 ActionWatchDogRefreshSuccess。
	EventTypeRenewed

	// EventTypeLost 看门狗确认持有权丢失(他人抢占、锁删除或租约过期),业务侧应停止使用该锁。
	// 对应 OnLockLost 回调与 ActionNotLockOwner/ErrLockLost 路径。
	EventTypeLost

	// EventTypeWaitChanged 锁记录上的等待队列发生变化(有人排队、离开或队首接管)。
	EventTypeWaitChanged
)

func (EventType) String added in v0.0.5

func (x EventType) String() string

String 返回事件类型的可读名称,供日志、审计和指标使用。 未知类型返回 "unknown"。

type Eventable added in v0.0.2

type Eventable interface {
	SetEvent(e *Event)
}

Eventable

type Listener

type Listener interface {

	// Name 当有多个事件监听器的时候用于区分彼此
	Name() string

	// On 每次事件被触发的时候此函数被执行一次
	On(ctx context.Context, e *Event)
}

Listener 事件监听器,当有任何事件的时候都会触发此监听器把事件传给它处理

type ListenerWrapper

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

ListenerWrapper 如果不想声明struct实现Listener接口的话,可以使用这个struct来对函数来包裹函数实现

func NewListenerWrapper

func NewListenerWrapper(name string, listenerFunc func(ctx context.Context, e *Event)) *ListenerWrapper

func (*ListenerWrapper) Name

func (x *ListenerWrapper) Name() string

func (*ListenerWrapper) On

func (x *ListenerWrapper) On(ctx context.Context, e *Event)

Jump to

Keyboard shortcuts

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