sysRoleModel.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. package role
  2. import (
  3. "context"
  4. "database/sql"
  5. "errors"
  6. "fmt"
  7. "sort"
  8. "strings"
  9. "perms-system-server/internal/consts"
  10. "github.com/zeromicro/go-zero/core/logx"
  11. "github.com/zeromicro/go-zero/core/stores/cache"
  12. "github.com/zeromicro/go-zero/core/stores/sqlx"
  13. )
  14. var ErrUpdateConflict = errors.New("update conflict: data has been modified by another operation")
  15. var _ SysRoleModel = (*customSysRoleModel)(nil)
  16. type (
  17. SysRoleModel interface {
  18. sysRoleModel
  19. FindListByProductCode(ctx context.Context, productCode string, page, pageSize int64) ([]*SysRole, int64, error)
  20. FindByIds(ctx context.Context, ids []int64) ([]*SysRole, error)
  21. FindMinPermsLevelByUserIdAndProductCode(ctx context.Context, userId int64, productCode string) (int64, error)
  22. UpdateWithOptLock(ctx context.Context, data *SysRole, expectedUpdateTime int64) error
  23. // LockByIdTx 在当前事务里锁住 sys_role 行(SELECT ... FOR UPDATE),用于把"同一 role 的
  24. // BindRolePerms 并发覆盖"串行化,消除"existing 在事务外读 + 事务内 delete/insert"
  25. // 造成的第三态合并问题(见审计 M-R10-2)。
  26. LockByIdTx(ctx context.Context, session sqlx.Session, id int64) (*SysRole, error)
  27. // LockRolesForShareTx 在当前事务里对一批 sys_role 行取 S 锁(SELECT ... LOCK IN SHARE MODE),
  28. // 用于闭合 BindRoles × DeleteRole 的写偏斜(审计 M-R12-1):
  29. // DeleteRole 在事务末尾对 sys_role[R] 取 X 锁,会被本 S 锁阻塞;等 BindRoles 提交后
  30. // DeleteRole 再去 FindUserIdsByRoleIdForUpdateTx 时即能看到新插入的 sys_user_role 行,
  31. // 可选择抛错阻断删除或一并清理,不再留下 roleId 指向已删 sys_role 的孤儿。
  32. // 若命中行数 != len(ids) 或有行 status != Enabled,返回 sqlx.ErrNotFound 让调用方
  33. // 转成 400 "包含无效的角色ID"——因为 DeleteRole 的删除发生在 sys_role 行被移走、
  34. // 或者 UpdateRole 把角色 status 改为 Disabled,业务上都不应再绑定。
  35. // 本方法不走缓存,必须在 TransactCtx / Session 下调用;入参 ids 会在内部按升序排序
  36. // 取锁以避免死锁。
  37. LockRolesForShareTx(ctx context.Context, session sqlx.Session, ids []int64) error
  38. // InvalidateRoleCache 失效 sysRole 的 id / (productCode, name) 两把低层缓存键。对齐
  39. // sysDeptModel.InvalidateDeptCache 与 sysUserModel.InvalidateProfileCache 的 L-R12-1
  40. // 契约(审计 H-R17-2):仅应在事务 commit 成功后调用,兜底 `*WithTx` 路径里 sqlc
  41. // `ExecCtx` "exec → DelCache" 钩子过早清缓存之后、commit 之前被并发 `FindOne` 把旧行
  42. // 回填进 Redis 的幽灵快照。best-effort:失败只记日志,TTL 兜底。
  43. //
  44. // 调用方必须传入删除/更新前真实的 (productCode, name)——因为 name 键由这两个字段拼接,
  45. // 如果更新修改了 name,post-commit 失效时要同时清老 name 和新 name 两个键(可由调用方
  46. // 分别调两次本方法,或在调用方自行按需去重)。
  47. InvalidateRoleCache(ctx context.Context, id int64, productCode, name string)
  48. }
  49. customSysRoleModel struct {
  50. *defaultSysRoleModel
  51. }
  52. )
  53. func NewSysRoleModel(conn sqlx.SqlConn, c cache.CacheConf, cachePrefix string, opts ...cache.Option) SysRoleModel {
  54. return &customSysRoleModel{
  55. defaultSysRoleModel: newSysRoleModel(conn, c, cachePrefix, opts...),
  56. }
  57. }
  58. func (m *customSysRoleModel) FindListByProductCode(ctx context.Context, productCode string, page, pageSize int64) ([]*SysRole, int64, error) {
  59. var total int64
  60. countQuery := fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE `productCode` = ?", m.table)
  61. if err := m.QueryRowNoCacheCtx(ctx, &total, countQuery, productCode); err != nil {
  62. return nil, 0, err
  63. }
  64. var list []*SysRole
  65. query := fmt.Sprintf("SELECT %s FROM %s WHERE `productCode` = ? ORDER BY `permsLevel` ASC, id DESC LIMIT ?,?", sysRoleRows, m.table)
  66. if err := m.QueryRowsNoCacheCtx(ctx, &list, query, productCode, (page-1)*pageSize, pageSize); err != nil {
  67. return nil, 0, err
  68. }
  69. return list, total, nil
  70. }
  71. func (m *customSysRoleModel) FindByIds(ctx context.Context, ids []int64) ([]*SysRole, error) {
  72. if len(ids) == 0 {
  73. return nil, nil
  74. }
  75. args := make([]interface{}, len(ids))
  76. marks := make([]string, len(ids))
  77. for i, id := range ids {
  78. args[i] = id
  79. marks[i] = "?"
  80. }
  81. var list []*SysRole
  82. query := fmt.Sprintf("SELECT %s FROM %s WHERE `id` IN (%s)", sysRoleRows, m.table, strings.Join(marks, ","))
  83. if err := m.QueryRowsNoCacheCtx(ctx, &list, query, args...); err != nil {
  84. return nil, err
  85. }
  86. return list, nil
  87. }
  88. func (m *customSysRoleModel) UpdateWithOptLock(ctx context.Context, data *SysRole, expectedUpdateTime int64) error {
  89. sysRoleIdKey := fmt.Sprintf("%s%v", cacheSysRoleIdPrefix, data.Id)
  90. sysRoleProductCodeNameKey := fmt.Sprintf("%s%v:%v", cacheSysRoleProductCodeNamePrefix, data.ProductCode, data.Name)
  91. res, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (sql.Result, error) {
  92. query := fmt.Sprintf("UPDATE %s SET `name`=?, `remark`=?, `status`=?, `permsLevel`=?, `updateTime`=? WHERE `id`=? AND `updateTime`=?", m.table)
  93. return conn.ExecCtx(ctx, query, data.Name, data.Remark, data.Status, data.PermsLevel, data.UpdateTime, data.Id, expectedUpdateTime)
  94. }, sysRoleIdKey, sysRoleProductCodeNameKey)
  95. if err != nil {
  96. return err
  97. }
  98. affected, _ := res.RowsAffected()
  99. if affected == 0 {
  100. return ErrUpdateConflict
  101. }
  102. return nil
  103. }
  104. // LockRolesForShareTx 见接口注释(审计 M-R12-1)。
  105. func (m *customSysRoleModel) LockRolesForShareTx(ctx context.Context, session sqlx.Session, ids []int64) error {
  106. if len(ids) == 0 {
  107. return nil
  108. }
  109. // 去重 + 升序,避免同一事务重复 SELECT 相同 id 造成的等待链加长,并保证多条 BindRoles
  110. // 并发时按统一顺序取锁(避免 A 锁 1→2、B 锁 2→1 的死锁)。
  111. seen := make(map[int64]struct{}, len(ids))
  112. sorted := make([]int64, 0, len(ids))
  113. for _, id := range ids {
  114. if _, ok := seen[id]; ok {
  115. continue
  116. }
  117. seen[id] = struct{}{}
  118. sorted = append(sorted, id)
  119. }
  120. sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
  121. placeholders := make([]string, len(sorted))
  122. args := make([]interface{}, 0, len(sorted)+1)
  123. for i, id := range sorted {
  124. placeholders[i] = "?"
  125. args = append(args, id)
  126. }
  127. args = append(args, consts.StatusEnabled)
  128. var lockedIds []int64
  129. query := fmt.Sprintf(
  130. "SELECT `id` FROM %s WHERE `id` IN (%s) AND `status` = ? ORDER BY `id` LOCK IN SHARE MODE",
  131. m.table, strings.Join(placeholders, ","),
  132. )
  133. if err := session.QueryRowsCtx(ctx, &lockedIds, query, args...); err != nil {
  134. return err
  135. }
  136. // 任一 id 对不上(已被 DeleteRole 删掉、或 UpdateRole 改为 Disabled)都一刀切回 ErrNotFound,
  137. // 让调用方 BindRoles 立即终止事务并返回 400;不在本函数里做"部分成功 + 分辨哪些失败"的返回值
  138. // 语义(DeleteRole 对 sys_role 的 X 锁在本事务提交前不会释放,所以本 S 锁"全捕获"才是正确信号)。
  139. if len(lockedIds) != len(sorted) {
  140. return sqlx.ErrNotFound
  141. }
  142. return nil
  143. }
  144. // InvalidateRoleCache 见接口注释(审计 H-R17-2)。与 sysDeptModel.InvalidateDeptCache 同型:
  145. // post-commit best-effort 失效,ctx 取消与其它错误分档日志,方便 Redis 抖动与主动取消区分告警。
  146. func (m *customSysRoleModel) InvalidateRoleCache(ctx context.Context, id int64, productCode, name string) {
  147. keys := []string{fmt.Sprintf("%s%v", cacheSysRoleIdPrefix, id)}
  148. if productCode != "" && name != "" {
  149. keys = append(keys, fmt.Sprintf("%s%v:%v", cacheSysRoleProductCodeNamePrefix, productCode, name))
  150. }
  151. if err := m.DelCacheCtx(ctx, keys...); err != nil {
  152. if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
  153. logx.WithContext(ctx).Errorw("cache invalidation skipped: ctx canceled",
  154. logx.Field("audit", "cache_invalidation_skipped_due_to_ctx_cancel"),
  155. logx.Field("scope", "sysRoleModel.InvalidateRoleCache"),
  156. logx.Field("id", id),
  157. logx.Field("err", err.Error()),
  158. )
  159. } else {
  160. logx.WithContext(ctx).Errorf("sysRoleModel.InvalidateRoleCache failed: id=%d err=%v", id, err)
  161. }
  162. }
  163. }
  164. // LockByIdTx 见接口注释。注意:本函数不走缓存层,必须在 TransactCtx / Session 下调用;
  165. // SELECT ... FOR UPDATE 的行锁由 InnoDB 持有到事务结束。
  166. func (m *customSysRoleModel) LockByIdTx(ctx context.Context, session sqlx.Session, id int64) (*SysRole, error) {
  167. var data SysRole
  168. query := fmt.Sprintf("SELECT %s FROM %s WHERE `id` = ? LIMIT 1 FOR UPDATE", sysRoleRows, m.table)
  169. if err := session.QueryRowCtx(ctx, &data, query, id); err != nil {
  170. return nil, err
  171. }
  172. return &data, nil
  173. }
  174. func (m *customSysRoleModel) FindMinPermsLevelByUserIdAndProductCode(ctx context.Context, userId int64, productCode string) (int64, error) {
  175. var level int64
  176. query := fmt.Sprintf(
  177. "SELECT IFNULL(MIN(r.`permsLevel`), -1) FROM %s r INNER JOIN `sys_user_role` ur ON r.`id` = ur.`roleId` WHERE ur.`userId` = ? AND r.`productCode` = ? AND r.`status` = ?",
  178. m.table,
  179. )
  180. if err := m.QueryRowNoCacheCtx(ctx, &level, query, userId, productCode, consts.StatusEnabled); err != nil {
  181. return 0, err
  182. }
  183. if level < 0 {
  184. return 0, ErrNotFound
  185. }
  186. return level, nil
  187. }