WuKongIM MQTT 接收授权(Receive Authority)实现解析:以成员快照与 incarnation 为核心的订阅准入契约

原创2026-10-14 14:03:551,395 阅读
文章标签:即时通讯后端

WuKongIM MQTT 接收授权(Receive Authority)实现解析:以成员快照与 incarnation 为核心的订阅准入契约

导读:本文以 docs/specs/mqtt-receive-authority.md 为主线,系统拆解 WuKongIM 在生产环境中如何通过 RPC 106 read kind 19(MQTTReadMembership)与 ReceiveAuthorization 端口,建立"以实时成员关系为准、以 incarnation 版本为证"的 MQTT 接收授权策略。读者将掌握:授权决策的排序点(ordering point)与陈旧意图拒绝机制、三种点读构成的成员快照模型、不可用/畸形证据的 fail-closed 原则、群组与自收件箱(self inbox)的差异化判定,以及实现前发现并修复的 idle-anchor 提交前沿传播回归。文中全部结论均可在当前仓库源码与测试中交叉验证。

一、背景:为什么接收权限不能依赖 SEND 权限或异步目录投影

MQTT 订阅(尤其是群组消息接收)在生产环境下必须回答一个核心问题:某个 UID 当前是否有权接收某频道(channel)的消息? 这个问题看似简单,但分布式多节点部署使其变得棘手——回答它依赖的成员数据可能来自过期的副本缓存、滞后的 UID 目录投影,甚至是不完整的点读。

WuKongIM 的接收策略给出了明确约定(见 mqtt-receive-authority.md 的 "Contract and ordering" 一节):

  • 生产环境的接收判定需要一份新鲜的、自洽的 channel/membership 视图;
  • 它不是 SEND 权限,也不是异步 UID 目录投影;
  • 判定由 RPC 106 read kind 19(MQTTReadMembership)承载,走现有 foreground-gated Node 与当前 Slot 路由。

从源码看,这一契约被明确落在两个层次:

  1. 存储层(读模型):pkg/db/meta/mqtt_membership.go 定义了 SubscriberKey 与 MQTTMembershipView,一次读取恰好覆盖 channel、member、subscriber allocation 三个点读;
  2. 用例层(判定端口):internal/usecase/mqttsession/receive_authorization.go 实现 SubscriptionAuthorizer 接口,把"读到的证据"翻译成"允许/拒绝/无法判定"。

核心接口定义如下(receive_authorization.go):

// ReceiveMetadata must read a coherent snapshot at current Slot authority after
// a fresh apply barrier. Replica caches and separate channel/member reads cannot
// implement this port; production composition uses the foreground-gated Node.
type ReceiveMetadata interface {
	ReadMQTT(context.Context, meta.MQTTRead) (meta.MQTTReadResult, error)
}

type ReceiveAuthorizationOptions struct {
	Store ReceiveMetadata
	// Timeout bounds an authority call; default five seconds, maximum thirty.
	// The dependency must obey cancellation; no detached worker is created.
	Timeout time.Duration
}

// ReceiveAuthorization returns the current ordinary membership incarnation.
// It owns no cached grants, membership mutations or SEND privilege decisions.
type ReceiveAuthorization struct{ options ReceiveAuthorizationOptions }

var _ SubscriptionAuthorizer = (*ReceiveAuthorization)(nil)

注意 var _ SubscriptionAuthorizer 的编译期断言:ReceiveAuthorization 必须实现 subscription_types.go 中的接口——

// SubscriptionAuthorizer checks current receive permission, never SEND privilege
// or membership mutation. Version identifies the permission incarnation, not a
// cached grant. Zero is reserved for authorities with no versioned membership.
type SubscriptionAuthorizer interface {
	AuthorizeSubscription(context.Context, string, SubscriptionRequest) (uint64, error)
}

该接口返回的 uint64 版本号不是缓存授权标记,而是权限 incarnation(成员化身版本),这是整篇契约的关键。

二、RPC 106 read kind 19:一次只读、三处点读、一个快照

