Files
hfb_sys/backend/internal/modules/chathub/hub.go
T

264 lines
6.8 KiB
Go

package chathub
import (
"encoding/json"
"sync"
"gorm.io/gorm"
)
// ChatEvent 是通过 SSE 推送给客户端的事件。
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"`
ReadAt string `json:"read_at,omitempty"`
}
// MessageData 是事件中携带的消息数据,与 chat.MessageDTO 对齐。
type MessageData struct {
ID uint64 `json:"id"`
ConversationID uint64 `json:"conversation_id"`
SenderType string `json:"sender_type"`
SenderID uint64 `json:"sender_id"`
SenderRole string `json:"sender_role"`
SenderName string `json:"sender_name"`
ContentType string `json:"content_type"`
Content string `json:"content"`
AttachmentURLS []string `json:"attachment_urls"`
AdminAttentionType string `json:"admin_attention_type,omitempty"`
CreatedAt string `json:"created_at"`
}
// principal 标识一个连接方。
type principal struct {
Type string // "user" or "admin"
ID uint64
TenantID uint64
PlatformAdmin bool
}
// Hub 管理所有 SSE 连接。
type Hub struct {
mu sync.RWMutex
clients map[principal]map[chan *ChatEvent]struct{}
db *gorm.DB
}
// NewHub 创建 Hub 实例。
func NewHub(db *gorm.DB) *Hub {
return &Hub{
clients: make(map[principal]map[chan *ChatEvent]struct{}),
db: db,
}
}
// 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)
h.mu.Lock()
if h.clients[key] == nil {
h.clients[key] = make(map[chan *ChatEvent]struct{})
}
h.clients[key][ch] = struct{}{}
h.mu.Unlock()
return ch
}
// Unsubscribe 注销 SSE 连接。
func (h *Hub) Unsubscribe(pType string, pID uint64, ch <-chan *ChatEvent) {
h.mu.Lock()
for key, clients := range h.clients {
if key.Type != pType || key.ID != pID {
continue
}
for sendCh := range clients {
if sendCh == ch {
delete(clients, sendCh)
close(sendCh)
break
}
}
if len(clients) == 0 {
delete(h.clients, key)
}
}
h.mu.Unlock()
}
// DisconnectUser 关闭指定用户当前进程内的全部实时连接。
func (h *Hub) DisconnectUser(userID uint64) {
h.disconnect("user", userID)
}
func (h *Hub) disconnect(pType string, pID uint64) {
h.mu.Lock()
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()
}
// NotifyConversation 查询会话参与者,向所有在线参与者推送事件。
func (h *Hub) NotifyConversation(conversationID uint64, event *ChatEvent) {
if h.db == nil {
return
}
// 查询会话参与者
type participantRow struct {
ParticipantType string
ParticipantID uint64
}
var rows []participantRow
h.db.Table("chat_participants").
Select("participant_type, participant_id").
Where("conversation_id = ?", conversationID).
Find(&rows)
h.mu.RLock()
defer h.mu.RUnlock()
seen := make(map[principal]struct{})
for _, row := range rows {
key := principal{Type: row.ParticipantType, ID: row.ParticipantID}
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
if clients, ok := h.clients[key]; ok {
for ch := range clients {
select {
case ch <- event:
default:
// channel 满了,丢弃事件避免阻塞
}
}
}
}
}
// NotifyUser 直接向指定用户/Admin 推送事件。
func (h *Hub) NotifyUser(pType string, pID uint64, event *ChatEvent) {
h.mu.RLock()
defer h.mu.RUnlock()
for key, clients := range h.clients {
if key.Type != pType || key.ID != pID {
continue
}
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" {
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)
return string(raw)
}
// OnlineCount 返回当前在线连接数。
func (h *Hub) OnlineCount() int {
h.mu.RLock()
defer h.mu.RUnlock()
count := 0
for _, clients := range h.clients {
count += len(clients)
}
return count
}
// OnlineCountByType 返回当前进程内指定主体类型的 SSE 连接数。
func (h *Hub) OnlineCountByType(pType string) int {
h.mu.RLock()
defer h.mu.RUnlock()
count := 0
for key, clients := range h.clients {
if key.Type == pType {
count += len(clients)
}
}
return count
}