WuKongIM webhook workqueue 迁移实战:基于 pkg/workqueue 的节点级有界尽力投递运行时

原创2026-10-15 15:48:051,424 阅读
文章标签:即时通讯后端

WuKongIM webhook workqueue 迁移实战:基于 pkg/workqueue 的节点级有界尽力投递运行时

本文基于 WuKongIM 仓库中的实现计划 2026-06-24-internalv2-webhook-workqueue-migration.md 展开,完整讲解如何将遗留 webhook 行为迁移为一个节点本地、有界、尽力而为(best-effort)的运行时:包括三类事件(msg.notify、msg.offline、user.onlinestatus)的 DTO 与 JSON 映射、pkg/workqueue 批处理队列的选型与接入、有限重试与低基数观测、WK_WEBHOOK_* 配置项的默认值与校验,以及 app 层装配与生命周期顺序。读完后你可以掌握"如何把慢速外部端点从消息主链路中隔离出去"这一通用模式,并能在当前仓库中定位每一处对应实现。

1. 迁移目标与可靠性边界

计划开篇给出的目标是:将遗留 webhook 行为迁移为 internalv2 下节点本地、有界、尽力而为的运行时,用 pkg/workqueue 承载高吞吐事件准入与批量发送。覆盖三类遗留事件:

  • msg.notify:已提交(committed)的持久化消息批次;
  • msg.offline:presence 解析后、无在线路由的离线接收者分块;
  • user.onlinestatus:批量在线/离线路由状态字符串。

整个设计的第一原则是可靠性边界(计划原文 Reliability boundary):

  • 队列是尽力而为的、有界的、纯内存的(best-effort, bounded, in-memory queues);
  • 重试在 webhook 运行时内部有限进行(finite retry);
  • 队列满(queue-full)与重试耗尽(retry-exhausted)的事件被丢弃,并伴随观测/日志;
  • webhook 失败绝不改变持久化 append 成功、SENDACK、会话活跃准入(conversation active admission)或 owner 投递的结果;
  • 进程崩溃后的重放(crash replay)不在本计划范围内。

传输边界上,本计划只实现 HTTP 投递;运行时定义了 Sender 接口,gRPC 留待后续计划引入根级 pkg/wkhook 协议包和 google.golang.org/grpc 依赖后另行添加——计划中明确说明当前根仓库没有 pkg/wkhook 包、也没有 gRPC 依赖。从仓库现状看,这个约束仍然成立:internal/runtime/webhook 的对外投递只有 HTTP 一种实现(internal/runtime/webhook/sender.go),但 Sender 接口确实被保留为可替换的抽象。

这种"外部端点慢或挂掉时,主链路完全无感"的设计,是理解后续所有代码的钥匙:webhook 运行时只消费已经决定的事件,不参与任何产品级成功语义。这一点也被落地的 FLOW 文档固化在 internal/runtime/webhook/FLOW.md 的"边界"一节:

It receives already-decided events from app adapters and does not own message durability, subscriber scans, presence, plugin hooks, Channel ordering, or crash replay.

2. 总体架构:一个类型化运行时 + 三条事件流