2.1 读类型与路由

在 pkg/db/meta/mqtt_read.go 中,MQTTReadKind 定义了 20+ 种封闭的元数据读操作,其中 kind 19 即 MQTTReadMembership:

// MQTTReadMembership pins channel flags, ordinary membership and its allocator.
MQTTReadMembership

该读操作携带 MembershipKey(SubscriberKey,由 ChannelID、ChannelType、UID 三元组组成),并由 pkg/slot/proxy/mqtt_route.go 的 mqttReadRoutingKey 决定路由:

case metadb.MQTTReadMembership:
	return q.MembershipKey.ChannelID, nil

也就是说,成员查询按 ChannelID 路由到对应的 hash Slot,与 Session(按 namespace/clientID 路由)相互独立,符合文档中"routes by channel ID"的描述。

2.2 三处点读构成一个快照

MQTTMembershipView(mqtt_membership.go)恰好持有三个值:

type MQTTMembershipView struct {
	Key     SubscriberKey `json:"key"`
	Channel *Channel      `json:"channel,omitempty"`
	Member  *Subscriber   `json:"member,omitempty"`
	// Sequence witnesses the member's incarnation, including the legacy floor 1.
	Sequence uint64 `json:"sequence"`
}
  • Channel:频道行(含 Disband 解散标志等);
  • Member:成员行(含 Incarnation);
  • Sequence:该 hash Slot 的 subscriber 分配器高水位(high water)。

实现位于 readMQTTMembership,关键点在于绕过 live channel cache,三处值全部来自 readMQTTState 持有的同一份 pinned snapshot:

// readMQTTMembership bypasses the live channel cache: all three values must
// belong to readMQTTState's pinned snapshot, including authoritative absences.
func (s *Shard) readMQTTMembership(ctx context.Context, k SubscriberKey) (*MQTTMembershipView, error) {
	v := &MQTTMembershipView{Key: k}
	c, found, err := channelTable.Get(ctx, s, KeyParts{String(k.ChannelID), Int64Ordered(k.ChannelType)})
	...
	m, found, err := s.GetSubscriber(ctx, k.ChannelID, k.ChannelType, k.UID)
	...
	v.Sequence, err = s.SubscriberSequence(ctx)
	...
}

这正对应文档中的三句断言:

  • "Exactly three point reads cover the channel, member and subscriber allocation sequence";
  • "The channel cache must not override the pinned snapshot";
  • 缺失行只有在完整且结构良好的回复中才构成权威性缺失(authoritative absence)。

2.3 快照一致性校验

ValidateMQTTMembershipView 对视图做确定性校验:

func ValidateMQTTMembershipView(k SubscriberKey, v *MQTTMembershipView) error {
	if validateMQTTMembershipKey(k) != nil || v == nil || v.Key != k || v.Sequence == 0 {
		return dberrors.ErrCorruptValue
	}
	if c := v.Channel; c != nil && (c.ChannelID != k.ChannelID || c.ChannelType != k.ChannelType || validateChannel(*c) != nil) {
		return dberrors.ErrCorruptValue
	}
	if m := v.Member; m != nil && (m.ChannelID != k.ChannelID || m.ChannelType != k.ChannelType || m.UID != k.UID || m.Incarnation == 0 || m.Incarnation > v.Sequence) {
		return dberrors.ErrCorruptValue
	}
	return nil
}

三个不变式值得注意:

  1. 视图的 Key 必须与请求键完全一致(防止跨键串读);
  2. Channel 与 Member 必须属于同一个 key(频道/成员身份必须匹配);
  3. 成员的 Incarnation 必须大于 0 且不大于 Sequence——这正对应文档中 "A present member must carry a positive incarnation at or below that water"。

2.4 权威性:ReadIndex/apply barrier 与 pinned snapshot

