feat(tenant): 隔离客服通知文件与后台任务

This commit is contained in:
yml
2026-11-15 16:23:28 +08:00
parent c7dacfa025
commit e994fd9166
52 changed files with 1670 additions and 254 deletions
+11 -4
View File
@@ -6,6 +6,7 @@ import (
"time"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/internal/tenancy"
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
@@ -38,7 +39,7 @@ func (h *Handler) UserEvents(c *gin.Context) {
response.Unauthorized(c, "用户上下文无效")
return
}
h.serveSSE(c, "user", userID)
h.serveSSE(c, "user", userID, tenancy.IDFromContext(c.Request.Context()), false)
}
// AdminEvents 处理管理端 SSE 连接: GET /api/admin/chats/events
@@ -53,14 +54,20 @@ func (h *Handler) AdminEvents(c *gin.Context) {
response.Unauthorized(c, "管理员上下文无效")
return
}
h.serveSSE(c, "admin", adminID)
platform := h.hub.IsPlatformAdmin(adminID)
h.serveSSE(c, "admin", adminID, tenancy.IDFromContext(c.Request.Context()), platform)
}
func (h *Handler) serveSSE(c *gin.Context, pType string, pID uint64) {
func (h *Handler) serveSSE(c *gin.Context, pType string, pID, tenantID uint64, platform bool) {
startedAt := time.Now()
disconnectReason := "handler_completed"
var disconnectErr error
ch := h.hub.Subscribe(pType, pID)
var ch <-chan *ChatEvent
if pType == "admin" {
ch = h.hub.SubscribeAdmin(pID, tenantID, platform)
} else {
ch = h.hub.SubscribeForTenant(pType, pID, tenantID)
}
h.logger.Info("SSE 连接建立", h.connectionLogFields(c, pType, pID)...)
defer func() {
h.hub.Unsubscribe(pType, pID, ch)
+86 -29
View File
@@ -12,6 +12,8 @@ type ChatEvent struct {
Type string `json:"type"` // "new_message" | "conversation_updated" | "conversation_read"
ConversationID uint64 `json:"conversation_id"`
Message *MessageData `json:"message,omitempty"`
// TenantIDs 仅用于进程内推送路由,不返回给前端。
TenantIDs []uint64 `json:"-"`
// 以下字段仅在 conversation_read 事件中使用,标识谁在何时读取了会话。
ReaderType string `json:"reader_type,omitempty"`
ReaderID uint64 `json:"reader_id,omitempty"`
@@ -35,8 +37,10 @@ type MessageData struct {
// principal 标识一个连接方。
type principal struct {
Type string // "user" or "admin"
ID uint64
Type string // "user" or "admin"
ID uint64
TenantID uint64
PlatformAdmin bool
}
// Hub 管理所有 SSE 连接。
@@ -56,8 +60,21 @@ func NewHub(db *gorm.DB) *Hub {
// Subscribe 注册一个 SSE 连接,返回事件 channel。
func (h *Hub) Subscribe(pType string, pID uint64) <-chan *ChatEvent {
return h.SubscribeForTenant(pType, pID, 0)
}
// SubscribeForTenant 注册租户范围内的 SSE 连接。
func (h *Hub) SubscribeForTenant(pType string, pID, tenantID uint64) <-chan *ChatEvent {
return h.subscribe(principal{Type: pType, ID: pID, TenantID: tenantID})
}
// SubscribeAdmin 注册后台连接;平台超管可以接收全部租户会话事件。
func (h *Hub) SubscribeAdmin(adminID, tenantID uint64, platform bool) <-chan *ChatEvent {
return h.subscribe(principal{Type: "admin", ID: adminID, TenantID: tenantID, PlatformAdmin: platform})
}
func (h *Hub) subscribe(key principal) <-chan *ChatEvent {
ch := make(chan *ChatEvent, 16)
key := principal{Type: pType, ID: pID}
h.mu.Lock()
if h.clients[key] == nil {
h.clients[key] = make(map[chan *ChatEvent]struct{})
@@ -69,10 +86,11 @@ func (h *Hub) Subscribe(pType string, pID uint64) <-chan *ChatEvent {
// Unsubscribe 注销 SSE 连接。
func (h *Hub) Unsubscribe(pType string, pID uint64, ch <-chan *ChatEvent) {
key := principal{Type: pType, ID: pID}
h.mu.Lock()
if clients, ok := h.clients[key]; ok {
// 找到对应的发送 channel 并删除
for key, clients := range h.clients {
if key.Type != pType || key.ID != pID {
continue
}
for sendCh := range clients {
if sendCh == ch {
delete(clients, sendCh)
@@ -93,12 +111,15 @@ func (h *Hub) DisconnectUser(userID uint64) {
}
func (h *Hub) disconnect(pType string, pID uint64) {
key := principal{Type: pType, ID: pID}
h.mu.Lock()
clients := h.clients[key]
delete(h.clients, key)
for ch := range clients {
close(ch)
for key, clients := range h.clients {
if key.Type != pType || key.ID != pID {
continue
}
delete(h.clients, key)
for ch := range clients {
close(ch)
}
}
h.mu.Unlock()
}
@@ -143,27 +164,10 @@ func (h *Hub) NotifyConversation(conversationID uint64, event *ChatEvent) {
// NotifyUser 直接向指定用户/Admin 推送事件。
func (h *Hub) NotifyUser(pType string, pID uint64, event *ChatEvent) {
key := principal{Type: pType, ID: pID}
h.mu.RLock()
defer h.mu.RUnlock()
if clients, ok := h.clients[key]; ok {
for ch := range clients {
select {
case ch <- event:
default:
}
}
}
}
// NotifyAllAdmins 向所有在线管理员(客服)推送事件。
// 客服工作台的「未分配 / 全部」视图会展示当前客服并非参与者的会话,
// 仅靠 NotifyConversation(只推参与者)无法实时刷新,故对所有在线客服广播。
func (h *Hub) NotifyAllAdmins(event *ChatEvent) {
h.mu.RLock()
defer h.mu.RUnlock()
for key, clients := range h.clients {
if key.Type != "admin" {
if key.Type != pType || key.ID != pID {
continue
}
for ch := range clients {
@@ -175,6 +179,59 @@ func (h *Hub) NotifyAllAdmins(event *ChatEvent) {
}
}
// NotifyAllAdmins 向事件所属租户的在线管理员推送事件。
// 客服工作台的「未分配 / 全部」视图会展示当前客服并非参与者的会话,
// 仅靠 NotifyConversation(只推参与者)无法实时刷新,故对所有在线客服广播。
func (h *Hub) NotifyAllAdmins(event *ChatEvent) {
h.mu.RLock()
defer h.mu.RUnlock()
for key, clients := range h.clients {
if key.Type != "admin" {
continue
}
if !key.PlatformAdmin && !adminClientMatchesEventTenant(key.TenantID, event) {
continue
}
for ch := range clients {
select {
case ch <- event:
default:
}
}
}
}
func adminClientMatchesEventTenant(tenantID uint64, event *ChatEvent) bool {
if event == nil {
return false
}
if len(event.TenantIDs) == 0 {
return tenantID == 0
}
if tenantID == 0 {
return false
}
for _, id := range event.TenantIDs {
if id == tenantID {
return true
}
}
return false
}
// IsPlatformAdmin 判断管理员是否拥有平台超管角色。
func (h *Hub) IsPlatformAdmin(adminID uint64) bool {
if h == nil || h.db == nil || adminID == 0 {
return false
}
var count int64
err := h.db.Table("admin_user_roles AS aur").
Joins("JOIN roles AS r ON r.id = aur.role_id").
Where("aur.admin_user_id = ? AND aur.tenant_id = 0 AND r.code = ?", adminID, "super_admin").
Count(&count).Error
return err == nil && count > 0
}
// MarshalEvent 将事件序列化为 SSE data 行。
func MarshalEvent(event *ChatEvent) string {
raw, _ := json.Marshal(event)
@@ -30,3 +30,28 @@ func TestDisconnectUserClosesAllConnections(t *testing.T) {
t.Fatalf("online admin connection count = %d, want 1", got)
}
}
func TestNotifyAllAdminsRespectsTenantAndPlatformScope(t *testing.T) {
hub := NewHub(nil)
tenantA := hub.SubscribeAdmin(1, 101, false)
tenantB := hub.SubscribeAdmin(2, 202, false)
platform := hub.SubscribeAdmin(3, 101, true)
hub.NotifyAllAdmins(&ChatEvent{
Type: "conversation_updated",
ConversationID: 9,
TenantIDs: []uint64{101},
})
if got := <-tenantA; got.ConversationID != 9 {
t.Fatalf("tenant A conversation = %d", got.ConversationID)
}
if got := <-platform; got.ConversationID != 9 {
t.Fatalf("platform conversation = %d", got.ConversationID)
}
select {
case event := <-tenantB:
t.Fatalf("tenant B received cross-tenant event: %+v", event)
default:
}
}