Documentation
¶
Index ¶
- Constants
- Variables
- func ActiveAdminUIDs(session *dbr.Session, spaceID string, limit uint64) ([]string, error)
- func ApproveJoinApplyForTest(ctx *config.Context, applyID int64, reviewerUID, spaceID string, maxUsers int) (string, error)
- func CloseAllSpaceSeats(ctx *config.Context, uid, operatorUID, reason string) (closed []string, err error)
- func GetCoMemberUIDs(ctx *config.Context, uid string) ([]string, error)
- func GetCommonSpaceID(ctx *config.Context, uid1, uid2 string) string
- func GetSpaceMemberUIDs(ctx *config.Context, spaceID string) ([]string, error)
- func GetUserDefaultSpaceID(ctx *config.Context, uid string) stringdeprecated
- func GetUserDefaultSpaceIDE(ctx *config.Context, uid string) (string, error)
- func HasActiveCommonSpace(ctx *config.Context, uid1, uid2 string) (bool, error)
- func IsMemberRemoveReason(reason string) bool
- func IsUserCreateDisabled() bool
- func MemberRemovalCleanupStepNames() []string
- func ReactivateMemberForTest(ctx *config.Context, spaceID, uid string, role int) error
- func ReactivateMemberIfNotFullForTest(ctx *config.Context, spaceID, uid string, maxUsers int) error
- func RegisterDefaultCategoryProvisioner(fn DefaultCategoryProvisioner)
- func RegisterMemberRemovalCleanupStep(name string, fn MemberRemovalCleanupStep)
- func RegisterPresetGroupAdmitter(fn PresetGroupAdmitter)
- func RegisterSeatTransitionTxStep(name string, fn SeatTransitionTxStep)
- func RemoveMemberForTest(ctx *config.Context, spaceID, uid string, rejectRoleAtOrAbove int, ...) (bool, error)
- func RemoveMembersForceForTest(ctx *config.Context, spaceID string, uids []string, operatorUID string) ([]string, error)
- func SetInviteEmailSenderForTest(s inviteEmailSender)
- func UpsertJoinApplyForTest(ctx *config.Context, spaceID, uid string) (int64, error)
- func UpsertMembersForTest(ctx *config.Context, spaceID string, uids []string) error
- type BotDetailModel
- type DB
- type DefaultCategoryProvisioner
- type InitialSpaceJoinOutcome
- type InvitationModel
- type Manager
- type MemberDetailModel
- type MemberModel
- type MemberRemoval
- type MemberRemovalCleanupStep
- type PresetGroupAdmitter
- type SeatRef
- type SeatTransition
- type SeatTransitionTxStep
- type Space
- type SpaceDetailModel
- type SpaceModel
- type SpaceRef
Constants ¶
const ( // MemberRemoveReasonKicked owner/admin 通过 members/remove 踢出 MemberRemoveReasonKicked = "kicked" // MemberRemoveReasonLeft 成员自助退出 MemberRemoveReasonLeft = "left" // MemberRemoveReasonForceRemoved 超管在管理端强制移除 MemberRemoveReasonForceRemoved = "force_removed" // MemberRemoveReasonSpaceDisbanded 空间被强制解散,全员一并移除 MemberRemoveReasonSpaceDisbanded = "space_disbanded" // MemberRemoveReasonBotDeleted Bot 被其所有者删除,账号整体消失, // 因此它在**所有** Space 的席位一并关闭(见 CloseAllSpaceSeats)。 // // 它与 force_removed 分开,是因为群侧级联要按 Reason 决定发不发 // 「X 被 Y 移出群聊」。对一个整体消失的账号,那句话是错的——没有人把它 // 移出这个群。复用 force_removed 会让这句话出现在它待过的每个群里。 MemberRemoveReasonBotDeleted = "bot_deleted" // MemberRemoveReasonRejoined recognizes persisted projection jobs so the // worker can retire them without running Space removal steps. MemberRemoveReasonRejoined = "rejoined" )
成员移除原因。低基数枚举,直接进 DB 与日志,不含用户内容。
const ( JoinModeDirect = 0 // 直接加入 JoinModeApproval = 1 // 需要审批 )
const ( SpaceStatusDisbanded = 0 // 已解散 SpaceStatusNormal = 1 // 正常 SpaceStatusBanned = 2 // 已封禁 )
Space 状态常量(SpaceModel.Status)
const ( EmailInviteTypeOwner = 1 // 邀请成为新空间的 owner(lazy-create) EmailInviteTypeMember = 2 // 邀请加入已有空间作为成员/管理员 )
EmailInvite 类型常量
const ( EmailInviteStatusPending = 0 EmailInviteStatusConsumed = 1 EmailInviteStatusExpired = 2 EmailInviteStatusRevoked = 3 )
EmailInvite 状态常量
const ( EmailInviteRoleMember = 0 EmailInviteRoleAdmin = 1 )
EmailInvite 角色常量(仅 member 类型)
const ( // MarketplaceInternalTokenEnv gates this endpoint. Exported so main.go can // feed the value into // cardactiondispatch.Registry.ValidateNotifyTokenExclusions by qualified // reference instead of a duplicated literal — the repo-root // main_marketplace_token_test.go and this package's main_wiring_test.go // assert the qualified form, and a literal would silently drift from this // constant. // // RENAMED from OCTO_MARKETPLACE_ADMIN_LIST_TOKEN when the roster endpoint // was deleted: the credential no longer authorizes listing anything, and an // env name that describes a capability the process does not have is a // standing invitation to misconfigure it. The name now matches its sibling // OCTO_DRIVE_INTERNAL_TOKEN (one consumer, one internal capability set). MarketplaceInternalTokenEnv = "OCTO_MARKETPLACE_INTERNAL_TOKEN" )
Internal single-subject Space role lookup for octo-marketplace.
GET /v1/internal/spaces/:space_id/members/:uid/role answers exactly one question — "what is this uid's space_member.role in this Space right now?" — and returns nothing else. It is a service-to-service endpoint: no user token, no Space middleware; the only credential is X-Internal-Token bound to OCTO_MARKETPLACE_INTERNAL_TOKEN.
Why a single-subject lookup and not a roster ¶
An earlier revision of this branch exposed GET /v1/internal/spaces/:space_id/admins, which returned {uid, name, role} for every owner/admin of any Space the caller could name. Two defects killed it:
- It leaked verified legal names cross-tenant. The roster reused MemberDetailModel.DisplayName(), whose fallback chain reaches user_verification.real_name — the legal name returned by CAS / WeCom / Feishu. That chain is correct for queryMembers, whose audience is other members of the same Space. On a cross-tenant service endpoint it handed any token holder the leadership roster, by legal name, of every org whose space_id it could guess or obtain.
- Empty-vs-non-empty was itself an existence oracle. The roster claimed an unknown Space was indistinguishable from an admin-less one, but every real Space has at least one role=2 creator, so "[]" meant "no such Space" in practice.
The consumer needed the roster for two things, and neither actually requires one:
- Delivery targeting for the IM approval card. octo-server already owns space_member and already delivers the card, so the consumer can ask for role-targeted delivery instead of learning who the admins are — see NotifyReq.target_role in modules/notify and ActiveAdminUIDs in admin_targets.go.
- Re-verifying the operator who clicked approve/deny. The card-action callback carries only an asserted operator_uid (the dispatch is an async queue with retries and a DLQ, so there is no user token to forward), and marketplace must independently confirm that uid still holds the role. That is this endpoint: one subject, one integer.
Deliberately lives in modules/space (not modules/internal_resolve) because the space_member isolation semantics belong here; internal_resolve additionally carries route-shape source assertions that pin its own route.
Variables ¶
var ErrAlreadyMember = errors.New("already_member")
ErrAlreadyMember indicates the user is already an active member
var ErrCannotRemoveOwner = errors.New("cannot remove space owner; transfer ownership first")
ErrCannotRemoveOwner 拦截删除 owner 的请求,调用方需先转让所有权
var ErrRemoveHierarchy = errors.New("operator does not outrank removal target")
ErrRemoveHierarchy 操作者未严格高于目标角色,不能移除目标成员
var ErrSeatNotFound = errors.New("space: seat row not found for canonicalisation")
ErrSeatNotFound means the row a write had just matched could not be read back in the same transaction.
var ErrSpaceBannedForUpdate = errors.New("space is banned and caller disallowed banned updates")
ErrSpaceBannedForUpdate 事务内发现空间已封禁,且调用方未授权对封禁空间执行更新。 用户端 PUT 应映射为 4xx;管理端调用 updateSpaceProfile 时 allowBanned=true, 该 sentinel 不会被触发。
var ErrSpaceDisbandedForUpdate = errors.New("space already disbanded")
ErrSpaceDisbandedForUpdate 事务内发现空间已解散,禁止更新基础信息
var ErrSpaceFull = errors.New("SPACE_FULL")
ErrSpaceFull indicates the space has reached its member capacity
var ErrSpaceNotFound = errors.New("space not found")
ErrSpaceNotFound 空间不存在(事务内 SELECT FOR UPDATE 未命中)
var ErrSpaceRowNotFound = errors.New("space: space row not found for canonicalisation")
ErrSpaceRowNotFound means the `space` row a disband had just written could not be read back in the same transaction.
var ErrTransferTargetMissing = errors.New("transfer target not found or already removed")
ErrTransferTargetMissing 目标成员不存在或已被移除,不能成为新 owner
Functions ¶
func ActiveAdminUIDs ¶ added in v1.19.0
ActiveAdminUIDs returns the uids of a Space's active owners and admins: space_member rows with status=1 AND role>=1, in an ACTIVE space, excluding bot identities. Ordered (role DESC, created_at ASC, uid ASC) and capped at `limit` rows so callers get deterministic, bounded output.
Every predicate is load-bearing:
status=1 AND role>=1 — the reviewer set. A removed admin (status=0) or a plain member (role=0) must never receive an approval card, because the recipient's uid is subsequently treated as an authorized approver by the consumer.
INNER JOIN space ON s.status=1 — disbanding a Space only flips space.status; its space_member rows stay status=1. Without this join a disbanded org's former admins would keep receiving cards. Same hardening as queryUserSpaceContext (modules/user/api.go, v3.3.1 §A.1) and queryActiveMemberRole (api_internal.go).
the robot LEFT JOIN … IS NULL — bots are ordinary space_member rows. queryMembers (db.go:179-201) already filters bots the viewer does not own; here there is no viewer, and delivering an approval card to a bot would put a machine uid into the approver set. So exclude every uid that has a robot row, regardless of robot.status: a soft-deleted bot is still not a person.
App bots (the app_bot table) need no filter here: createBot persists the bot's scope in app_bot.space_id and deliberately does NOT insert the App Bot uid into space_member (see modules/app_bot/app_bot.go:1122-1126), so an app bot cannot appear in this result at all.
A caller that wants to detect truncation should over-fetch by one and compare against its own cap; this function does not log, because the useful log line (which Space, which cap) belongs to the caller.
func ApproveJoinApplyForTest ¶ added in v1.19.0
func ApproveJoinApplyForTest( ctx *config.Context, applyID int64, reviewerUID, spaceID string, maxUsers int, ) (string, error)
ApproveJoinApplyForTest runs the join-apply approval transaction — including its reactivation branch, which reopens an existing removed seat.
func CloseAllSpaceSeats ¶ added in v1.19.0
func CloseAllSpaceSeats(ctx *config.Context, uid, operatorUID, reason string) (closed []string, err error)
CloseAllSpaceSeats 关闭 uid 在所有 Space 的活跃席位,并为每个真的被关掉的席位 写出一条会话面清理工单,返回被关掉席位的 Space 列表。
这是「一个账号整体消失」的唯一正确入口。调用方**不要**自己写 `UPDATE space_member SET status=0`:那样写会跳过整条级联链(P0 关项目席位、 P1 从项目群移除、群侧退群、会话扩展清理),而这条链上的每一步都注册在 RegisterMemberRemovalCleanupStep 里,从这里看不见。
reason 必须是 MemberRemoveReason* 之一。对被删除的 Bot 用 MemberRemoveReasonBotDeleted —— 群侧级联会按它抑制「被 X 移出群聊」系统消息, 那句话对一个整体消失的账号是错的(没有人把它移出这个群)。
席位关闭本身是**同步**的:函数返回时,被列出的每个 Space 里这个 uid 已经不是 活跃成员,鉴权缓存也已清掉。异步的只有工单驱动的那些清理步骤。调用方若在返回后 立刻断言 `space_member.status=0`,断言仍然成立。
部分失败会返回 error 且 closed 非空:已提交的 Space 是真的已提交,没有什么可 回滚的,而重试整个函数是幂等的(已关的席位 affected=0,不会重复入队)。
调用方**不要只记日志就往下走**。上一版这里写着"应当记日志而不是回滚",而第四轮 review 恰好把那条行为从唯一的调用方身上删掉了:botfather 删 Bot 现在在 closeErr 非空时中止删除并让用户重试,正因为往下走会留下一个"Space 席位还活着、 robot 行已禁用"的残留,而上面那段说明了没有扫描看得见它。正确的处置是**中止 本次操作、让它可重试**;"没有什么可回滚的"说的是不必补偿已提交的部分,不是 可以当作成功。PR #855 第五轮 review 的 Q6。
func GetCoMemberUIDs ¶
GetCoMemberUIDs 包级别函数,供其他模块调用,查询与指定用户同在至少一个空间的所有用户UID
func GetCommonSpaceID ¶
GetCommonSpaceID 查找两个用户共同所在的第一个 Space 返回 space_id 或空字符串(无共同 Space)
注意:本函数**不校验 Space 活性**(不 JOIN space 表),仅供展示用途。 授权判定请用 HasActiveCommonSpace。
func GetSpaceMemberUIDs ¶
GetSpaceMemberUIDs 获取指定 Space 的所有成员 UID
func GetUserDefaultSpaceID
deprecated
GetUserDefaultSpaceID 获取用户最早加入的 Space(默认 Space)
Deprecated: 内部吞掉 DB 错误,调用方无法区分"用户没默认 Space"和"查询失败"。 对于"authoritative-empty 契约"敏感的路径(如 /v1/conversation/sync 的 space_memberships sideband),请改用 GetUserDefaultSpaceIDE 拿到 error 后 fail-closed 返回非 200。
func GetUserDefaultSpaceIDE ¶ added in v1.5.0
GetUserDefaultSpaceIDE 是 GetUserDefaultSpaceID 的 error-returning 变体。 用户没默认 Space 时返回 ("", nil);DB 查询失败时返回 ("", err)。
func HasActiveCommonSpace ¶ added in v1.14.0
HasActiveCommonSpace 判定两个用户是否同属一个**正常状态**的 Space(双方在籍 status=1,且 space.status=SpaceStatusNormal)。
与 GetCommonSpaceID 的关键差别是 JOIN 了 space 表校验父实体活性:封禁 / 解散 Space 走的是 updateSpaceStatus(db_manager.go),它**只翻 space.status、不清 space_member 行**(与 forceDisbandSpace 不同)。因此只查关联表的判定会让封禁 Space 的两个成员仍被视为"同 Space 可达",绕过封禁冻结——与 api_member_search.go 里已经处理过的同一类问题。
授权判定必须用本函数;GetCommonSpaceID 保留给展示/兼容用途(它有十余个调用方, 语义不在本次范围内变更)。
func IsMemberRemoveReason ¶ added in v1.16.0
IsMemberRemoveReason 校验原因取值。写库前拦住拼错的字面量,避免出现 永远匹配不到的工单原因。
func IsUserCreateDisabled ¶
func IsUserCreateDisabled() bool
IsUserCreateDisabled 是否已通过环境变量关闭用户侧创建空间。env-only 的低层 解析器,语义与 modules/common/system_settings.go:parseSpaceDisableUserCreateEnv 保持一致 —— 后者是 system_setting 查询的 env fallback。修改此函数的解析 规则时必须同步那一处,否则同一开关会在两个出口产生漂移。
调用方应优先走 (*Space).isUserCreateDisabled 以获得 DB → env 完整链路;本 函数保留是为了向前兼容已有 callers / 测试,以及作为最简 env-only 探测点。
func MemberRemovalCleanupStepNames ¶ added in v1.18.0
func MemberRemovalCleanupStepNames() []string
MemberRemovalCleanupStepNames returns a snapshot of the registered member-removal cleanup step names.
Exported for downstream modules' tests: the registry is the reverse-registration extension point (RegisterMemberRemovalCleanupStep), and a downstream module whose whole asynchronous guarantee depends on its step BEING registered needs a way to assert that. Before this accessor existed, deleting a module's registerSpaceMemberRemovalCleanup call left every downstream suite green — the step was simply never in the registry and nothing checked.
Latest-wins semantics apply: a name re-registered keeps one entry.
func ReactivateMemberForTest ¶ added in v1.19.0
ReactivateMemberForTest runs the single-member reactivation transaction — the invite/add-back path — including its registered synchronous tx steps.
func ReactivateMemberIfNotFullForTest ¶ added in v1.19.0
ReactivateMemberIfNotFullForTest runs the capacity-checked reactivation transaction — the join path — including its registered synchronous tx steps.
func RegisterDefaultCategoryProvisioner ¶
func RegisterDefaultCategoryProvisioner(fn DefaultCategoryProvisioner)
RegisterDefaultCategoryProvisioner 由 modules/category 的 init 调用完成注册。 覆盖允许(latest wins),方便测试替身。nil 时等价于取消注册。
func RegisterMemberRemovalCleanupStep ¶ added in v1.16.0
func RegisterMemberRemovalCleanupStep(name string, fn MemberRemovalCleanupStep)
RegisterMemberRemovalCleanupStep 由下游模块在 init 中反向注册清理步骤。
为什么是反向注册而不是让 space 直接调用 group/user:modules/group 与 modules/user 都已经 import modules/space,反向 import 即构成 import cycle。 同样的手法见 hooks.go 的 DefaultCategoryProvisioner。
同名重复注册会覆盖(latest wins),方便测试替身。
func RegisterPresetGroupAdmitter ¶ added in v1.19.0
func RegisterPresetGroupAdmitter(fn PresetGroupAdmitter)
RegisterPresetGroupAdmitter is called by modules/group at construction. Re-registration replaces (latest wins), which is what lets a test install a stand-in.
func RegisterSeatTransitionTxStep ¶ added in v1.19.0
func RegisterSeatTransitionTxStep(name string, fn SeatTransitionTxStep)
RegisterSeatTransitionTxStep 由下游模块在 init 中反向注册事务内步骤。
反向注册的理由与 RegisterMemberRemovalCleanupStep 相同:modules/project 已经 import modules/space,反向 import 即构成 import cycle。
同名重复注册会覆盖(latest wins),方便测试替身。
func RemoveMemberForTest ¶ added in v1.19.0
func RemoveMemberForTest( ctx *config.Context, spaceID, uid string, rejectRoleAtOrAbove int, operatorUID, reason string, ) (bool, error)
RemoveMemberForTest runs the single-member removal transaction — the kick and self-leave path — including its registered synchronous tx steps.
func RemoveMembersForceForTest ¶ added in v1.19.0
func RemoveMembersForceForTest( ctx *config.Context, spaceID string, uids []string, operatorUID string, ) ([]string, error)
RemoveMembersForceForTest runs the admin batch removal transaction — one transaction for the whole batch — including its registered synchronous tx steps.
func SetInviteEmailSenderForTest ¶
func SetInviteEmailSenderForTest(s inviteEmailSender)
SetInviteEmailSenderForTest 测试专用:替换全局发送器。production 代码不要调用。
func UpsertJoinApplyForTest ¶ added in v1.19.0
UpsertJoinApplyForTest creates or resets a pending join apply and returns its id.
Types ¶
type BotDetailModel ¶
BotDetailModel Bot 详情模型
type DefaultCategoryProvisioner ¶
DefaultCategoryProvisioner 保证 (uid, spaceID) 下默认分类存在的钩子。
为什么用 hook 而不是直接 import:modules/category 的测试通过 blank import 拉入 modules/space 进行迁移注册;若 modules/space 反过来 import modules/category,即构成测试期 import cycle。此处由 category 在 init 中反向 注入 provisioner,两模块生产代码单向依赖(category → space),cycle 消除。
调用方需把任何错误视作非关键路径(降级为 warn),因为:
- category.EnsureDefaultCategory 内部依赖表唯一索引 + INSERT IGNORE, 重复 / 并发调用天然幂等;
- GET /v1/spaces/{id}/categories 端有兜底补偿;
- 生产 flow(创建/加入空间)绝不能因 category 初始化失败而回滚。
type InitialSpaceJoinOutcome ¶ added in v1.18.0
type InitialSpaceJoinOutcome string
InitialSpaceJoinOutcome 描述一次"自动加入初始 Space"的结果。
调用方(modules/oidc)直接把它当 Prometheus 的 result label 用,所以取值是 稳定的小写下划线常量,改动等于改 dashboard 契约。除 InitialSpaceJoined / InitialSpaceAlreadyMember 外都代表没建立成员关系。
const ( // InitialSpaceJoined 本次调用真的写入了成员行,副作用(预设群、默认分类、 // SpaceMemberJoin 事件、成员缓存失效)已按普通加入路径执行。 InitialSpaceJoined InitialSpaceJoinOutcome = "ok" // InitialSpaceAlreadyMember 该 uid 在这个 Space 已经有成员行(在籍或已被移除)。 // 没有任何写入,视为成功。 InitialSpaceAlreadyMember InitialSpaceJoinOutcome = "already_member" // InitialSpaceFull 空间人数已达 max_users,没有加入。 InitialSpaceFull InitialSpaceJoinOutcome = "space_full" // InitialSpaceInactive 目标 Space 不存在或已解散/封禁,没有加入。 InitialSpaceInactive InitialSpaceJoinOutcome = "space_inactive" // InitialSpaceFailed 查询或写入出错,没有(或不确定是否)加入。err 非 nil。 InitialSpaceFailed InitialSpaceJoinOutcome = "error" )
func AutoJoinInitialSpace ¶ added in v1.18.0
func AutoJoinInitialSpace(ctx *config.Context, uid, spaceID string) (InitialSpaceJoinOutcome, error)
AutoJoinInitialSpace 把 uid 作为普通成员(role=0)加入 spaceID 指定的 Space。
用于「运维配了一个初始 Space,之后 OIDC 建出来的账号自动进这个空间」 (task oidc-auto-join-initial-space)。调用方必须把失败当成非致命:本函数 不做任何 HTTP 响应,返回值只用于打日志和计数。
与用户主动加入(executeJoinSpace)的三点差异,都是刻意的:
**先校验 Space 活性**。executeJoinSpace 由 handler 在 checkSpaceActive 之后调用,自己不查 status;本函数没有那层 handler,配置写入后 Space 才被 解散是真实存在的时序,所以必须自己挡,否则会往已解散的空间插成员行。
**绝不复活已被移除的成员**。executeJoinSpace 命中 status=0 的行会 reactivate——那是"用户拿着邀请码重新申请加入"的正确语义。这里不是:管理员 把人移出初始 Space 之后,任何自动流程都不该把他加回去。所以只要成员行存在 (无论 status),一律原样返回 already_member,不写库。 当前触发点只有建号那一刻、uid 全新,这条分支理论上打不到;写成拒绝而不是 复活,是为了让日后若有人从登录路径复用本函数时,语义仍然是安全的那个。
**绕过审批模式**。join_mode=1 的 Space 走审批是给邀请码路径用的;运维在 后台钦定的初始 Space 等价于管理端强制添加,不产生 space_join_apply 行。
容量上限(max_users)语义与普通加入一致,但**判定在本路径自己的事务里** (atomicJoinInitialSpace),不是 atomicAddMemberIfNotFull —— 后者服务于用户主动 加入,本函数不经过它。两者各自用加锁 COUNT 保证并发下不超员;要确认这一点请看 TestAutoJoinInitialSpace_ConcurrentJoinersRespectCapacity,别从函数名推断。
每次调用构造一个 *Space:New 只是几个结构体字面量加一个共享的 settings 单例, 没有连接池或 goroutine,而本函数只在建号那一刻跑一次,不值得为它引一个全局单例。
type InvitationModel ¶
type InvitationModel struct {
SpaceId string // 空间ID
InviteCode string // 邀请码
Creator string // 创建者uid
MaxUses int // 最大使用次数
UsedCount int // 已使用次数
ExpiresAt *db.Time // 过期时间
Status int // 状态 1.有效 0.无效
db.BaseModel
}
InvitationModel 邀请表模型
type Manager ¶
Manager Space 后台管理 API
func NewManager ¶
NewManager 创建 Space 管理实例。space 参数用于复用业务侧的 Space 实例 (共享 executeJoinSpace / notifyApplicantJoinResult / loadKnownSpaceIDs), 避免创建冗余实例;space 为 nil 时会兜底自建(主要给老调用点留后路)。
type MemberDetailModel ¶
type MemberDetailModel struct {
MemberModel
Name string // 用户名称(user.name)
RealName string // 实名兜底(user_verification.real_name),仅作 name 为空时的回退源
Robot int // 是否机器人 1=是 0=否
}
MemberDetailModel 带用户名的成员详情
func (*MemberDetailModel) DisplayName ¶ added in v1.7.0
func (m *MemberDetailModel) DisplayName() string
DisplayName 返回成员的展示名,按 issue #344 的兜底链解析:
- user.name 非空 → 原样返回;
- 否则 user_verification.real_name 非空 → 返回实名;
- 都空 → 返回稳定占位符 "User <uid>"。
任何分支都不会返回空串,也不会暴露 short_no / username。
type MemberModel ¶
type MemberModel struct {
SpaceId string // 空间ID
UID string // 成员uid
Role int // 成员角色 0.普通成员 1.管理员 2.拥有者
Status int // 状态 1.正常 0.已移除
Version int64 // 版本号
db.BaseModel
}
MemberModel 空间成员表模型
type MemberRemoval ¶ added in v1.16.0
type MemberRemoval struct {
SpaceID string
UID string
// OperatorUID 触发这次移除的人;自助退出时等于 UID。
// 可能并不是目标群/会话的成员,步骤在用它渲染文案时要考虑这一点。
OperatorUID string
// Reason 取 MemberRemoveReason* 之一。
Reason string
}
MemberRemoval 描述一次已提交的成员移除,传给每个清理步骤。
type MemberRemovalCleanupStep ¶ added in v1.16.0
type MemberRemovalCleanupStep func(ctx *config.Context, removal MemberRemoval) error
MemberRemovalCleanupStep 是一次「把被移除成员从会话面清出去」的可重试步骤。
契约:
- 必须幂等。失败时整条工单会被重跑,已成功的步骤会再执行一次。
- 必须自行判断「无事可做」并返回 nil,而不是报错。
- 返回 error 表示这次没做完,需要重试;整条工单(含已成功的其它步骤)都会重跑。
- 步骤之间**互不阻塞**:一个步骤返回 error 不会让同一轮里的其余步骤被跳过 (见 runMemberRemovalCleanupJob)。所以不要把「前一个步骤已经成功」当作 前置条件——每个步骤都要能独立地从当前 DB 状态判断自己该做什么。
type PresetGroupAdmitter ¶ added in v1.19.0
PresetGroupAdmitter admits uid into a Space's preset group.
Why a registry instead of a call ¶
modules/group imports modules/space, so modules/space cannot import modules/group — an import cycle. joinPresetGroups worked around that by doing raw DML against group_member, and the workaround is what this file replaces. The pattern is the one already used for the other direction of the same problem: RegisterMemberRemovalCleanupStep, and hooks.go's DefaultCategoryProvisioner.
What the raw INSERT actually cost ¶
`INSERT INTO group_member (group_no, uid) VALUES (?, ?)` — two columns, no transaction, launched as a bare goroutine, every failure a Warn + continue. Four defects in one statement, all of which the admission funnel fixes as a side effect of being the funnel:
- The presence check filtered is_deleted = 0, so a uid who had previously LEFT the group passed it. The INSERT then hit `unique index group_no_uid`, MySQL returned 1062, the error was logged as a warning, and that user was PERMANENTLY never re-added to that preset group — on every subsequent Space join, forever. Two places in this tree already document the defect (modules/space/db_manager.go:219 and P0's migration).
- No `version`, so incremental member sync never sees the row: the member is in the group in the database and missing from every client's member list until something else bumps the group's member version.
- No `vercode`, `role`, `invite_uid`, `is_external` or `source_space_id`.
- No IMAddSubscriber, so the member joins and receives nothing over WuKongIM.
Fail-closed when unregistered ¶
A binary that contains modules/space but not modules/group leaves this nil. joinPresetGroups then SKIPS, and does not fall back to writing the row itself. Falling back would reintroduce all four defects and put a group_member write back outside the admission funnel, which is precisely what the source guard forbids — and the guard would not catch it, because it would be inside the allowlisted call path. Skipping is visible in the log; a defective row is not.
type SeatRef ¶ added in v1.19.0
type SeatRef struct {
// contains filtered or unexported fields
}
SeatRef is a `space_member` row identified by the bytes the DATABASE stores.
Why this is a type and not a pair of strings ¶
Everything downstream of a seat transition — the synchronous tx steps, the removal outbox, and through the outbox the async cascade — matches this identifier against a table with a DIFFERENT collation. `octo_project_member` is pinned utf8mb4_general_ci by every migration in this repo; `space_member` is dump-imported and sits at utf8mb4_0900_ai_ci in production. Those equivalence classes are not the same, and the gap is not symmetric: 0900_ai_ci (UCA 9.0.0 primary weights) folds compatibility decompositions to their base letter, general_ci does not.
Measured on MySQL 8.0.33 with both production collations, stored `alice`: U+FF41 FULLWIDTH a, U+212A KELVIN SIGN, U+2126 OHM SIGN and U+00AA FEMININE ORDINAL all match under 0900_ai_ci and do NOT match under general_ci. (Accents match under both, and ASCII case matches under both — those are NOT instances, though earlier rounds of this branch asserted they were.)
So a caller's spelling can flip a Space seat and then enumerate nothing on the project side: the seat moves, member_epoch does not, and a peer's cached decision keeps agreeing with an epoch that never changed. In the removal direction that is a revoked authorization surviving without bound, and the async cascade is not a backstop because the outbox row carries the same drifted spelling and completes successfully as a no-op.
The previous four fixes in this class each moved ONE hop of the decision into the database — a name, then an affected-rows convention, then a locking read, then a predicated write — and each left the next hop in Go. A struct with unexported fields ends the sequence rather than advancing it: there is no conversion from `string`, so a caller who has not resolved the identifier against `space_member` cannot construct one and the code does not compile. That property is what the source guards could not express, because the failure mode was always a call site nobody had thought of yet.
func ResolveSeatTx ¶ added in v1.19.0
ResolveSeatTx reads a seat's canonical uid back inside the caller's transaction.
Call it AFTER the write, not before ¶
The point is not to validate the uid — it is to learn which bytes the row the write actually matched holds.
Resolving FIRST is not merely more expensive, which is what this comment used to say. It would break an argument documented in another module. The SELECT below is plain and non-locking, so on the current ordering it is not the transaction's first consistency read on any of these paths — the seat UPDATE has already run. That is exactly what leg 2 of modules/project/db.go's read-view note depends on: under REPEATABLE READ the consistent-read view is assigned at the first CONSISTENCY read, and every statement before this one on the removal path is a locking read or a DML.
Move the resolve ahead of the write and, on the two doors whose first statement IS the seat UPDATE (modules/space/db.go reactivateMember, and atomicReactivateMemberIfNotFullOnce whenever maxUsers == 0 — the normal case for an unlimited Space), the read view gets pinned before any lock is taken. bumpMemberEpochForSpaceMemberTx's enumeration would then be able to miss a concurrently-committed admission, bump nothing, and leave a cached denial agreeing with an unchanged epoch.
Resolving after also avoids re-opening the question of what to do when the resolve misses but the write would have hit.
Status is deliberately not in the predicate ¶
Callers use this on both transitions: after a removal the row reads status = 0, after a reactivation it reads 1. Filtering on either would make the helper wrong for half its callers in a way that fails OPEN — an unresolvable seat would look like "no seat" rather than an error.
A miss is an error, and that is the safe direction ¶
This is only ever called where a write has just reported affecting a row, so zero rows here means the row vanished under a lock the transaction is still holding — i.e. an invariant violation, not a normal outcome. Returning an error rolls the transition back, which leaves the seat as it was and the peer's cached decision still correct. Falling back to the caller's spelling would instead commit the seat change and skip the invalidation, which is exactly the defect this type exists to make unrepresentable.
func SeatRefForTest ¶ added in v1.19.0
SeatRefForTest builds a SeatRef from bytes a test already knows, without a database round trip.
It lives HERE, behind the same testing.Testing() fence as the other seams, because it is the one way to obtain a SeatRef without going through ResolveSeatTx — and ResolveSeatTx reading the canonical spelling back out of `space_member` is the whole point of the type. An unfenced constructor taking two strings is a conversion from `string` in all but name, and this branch spent four rounds establishing that no such conversion should exist.
It was previously exported as NewSeatRefFromStored with a doc comment asking callers to only pass database-sourced bytes. Nothing in production called it — only tests — so the honest form is a test seam rather than a request. That is the same reasoning this file already applies to the removal entry points: "nothing calls it" is a property of the current tree, not a boundary.
type SeatTransition ¶ added in v1.19.0
type SeatTransition struct {
// Seat 的 uid 是 `space_member` **存的**那串字节,不是调用方发来的。
// 见 seatref.go:步骤要拿它去匹配 collation 更严的表。
Seat SeatRef
// Opened 为 true 表示一个已关闭的席位被重新打开;false 表示一个活跃席位被关闭。
Opened bool
}
SeatTransition 是一次 space_member 席位状态翻转,交给已注册的事务内步骤。
为什么是一个注册表而不是两个 ¶
关席位和开席位对下游是**同一个事实**:「这个人是不是成员」的答案变了。此前这里是 两套逐字对称的机件——两个 type、两个 mutex、两个 slice、两个 Register、两个 run—— 而唯一的注册方 modules/project 给两边注册的是**逐字相同的一行**。
那份对称不是白拿的,它是本分支两个 P1 的**形状**:
- 第八轮:移除方向接上了、重新加入方向没接,于是消费方缓存的一条**拒绝** 一直和 epoch 对得上,合法回归的成员被持续拒绝,安静的项目里没有上界。
- 第九轮:四扇重新激活门只接了两扇,而另外两扇的函数名里根本没有 "reactivate" 字样(approveJoinApplyAtomic 甚至是设计好的重新加入漏斗)。
两次都不是「没想到这个场景」,而是「一个必须手工保持成对的枚举漏了一个元素」。 合成一个注册表之后,**「只接了一半」不再可表达**——没有另一半可以漏。
方向没有丢,它变成了数据(Opened)。需要区分方向的步骤仍然写得出来,而**忘记** 区分不再是一个默认行为。
与 MemberRemovalCleanupStep 的区别是本质的,不是时机上的微调 ¶
- 清理步骤是**异步**的,可以退避、可以重试、耗尽后进 abandoned 终态。适合 「把这个人从各处摘出去」这类最终一致就够的收尾工作。
- 事务步骤是**同步**的,它的失败会让整次翻转回滚。只放那些「一旦提交就必须 已经成立」的事实——典型的是对外发布的失效信号:如果翻转提交了而信号没发, 消费方会拿着一个它自己检查不出过期的判定,而异步补偿的窗口在作业被 abandoned 之后是无限的。
type SeatTransitionTxStep ¶ added in v1.19.0
type SeatTransitionTxStep func(tx *dbr.Tx, t SeatTransition) error
SeatTransitionTxStep 是在席位翻转**事务内**同步执行的一步。
契约:
- 必须只做一件小事,并且是**一条语句量级**的。它跑在面向用户的事务里。
- 返回 error 会让整次翻转失败。这是刻意的:宁可这次失败让调用方重试, 也不要提交一次没有失效信号的翻转。
- 必须幂等:调用方可能重试整个事务。
- 两个方向都会调用它。如果某一步真的只该对一个方向生效,读 t.Opened—— 但先确认那不是又一次「只做一半」。
type Space ¶
Space 团队空间API
func (*Space) GetCoMemberUIDs ¶
GetCoMemberUIDs 获取与指定用户同在至少一个空间的所有用户UID(公开方法,供其他模块调用)
type SpaceDetailModel ¶
type SpaceDetailModel struct {
SpaceModel
Role int // 当前用户角色
MemberCount int // 成员数
}
SpaceDetailModel 带成员数和角色的空间详情(MaxUsers 从 SpaceModel 继承)
type SpaceModel ¶
type SpaceModel struct {
SpaceId string // 空间ID
Name string // 空间名称
Description string // 空间描述
Logo string // 空间Logo
Creator string // 创建者uid
MaxUsers int // 最大成员数 0.不限制
PresetGroupIds *string // 预设群组ID列表(JSON数组)
JoinMode int // 加入模式 0=直接加入 1=需要审批
Status int // 状态 1.正常 0.已解散
Version int64 // 版本号
db.BaseModel
}
SpaceModel 空间表模型
type SpaceRef ¶ added in v1.19.0
type SpaceRef struct {
// contains filtered or unexported fields
}
SpaceRef is a `space` row identified by the bytes the DATABASE stores.
SeatRef's argument, one table over. The two Space-DISBAND doors are the only removal-outbox producers that do not have a seat to resolve — they enqueue for the whole roster at once — so they took the space_id as a plain string, and both of them passed `c.Param("space_id")` straight through.
The consequence is the same one SeatRef exists to prevent, arrived at from the other column. The `uid` on those outbox rows IS canonical (lockActiveMemberUIDsTx reads it out of space_member); the space_id was not. The async cascade then queries octo_project_member on the PAIR, under utf8mb4_general_ci, which does not fold the fullwidth forms utf8mb4_0900_ai_ci matched on the way in — so it enumerates zero project seats, marks the job `done`, and every project seat in that Space stays status = 1 forever, with the I1 scan reporting a violation nothing can repair.
It grants nothing — the actor is disbanding their own Space, and both the Space middleware and ProjectEpochsInSpace's IsActiveSpace fold deny against a disbanded Space — so the cost is orphaned rows and permanent reconcile noise rather than an escalation. It is here as a TYPE anyway, rather than as two rebinds, because two rebinds is what rounds 13 through 15 tried three times: fix the doors you can see, and the guard stays blind to the door you cannot. Both spelling guards missed these two by construction — one scans checkSpaceActive call sites and disbandSpace has none, the other drives a table of manager doors that forceDisband is not in.
There is no conversion from string, so the next batch-enqueue door does not compile until it has resolved the row.
func ResolveSpaceIDTx ¶ added in v1.19.0
ResolveSpaceIDTx reads a Space's canonical space_id back inside the caller's transaction.
Call it while the row is already locked ¶
The read is a LOCKING one, and both properties matter:
- it must not be the transaction's first CONSISTENCY read. Under REPEATABLE READ that is where the read view gets assigned, and the disband transactions do plain SELECTs nowhere after this point today — but a helper is called by code that has not been written yet. FOR UPDATE assigns no view.
- it must add no lock-order edge. Both callers have just executed `UPDATE space ... WHERE space_id = ?`, so the X lock on this row is already held and this statement waits for nothing. A caller that has NOT locked the row first would be introducing a new edge into a graph that three review rounds found cycles in — so do not call it from anywhere else without redoing that analysis.
A miss is an error. This is only called after a write that was supposed to match the row, so zero rows means it vanished under a lock this transaction holds. Rolling back leaves the Space undisbanded, which is recoverable; committing the disband with a roster of poisoned outbox rows is not.
Source Files
¶
- 1module.go
- admin_targets.go
- api.go
- api_directory.go
- api_email_invite.go
- api_email_invite_public.go
- api_i18n.go
- api_internal.go
- api_manager.go
- api_manager_email_invite.go
- api_member_search.go
- api_welcome.go
- db.go
- db_directory.go
- db_email_invite.go
- db_manager.go
- db_member_removal.go
- email_invite_sender.go
- email_invite_template.go
- email_invite_token.go
- hooks.go
- initial_space.go
- invite_code.go
- member_removal.go
- member_removal_all_spaces.go
- member_removal_metrics.go
- member_removal_registry.go
- model.go
- preset_group_admitter.go
- removal_testseam.go
- seat_transition.go
- seatref.go