存储层只负责"在一份快照上做点读",真正建立"当前权威"的是 Slot proxy 层。在 pkg/slot/proxy/mqtt_read.go 的 readMQTTLocal 中,完整链路为:

  1. 校验 Format == 1 与 ValidateMQTTRead(q);
  2. 校验路由匹配(mqttRouteMatches),防止路由表版本变化后仍用旧 Slot 服务;
  3. 获取当前 Slot leader,非本地 leader 返回 rpcStatusNotLeader;
  4. 建立 fresh apply barrier(ReadSlotBarrier,无该端口的嵌入实现则提交本地 noop);
  5. 调用 s.db.ReadMQTTState(ctx, req.HashSlot, req.Query) 做 pinned snapshot 读取;
  6. 读完后再次校验 leader 未变、路由未变、路由表版本一致(ErrReadStaleRoute fail-closed)。

这一步正是文档中 "fresh local ReadIndex/apply barrier and one pinned metadata snapshot" 的源码实现。而 ReadMQTTState 在引擎上 NewSnapshot() 并在读完后 snapshot.Close(),确保"快照不能逃逸本次调用"。

2.5 线格式兼容性与老节点拒绝

文档要求:"New query/result fields are omitted on older kinds; old peers reject kind 19, and no fallback to separate reads, caches or convenient replicas is allowed."

源码中的印证:

  • MQTTReadCursor 的字段带 omitzero/omitempty 标签,明确注释 "Session is absent on older read kinds, preserving their JSON"、"Directory is omitted from older kinds to preserve their wire representation"(mqtt_read.go);
  • ValidateMQTTRead 对无关字段拒绝而非忽略:want := MQTTRead{Kind: q.Kind},随后逐字段比对,任何多余字段都会导致 dberrors.ErrInvalidArgument(mqtt_read.go);
  • 解码回复时 decodeMQTTReadReply 强制 r.Format != 1 || r.SlotID != req.SlotID || r.HashSlot != req.HashSlot || r.Query != req.Query 即报 ErrCorruptValue(mqtt_read.go),且 validateMQTTReadShape 只允许 kind 19 携带 Membership 字段,其余字段一律判坏(mqtt_read.go)。

这套设计确保:老版本节点不认识 kind 19 时直接拒绝,而不会偷偷降级到"分别读 channel、分别读 member"的不一致路径。

三、ReceiveAuthorization 判定逻辑:群组、自收件箱与证据边界

3.1 主流程(AuthorizeSubscription)

核心实现在 receive_authorization.go:

func (a *ReceiveAuthorization) AuthorizeSubscription(ctx context.Context, uid string, r SubscriptionRequest) (version uint64, err error) {
	defer func() {
		if recover() != nil {
			version, err = 0, ErrSubscriptionCallback
		}
	}()
	if a == nil || ctx == nil || !contract.ValidIdentity(uid, 1024) || !validSubscriptionRequest(r) {
		return 0, ErrInvalid
	}
	if err = ctx.Err(); err != nil {
		return 0, err
	}
	if r.TargetKind == meta.MQTTSubscriptionUserInbox {
		if r.TargetID != uid {
			return 0, ErrSubscriptionDenied
		}
		return 0, nil
	}
	ctx, cancel := context.WithTimeout(ctx, a.options.Timeout)
	defer cancel()
	key := meta.SubscriberKey{ChannelID: r.TargetID, ChannelType: 2, UID: uid}
	result, err := a.options.Store.ReadMQTT(ctx, meta.MQTTRead{Kind: meta.MQTTReadMembership, MembershipKey: key})
	if canceled := ctx.Err(); canceled != nil {
		return 0, canceled
	}
	if err != nil {
		return 0, err
	}
	if !result.Done || result.After != (meta.MQTTReadCursor{}) || result.Session != nil || result.Accounting != nil {
		return 0, ErrEvidence
	}
	if len(result.Sessions)+len(result.Subscriptions)+len(result.DeliveryCursors)+len(result.Inflight)+len(result.Bindings)+len(result.Wills)+len(result.SourceOwners) != 0 || meta.ValidateMQTTMembershipView(key, result.Membership) != nil {
		return 0, ErrEvidence
	}
	view := result.Membership
	if view.Channel == nil || view.Channel.Disband != 0 || view.Member == nil {
		return 0, ErrSubscriptionDenied
	}
	return view.Member.Incarnation, nil
}

