合并 main:同步聊天、风控诊断与迁移基线
This commit is contained in:
commit
a6c0d36ee9
89 files changed
+2974
-365
No files matched your search
@@ -22,6 +22,12 @@ type Repository interface {
|
||||
UpdateMessageType(ctx context.Context, cookieID, key, messageType string) error
|
||||
// UpdateMessageStatus 更新外发消息状态并返回最新消息。
|
||||
UpdateMessageStatus(ctx context.Context, cookieID, key, status string) (*db.ChatMessage, error)
|
||||
// CountUnreadUserMessages 返回当前会话中非系统入站消息的未读数量。
|
||||
CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error)
|
||||
// MarkMessageRead 根据平台回执标记指定出站消息已读。
|
||||
MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*db.ChatMessage, error)
|
||||
// MarkLatestOutgoingRead 在回执缺失消息键时标记会话最近一条未读出站消息。
|
||||
MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*db.ChatMessage, error)
|
||||
}
|
||||
|
||||
// storeRepository 将聚合 Store 的聊天相关 repository 适配为窄接口。
|
||||
@@ -65,6 +71,21 @@ func (r storeRepository) UpdateMessageStatus(ctx context.Context, cookieID, key,
|
||||
return r.store.Chats.UpdateMessageStatus(ctx, cookieID, key, status)
|
||||
}
|
||||
|
||||
// CountUnreadUserMessages 委托消息级真实用户未读数统计。
|
||||
func (r storeRepository) CountUnreadUserMessages(ctx context.Context, cookieID, chatID string) (int, error) {
|
||||
return r.store.Chats.CountUnreadUserMessages(ctx, cookieID, chatID)
|
||||
}
|
||||
|
||||
// MarkMessageRead 委托指定出站消息的已读回执写入。
|
||||
func (r storeRepository) MarkMessageRead(ctx context.Context, cookieID, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
return r.store.Chats.MarkMessageRead(ctx, cookieID, key, readAt)
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 委托会话级出站消息已读回退写入。
|
||||
func (r storeRepository) MarkLatestOutgoingRead(ctx context.Context, cookieID, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
return r.store.Chats.MarkLatestOutgoingRead(ctx, cookieID, chatID, readAt)
|
||||
}
|
||||
|
||||
// newStoreRepository 从完整 Store 构造聊天服务使用的窄 repository。
|
||||
func newStoreRepository(store *db.Store) Repository {
|
||||
if store == nil || store.Cookies == nil || store.Chats == nil {
|
||||
|
||||
@@ -42,6 +42,21 @@ func (*fakeRepository) UpdateMessageStatus(_ context.Context, _ string, _ string
|
||||
return &db.ChatMessage{Status: status}, nil
|
||||
}
|
||||
|
||||
// CountUnreadUserMessages 为窄仓储测试提供空的真实用户未读统计结果。
|
||||
func (*fakeRepository) CountUnreadUserMessages(context.Context, string, string) (int, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// MarkMessageRead 为窄仓储测试模拟指定出站消息的已读更新。
|
||||
func (*fakeRepository) MarkMessageRead(_ context.Context, _ string, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
return &db.ChatMessage{MessageKey: key, ReadStatus: 2, ReadAt: readAt}, nil
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 为窄仓储测试模拟缺失消息键时的会话级回退更新。
|
||||
func (*fakeRepository) MarkLatestOutgoingRead(_ context.Context, _ string, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
return &db.ChatMessage{ChatID: chatID, ReadStatus: 2, ReadAt: readAt}, nil
|
||||
}
|
||||
|
||||
// TestServiceUsesNarrowRepository 验证聊天服务可以脱离完整 db.Store 运行。
|
||||
func TestServiceUsesNarrowRepository(t *testing.T) {
|
||||
// repository 是只实现聊天所需方法的内存替身。
|
||||
|
||||
+118
-8
@@ -145,10 +145,12 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
if lastMessageAt <= 0 {
|
||||
lastMessageAt = modifyTime
|
||||
}
|
||||
// session 保存会话,供当前处理流程使用
|
||||
// unreadCount 是平台红点与本地真实用户消息状态归一后的展示数量。
|
||||
unreadCount := s.conversationUnreadCount(ctx, accountID, cid, peerID, conv, last, summary)
|
||||
// session 保存待写入的非敏感会话摘要及归一后的未读数量。
|
||||
session := db.ChatSession{CookieID: accountID, ChatID: cid, BuyerID: peerID, BuyerName: peerName, BuyerAvatar: avatar,
|
||||
ItemID: cleanNilString(ext["itemId"]), ItemTitle: cleanNilString(ext["itemTitle"]), LastMessage: summary,
|
||||
LastMessageAt: lastMessageAt, UnreadCount: int(int64Value(conv["redPoint"]))}
|
||||
LastMessageAt: lastMessageAt, UnreadCount: unreadCount}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := s.repository.UpsertSession(ctx, session); err != nil {
|
||||
return page, err
|
||||
@@ -161,7 +163,79 @@ func (s *Service) RecordConversationPage(ctx context.Context, accountID, myID st
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// invalidNicknames 保存invalidNicknames,供当前处理流程使用
|
||||
// conversationUnreadCount 以平台红点为上限,并用本地真实用户消息已读状态排除系统卡片。
|
||||
func (s *Service) conversationUnreadCount(ctx context.Context, accountID, chatID, peerID string, conv, last map[string]any, summary string) int {
|
||||
// official 保存平台会话红点;负数响应按零处理。
|
||||
official := int(int64Value(conv["redPoint"]))
|
||||
if official < 0 {
|
||||
official = 0
|
||||
}
|
||||
if official == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// local、err 保存本地真实用户未读数及查询错误;查询失败时回退平台红点。
|
||||
if local, err := s.repository.CountUnreadUserMessages(ctx, accountID, chatID); err == nil && local > 0 {
|
||||
// A stale local event must not make the badge exceed the official
|
||||
// conversation signal. In normal operation these values are equal.
|
||||
if local > official {
|
||||
return official
|
||||
}
|
||||
return local
|
||||
}
|
||||
|
||||
if !historyMessageIsSystem(last, summary) {
|
||||
// No message-level row exists yet (for example immediately after a
|
||||
// fresh login), so retain the official count as a safe fallback.
|
||||
return official
|
||||
}
|
||||
|
||||
// 闲小蜜会话只包含平台消息,永远不能制造用户红点。
|
||||
if strings.TrimSuffix(strings.TrimSpace(peerID), "@goofish") == "1400" {
|
||||
return 0
|
||||
}
|
||||
|
||||
// The official last-message envelope exposes unreadCount/readStatus for
|
||||
// that item. Subtract that system portion from redPoint; when older server
|
||||
// responses omit the fields, conservatively remove one system item.
|
||||
// systemUnread 保存最后一条系统消息在官方会话红点中的未读份额。
|
||||
systemUnread := int(int64Value(last["unreadCount"]))
|
||||
// readStatus 保存最后一条系统消息的协议已读状态,缺少未读数时用于保守扣除。
|
||||
readStatus := int64Value(last["readStatus"])
|
||||
if systemUnread <= 0 && readStatus != 2 {
|
||||
systemUnread = 1
|
||||
}
|
||||
if systemUnread > official {
|
||||
systemUnread = official
|
||||
}
|
||||
return official - systemUnread
|
||||
}
|
||||
|
||||
// historyMessageIsSystem 判断平台会话摘要是否代表系统消息,避免系统卡片制造用户未读。
|
||||
func historyMessageIsSystem(last map[string]any, summary string) bool {
|
||||
// extension 保存会话末条消息的扩展字段,包含协议发送者身份。
|
||||
extension := mapValue(last["extension"])
|
||||
// senderID 保存协议发送者标识,供系统账号和系统卡片分类使用。
|
||||
senderID := cleanNilString(extension["senderUserId"])
|
||||
// content 保存解码后的系统卡片内容;解码失败时保留空对象供后续摘要规则判断。
|
||||
content := map[string]any{}
|
||||
// contentMap、ok 保存消息内容对象及其类型断言结果,非对象响应无需继续读取卡片字段。
|
||||
if contentMap, ok := last["content"].(map[string]any); ok {
|
||||
// custom、ok 保存自定义消息容器及其类型断言结果,卡片编码仅存在于该容器。
|
||||
if custom, ok := contentMap["custom"].(map[string]any); ok {
|
||||
// encoded 保存 Base64 卡片载荷,空载荷代表没有可解码的系统协议内容。
|
||||
if encoded := cleanNilString(custom["data"]); encoded != "" {
|
||||
// raw、err 保存解码后的卡片 JSON 与解码错误;错误时退回摘要分类,且不传播载荷。
|
||||
if raw, err := base64.StdEncoding.DecodeString(encoded); err == nil {
|
||||
_ = json.Unmarshal(raw, &content)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return isOfficialSystemMessage(content, senderID, summary)
|
||||
}
|
||||
|
||||
// invalidNicknames 保存不能作为买家真实昵称持久化的系统展示文本。
|
||||
var invalidNicknames = map[string]struct{}{
|
||||
"交易消息": {}, "系统消息": {}, "卡片消息": {}, "我完成了评价": {}, "对方完成了评价": {},
|
||||
"快给ta一个评价吧~": {}, "卖家已发货": {}, "买家已付款": {}, "买家已确认收货": {},
|
||||
@@ -207,6 +281,7 @@ type Incoming struct {
|
||||
BuyerID string
|
||||
BuyerName string
|
||||
Text string
|
||||
MessageID string
|
||||
ItemID string
|
||||
Raw map[string]any
|
||||
}
|
||||
@@ -308,8 +383,11 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
if sentAt == 0 {
|
||||
sentAt = time.Now().UTC().UnixMilli()
|
||||
}
|
||||
// key 保存key,供当前处理流程使用
|
||||
key := extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||
// key 优先使用引擎提供的稳定平台消息 ID,缺失时再从原始消息递归提取。
|
||||
key := strings.TrimSpace(in.MessageID)
|
||||
if key == "" {
|
||||
key = extractString(in.Raw, "messageId", "message_id", "msgId", "mid", "uuid")
|
||||
}
|
||||
if key == "" {
|
||||
// raw 保存原始,供当前处理流程使用
|
||||
raw, _ := json.Marshal(in.Raw)
|
||||
@@ -334,8 +412,8 @@ func (s *Service) RecordIncoming(ctx context.Context, in Incoming) (*db.ChatMess
|
||||
// message 保存消息,供当前处理流程使用
|
||||
message := db.ChatMessage{MessageKey: key, Direction: "incoming", SenderID: in.BuyerID,
|
||||
SenderName: in.BuyerName, MessageType: messageType, Content: content, Status: "received", SentAt: sentAt}
|
||||
// stored、inserted、err 保存stored、inserted、err,供当前处理流程使用
|
||||
stored, inserted, err := s.repository.SaveMessage(ctx, session, message, true)
|
||||
// stored、inserted、err 保存落库消息、首次插入标识及错误;系统消息永不增加用户红点。
|
||||
stored, inserted, err := s.repository.SaveMessage(ctx, session, message, messageType != "system")
|
||||
if err == nil && inserted {
|
||||
s.Publish(in.AccountID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
@@ -665,7 +743,27 @@ func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status
|
||||
return message, err
|
||||
}
|
||||
|
||||
// randomID 负责randomID相关处理。
|
||||
// MarkOutgoingRead 根据平台回执把指定出站消息标记已读并广播增量事件。
|
||||
func (s *Service) MarkOutgoingRead(ctx context.Context, accountID, key string, readAt int64) (*db.ChatMessage, error) {
|
||||
// message、err 保存已读更新后的消息及持久化错误。
|
||||
message, err := s.repository.MarkMessageRead(ctx, accountID, key, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
// MarkLatestOutgoingRead 在回执未带幂等键时回退标记会话最近待确认的出站消息。
|
||||
func (s *Service) MarkLatestOutgoingRead(ctx context.Context, accountID, chatID string, readAt int64) (*db.ChatMessage, error) {
|
||||
// message、err 保存回退更新后的消息及持久化错误。
|
||||
message, err := s.repository.MarkLatestOutgoingRead(ctx, accountID, chatID, readAt)
|
||||
if err == nil {
|
||||
s.Publish(accountID, Event{Type: "message.updated", Message: message})
|
||||
}
|
||||
return message, err
|
||||
}
|
||||
|
||||
// randomID 生成本地出站消息幂等键的随机后缀;随机源失败时使用时间回退避免阻断发送。
|
||||
func randomID() string {
|
||||
// value 保存值,供当前处理流程使用
|
||||
var value [16]byte
|
||||
@@ -715,6 +813,18 @@ func extractString(value any, keys ...string) string {
|
||||
return text
|
||||
}
|
||||
}
|
||||
case string:
|
||||
// Live WS envelopes often keep extJson/bizTag as an encoded JSON
|
||||
// string. Decode it so messageId is preserved instead of falling
|
||||
// back to a local in-* key.
|
||||
// decoded 保存 extJson/bizTag 解码后的动态对象,供递归查找平台消息键。
|
||||
var decoded any
|
||||
if json.Unmarshal([]byte(x), &decoded) == nil {
|
||||
// text 保存递归命中的非空消息键,命中后立即返回避免生成本地回退键。
|
||||
if text := walk(decoded); text != "" {
|
||||
return text
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -130,7 +130,29 @@ func TestRecordIncomingClassifiesXianxiaomiAndPlaceholder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageImportsHistoricalContacts 负责TestRecordConversation页码ImportsHistoricalContacts相关处理。
|
||||
// TestRecordIncomingExtractsMessageIDFromEncodedExtension 验证嵌套扩展中的平台消息键优先进入实时落库。
|
||||
func TestRecordIncomingExtractsMessageIDFromEncodedExtension(t *testing.T) {
|
||||
// store、cleanup 保存隔离聊天数据库及清理函数,确保消息键提取不依赖其他用例数据。
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
// service 是待测聊天服务,使用上述存储验证实时消息落库。
|
||||
service := New(store)
|
||||
// message、err 保存落库后的消息和处理错误,消息键必须来自编码扩展字段。
|
||||
message, _, err := service.RecordIncoming(context.Background(), Incoming{
|
||||
AccountID: "account-1", ChatID: "live", BuyerID: "peer", BuyerName: "对方", Text: "实时消息",
|
||||
Raw: map[string]any{"1": map[string]any{"10": map[string]any{
|
||||
"extJson": `{"messageId":"live-123"}`,
|
||||
}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if message.MessageKey != "live-123" {
|
||||
t.Fatalf("实时消息未提取平台 messageId: %+v", message)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageImportsHistoricalContacts 验证联系人历史页不会覆盖较新的会话摘要。
|
||||
func TestRecordConversationPageImportsHistoricalContacts(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := chatTestStore(t)
|
||||
@@ -197,6 +219,7 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "singleChatConversation": map[string]any{"cid": "platform@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "900"}}}},
|
||||
map[string]any{"singleChatUserConversation": map[string]any{"visible": float64(1), "modifyTime": float64(123),
|
||||
"singleChatConversation": map[string]any{"cid": "xiaomi@goofish", "pairFirst": "self@goofish", "pairSecond": "0@goofish", "extension": map[string]any{"extUserId": "1400"}},
|
||||
"redPoint": float64(3),
|
||||
"lastMessage": map[string]any{"message": map[string]any{"extension": map[string]any{"senderUserId": "1400@goofish", "reminderTitle": "闲小蜜发来一条新消息"}, "content": map[string]any{"custom": map[string]any{"summary": "邀您填写售后问卷"}}}}}},
|
||||
}}
|
||||
if // err 保存err,供当前处理流程使用
|
||||
@@ -210,12 +233,75 @@ func TestRecordConversationPageHandlesXianxiaomiAndRemovesInvisibleSessions(t *t
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar {
|
||||
if len(rows) != 1 || rows[0].BuyerID != "1400" || rows[0].BuyerName != "闲小蜜" || rows[0].BuyerAvatar != xianxiaomiAvatar || rows[0].UnreadCount != 0 {
|
||||
t.Fatalf("unexpected sessions: %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageSkipsEmptyConversationShells 负责TestRecordConversation页码SkipsEmptyConversationShells相关处理。
|
||||
// TestConversationUnreadCountUsesRedPointButFiltersSystemMessages 验证官方红点不会把系统卡片计为用户未读。
|
||||
func TestConversationUnreadCountUsesRedPointButFiltersSystemMessages(t *testing.T) {
|
||||
// store、cleanup 保存隔离聊天数据库及清理函数,供红点与本地未读数交叉验证。
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
// service 是待测聊天服务,负责按系统消息规则折算会话红点。
|
||||
service := New(store)
|
||||
|
||||
// systemCard 保存模拟交易通知的 Base64 卡片载荷,使末条消息被归类为系统消息。
|
||||
systemCard := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26}`))
|
||||
// systemLast 保存带官方红点和系统未读状态的末条消息协议对象。
|
||||
systemLast := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "[交易通知]", "data": systemCard}},
|
||||
"unreadCount": float64(1), "readStatus": float64(1),
|
||||
}
|
||||
// got 保存扣除系统消息后的用户未读数,系统部分不得显示为用户红点。
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "system-last", "peer", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 2 {
|
||||
t.Fatalf("系统未读未从 redPoint 扣除: got=%d", got)
|
||||
}
|
||||
// got 保存闲小蜜会话的折算未读数;该官方系统账号永远不产生用户红点。
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "xiaomi", "1400", map[string]any{"redPoint": float64(3)}, systemLast, "[交易通知]"); got != 0 {
|
||||
t.Fatalf("闲小蜜全是系统消息时仍显示红点: got=%d", got)
|
||||
}
|
||||
|
||||
// err 保存真实用户消息持久化错误;成功后本地消息级未读数应优先于官方红点。
|
||||
if _, _, err := service.RecordIncoming(context.Background(), Incoming{
|
||||
AccountID: "account-1", ChatID: "real", BuyerID: "peer", BuyerName: "真实用户", Text: "未读消息",
|
||||
MessageID: "real-unread", Raw: map[string]any{"messageId": "real-unread"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// userLast 保存真实用户末条消息协议对象,不含系统卡片字段。
|
||||
userLast := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "未读消息"}},
|
||||
}
|
||||
// got 保存本地记录的真实用户未读数,必须防止较慢官方刷新复活已读红点。
|
||||
if got := service.conversationUnreadCount(context.Background(), "account-1", "real", "peer", map[string]any{"redPoint": float64(3)}, userLast, "未读消息"); got != 1 {
|
||||
t.Fatalf("未使用消息级真实未读数: got=%d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHistoryMessageIsSystem 验证历史卡片载荷和普通用户文本被正确区分,避免误算未读。
|
||||
func TestHistoryMessageIsSystem(t *testing.T) {
|
||||
// encoded 保存模拟交易卡片的 Base64 载荷,触发内容类型的系统消息识别。
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(`{"contentType":26,"dxCard":{}}`))
|
||||
// last 保存待识别的历史末条消息协议对象。
|
||||
last := map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"data": encoded}},
|
||||
}
|
||||
if !historyMessageIsSystem(last, "[我已拍下,待付款]") {
|
||||
t.Fatal("交易卡片应被识别为系统消息")
|
||||
}
|
||||
if historyMessageIsSystem(map[string]any{
|
||||
"extension": map[string]any{"senderUserId": "peer@goofish"},
|
||||
"content": map[string]any{"custom": map[string]any{"summary": "你好"}},
|
||||
}, "你好") {
|
||||
t.Fatal("真实用户文本不应被识别为系统消息")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordConversationPageSkipsEmptyConversationShells 验证空会话壳不会被错误展示为联系人。
|
||||
func TestRecordConversationPageSkipsEmptyConversationShells(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := chatTestStore(t)
|
||||
|
||||
Reference in new issue
Block a user