计划的 Architecture 一节规定:新增 internalv2/runtime/webhook(在当前仓库树中落地为 internal/runtime/webhook),作为类型化运行时,独占 webhook DTO、有界队列、HTTP 投递、有限重试和低基数观测;只从 app 层接线,由 channel append 的 post-commit 副作用和 presence 激活/停用提供适配器;同时保持 access/* 协议适配器保持"薄",并保证 channel append 的 SENDACK 与 webhook 成功相互独立。

计划给出的文件结构(计划中路径带 internalv2/ 前缀,当前仓库对应实现位于 internal/ 下同构位置):

计划文件 职责 当前仓库对应
runtime/webhook/FLOW.md 运行时所有权、事件流、有界准入、重试与性能规则 internal/runtime/webhook/FLOW.md
runtime/webhook/types.go Event、Message、OfflineMessage、OnlineStatus、Options、观测契约 internal/runtime/webhook/types.go
runtime/webhook/sender.go Sender、SendRequest、HTTPSender、事件常量、JSON 编码与 HTTP 成功规则 internal/runtime/webhook/sender.go
runtime/webhook/runtime.go notify/online 的 BoundedBatchPool、offline 的 ShardedMailbox、生命周期、准入、重试与队列快照 internal/runtime/webhook/runtime.go
runtime/webhook/mapper.go 由运行时 DTO 构造遗留兼容 JSON 形状 internal/runtime/webhook/mapper.go
app/webhook.go 把 channelappend 与 presence 事件适配为运行时输入,组合 hook fanout internal/app/webhook.go
app/config.go WebhookConfig、默认值与校验 internal/app/config.go
cmd 配置解析 WK_WEBHOOK_* 支持键 internal/config/schema.go

三条事件流(对应落地的 FLOW 文档 Main Flows):

msg.notify
  -> app 适配器收到 channelappend 的持久化 committed envelope
  -> webhook 运行时把一条 Message 准入到 notify 批量池
  -> worker 向 {HTTPAddr}?event=msg.notify 发送一个 JSON 数组

msg.offline
  -> channelappend 接收者处理器把接收者分类为离线
  -> 批量 observer 以有界 UID 分块传给 app 适配器
  -> webhook 运行时把 OfflineMessage 分块准入到分片邮箱
  -> worker 向 {HTTPAddr}?event=msg.offline 发送一个 JSON 对象

user.onlinestatus
  -> presence 用例在路由激活/停用成功后产生观测
  -> app 适配器格式化成遗留状态字符串
  -> webhook 运行时准入到 online-status 批量池
  -> worker 向 {HTTPAddr}?event=user.onlinestatus 发送一个 JSON 数组

3. 事件模型与遗留兼容的 JSON 映射

3.1 事件常量与 DTO

types.go 定义三个事件常量与核心 DTO。以下代码继承自计划的 Task 2(落地代码在 internal/runtime/webhook/types.go 基础上增加了 Setting、Topic、Expire、SourceID 等遗留字段):

const (
	// EventMsgNotify reports committed durable messages.
	EventMsgNotify = "msg.notify"
	// EventMsgOffline reports offline recipients for one committed message chunk.
	EventMsgOffline = "msg.offline"
	// EventUserOnlineStatus reports online/offline route status strings.
	EventUserOnlineStatus = "user.onlinestatus"
)

// Message is the event-neutral committed message shape accepted by the webhook runtime.
type Message struct {
	MessageID         uint64
	MessageSeq        uint64
	ChannelID         string
	ChannelType       uint8
	FromUID           string
	ClientMsgNo       string
	ServerTimestampMS int64
	Payload           []byte
	RedDot            bool
	SyncOnce          bool
}

// OfflineMessage carries one committed message plus one bounded recipient UID chunk.
type OfflineMessage struct {
	Message Message
	ToUIDs  []string
}

// OnlineStatus records one legacy-compatible user online status string.
type OnlineStatus struct {
	Value string
}

// SendRequest is one encoded webhook request.
type SendRequest struct {
	Event string
	Body  []byte
}

// Sender delivers one encoded webhook request to an external endpoint.
type Sender interface {
	Send(context.Context, SendRequest) error
}

// Observer receives low-cardinality webhook runtime observations.
type Observer interface {
	ObserveWebhook(Observation)
}

Observation 结构承载一次准入、发送、重试或丢弃事件的低基数快照:Queue、Event、Result、Items、QueueDepth、QueueSize、Attempt、Duration、Err。计划特别强调:观测中不得包含 UID、channel id、session id 或端点地址,避免高基数标签污染指标系统。

3.2 mapper:MessageResp 兼容形状与 UID gzip 压缩

mapper.go 负责把运行时 DTO 翻译成遗留系统可识别的 JSON。核心结构:

type messageResp struct {
	Header       messageHeader `json:"header"`
	Setting      uint8         `json:"setting"`
	MessageID    uint64        `json:"message_id"`
	MessageIDStr string        `json:"message_idstr"`
	ClientMsgNo  string        `json:"client_msg_no"`
	MessageSeq   uint64        `json:"message_seq"`
	FromUID      string        `json:"from_uid"`
	ChannelID    string        `json:"channel_id"`
	ChannelType  uint8         `json:"channel_type"`
	Timestamp    int32         `json:"timestamp"`
	Payload      []byte        `json:"payload"`
}

type messageHeader struct {
	NoPersist uint8 `json:"no_persist"`
	RedDot    uint8 `json:"red_dot"`
	SyncOnce  uint8 `json:"sync_once"`
}

type offlineResp struct {
	MessageResp
	ToUIDs         []string `json:"to_uids,omitempty"`
	Compress       string   `json:"compress,omitempty"`
	CompressToUIDs string   `json:"compress_to_uids,omitempty"`
	SourceID       int64    `json:"source_id,omitempty"`
}

三个构造函数的要点:

  • buildNotifyBody 把 []Message 映射为 []messageResp 后整体 json.Marshal,即一次 HTTP 请求体就是一个 JSON 数组,payload 字段经 base64 编码进入 JSON;
  • buildOfflineBody 实现离线 UID 压缩:当 compressThreshold > 0 && len(ToUIDs) >= compressThreshold 时,把 UID 切片编码为 JSON 后 gzip、再 base64,写入 compress: "gzip" 与 compress_to_uids 字段,并省略明文 to_uids;否则原样携带 to_uids。大群离线广播场景下这能显著压缩请求体;
  • buildOnlineStatusBody 把 []OnlineStatus 过滤空串后序列化为字符串数组。

计划对应的 mapper 测试(mapper_test.go,落地于 internal/runtime/webhook/mapper_test.go)验证了:message_id/message_seq 的数值映射、header.red_dot=1、sync_once=0、no_persist=0,以及压缩分支下 compress == "gzip"、compress_to_uids 非空、to_uids 不存在。

4. HTTP Sender:只有 200 算成功

sender.go 定义了唯一的投递实现 HTTPSender。请求语义很克制:

  • 请求方式为 POST,目标地址是 {HTTPAddr}?event=<事件名>,event 作为查询参数追加;
  • Content-Type: application/json;
  • 单次尝试受 Timeout 约束(context.WithTimeout 包裹);
  • 只有 HTTP 200 判定为成功,其他状态码(包括 202)都返回错误进入重试流程;
  • 响应体统一 io.Copy(io.Discard, ...) 丢弃,不解析任何内容。
// Send posts the encoded webhook body as JSON. Only HTTP 200 is classified as success.
func (s *HTTPSender) Send(ctx context.Context, req SendRequest) error {
	// ... 省略 addr 校验与 context 超时包裹 ...
	query := target.Query()
	query.Set("event", req.Event)
	target.RawQuery = query.Encode()
	httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, target.String(), bytes.NewReader(req.Body))
	// ...
	resp, err := s.client.Do(httpReq)
	// ...
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("webhook: http status %s", strconv.Itoa(resp.StatusCode))
	}
	return nil
}

计划中的 sender 测试(落地于 internal/runtime/webhook/sender_test.go)覆盖两点:event 查询参数与 JSON 请求体原样送达;非 200(如 202)必须返回错误。HTTPSenderOptions 还预留了 Client *http.Client 字段,允许测试注入 httptest.Server 或自定义 transport。

5. 队列选型:为什么是"两个批量池 + 一个分片邮箱"

这是本计划最有信息量的部分。Start 方法根据三种事件的不同并发特征,选择了 pkg/workqueue(pkg/workqueue/USAGE.md)里两类不同的原语:

notify, err := workqueue.NewBoundedBatchPoolMessage workqueue.BatchOptions {
		return workqueue.BatchOptions{MaxItems: r.opts.NotifyBatchMaxItems, MaxWait: r.opts.NotifyBatchMaxWait}
	},
}, r.handleNotifyBatch)

online, err := workqueue.NewBoundedBatchPoolOnlineStatus

offline, err := workqueue.NewShardedMailboxOfflineMessage

选型的理由(结合 pkg/workqueue/USAGE.md 的使用指南可以推断):

  • msg.notify 与 user.onlinestatus 用 BoundedBatchPool<a href="https://link.gitcode.com/i/2d6c060dd7a25c84741619ceb1a70412" target="_blank">T]([bounded_batch_pool.go):这两类事件之间没有顺序依赖,关心的是"把相邻项聚成一批再发"以降低请求数——Policy 回调返回 BatchOptions{MaxItems, MaxWait},池会在"凑够 MaxItems 或等待 MaxWait"两个条件满足其一时调用一次 handler。这正是 NotifyBatchMaxItems=100 / NotifyBatchMaxWait=500ms 这类配置存在的意义;
  • msg.offline 用 ShardedMailbox<a href="https://link.gitcode.com/i/6fdb11e64937a24a8ec54124442b5292" target="_blank">T]([sharded_mailbox.go):离线分块以 ChannelID 为 key 提交(r.offline.Submit(ctx, msg.Message.ChannelID, msg)),同一渠道的离线分块落到同一分片、串行排空,从结构上避免了同一渠道的离线通知被不同 worker 交错发送。计划里 mailbox 的 BatchMaxItems: 1,即每次 handler 调用处理一个分块,批量语义完全由上游的 UID 分块承担。

一个值得注意的演进:计划中 offline mailbox 的 Shards 直接取 Workers,而当前落地的 internal/runtime/webhook/runtime.go 引入了 defaultOfflineShards = 256 常量和 offlineMailboxSizing 辅助函数,把分片数与每分片队列容量按 QueueSize 重新分配——说明实现阶段对"分片数=worker 数"这一简化做了修正。同时落地代码还加入了 runtimeState 状态机(New/Started/Stopping/Stopped)与 goruntimeregistry 归属注册,使 Start/Stop 对并发调用幂等,这些属于计划骨架之上的加固。

Start 的错误处理遵循"后建先关"原则:online 池创建失败时先 notify.Close,offline mailbox 创建失败时再依次关闭 online、notify。Stop 则用 errors.Join 合并三个队列的 Close(ctx) 结果,Close 语义(关闭准入 → 等待已受理工作排空至 ctx 到期)由 workqueue 原语保证。

6. 准入、克隆与结果分类

三个准入方法全部是非阻塞的,这是"webhook 永不拖累主链路"的关键。以 Notify 为例:

// Notify admits one committed message for msg.notify delivery.
func (r *Runtime) Notify(ctx context.Context, msg Message) {
	if r == nil || !r.enabled(EventMsgNotify) {
		return
	}
	err := r.notify.Submit(ctx, cloneMessage(msg))
	r.observeAdmission(EventMsgNotify, "webhook_notify", err, r.notify.QueueDepth(), r.notify.QueueCapacity())
}

Submit 是 workqueue 的非阻塞准入契约(见 pkg/workqueue/USAGE.md 的 Admission 一节):入队成功返回 nil;队列满返回 ErrFull;已关闭返回 ErrClosed;context 已取消则透传。运行时把这些结果映射为有界的结果标签:

  • workqueue.ErrFull → "full"
  • workqueue.ErrClosed → "closed"
  • context 错误 → "canceled" / "timeout"
  • nil → "accepted"
  • 发送侧另有 "ok"、"retry"、"retry_exhausted"、"encode_error"

完整的结果常量集中在 internal/runtime/webhook/runtime.go:accepted、ok、full、closed、canceled、timeout、error、retry、retry_exhausted、encode_error。全部是低基数、可枚举的字符串,可直接用于指标与日志。

准入前对入队项做防御性克隆,切断与主链路 buffer 的共享:

func cloneMessage(msg Message) Message {
	msg.Payload = append([]byte(nil), msg.Payload...)
	return msg
}

func cloneOfflineMessage(msg OfflineMessage) OfflineMessage {
	msg.Message = cloneMessage(msg.Message)
	msg.ToUIDs = append([]string(nil), msg.ToUIDs...)
	return msg
}

这与 workqueue 的既有约定一致:ShardedMailbox 的 MailboxBatch.Items 在 handler 返回后会被分片复用,任何想跨 handler 保留数据的一方都必须自行拷贝(USAGE.md 的 Batch Lifetime 一节)。webhook 运行时选择在准入侧克隆,比在消费侧克隆更保险——一旦入队,主链路就可以放心释放自己的 buffer。

FocusEvents 配置提供事件级过滤:enabled(event) 检查事件是否在 focus 集合内(空集合表示放行全部),过滤发生在准入之前,被过滤的事件连队列都不进。

7. 发送 handler 与有限重试

三类 batch handler 的形态一致:编码失败直接记 encode_error 并放弃(编码失败重试没有意义);编码成功则进入统一的有限重试循环:

func (r *Runtime) handleNotifyBatch(ctx context.Context, batch []Message) error {
	body, err := buildNotifyBody(batch)
	if err != nil {
		r.observeSend(EventMsgNotify, "encode_error", len(batch), 0, err, 0)
		return nil
	}
	r.sendWithRetry(ctx, EventMsgNotify, body, len(batch))
	return nil
}

func (r *Runtime) handleOfflineBatch(ctx context.Context, batch workqueue.MailboxBatch[OfflineMessage]) error {
	for _, item := range batch.Items {
		body, err := buildOfflineBody(item, r.opts.OfflineUIDBatchSize)
		if err != nil {
			r.observeSend(EventMsgOffline, "encode_error", len(item.ToUIDs), 0, err, 0)
			continue
		}
		r.sendWithRetry(ctx, EventMsgOffline, body, len(item.ToUIDs))
	}
	return nil
}

sendWithRetry 的实现刻意没有无界循环、也没有退避睡眠:

func (r *Runtime) sendWithRetry(ctx context.Context, event string, body []byte, items int) {
	attempts := r.opts.RetryMaxAttempts
	if attempts <= 0 {
		attempts = 1
	}
	for attempt := 1; attempt <= attempts; attempt++ {
		started := time.Now()
		err := r.sender.Send(ctx, SendRequest{Event: event, Body: body})
		if err == nil {
			r.observeSend(event, "ok", items, attempt, nil, time.Since(started))
			return
		}
		if attempt == attempts {
			r.observeSend(event, "retry_exhausted", items, attempt, err, time.Since(started))
			return
		}
		r.observeSend(event, "retry", items, attempt, err, time.Since(started))
	}
}

计划对此有明确注记:"除非测试表明紧密重试循环造成 CPU 压力,否则 v0 不引入重试睡眠;测量后可通过单个 RetryBackoff 字段添加有界退避。"这一"先测量再加参数"的克制与 workqueue 包"不拥有业务重试策略"的定位(USAGE.md Purpose 一节)一脉相承:重试次数、退避这类业务策略放在类型化运行时,而不是下沉到队列原语。

8. 配置体系:WebhookConfig 默认值、校验与 WK_WEBHOOK_* 键

8.1 结构体与默认值

计划 Task 1 在 app/config.go 的 Config 中、Delivery 之后加入 Webhook WebhookConfig 字段。落地实现位于 internal/app/config.go(当前结构还额外携带了独立启用的 BeforeSend 同步准入子配置)。核心字段与默认值:

type WebhookConfig struct {
	Enabled             bool
	HTTPAddr            string
	FocusEvents         []string
	QueueSize           int
	Workers             int
	NotifyBatchMaxItems int
	NotifyBatchMaxWait  time.Duration
	OnlineBatchMaxItems int
	OnlineBatchMaxWait  time.Duration
	OfflineUIDBatchSize int
	RequestTimeout      time.Duration
	RetryMaxAttempts    int
}
参数 默认值 语义
Enabled 配置了 HTTPAddr 即自动置 true 是否启动 webhook 运行时
QueueSize 1024 每个事件队列在内存中可驻留的事件上限
Workers 16 每个事件队列的并发 sender 调用上限
NotifyBatchMaxItems 100 单个 msg.notify 请求最多包含的消息数
NotifyBatchMaxWait 500ms msg.notify 收集相邻消息的最长等待
OnlineBatchMaxItems 512 单个 user.onlinestatus 请求最多包含的记录数
OnlineBatchMaxWait 2s user.onlinestatus 收集相邻记录的最长等待
OfflineUIDBatchSize 512 单个 msg.offline 请求最多包含的离线接收者 UID 数(同时是 gzip 压缩阈值)
RequestTimeout 5s 单次外发请求的超时
RetryMaxAttempts 3 单个已受理 webhook 批次的最大尝试次数,耗尽即丢弃

归一化流程是 NormalizeWebhookConfig = defaultWebhookConfig + validateWebhookConfig:

func NormalizeWebhookConfig(cfg WebhookConfig) (WebhookConfig, error) {
	cfg = defaultWebhookConfig(cfg)
	if err := validateWebhookConfig(cfg); err != nil {
		return WebhookConfig{}, err
	}
	return cfg, nil
}

默认值填充规则是"== 0 才填默认",因此可以显式配置 0(比如 RetryMaxAttempts = 0 表示不重试直接尝试一次——sendWithRetry 里 attempts <= 0 会被抬到 1)。校验规则(与 internal/app/config.go 一致):

  • 未启用时直接放行;
  • 启用但 HTTPAddr 为空 → webhook HTTPAddr is required when webhook is enabled(包装 ErrInvalidConfig);
  • 所有数值与时长参数必须 >= 0,负值逐条报错(如 webhook QueueSize must be >= 0)。

计划给出的失败测试表(落地后由 internal/app/config_test.go 中 WebhookConfig 相关测试覆盖)包含六个用例:enabled without endpoint、negative queue、negative workers、negative notify batch、negative online wait、negative retry,均断言 NormalizeWebhookConfig 必须返回错误。

8.2 WK_WEBHOOK_* 配置键

计划 Task 7 要求在 cmd 配置解析中加入支持键。当前仓库把这类映射收敛到 internal/config/schema.go,TOML 路径与环境变量一一对应:

环境变量 TOML 路径 类型
WK_WEBHOOK_HTTP_ADDR webhook.http_addr string(标记为敏感项)
WK_WEBHOOK_FOCUS_EVENTS webhook.focus_events string list
WK_WEBHOOK_QUEUE_SIZE webhook.queue_size int
WK_WEBHOOK_WORKERS webhook.workers int
WK_WEBHOOK_MSG_NOTIFY_BATCH_MAX_ITEMS webhook.msg_notify_batch_max_items int
WK_WEBHOOK_MSG_NOTIFY_BATCH_MAX_WAIT webhook.msg_notify_batch_max_wait duration
WK_WEBHOOK_ONLINE_STATUS_BATCH_MAX_ITEMS webhook.online_status_batch_max_items int
WK_WEBHOOK_ONLINE_STATUS_BATCH_MAX_WAIT webhook.online_status_batch_max_wait duration
WK_WEBHOOK_OFFLINE_UID_BATCH_SIZE webhook.offline_uid_batch_size int
WK_WEBHOOK_REQUEST_TIMEOUT webhook.request_timeout duration
WK_WEBHOOK_RETRY_MAX_ATTEMPTS webhook.retry_max_attempts int

解析规则(计划原文):WK_WEBHOOK_FOCUS_EVENTS 按 JSON 数组反序列化,失败时返回 parse WK_WEBHOOK_FOCUS_EVENTS: ... 包装错误;数值字段复用现有 parseInt 帮助函数,且 < 0 一律拒绝,错误风格与 delivery 配置一致。计划附带的完整示例配置注释(应写入示例配置文件)如下,可直接复制到运维文档:

# Enables node-local best-effort webhook delivery when an endpoint is configured.
# The runtime uses bounded in-memory queues; webhook failure never changes SENDACK or durable append success.
# WK_WEBHOOK_HTTP_ADDR=http://127.0.0.1:19090/webhook

# JSON array of event names to deliver. Empty means all supported events: msg.notify, msg.offline, user.onlinestatus.
# WK_WEBHOOK_FOCUS_EVENTS=["msg.notify","msg.offline","user.onlinestatus"]

# Maximum queued webhook events retained in memory per queue before new events are dropped.
# WK_WEBHOOK_QUEUE_SIZE=1024

# Maximum concurrent webhook sender workers per event queue.
# WK_WEBHOOK_WORKERS=16

# Maximum msg.notify messages sent in one webhook request.
# WK_WEBHOOK_MSG_NOTIFY_BATCH_MAX_ITEMS=100

# Maximum wait used to collect adjacent msg.notify messages into one request.
# WK_WEBHOOK_MSG_NOTIFY_BATCH_MAX_WAIT=500ms

# Maximum user.onlinestatus records sent in one webhook request.
# WK_WEBHOOK_ONLINE_STATUS_BATCH_MAX_ITEMS=512

# Maximum wait used to collect adjacent user.onlinestatus records into one request.
# WK_WEBHOOK_ONLINE_STATUS_BATCH_MAX_WAIT=2s

# Maximum offline recipient UIDs sent in one msg.offline request.
# WK_WEBHOOK_OFFLINE_UID_BATCH_SIZE=512

# Timeout for one outbound webhook request attempt.
# WK_WEBHOOK_REQUEST_TIMEOUT=5s

# Maximum attempts for one admitted webhook batch before it is dropped.
# WK_WEBHOOK_RETRY_MAX_ATTEMPTS=3

一个值得注意的行为细节:HTTPAddr 非空即隐式启用,这与 internal/app/webhook_config.go 中 WebhookConfigSnapshot 的只读快照视图(包含 SupportedEvents 与 RequiresRestart: true)共同表明:webhook 配置是启动期配置,修改后需要重启生效。

9. channelappend 批量离线 observer:大群场景的关键改造

计划 Task 4 解决的是一个性能陷阱:如果离线观测沿用"每个离线 UID 回调一次"的单接收者接口,一个 1000 人的群发一条消息就会产生 1000 次队列准入。改造方案是在 internal/runtime/channelappend 中新增批量接口而不删除旧接口:

// OfflineRecipientsEvent reports one durable message with a bounded offline UID slice.
type OfflineRecipientsEvent struct {
	Event CommittedEnvelope
	UIDs  []string
}

// OfflineRecipientsObserver receives offline recipient candidates in bounded batches.
type OfflineRecipientsObserver interface {
	ObserveOfflineRecipients(context.Context, OfflineRecipientsEvent)
}

delivery.go 的 observeOfflineRecipients 先用 online / seenOffline 两个集合完成"空 UID 跳过、在线跳过、离线去重",然后做接口断言分流:

if batchObserver, ok := observer.(OfflineRecipientsObserver); ok {
	batchObserver.ObserveOfflineRecipients(ctx, OfflineRecipientsEvent{
		Event: batch.Event,
		UIDs:  append([]string(nil), offlineUIDs...),
	})
	return
}
for _, uid := range offlineUIDs {
	observer.ObserveOfflineRecipient(ctx, OfflineRecipientEvent{Event: batch.Event, UID: uid})
}

回归测试直接量化了这个改进:1000 个全离线接收者 + 批量 observer 时,singleCalls == 0、batchCalls == 1、UID 总数 1000;而纯单接收者 observer 仍然按 UID 逐个回调(2 个离线 UID 收到 2 次调用)。这套"双接口 + 运行时断言"的兼容策略也被 FLOW 文档固化为规则:

Offline recipient observers may implement the batch observer interface. The recipient processor prefers the batch interface when available so large groups do not enqueue one external side-effect per UID.

该文档位于 internal/runtime/channelappend/FLOW.md,与计划"在 FLOW.md 中记录批量离线 observer 行为与 no-SENDACK-impact 规则"的要求一致。

10. presence 状态观测器:user.onlinestatus 的事件源

计划 Task 5 让 user.onlinestatus 有了类型化的事件源。internalv2/usecase/presence(当前树中为 internal/usecase/presence)新增:

type PresenceStatus string

const (
	PresenceOnline  PresenceStatus = "online"
	PresenceOffline PresenceStatus = "offline"
)

type PresenceStatusEvent struct {
	Kind              PresenceStatus
	Route             OwnerRoute
	DeviceOnlineCount int
	TotalOnlineCount  int
}

type PresenceObserver interface {
	ObservePresenceStatus(PresenceStatusEvent)
}

观测的发射时机被精确约束在本地路由状态真正变化之后:

  • Activate 中 MarkActive 成功后才发 PresenceOnline;
  • Deactivate 中 MarkClosingAndUnregister 成功后、且路由元数据仍可得时才发 PresenceOffline。

在线计数通过扩展本地注册表端口获得,避免昂贵的全局扫描:

// LocalSessionsByUID returns copies of local sessions currently indexed for uid.
LocalSessionsByUID(uid string) []LocalSession

presenceStatusEvent 辅助方法遍历这些 session 副本,只统计 RouteStateActive 的路由,分别得出该 UID 的总在线数与同 DeviceFlag 的设备在线数。计划中的两个测试(TestActivateObservesOnlineAfterLocalActivation、TestDeactivateObservesOfflineWithRouteMetadata)分别断言激活后恰好 1 条 online 事件且携带正确的 Route.UID/SessionID,以及停用后恰好 1 条 offline 事件且保留被移除路由的 DeviceFlag/SessionID 元数据。

11. app 层装配:适配器、fanout 组合与生命周期顺序

internalv2/app/webhook.go(当前为 internal/app/webhook.go)承担三个适配器与两套 fanout 组合。

11.1 三个适配器

type webhookNotifyEnqueuer struct {
	runtime webhookRuntime
}

type webhookOfflineObserver struct {
	runtime      webhookRuntime
	uidBatchSize int
}

type webhookPresenceObserver struct {
	runtime webhookRuntime
}
  • webhookNotifyEnqueuer 实现 channelappend 的 PersistAfterEnqueuer,把 committed envelope 转成 Message 提交 Notify(MessageSeq == 0 直接忽略);
  • webhookOfflineObserver 实现单/批量双 observer 接口,ObserveOfflineRecipients 按 uidBatchSize(0 时回退 512)把 UID 切片切块后逐块 Offline;
  • webhookPresenceObserver 把 PresenceStatusEvent 格式化为遗留状态字符串:
value := fmt.Sprintf("%s-%d-%s-%d-%d-%d",
	event.Route.UID,
	event.Route.DeviceFlag,
	string(event.Kind),
	event.Route.SessionID,
	event.DeviceOnlineCount,
	event.TotalOnlineCount,
)

webhookMessageFromEnvelope 在转换时对 Payload 做一次防御性拷贝,把 app 层的 buffer 与运行时隔离。

11.2 fanout 组合:webhook 与插件共存而非互斥

计划明确 webhook 必须组合(compose)而不是替换既有的插件钩子。两个组合器:

type persistAfterFanout []channelappend.PersistAfterEnqueuer

func (f persistAfterFanout) EnqueuePersistAfter(ctx context.Context, event channelappend.CommittedEnvelope) {
	for _, next := range f {
		if next != nil {
			next.EnqueuePersistAfter(ctx, event)
		}
	}
}

func composePersistAfterEnqueuers(items ...channelappend.PersistAfterEnqueuer) channelappend.PersistAfterEnqueuer {
	// 过滤 nil;0 个返回 nil;1 个直接返回原实现;多个返回 fanout
}

offlineObserverFanout 更精细:批量事件到来时,对实现了 OfflineRecipientsObserver 的成员走批量路径,对只有单接收者接口的成员逐 UID 降级回调——保证任何既有适配器都不需要改动即可共存。测试 TestWebhookPluginHooksAreComposed 验证组合后插件与 webhook 的 persist 计数器都恰好 +1,TestWebhookOfflineBatchAdapterChunksUIDs 验证 3 个 UID、批大小 2 时产生 [2, 1] 两个分块。

11.3 生命周期顺序

wiring 与 lifecycle 的改动保证了"生产者启动前消费者就绪、生产者排空后消费者再停":

  • New 中在 ensureOnlineRegistry() 之后、wirePresence() 之前调用 wireWebhook;wirePresence 传入 Observer: a.webhookPresence;wireChannelAppend 中 opts.PersistAfterEnqueuer = composePersistAfterEnqueuers(a.pluginPersistAfter, a.webhookNotify),接收者处理器传入 composeOfflineRecipientObservers(a.pluginReceive, a.webhookOffline);
  • 启动顺序:webhook worker 在 channelappend 之前启动(先开队列再接收事件),启动失败则 rollbackStarted 反向回滚并 errors.Join 错误;
  • 停止顺序:webhook 在 channelappend 与 delivery worker 之后停止,等待已受理的 webhook 工作排空。

这个顺序原则在计划 Task 8 的 FLOW 更新中再次强调:"start webhook queues before channelappend starts producing post-commit effects"。当前仓库 internal/app/FLOW.md 中保留了 webhook 运行时在装配图中的位置说明。

12. 验证策略:TDD 流程、竞态测试与准入基准

计划把 9 个 Task 全部写成"先写失败测试 → 跑测试确认编译失败 → 实现 → 跑测试通过"的 TDD 步骤,每个 Task 都给出了精确的 go test 命令(统一带 GOWORK=off 与 -count=1)。核心验证矩阵:

验证目标 测试 命令(计划原文)
配置默认值/非法值 TestWebhookConfigDefaultsWhenEndpointConfigured、TestWebhookConfigRejectsInvalidValues GOWORK=off go test ./internalv2/app -run 'WebhookConfig' -count=1
JSON 映射与压缩 TestBuildNotifyBodyMapsCommittedMessages、TestBuildOfflineBodyChunksAndCompressesUIDs GOWORK=off go test ./internalv2/runtime/webhook -run 'TestBuild' -count=1
HTTP 成功/失败分类 TestHTTPSenderPostsEventQueryAndBody、TestHTTPSenderReturnsErrorOnNonOK 同上 -run 'TestHTTPSender'
批量/队列满/重试耗尽 TestRuntimeBatchesNotifyMessages、TestRuntimeDropsOnFullQueueWithoutBlocking、TestRuntimeRetriesThenDrops GOWORK=off go test ./internalv2/runtime/webhook -run 'TestRuntime' -count=1
大群批量 observer TestRecipientProcessorUsesBatchOfflineObserverWhenAvailable `GOWORK=off go test ./internalv2/runtime/channelappend -run 'OfflineObserver
presence 观测 TestActivateObservesOnline*、TestDeactivateObservesOffline* GOWORK=off go test ./internalv2/usecase/presence -count=1
竞态安全 — GOWORK=off go test -race -count=1 ./internalv2/runtime/webhook ./internalv2/runtime/channelappend ./internalv2/usecase/presence

其中两个队列压力测试值得单独说明:

  • TestRuntimeDropsOnFullQueueWithoutBlocking 用 blockingSender 占住唯一 worker,配合 QueueSize: 1 的 notify 池连续 Notify 三条消息,断言 observer 记录到 ("msg.notify", "full")——直接验证"队列满时准入立即失败且不阻塞调用方";
  • TestRuntimeRetriesThenDrops 用 failingSender 配 RetryMaxAttempts: 2,断言 sender 恰好被调用 2 次且最终观测到 retry_exhausted——把"有限重试"钉死在确切次数上。

Task 9 还要求新增准入微基准 internal/runtime/webhook/benchmark_test.go:BenchmarkRuntimeNotifyAdmission 以 QueueSize: 65536、Workers: 16、NotifyBatchMaxItems: 100 的运行时连续 Notify,b.ReportAllocs() 监控分配,执行命令为:

GOWORK=off go test ./internalv2/runtime/webhook -run '^$' -bench 'BenchmarkRuntimeNotifyAdmission' -benchtime=500ms -count=5 -benchmem

验收标准是"无无界分配增长或阻塞",并要求把结果记入最终实现报告。最后一步 git diff --check + cmd 全量配置测试收口。

13. 与当前仓库实现的对照:计划落地后的演进

从源码结构看,该计划的最终落地位置是 internal/ 而非计划文本中的 internalv2/(当前仓库树中不存在 internalv2 目录,internalv2 命名应属于当时的迁移上下文),且实现在计划骨架之上有多处可考的演进:

  1. Message DTO 扩展:internal/runtime/webhook/types.go 的 Message 相比计划增加了 Setting、Topic、Expire、SourceID 字段,补齐遗留 MessageResp 的完整形状;
  2. offline 分片调参:引入 defaultOfflineShards = 256 与 offlineMailboxSizing,不再简单以 Workers 充当分片数;
  3. 运行时状态机:Start/Stop 增加 runtimeState 与 stopCh,支持并发幂等与"等待正在进行的停止";
  4. goroutine 归属:三个队列构造时传入 goruntimeregistry 的 TaskWebhookNotify/TaskWebhookOnline/TaskWebhookOffline 任务归属,纳入仓库统一的协程注册体系;
  5. 参数校验收紧:落地 New 中 RequestTimeout <= 0 直接视为 ErrInvalidConfig(计划版本允许 0),批量上限 0 时回退为 1;
  6. 配置面扩展:internal/config/schema.go 在 webhook 组内还追加了 WK_WEBHOOK_BEFORE_SEND_* 系列键,对应同步"发送前准入"webhook——这是晚于本计划的独立能力(见 internal/app/before_send_webhook.go 与 internal/app/config.go 中的 BeforeSend BeforeSendWebhookConfig 字段),与本文的异步投递运行时相互独立;
  7. 端到端验证:仓库在 test/e2e/message/webhook/ 下维护了针对 msg.notify 等事件的 e2e 测试(webhook_test.go、go_example_test.go),并在 docs-site/content/docs/guide/integration/webhooks.mdx 中面向外部接收方文档化了事件契约。

14. 设计要点回顾与限制

把整个方案浓缩为五条可复用的工程规则:

  1. 慢外部依赖一律走"有界准入 + 丢弃观测":Submit 非阻塞、ErrFull 即丢,主链路(SENDACK、持久化 append、owner 投递)的时延与正确性不受 webhook 影响;
  2. 队列原语与业务策略分层:pkg/workqueue 只负责有界队列/worker 机制,重试次数、压缩阈值、事件过滤都留在类型化运行时,符合 pkg/workqueue/USAGE.md "Migration Pattern" 一节"用类型化适配器包住泛型原语"的推荐模式;
  3. 批量优先的旁路扇出:大群场景下"每 UID 一次外部副作用"被明确禁止(FLOW 文档 Performance Rules:"Do not enqueue one webhook item per UID for large groups"),批量接口用"接口断言 + 单接口降级"保证向后兼容;
  4. 观测标签低基数化:结果集是封闭枚举(accepted/full/closed/canceled/timeout/ok/retry/retry_exhausted/encode_error),观测中禁止出现 UID、channel id、session id、端点地址;
  5. 生命周期"先开后关":webhook worker 早于 channelappend 启动、晚于其停止,配合 Close 的排空语义保证停机时不丢"已受理"的工作。

明确不在范围内的边界同样需要向读者交代清楚:本运行时不提供持久化与崩溃重放保证——进程重启后,未发出去的 webhook 批次即永久丢失,这是以"绝不拖累主链路"为目标的显式取舍;gRPC 传输、重试退避参数(RetryBackoff)都留待后续计划,且前提是先有测量数据支撑。

15. 延伸阅读

登录后查看全文
WuKongIM