逐条对应文档契约:

文档要求 源码实现
群组目标使用 type 2 key := meta.SubscriberKey{ChannelID: r.TargetID, ChannelType: 2, UID: uid}
要求已存在且未解散的频道 `view.Channel == nil
要求真实 UID 成员,返回 incarnation view.Member == nil → 拒绝;否则返回 view.Member.Incarnation
Ban/SendBan、AllowStranger 不能替代成员 判定只看 Channel 存在性 + Member 存在性,不看任何 SEND 标志(测试 receive_authorization_test.go 中 checkDenied() 在 AllowStranger:1, Large:1, Ban:1, SendBan:1 频道上仍然拒绝)
发送静默不剥夺接收 TestReceiveAuthorizationUsesNativeMembershipIncarnation 中 require.Greater(t, first.AuthorizationVersion, uint64(1), "sending mute does not remove receiving")
自收件箱是"不可变 admitted UID 绑定(version 0)" TargetKind == MQTTSubscriptionUserInbox 分支:TargetID != uid 拒绝,否则返回 (0, nil),version 固定为 0,且不发起任何元数据读取
校验有界输入 contract.ValidIdentity(uid, 1024)、validSubscriptionRequest(subscriptions.go:topic 不含 +#、非 $share/、QoS ≤ 2、RetainHandling ≤ 2、SubscriptionIdentifier ≤ 268435455)
遵守取消与有界超时 入参先查 ctx.Err();内部 context.WithTimeout(ctx, a.options.Timeout),超时默认 5 秒、最大 30 秒(NewReceiveAuthorization 校验)
回调 panic 被屏蔽 defer func() { recover() } → ErrSubscriptionCallback
不可用/畸形证据不构成确定性拒绝 错误原样返回(如 unavailable),畸形结果返回 ErrEvidence,而不是"拒绝"——调用方会把不可用当作债务(debt)保留,而非撤销

3.2 成员 incarnation 与 allocator 高水位

成员行的 Incarnation 定义在 pkg/db/meta/compat.go:

// Subscriber stores one durable channel subscriber.
type Subscriber struct {
	// Incarnation changes only on a new join; 1 identifies legacy empty rows.
	Incarnation uint64
	ChannelID   string
	ChannelType int64
	UID         string
}
  • 每次新加入(rejoin)都会产生新的 incarnation;
  • incarnation 由 hash Slot 级的 allocator(SubscriberSequence,见 pkg/db/meta/subscriber_incarnation.go)持续单调分配,作为"分配器高水位";
  • ValidateMQTTMembershipView 强制 m.Incarnation > 0 && m.Incarnation <= v.Sequence,因此畸形或回退(regressed)的分配器状态无法铸造一个授权(文档失败清单第 3 条)。

3.3 排序点与陈旧意图拒绝

文档核心句:"A successful fresh read is the authorization decision's ordering point. A removal committed before that read must deny. A remove/rejoin changes the incarnation, so subscription/recovery/accounting/sender comparisons reject old intent even if membership is present again."

其工程含义:授权版本(AuthorizationVersion)被持久化进订阅行、投递游标、源绑定中,任何后续环节拿"当前读到的 incarnation"与"持久化意图中的 AuthorizationVersion"比较,不一致即 ErrSubscriptionRevoked。

证据链:

  1. MQTTSubscription.AuthorizationVersion 字段(mqtt_subscription.go),注释明确 "identifies the captured permission incarnation";
  2. Accounting 的 authorize 方法(accounting.go):
func (a *Accounting) authorize(ctx context.Context, uid string, sub meta.MQTTSubscription) error {
	if err := ctx.Err(); err != nil {
		return err
	}
	version, err := a.options.Authorization.AuthorizeSubscription(ctx, uid, subscriptionRequestFromRow(sub))
	if err != nil {
		return err
	}
	if err = ctx.Err(); err != nil {
		return err
	}
	if version != sub.AuthorizationVersion {
		return ErrSubscriptionRevoked
	}
	return nil
}
  1. Sender 的最终检查:Sender 在入队前调用 authorizeEnqueue(sender.go),并在 sender.go 中把 ErrSubscriptionDenied/ErrSubscriptionRevoked 转为 MQTTSessionRevoked 精确结束 Session:
if errors.Is(err, ErrSubscriptionDenied) || errors.Is(err, ErrSubscriptionRevoked) {
	s.closed, s.ending = true, true
	s.endReason = meta.MQTTSessionRevoked
}

这对应文档:"Definite denial or changed incarnation ends the exact Session through the existing sender path." 同时,"previously authorized or queued data cannot be recalled"——所以旧的已投递内容不会被追回,Session 结束时会保留未完成债务(见测试中对 PendingMessages、OutboundInflight、DeliveryCursors 的保留断言)。

四、失败清单(Failure Inventory)逐条解读

文档在实现前罗列了 8 类必须防住的失败模式,这里是每条对应的源码/测试证据:

  1. 群组缺失/移除/解散拒绝;空/开放群组或 SEND 权限永不给成员资格;发送静默不剥夺接收——AuthorizeSubscription 只认 Channel != nil && Disband == 0 && Member != nil;receive_authorization_test.go 在同时带 Ban:1, SendBan:1, AllowStranger:1 的频道上验证拒绝。

  2. 重复加入与无关成员变更保留授权;移除/重加入与频道重建使旧授权失效——incarnation 机制天然满足:无关变更不触碰该成员的 incarnation,版本不变;remove/rejoin 改变 incarnation,版本比较失败。测试同文件覆盖 stable 相等、ErrSubscriptionRevoked、recreated > fresh。

  3. channel 与 member 必须属于同一快照,尽管有 live cache 刷新;畸形/回退分配器状态不能铸造授权——readMQTTMembership 绕过缓存走 pinned snapshot;ValidateMQTTMembershipView 的 Incarnation > Sequence 检查。测试用例 sequence_regressed、wrong_uid、wrong_channel 均期望 ErrEvidence(receive_authorization_test.go)。

  4. 本地与远端读取都需要 fresh apply barrier;陈旧 origin 副本、路由变化、错误 Slot/key、不完整回复、不可用权威都 fail-closed 而不声明确定性撤销——readMQTTLocal 的前后双重复核路由/leader + ReadSlotBarrier;返回 ErrReadStaleRoute、ErrCorruptValue 或依赖错误,均不落入"拒绝"分支。

  5. Kind 19 独占且有界;旧版 read JSON 保持字节兼容;畸形/多余字段与外来 channel/member 身份校验失败——ValidateMQTTRead 严格白名单比对;validateMQTTReadShape 限定字段集与数量上限(count > max(1, q.Limit));请求体上限 64 KiB、回复体上限 8 MiB(mqtt_read.go)。

  6. 自收件箱限于 admitted UID;无效输入与取消不产生权威调用;panic 与超时不能逃逸或变成拒绝——TestReceiveAuthorizationBoundsSelfInboxAndCancellation 验证 calls == 0(未发起元数据调用)、context.Canceled 原样返回、非法选项 ErrInvalid、panic 被转成 ErrSubscriptionCallback 且错误信息不含内部 token("private token" 不泄漏)。

  7. 实际 Slot 成员变更必须驱动既有订阅与发送检查:重加入者不能重发旧交换或恢复旧 backlog;新 Session/订阅意图可获取新 incarnation——集成测试 mqtt_receive_authorization_integration_test.go:移除成员 → 重加入 → 新连接 Resume 后,stream.Turn 报 ErrSubscriptionRevoked 且 turn.Ended,Session 状态 MQTTSessionEnded、原因 MQTTSessionRevoked,随后全新连接获得更高 generation 并成功重新订阅。

  8. 单节点与三节点集成必须使用生产授权、保留原生订阅/移除行为并保留精确结束债务——即集成测试的 mqtt_receive_authority_evidence 工件断言:"same_version_rejoin=true resume_before_revocation_check=true old_exchange_and_backlog_denied=true exact_session_ended=true ending_debt_retained=true fresh_lifetime_and_subscription=true"(mqtt_receive_authorization_integration_test.go)。

五、Scope 边界:本特性完成什么、不做什么

文档明确列出本特性不覆盖的范围("Scope" 一节):

  • 产品级监听器(product listener);
  • 公平投递调度器(fair delivery scheduler);
  • 无人值守的撤销发现(unattended revocation discovery);
  • 收件箱投影(inbox projection);
  • Will 执行(Will execution);
  • 进程级功能验收。

这些是独立的后续工作项。本特性只完成"生产接收策略及其权威端口"。

六、实现前发现的 idle-anchor 传播回归与修复

这是文档中最有价值的工程发现之一:三节点接收测试复现了第二个消费者的永久性准备失败("Discovered idle-anchor propagation regression")。

6.1 复现场景

  • Leader 在 HW 4 处持有 anchor 4,而一个 ISR 副本的 LEO 为 4、checkpoint/HW 为 3;
  • 规划(planning)返回了一个"仅维护性尾部"的有效计划,于是业务 append 与另一个副本都没有传播已提交前沿(committed frontier);
  • 恢复流程正确拒绝了该副本的未提交日志(journal),单纯重试也无法修复。

也就是说:一个"合法的 anchored planning 读取"可能因 idle(空闲)而永远不推进副本的提交水位,从而让依赖该前沿的恢复流程永久卡死。

6.2 修复要点

文档要求("Before repair, extend the failure inventory"):

  • leader 的合法 anchored planning 读取必须请求有界的原生 committed-frontier 传播,包括 idle 与 write-fenced 计划;
  • 请求携带精确安装的权威信息,绝不用调用方提供的 HW;
  • 缺失能力、取消、刷新失败、放置变化都必须 withhold 计划;
  • 畸形/无 anchor 计划不得调度;转发只在 leader 调度;
  • 一条 hint 即可证明无副本恢复;该机制也能恢复"观察者在发出 hint 前停止"的提交;
  • 无需线格式或持久格式变更。

6.3 源码印证

planMQTTReplay 中,当计划返回 p.HasAnchor 且当前节点是 leader 时:

if p.HasAnchor && m.Leader == s.localNode {
	if s.replicaCommitRefresh == nil {
		return empty, ch.ErrInvalidConfig
	}
	// An idle anchor can be durable on a voter whose committed checkpoint
	// still lags. Re-drive native propagation even after lost commit replies
	// or a restart, without treating this captured plan's HW as authority.
	// This bounded hint also works under an unchanged write fence; recovery
	// must subsequently verify each replica's own committed journal/content.
	if err = s.replicaCommitRefresh.RequestCommittedReplicaRefresh(ctx, mqttReplicaAuthority(m)); err != nil {
		return empty, err
	}
	if err = ctx.Err(); err != nil {
		return empty, err
	}
	if err = s.recheckMQTTRepairAuthority(ctx, authorityRequest, m); err != nil {
		return empty, err
	}
}

注意注释中的两个关键词:

  • "without treating this captured plan's HW as authority"——即文档要求的"请求携带精确安装的权威,而非调用方提供的 HW";
  • 刷新后重新检查权威(recheckMQTTRepairAuthority),对应"缺失能力、取消、刷新失败与放置变化必须 withhold 计划"。

计划本身仍是调度证据而非副本就绪证明,最终每个副本的已提交日志/内容仍需恢复流程自行验证("recovery must subsequently verify each replica's own committed journal/content")。

对应测试位于 pkg/cluster/channels/mqtt_plan_test.go,覆盖 idle、fenced、missing、failed、canceled、changed、malformed、no_anchor 等模式。

七、验证记录:本地与三节点集成的可复现证据

文档 "Validation and remaining scope" 记录了 2026-09-24 的完整验证,这些命令可在仓库中直接复现:

  1. 元数据、Slot proxy 与 usecase 单测(全部 -race):
GOWORK=off go test -race -p 2 ./pkg/db/meta ./pkg/slot/proxy ./internal/usecase/mqttsession -count=1

(文档记录分别通过:28.370 s、14.716 s、52.306 s)

  1. channel 层 idle/fenced 刷新回归:
GOWORK=off go test -race -p 2 ./pkg/cluster/channels -count=1

(7.813 s,覆盖 idle/fenced 刷新、拒绝畸形证据、取消、不可用刷新、放置变化)

  1. 接收授权与协议聚焦用例:
GOWORK=off go test -race -p 2 ./pkg/cluster ./internal/app ./internal/usecase/mqttsession -run 'Test(ReceiveAuthorization|MQTT.*NodeForegroundGates|MQTTProtocol)' -count=1
  1. 三节点集成(非 race):
GOWORK=off go test -tags=integration -p 2 ./internal/app -run 'TestMQTT(SubscriptionIntentSingleNodeCluster|GroupSourcePreparationThreeNodeRecovery)$' -count=1 -timeout=4m -v

(23.328 s;同一组用例加 -race 为 25.689 s,无数据竞争报告)

文档还提到两点工程纪律:

  • 测试先行:新元数据、Slot 与 usecase 测试在实现前编写,初始编译失败记录在 /tmp/mqtt-receive-red.log 与 /tmp/mqtt-receive-app-red.log;
  • 格式不变:本特性不引入新表、新持久格式、新进程 goroutine 或全组扫描;RPC 106 kind 19 要求节点版本匹配(matched nodes)。

八、生产组合与后续开放项

在 internal/app/mqtt_product.go 中,newMQTTReceiveAuthorization(node) 把同一份授权端口注入到群组投影、收件箱投影、消费者、订阅编排与投递协调器:

authorization, err := newMQTTReceiveAuthorization(node)
...
groups, err := newMQTTGroupProjection(node, owners, authorization, a.messageIDs)
...
inbox, err := newMQTTInboxProjection(node, owners, authorization, a.messageIDs)
...
m.consumers, err = a.wireMQTTConsumers(node, authorization, sessions, groups, inbox)
...
subscriptions, err := sessioncase.NewSubscriptions(sessioncase.SubscriptionOptions{Store: node, Owners: owners, Authorization: authorization, ...})
...
coordinator, err := newMQTTDeliveryCoordinator(node, owners, authorization, sessions, c.MaxSubscriptions)

组装函数 newMQTTReceiveAuthorization 直接把 foreground-gated cluster.Node 作为 ReceiveMetadata 存储端口,并复用默认 5 秒超时。这意味着授权、记账、恢复、发送终检共享同一份"当前 Slot 权威"视图,但都不缓存授权——每次决策都重新读取新鲜快照。

文档明确列出的后续开放项("remaining scope"):公平投递调度、收件箱未来源准入(inbox future-source admission)、自动结束/清理发现、Will 执行、restore/不可用 owner fencing、完整 MQTT 离线转移。生产接收策略本身已由本文所述契约闭环。

结语

WuKongIM 的 MQTT 接收授权是一个"少即是多"的设计:不做 SEND 权限的复用、不做异步投影的猜测、不做缓存授权的承诺,只做一件事——在每次决策的排序点上,从当前 Slot 权威拿一份 fresh、完整、自洽的 channel/member/incarnation 快照,并让该 incarnation 贯穿订阅、恢复、记账与发送终检的整个生命周期。配合实现前补齐的 idle-anchor 传播回归,它证明了"权威读"不能只保证读本身的一致性,还必须保证让权威状态真正推进。这正是分布式消息系统中"权限即状态版本"这一原则的完整落地示范。

登录后查看全文
WuKongIM