carddispatch

package
v1.24.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package carddispatch is the sole supported boundary for trusted in-process InteractiveCard origination. It owns producer capability, authorization, envelope construction, final bytes, concurrency, and transport semantics.

Index

Constants

View Source
const MaxPersistedFrameBytes = maxContentEditBytes

MaxPersistedFrameBytes 是 maxContentEditBytes 的导出别名,供发送侧做同口径预检 (modules/bot_api 的模板分支)。发送侧不写 content_edit,但一张发出后编辑不了的卡 等于发出即报废,所以它需要拿到同一个数而不是自己抄一份 —— 抄的那份会漂移。

Variables

View Source
var (
	ErrTargetDenied             = errors.New("carddispatch: target denied")
	ErrRegistryAlreadyInstalled = errors.New("carddispatch: registry already installed")
)
View Source
var (
	ErrCardMutationInvalid   = errors.New("carddispatch: invalid card mutation")
	ErrCardMutationNotFound  = errors.New("carddispatch: card mutation target not found")
	ErrCardMutationForbidden = errors.New("carddispatch: card mutation sender mismatch")
	ErrCardMutationConflict  = errors.New("carddispatch: stale card mutation")

	// ErrCardMutationTooLarge 是「帧合法但存不下」——它刻意 wrap ErrCardMutationInvalid,
	// 这样既给调用方/测试一个可区分的哨兵,又让既有的 ErrCardMutationInvalid 映射
	// (bot_api → ErrBotAPICardInvalid)继续成立,不必新增对外错误码。
	ErrCardMutationTooLarge = fmt.Errorf("%w: frame exceeds the persistence column", ErrCardMutationInvalid)
)

Functions

func Install

func Install(ctx ValueStore, registry *Registry) error

Install publishes one immutable registry into one application context. It is called only by the single-threaded bootstrap path before module construction.

func NormalizeFrameForPersistence added in v1.14.0

func NormalizeFrameForPersistence(contentEdit string) (string, error)

NormalizeFrameForPersistence 是「一帧卡片能否落库」的唯一判据。返回 canonical 字节 (cardmsg 已重算权威 plain),可直接写库。

