docs: 整理文档目录结构 — 清理过时文档、归集功能子目录、统一命名规范
清理: - 删除 34 份过时文档(gap reports/QA临时报告/验收报告/阶段性文档) - 删除 docs/.hermes/skills 第三方 skills 副本(16 文件) - 删除 skills-lock.json 目录归集: - 根目录仅保留 README.md 索引 - product/ — 产品与架构设计(PRD + ARCHITECTURE + P2设计文档 + AI/企业路线图) - tracking/ — Chatwoot parity 开发跟踪 - requirements/ — M01-M12 模块需求 - plans/ — 历史实现计划 - parity/ — 路由 parity 与前端契约 - qa/ — QA 报告与测试计划 - ops/ — 运维部署 命名规范: - 全小写 kebab-case,禁止全大写文件名 - product/tracking/ops 用 NN- 序号前缀 - requirements 用 MNN- 两位零填充模块号 - plans/qa 用 YYYY-MM-DD- 日期前缀 - requirements M1-M9 零填充为 M01-M09(修复字典序) 同步更新: - backend/cmd/route_parity/main.go 路径默认值 - backend/scripts/parity_frontend_smoke.sh 报告路径 - 所有 docs 内部交叉引用 - .gitignore 排除编译产物 (backend/gochat, backend/route_parity) - 新增迁移 000052/000053 - 前端 WS 相关修改
This commit is contained in:
@@ -257,6 +257,8 @@ func autoMigrate(db *gorm.DB) error {
|
||||
&model.BackgroundJob{},
|
||||
// S6: WorkingHour — out-of-office / business hours per inbox
|
||||
&model.WorkingHour{},
|
||||
// Notification settings — per-user per-account notification preferences
|
||||
&model.NotificationSetting{},
|
||||
}
|
||||
|
||||
for _, m := range models {
|
||||
|
||||
@@ -195,6 +195,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
notificationPrefRepo := repository.NewNotificationPreferenceRepo(db)
|
||||
pushTokenRepo := repository.NewPushTokenRepo(db)
|
||||
notificationSubscriptionRepo := repository.NewNotificationSubscriptionRepo(db)
|
||||
notificationSettingRepo := repository.NewNotificationSettingRepo(db)
|
||||
webhookSubRepo := repository.NewWebhookSubscriptionRepo(db)
|
||||
conversationParticipantRepo := repository.NewConversationParticipantRepo(db)
|
||||
draftMessageRepo := repository.NewDraftMessageRepo(db)
|
||||
@@ -556,6 +557,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
// P4 Notification+Webhook services
|
||||
pushSubscriptionService := service.NewPushSubscriptionService(pushTokenRepo)
|
||||
notificationSubscriptionService := service.NewNotificationSubscriptionService(notificationSubscriptionRepo)
|
||||
notificationSettingService := service.NewNotificationSettingService(notificationSettingRepo)
|
||||
pushDeliveryService := service.NewPushDeliveryService(pushTokenRepo, cfg.Push.VapidPublicKey, cfg.Push.VapidPrivateKey, cfg.Push.VapidSubject)
|
||||
webhookSubscriptionService := service.NewWebhookSubscriptionService(webhookSubRepo)
|
||||
webhookDeliveryService := service.NewWebhookDeliveryService(webhookSubRepo)
|
||||
@@ -831,6 +833,7 @@ func Bootstrap(env string) (*App, error) {
|
||||
CannedResponse: v1.NewCannedResponseHandler(cannedResponseService),
|
||||
PushSubscription: v1.NewPushSubscriptionHandler(pushSubscriptionService),
|
||||
NotificationSubscription: v1.NewNotificationSubscriptionHandler(notificationSubscriptionService),
|
||||
NotificationSetting: v1.NewNotificationSettingHandler(notificationSettingService),
|
||||
WebhookSubscription: v1.NewWebhookSubscriptionHandler(webhookSubscriptionService),
|
||||
TelegramWebhook: telegramWebhookHandler,
|
||||
FacebookWebhook: facebookWebhookHandler,
|
||||
|
||||
@@ -36,13 +36,19 @@ type Handler struct {
|
||||
// The authenticator provides both JWT (agent) and pubsub_token (contact) auth paths.
|
||||
func NewHandler(hub *Hub, authenticator *wspkg.WSAuthenticator) *Handler {
|
||||
return &Handler{
|
||||
hub: hub,
|
||||
hub: hub,
|
||||
authenticator: authenticator,
|
||||
upgrader: websocket.Upgrader{
|
||||
ReadBufferSize: 1024,
|
||||
WriteBufferSize: 1024,
|
||||
// Allow all origins — CORS is handled at the Gin middleware layer
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
// ActionCable clients send Sec-WebSocket-Protocol: actioncable-v1-json.
|
||||
// If the server doesn't echo back a supported subprotocol, the JS
|
||||
// client immediately closes the connection ("Protocol is unsupported")
|
||||
// and enters a reconnect loop. gorilla/websocket picks the first
|
||||
// requested protocol listed here that the client also offered.
|
||||
Subprotocols: []string{"actioncable-v1-json"},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -91,6 +97,12 @@ func (h *Handler) ServeWS(c *gin.Context) {
|
||||
|
||||
logger.L().Infof("ws: connection established (user=%d, account=%d, is_contact=%v)", claims.UserID, claims.AccountID, claims.IsContact)
|
||||
|
||||
// Send ActionCable welcome frame — the JS client expects this immediately
|
||||
// after upgrade. Without it the client's ConnectionMonitor considers the
|
||||
// connection stale and enters a reconnect loop.
|
||||
welcomeData, _ := json.Marshal(WelcomeFrame{Type: ServerWelcome})
|
||||
client.Send <- welcomeData
|
||||
|
||||
// Start pumps in separate goroutines
|
||||
go h.writePump(client)
|
||||
go h.readPump(client)
|
||||
@@ -144,6 +156,11 @@ func (h *Handler) readPump(client *Client) {
|
||||
h.handleUnsubscribe(client, cmd)
|
||||
case CommandPing:
|
||||
h.handlePing(client)
|
||||
case CommandMessage:
|
||||
// ActionCable "message" command — client performs a channel action
|
||||
// (e.g. update_presence). We acknowledge but don't require a
|
||||
// specific handler for presence yet.
|
||||
logger.L().Debugf("ws: message command from user=%d, data=%s", client.UserID, cmd.Data)
|
||||
default:
|
||||
logger.L().Warnf("ws: unknown command '%s' from user=%d", cmd.Command, client.UserID)
|
||||
}
|
||||
@@ -177,9 +194,15 @@ func (h *Handler) writePump(client *Client) {
|
||||
}
|
||||
|
||||
case <-ticker.C:
|
||||
// Send ping frame for heartbeat
|
||||
// Send ActionCable-level ping message (JSON text frame).
|
||||
// The JS ConnectionMonitor expects periodic ping messages to
|
||||
// keep the connection alive (staleThreshold = 6s by default).
|
||||
pingMsg, _ := json.Marshal(PingFrame{
|
||||
Type: ServerPing,
|
||||
Message: time.Now().UTC().Format(time.RFC3339),
|
||||
})
|
||||
client.Conn.SetWriteDeadline(time.Now().Add(WriteWait))
|
||||
if err := client.Conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
|
||||
if err := client.Conn.WriteMessage(websocket.TextMessage, pingMsg); err != nil {
|
||||
logger.L().Errorf("ws: ping write failed for user=%d: %v", client.UserID, err)
|
||||
return
|
||||
}
|
||||
@@ -217,7 +240,9 @@ func (h *Handler) handleSubscribe(client *Client, cmd CommandFrame) {
|
||||
// Determine room name based on channel type (uses Hub's canonical naming)
|
||||
room := ""
|
||||
switch identifier.Channel {
|
||||
case ChannelAccount:
|
||||
case ChannelAccount, ChannelRoom:
|
||||
// RoomChannel is Chatwoot's single-subscription model — it maps
|
||||
// to the account room (all account-level events are delivered).
|
||||
room = accountRoomName(identifier.AccountID)
|
||||
case ChannelConversation:
|
||||
if identifier.ConversationID == 0 {
|
||||
@@ -243,6 +268,10 @@ func (h *Handler) handleSubscribe(client *Client, cmd CommandFrame) {
|
||||
// Subscribe the client to the room
|
||||
client.Subscribe(room)
|
||||
|
||||
// Store the ActionCable subscription identifier on the client so that
|
||||
// event frames can be wrapped with it for correct client-side routing.
|
||||
client.Identifier = cmd.Identifier
|
||||
|
||||
// Send confirmation frame
|
||||
confirmData, _ := json.Marshal(ConfirmFrame{
|
||||
Type: ServerConfirmSubscribe,
|
||||
@@ -262,7 +291,7 @@ func (h *Handler) handleUnsubscribe(client *Client, cmd CommandFrame) {
|
||||
// Determine room name (uses Hub's canonical naming)
|
||||
room := ""
|
||||
switch identifier.Channel {
|
||||
case ChannelAccount:
|
||||
case ChannelAccount, ChannelRoom:
|
||||
room = accountRoomName(identifier.AccountID)
|
||||
case ChannelConversation:
|
||||
room = conversationRoomName(identifier.AccountID, identifier.ConversationID)
|
||||
|
||||
@@ -35,6 +35,7 @@ type Client struct {
|
||||
Hub *Hub // reference back to Hub
|
||||
SubscribedRooms map[string]bool // rooms this client is subscribed to
|
||||
CancelPresence context.CancelFunc // cancel presence refresh on disconnect
|
||||
Identifier string // ActionCable subscription identifier (JSON string)
|
||||
}
|
||||
|
||||
// NewClient creates a new WebSocket client with the given identity and connection.
|
||||
@@ -201,12 +202,9 @@ func (h *Hub) Register(c *Client) {
|
||||
logger.L().Infof("ws hub: client registered (id=%s, user_id=%d, account_id=%d, is_contact=%v)",
|
||||
c.ID, c.UserID, c.AccountID, c.IsContact)
|
||||
|
||||
// Send welcome message
|
||||
welcomeMsg, _ := json.Marshal(wspkg.WSMessage{
|
||||
Event: wspkg.EventWelcome,
|
||||
Data: map[string]any{"client_id": c.ID},
|
||||
})
|
||||
c.Send <- welcomeMsg
|
||||
// Note: The ActionCable welcome frame is sent by handler.go's ServeWS
|
||||
// after upgrade. We do NOT send a WSMessage-format welcome here because
|
||||
// the JS ActionCable client only recognizes {type:"welcome"} frames.
|
||||
}
|
||||
|
||||
// Unregister removes a client from the Hub and cleans up presence.
|
||||
@@ -244,6 +242,37 @@ func (h *Hub) Unregister(c *Client) {
|
||||
logger.L().Infof("ws hub: client unregistered (id=%s, user_id=%d)", c.ID, c.UserID)
|
||||
}
|
||||
|
||||
|
||||
// wrapActionCableMessage wraps a raw event payload in the ActionCable wire format.
|
||||
// ActionCable JS expects: {"identifier":"<subscription identifier>","message":<payload>}
|
||||
// Without the identifier field, the JS client crashes with
|
||||
// "Cannot read properties of undefined (reading 'received')".
|
||||
// Without the message field, the received callback gets undefined.
|
||||
//
|
||||
// If the client has no subscription identifier yet (pre-subscribe), the
|
||||
// message is still sent but without an identifier — the JS client will
|
||||
// silently ignore it (no matching subscription).
|
||||
func wrapActionCableMessage(identifier string, data []byte) []byte {
|
||||
if identifier == "" {
|
||||
// Client hasn't subscribed yet — sending an unwrapped message would
|
||||
// crash the ActionCable JS client (no identifier to route to).
|
||||
// Return nil to signal the caller to skip delivery.
|
||||
return nil
|
||||
}
|
||||
wrapped := struct {
|
||||
Identifier string `json:"identifier"`
|
||||
Message json.RawMessage `json:"message"`
|
||||
}{
|
||||
Identifier: identifier,
|
||||
Message: data,
|
||||
}
|
||||
result, err := json.Marshal(wrapped)
|
||||
if err != nil {
|
||||
return data
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// SendToAccount sends a message to all clients subscribed to an account room.
|
||||
func (h *Hub) SendToAccount(accountID uint, data []byte) {
|
||||
h.mu.RLock()
|
||||
@@ -253,8 +282,12 @@ func (h *Hub) SendToAccount(accountID uint, data []byte) {
|
||||
if clientIDs, ok := h.rooms[roomName]; ok {
|
||||
for clientID := range clientIDs {
|
||||
if client, ok := h.clients[clientID]; ok {
|
||||
msg := wrapActionCableMessage(client.Identifier, data)
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case client.Send <- data:
|
||||
case client.Send <- msg:
|
||||
default:
|
||||
logger.L().Warnf("ws hub: dropping message for slow client %s", clientID)
|
||||
}
|
||||
@@ -273,8 +306,12 @@ func (h *Hub) SendToAccountConversation(accountID uint, conversationID uint, dat
|
||||
if clientIDs, ok := h.rooms[roomName]; ok {
|
||||
for clientID := range clientIDs {
|
||||
if client, ok := h.clients[clientID]; ok {
|
||||
msg := wrapActionCableMessage(client.Identifier, data)
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case client.Send <- data:
|
||||
case client.Send <- msg:
|
||||
default:
|
||||
logger.L().Warnf("ws hub: dropping message for slow client %s", clientID)
|
||||
}
|
||||
@@ -291,8 +328,12 @@ func (h *Hub) SendToRoom(room string, data []byte) {
|
||||
if clientIDs, ok := h.rooms[room]; ok {
|
||||
for clientID := range clientIDs {
|
||||
if client, ok := h.clients[clientID]; ok {
|
||||
msg := wrapActionCableMessage(client.Identifier, data)
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case client.Send <- data:
|
||||
case client.Send <- msg:
|
||||
default:
|
||||
logger.L().Warnf("ws hub: dropping message for slow client %s", clientID)
|
||||
}
|
||||
@@ -307,8 +348,12 @@ func (h *Hub) SendToClient(clientID string, data []byte) {
|
||||
defer h.mu.RUnlock()
|
||||
|
||||
if client, ok := h.clients[clientID]; ok {
|
||||
msg := wrapActionCableMessage(client.Identifier, data)
|
||||
if msg == nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case client.Send <- data:
|
||||
case client.Send <- msg:
|
||||
default:
|
||||
logger.L().Warnf("ws hub: dropping message for slow client %s", clientID)
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ const (
|
||||
CommandSubscribe CommandType = "subscribe"
|
||||
CommandUnsubscribe CommandType = "unsubscribe"
|
||||
CommandPing CommandType = "ping"
|
||||
CommandMessage CommandType = "message" // client→channel action (e.g. update_presence)
|
||||
)
|
||||
|
||||
// ServerMessageType — server→client message types
|
||||
@@ -31,11 +32,11 @@ const (
|
||||
// ServerEvent pushes a real-time event to subscribed clients
|
||||
ServerEvent ServerMessageType = "event"
|
||||
// ServerConfirmSubscribe acknowledges a successful subscription
|
||||
ServerConfirmSubscribe ServerMessageType = "confirm_subscribe"
|
||||
ServerConfirmSubscribe ServerMessageType = "confirm_subscription"
|
||||
// ServerConfirmUnsubscribe acknowledges a successful unsubscribe
|
||||
ServerConfirmUnsubscribe ServerMessageType = "confirm_unsubscribe"
|
||||
ServerConfirmUnsubscribe ServerMessageType = "confirm_unsubscribe" // NOTE: ActionCable uses confirm_subscription for both sub and unsub
|
||||
// ServerRejectSubscribe rejects a subscription attempt
|
||||
ServerRejectSubscribe ServerMessageType = "reject_subscribe"
|
||||
ServerRejectSubscribe ServerMessageType = "reject_subscription"
|
||||
// ServerPing is a heartbeat response
|
||||
ServerPing ServerMessageType = "ping"
|
||||
// ServerWelcome is sent immediately upon connection
|
||||
@@ -66,6 +67,7 @@ type ChannelIdentifier struct {
|
||||
const (
|
||||
ChannelAccount = "AccountChannel"
|
||||
ChannelConversation = "ConversationChannel"
|
||||
ChannelRoom = "RoomChannel" // Chatwoot single-subscription channel
|
||||
)
|
||||
|
||||
// --- Server → Client Frames ---
|
||||
@@ -158,5 +160,5 @@ const (
|
||||
|
||||
const (
|
||||
// PingInterval is how often the server sends ping frames to detect dead connections.
|
||||
PingInterval = 30 // seconds
|
||||
PingInterval = 5 // seconds — must be < ActionCable staleThreshold (6s) to avoid reconnect loops
|
||||
)
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
"github.com/ThreeDotsLabs/watermill/message"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
wspkg "github.com/gochat/gochat/internal/ws"
|
||||
|
||||
"github.com/gochat/gochat/pkg/logger"
|
||||
)
|
||||
|
||||
@@ -214,24 +216,26 @@ func (s *Subscriber) forwardToAccountAndConversation(eventType string) func(msg
|
||||
return nil
|
||||
}
|
||||
|
||||
// Build the event frame
|
||||
frame := EventFrame{
|
||||
Type: ServerEvent,
|
||||
Event: eventType,
|
||||
Payload: payload.Data,
|
||||
// Build the WSMessage — the frontend's onReceived handler expects
|
||||
// { event: "...", data: {...} } which matches WSMessage serialization.
|
||||
// Hub.SendToAccount wraps this in ActionCable format:
|
||||
// { identifier: "...", message: { event: "...", data: {...} } }
|
||||
wsMsg := wspkg.WSMessage{
|
||||
Event: eventType,
|
||||
Data: payload.Data,
|
||||
}
|
||||
frameData, err := json.Marshal(frame)
|
||||
msgData, err := json.Marshal(wsMsg)
|
||||
if err != nil {
|
||||
logger.L().Errorf("ws: failed to marshal event frame for %s: %v", eventType, err)
|
||||
logger.L().Errorf("ws: failed to marshal event for %s: %v", eventType, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Push to account room
|
||||
s.hub.SendToAccount(accountID, frameData)
|
||||
s.hub.SendToAccount(accountID, msgData)
|
||||
|
||||
// Also push to conversation room if conversation_id is present
|
||||
if payload.ConversationID > 0 {
|
||||
s.hub.SendToAccountConversation(accountID, payload.ConversationID, frameData)
|
||||
s.hub.SendToAccountConversation(accountID, payload.ConversationID, msgData)
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -254,18 +258,17 @@ func (s *Subscriber) forwardToAccount(eventType string) func(msg *message.Messag
|
||||
return nil
|
||||
}
|
||||
|
||||
frame := EventFrame{
|
||||
Type: ServerEvent,
|
||||
Event: eventType,
|
||||
Payload: payload.Data,
|
||||
wsMsg := wspkg.WSMessage{
|
||||
Event: eventType,
|
||||
Data: payload.Data,
|
||||
}
|
||||
frameData, err := json.Marshal(frame)
|
||||
msgData, err := json.Marshal(wsMsg)
|
||||
if err != nil {
|
||||
logger.L().Errorf("ws: failed to marshal event frame for %s: %v", eventType, err)
|
||||
logger.L().Errorf("ws: failed to marshal event for %s: %v", eventType, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
s.hub.SendToAccount(accountID, frameData)
|
||||
s.hub.SendToAccount(accountID, msgData)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -287,18 +290,17 @@ func (s *Subscriber) forwardToConversation(eventType string) func(msg *message.M
|
||||
return nil
|
||||
}
|
||||
|
||||
frame := EventFrame{
|
||||
Type: ServerEvent,
|
||||
Event: eventType,
|
||||
Payload: payload.Data,
|
||||
wsMsg := wspkg.WSMessage{
|
||||
Event: eventType,
|
||||
Data: payload.Data,
|
||||
}
|
||||
frameData, err := json.Marshal(frame)
|
||||
msgData, err := json.Marshal(wsMsg)
|
||||
if err != nil {
|
||||
logger.L().Errorf("ws: failed to marshal event frame for %s: %v", eventType, err)
|
||||
logger.L().Errorf("ws: failed to marshal event for %s: %v", eventType, err)
|
||||
return nil
|
||||
}
|
||||
|
||||
s.hub.SendToAccountConversation(accountID, conversationID, frameData)
|
||||
s.hub.SendToAccountConversation(accountID, conversationID, msgData)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
+13
-17
@@ -197,18 +197,23 @@ func (a *WSAuthenticator) findContactInboxByPubsubToken(ctx context.Context, pub
|
||||
}
|
||||
|
||||
// extractWSToken pulls the JWT token from websocket upgrade request.
|
||||
// Order of precedence:
|
||||
// 1. 'token' query parameter (browser WebSocket API can't set custom headers)
|
||||
// 2. Authorization header (Bearer token, for non-browser clients)
|
||||
// 3. Sec-WebSocket-Protocol header (some ActionCable-compatible clients)
|
||||
// Matches the HTTP auth middleware behaviour: accepts both 'token' and
|
||||
// 'access-token' query params (browser WebSocket API can't set custom headers),
|
||||
// plus the Authorization header (Bearer token, for non-browser clients).
|
||||
//
|
||||
// NOTE: Sec-WebSocket-Protocol header is NOT used as a JWT source.
|
||||
// ActionCable sets this to "actioncable-v1-json" for sub-protocol
|
||||
// negotiation, not for authentication.
|
||||
func extractWSToken(c *gin.Context) string {
|
||||
// Primary: 'token' query param
|
||||
token := c.Query("token")
|
||||
if token != "" {
|
||||
// Query params (browser WebSocket API compatible)
|
||||
if token := c.Query("token"); token != "" {
|
||||
return token
|
||||
}
|
||||
if token := c.Query("access-token"); token != "" {
|
||||
return token
|
||||
}
|
||||
|
||||
// Fallback: Authorization header
|
||||
// Authorization header (non-browser clients)
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader != "" {
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
@@ -217,15 +222,6 @@ func extractWSToken(c *gin.Context) string {
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Sec-WebSocket-Protocol header (ActionCable convention)
|
||||
proto := c.GetHeader("Sec-WebSocket-Protocol")
|
||||
if proto != "" {
|
||||
token = strings.TrimSpace(proto)
|
||||
if token != "" {
|
||||
return token
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user