refactor(message): implement atomic message merging and patching to prevent race conditions
Some checks failed
Frontend CI / ota-ios (push) Successful in 1m11s
Frontend CI / ota-android (push) Successful in 2m20s
Frontend CI / build-and-push-web (push) Successful in 3m55s
Frontend CI / build-android-apk (push) Failing after 9m29s

Introduce `mergeMessages` and `patchMessages` to the message store to handle
updates atomically within Zustand's `set` callback. This replaces manual
read-modify-write patterns in services, preventing message loss during
concurrent WebSocket updates and synchronization processes.

- Add `mergeMessages` for atomic merging of new messages into existing lists
- Add `patchMessages` for efficient field updates (e.g., sender info, status)
- Update `MessageSendService`, `MessageSyncService`, and `WSMessageHandler`
  to use these new atomic operations
- Remove reliance on external `mergeMessagesById` in service layers to
  ensure state consistency
This commit is contained in:
2026-05-25 01:44:23 +08:00
parent 7a17323e8d
commit f4db4eb1ed
4 changed files with 86 additions and 89 deletions

View File

@@ -7,7 +7,7 @@ import type { MessageResponse, MessageSegment, ConversationResponse } from '../.
import { messageService } from '@/services/message';
import { messageRepository } from '@/database';
import type { IMessageSendService } from '../types';
import { useMessageStore, mergeMessagesById } from '../store';
import { useMessageStore } from '../store';
export class MessageSendService implements IMessageSendService {
private getCurrentUserId: () => string | null;
@@ -36,8 +36,7 @@ export class MessageSendService implements IMessageSendService {
if (response) {
const currentUserId = this.getCurrentUserId();
// 添加到本地消息列表
const existingMessages = store.getMessages(conversationId);
// 原子性合并新消息到内存(防止并发 WS 消息丢失)
const newMessage: MessageResponse = {
id: response.id,
conversation_id: conversationId,
@@ -48,8 +47,7 @@ export class MessageSendService implements IMessageSendService {
status: 'normal',
};
const updatedMessages = mergeMessagesById(existingMessages, [newMessage]);
store.setMessages(conversationId, updatedMessages);
store.mergeMessages(conversationId, [newMessage]);
// 更新会话最后消息
this.updateConversationWithNewMessage(conversationId, newMessage);