覆盖面是**六处**,其中五处是写路径、一处是发送侧预检(此前这段注释只列了前三条,而 #712 后续轮次又接进来三处 —— 一段断言了不成立的不变量的注释,正是那两轮 blocker 的成因, 所以这里逐条列全,并由 TestPersistenceJudgeCallSitesMatchItsDocumentedCount 钉住计数):

写路径(帧确实要落库):

  1. CardMutator.Mutate(本文件)—— bot 模板编辑与内部生产者编辑
  2. pkg/cardtmpl CardUpdater.Append
  3. pkg/cardtmpl CardUpdater.ReplaceView
  4. modules/bot_api raw 卡片编辑分支 —— 一处调用覆盖它下游的三个写动作 (card_seq CAS / 非 card_seq LWW / 修订历史追加,三者消费同一份字节)
  5. CardMutator.WriteCAS 自己再查一次宽度(见那里的注释)—— 不是重复,而是让 旁路对未来的调用方也不可得,而非仅对今天的调用方关闭

非写路径(**不**落库,只借判据做判断):

  1. modules/bot_api 模板发送预检 —— 拿「最坏的首次编辑信封」问一次「这张卡将来编辑得动 吗」。它不写任何东西;走这个函数是为了让宽度判据只有一份,而不是在发送侧抄一个魔数。

不在覆盖面内、且**刻意**不在的:modules/robot 与 modules/message 的 content_edit 写入 载不了卡片帧(两者都在 cardmsg.RejectsCardEdit 之后,type-17 双向都拒),非卡片的 richtext content_edit 仍未对列宽设限(既有债,不在本函数职责内)。

为什么要有这个函数而不是各调用点自己拼:PR#712 的 P0 就是各点自己拼出来的 —— 渲染侧和回写侧对「同一帧是否合法」给出了不同答案,于是卡片发得出去、编辑必失败。 校验规则一旦有两份,它们就会漂移;这里让它只有一份。

func ProducerBindingFromContext added in v1.14.0

func ProducerBindingFromContext(ctx ValueStore, id ProducerID) (string, bool)

ProducerBindingFromContext 解析已安装 Registry 的只读 producer 身份绑定 (PR-C D3)。Registry 未安装或 producer 未注册一律 (\"\", false),调用方 对 dynamic provenance fail-close。与 SenderFromContext 不同,它绝不返回 发送能力 —— 业务 caller 无法借它构造 ProducerSpec 或拿到 Sender。

Types

type AuthorizationPolicy

type AuthorizationPolicy struct {
	SpacePolicy SpacePolicy
	GroupPolicy GroupPolicy
}

type Authorizer

type Authorizer interface {
	Authorize(ctx context.Context, identity *botidentity.Identity, target Target, policy AuthorizationPolicy) error
}

type Card

type Card struct {
	Profile string
	// RenderProfile selects the client visual compatibility profile. An empty
	// value asks the trusted platform dispatch boundary to author its stable
	// default; callers may only provide an explicitly accepted value.
	RenderProfile string
	Document      json.RawMessage
}

type CardMutationCASRequest added in v1.11.0

type CardMutationCASRequest struct {
	MessageID   string
	MessageSeq  uint32
	ChannelID   string
	ChannelType uint8
	ContentEdit string
	ContentHash string
	EditedAt    int
	CardSeq     int64
	// StorageChannel is true when ChannelID is already the persisted fake DM
	// channel. The existing Bot API resolves that before entering CAS.
	StorageChannel bool
}

type CardMutationRequest added in v1.11.0

type CardMutationRequest struct {
	SenderUID   string
	MessageID   string
	MessageSeq  uint32
	ChannelID   string
	ChannelType uint8
	ContentEdit string
}

type CardMutationResult added in v1.11.0

type CardMutationResult struct {
	Applied bool
	Replay  bool
}

type CardMutationSnapshot added in v1.12.0

type CardMutationSnapshot struct {
	Envelope json.RawMessage
	CardSeq  int64
}

CardMutationSnapshot is the current effective type-17 frame. Envelope is content_edit when present, otherwise the immutable original payload.

type CardMutationTarget added in v1.12.0

type CardMutationTarget struct {
	SenderUID   string
	MessageID   string
	MessageSeq  uint32
	ChannelID   string
	ChannelType uint8
}

CardMutationTarget identifies an existing message using only authoritative server-side values. MessageSeq is an optional lookup optimization.

type CardMutator added in v1.11.0

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

func NewCardMutator added in v1.11.0

func NewCardMutator(ctx *config.Context) *CardMutator

func (*CardMutator) Mutate added in v1.11.0

func (*CardMutator) Snapshot added in v1.12.0

Snapshot returns the active effective card after applying the same sender and lifecycle gates as Mutate. It exists for read-modify-write operations such as CardUpdater.Append; the subsequent Mutate still performs all checks again and owns the CAS.

func (*CardMutator) WriteCAS added in v1.11.0

func (m *CardMutator) WriteCAS(request CardMutationCASRequest) (bool, error)

type Category

type Category string
const (
	CategoryOK                Category = "ok"
	CategoryInvalidRequest    Category = "invalid_request"
	CategoryFeatureDisabled   Category = "feature_disabled"
	CategoryProducerDisabled  Category = "producer_disabled"
	CategoryIdentityUntrusted Category = "identity_untrusted"
	CategoryTargetDenied      Category = "target_denied"
	CategoryCardInvalid       Category = "card_invalid"
	CategoryPayloadTooLarge   Category = "payload_too_large"
	CategoryBusy              Category = "busy"
	CategoryDispatchFailed    Category = "dispatch_failed"
)

func CategoryOf

func CategoryOf(err error) Category

type DBAuthorizer

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

func NewDBAuthorizer

func NewDBAuthorizer(session *dbr.Session) *DBAuthorizer

func (*DBAuthorizer) Authorize

func (a *DBAuthorizer) Authorize(ctx context.Context, identity *botidentity.Identity, target Target, policy AuthorizationPolicy) error

type Dependencies

type Dependencies struct {
	IdentityResolver IdentityResolver
	Authorizer       Authorizer
	Transport        Transport
	Metrics          *Metrics
	Logger           liblog.Log
	FeatureEnabled   func() bool
}

type Error

type Error struct {
	Category Category
	Cause    error
}

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type GroupPolicy

type GroupPolicy string
const (
	GroupPolicyMemberRequired GroupPolicy = "member_required"
	GroupPolicyMemberExempt   GroupPolicy = "member_exempt"
)

type IdentityResolver

type IdentityResolver interface {
	Resolve(uid string) (*botidentity.Identity, error)
}

type Metrics

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

func NewMetrics

func NewMetrics(reg prometheus.Registerer) *Metrics

type ProducerID

type ProducerID string

type ProducerSpec

type ProducerSpec struct {
	ID                  ProducerID
	Enabled             bool
	SenderUID           string
	AllowedChannelTypes []uint8
	AllowedProfiles     []string
	SpacePolicy         SpacePolicy
	GroupPolicy         GroupPolicy
	ActionEventOwner    string
	MaxInFlight         int
}

type Registry

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

func NewRegistry

func NewRegistry(deps Dependencies, specs []ProducerSpec) *Registry

func (*Registry) ProducerBinding added in v1.14.0

func (r *Registry) ProducerBinding(id ProducerID) (string, bool)

ProducerBinding 返回 ProducerID 声明的权威 SenderUID。只读事实,不携带 发送能力;调用方不能据此拿到 Sender。

func (*Registry) Sender

func (r *Registry) Sender(id ProducerID) (Sender, error)

type Result

type Result struct {
	MessageID   int64
	MessageSeq  uint32
	ClientMsgNo string
}

type Sender

type Sender interface {
	Send(ctx context.Context, target Target, card Card) (*Result, error)
}

func SenderFromContext

func SenderFromContext(ctx ValueStore, id ProducerID) (Sender, error)

type SpacePolicy

type SpacePolicy string
const (
	SpacePolicyMembership         SpacePolicy = "membership"
	SpacePolicySystemNotification SpacePolicy = "system_notification"
)

type Target

type Target struct {
	SpaceID     string
	ChannelID   string
	ChannelType uint8
}

type Transport

type Transport interface {
	SendMessageWithResult(req *config.MsgSendReq) (*config.MsgSendResp, error)
}

type ValueStore

type ValueStore interface {
	SetValue(value interface{}, key string)
	Value(key string) interface{}
}

Jump to

Keyboard shortcuts

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