refactor(messaging): shift sequence generation responsibility to database transactions
All checks were successful
Build Backend / build (push) Successful in 1m59s
Build Backend / build-docker (push) Successful in 1m20s

Move the responsibility of sequence (`seq`) allocation from the application/cache layer to the database layer to ensure absolute consistency. Previously, sequences were pre-allocated via Redis/Lua, which introduced complexity in managing synchronization between the cache and the database.

Key changes:
- Implement `CreateMessageWithSeq` in `message_repo.go` using `SELECT FOR UPDATE` to lock the conversation row and atomically increment the `last_seq` within a single transaction.
- Simplify `SeqBufferManager` by removing the complex local buffering and Lua-based pre-allocation logic, reverting to a simpler model.
- Update `chat_service.go`, `group_service.go`, and `message_service.go` to remove manual sequence retrieval, relying instead on the repository's transactional allocation.
- Introduce `SyncConvSeq` in `conversation_cache.go` to perform "write-through" updates to Redis, ensuring the cache remains synchronized with the database's source of truth.
- Improve cold-start handling in `conversation_cache.go` with a new `syncSeqLua` script to prevent stale sequence reads.
This commit is contained in:
2026-05-25 14:51:46 +08:00
parent 2748c80095
commit 2084473fb5
6 changed files with 145 additions and 376 deletions

View File

@@ -2,7 +2,6 @@ package service
import (
"context"
"fmt"
"time"
"with_you/internal/cache"
@@ -88,21 +87,17 @@ func (s *MessageService) SendMessage(ctx context.Context, senderID, receiverID s
Status: model.MessageStatusNormal,
}
// 从 Redis 获取下一个 seq
if s.conversationCache != nil {
seq, seqErr := s.conversationCache.GetNextSeqWithGroup(context.Background(), conv.ID, false)
if seqErr != nil {
return nil, fmt.Errorf("failed to get next seq for conversation %s: %w", conv.ID, seqErr)
}
msg.Seq = seq
}
// 使用事务创建消息并更新seq
// 事务内原子分配 seq + 创建消息DB 是 seq 唯一来源)
err = s.messageRepo.CreateMessageWithSeq(msg)
if err != nil {
return nil, err
}
// 写透 seq 到 Redis保持缓存与 DB 一致
if s.conversationCache != nil {
s.conversationCache.SyncConvSeq(context.Background(), conv.ID, msg.Seq)
}
// 新消息会改变分页结果,先失效分页缓存,避免读到旧列表
if s.conversationCache != nil {
s.conversationCache.InvalidateMessagePages(conv.ID)