1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
| class ReadStatusService { constructor(databaseService, cacheService, messageQueue) { this.db = databaseService; this.cache = cacheService; this.mq = messageQueue;
this.batchSize = 1000; this.batchTimeout = 5000; this.pendingBatch = new Map();
this.initializeBatchProcessor(); }
async initializeReadStatus(messageId, groupMembers, senderId) { try { const statusRecords = groupMembers.map(member => ({ message_id: messageId, user_id: member.userId, is_read: member.userId === senderId ? 1 : 0, read_at: member.userId === senderId ? new Date() : null, created_at: new Date() }));
await this.db.batchInsert('message_read_status', statusRecords);
const readCount = senderId ? 1 : 0; const totalCount = groupMembers.length;
await this.db.insert('message_read_summary', { message_id: messageId, total_count: totalCount, read_count: readCount, unread_count: totalCount - readCount, last_read_at: senderId ? new Date() : null });
await this.initializeReadStatusCache(messageId, statusRecords);
console.log(`已初始化消息${messageId}的已读状态,共${totalCount}人`);
} catch (error) { console.error('初始化已读状态失败:', error); throw error; } }
async markAsRead(messageId, userId) { try { const currentStatus = await this.getReadStatus(messageId, userId); if (currentStatus && currentStatus.is_read) { return; }
const readTime = new Date();
const updateResult = await this.db.update( 'message_read_status', { is_read: 1, read_at: readTime, updated_at: readTime }, { message_id: messageId, user_id: userId, is_read: 0 } );
if (updateResult.affectedRows > 0) { await this.updateReadSummary(messageId, 1);
await this.updateReadStatusCache(messageId, userId, true, readTime);
this.mq.publish('read_status.updated', { messageId: messageId, userId: userId, isRead: true, readAt: readTime });
return true; }
return false;
} catch (error) { console.error('标记已读失败:', error); throw error; } }
async batchMarkAsRead(messageIds, userId, transaction = null) { const trx = transaction || this.db;
try { const readTime = new Date();
const updateSql = ` UPDATE message_read_status SET is_read = 1, read_at = ?, updated_at = ? WHERE message_id IN (${messageIds.map(() => '?').join(',')}) AND user_id = ? AND is_read = 0 `;
const updateResult = await trx.query(updateSql, [ readTime, readTime, ...messageIds, userId ]);
if (updateResult.affectedRows > 0) { const summaryUpdatePromises = messageIds.map(messageId => this.updateReadSummary(messageId, 1, trx) ); await Promise.all(summaryUpdatePromises);
const cacheUpdatePromises = messageIds.map(messageId => this.updateReadStatusCache(messageId, userId, true, readTime) ); await Promise.all(cacheUpdatePromises);
this.mq.publish('read_status.batch_updated', { messageIds: messageIds, userId: userId, readAt: readTime, count: updateResult.affectedRows }); }
return updateResult.affectedRows;
} catch (error) { console.error('批量标记已读失败:', error); throw error; } }
async getReadStatusSummary(messageId) { try { const cacheKey = `read_summary:${messageId}`; let summary = await this.cache.get(cacheKey);
if (!summary) { summary = await this.db.selectOne( 'message_read_summary', { message_id: messageId } );
if (!summary) { summary = await this.calculateReadSummary(messageId); }
await this.cache.set(cacheKey, summary, 300); }
return { messageId: messageId, totalCount: summary.total_count, readCount: summary.read_count, unreadCount: summary.unread_count, lastReadAt: summary.last_read_at, readUsers: await this.getReadUsers(messageId) };
} catch (error) { console.error('获取已读状态汇总失败:', error); throw error; } }
async calculateReadSummary(messageId) { try { const sql = ` SELECT COUNT(*) as total_count, SUM(CASE WHEN is_read = 1 THEN 1 ELSE 0 END) as read_count, SUM(CASE WHEN is_read = 0 THEN 1 ELSE 0 END) as unread_count, MAX(read_at) as last_read_at FROM message_read_status WHERE message_id = ? `;
const result = await this.db.query(sql, [messageId]); const summary = result[0];
await this.db.insertOrUpdate('message_read_summary', { message_id: messageId, total_count: summary.total_count, read_count: summary.read_count, unread_count: summary.unread_count, last_read_at: summary.last_read_at });
return summary;
} catch (error) { console.error('计算已读状态汇总失败:', error); throw error; } }
async getReadUsers(messageId, limit = 100) { try { const cacheKey = `read_users:${messageId}`; let readUsers = await this.cache.get(cacheKey);
if (!readUsers) { const sql = ` SELECT mrs.user_id, mrs.read_at, u.username, u.avatar_url FROM message_read_status mrs LEFT JOIN users u ON mrs.user_id = u.user_id WHERE mrs.message_id = ? AND mrs.is_read = 1 ORDER BY mrs.read_at ASC LIMIT ? `;
readUsers = await this.db.query(sql, [messageId, limit]);
await this.cache.set(cacheKey, readUsers, 60); }
return readUsers;
} catch (error) { console.error('获取已读用户列表失败:', error); return []; } }
async getUserUnreadMessages(userId, limit = 100) { try { const sql = ` SELECT m.message_id, m.group_id, m.sender_id, m.content, m.created_at, mrs.created_at as status_created_at FROM message_read_status mrs JOIN messages m ON mrs.message_id = m.message_id WHERE mrs.user_id = ? AND mrs.is_read = 0 AND m.is_deleted = 0 ORDER BY m.created_at DESC LIMIT ? `;
return await this.db.query(sql, [userId, limit]);
} catch (error) { console.error('获取用户未读消息失败:', error); return []; } }
async updateReadSummary(messageId, readCountDelta, transaction = null) { const trx = transaction || this.db;
try { const sql = ` UPDATE message_read_summary SET read_count = read_count + ?, unread_count = unread_count - ?, last_read_at = CASE WHEN ? > 0 THEN NOW() ELSE last_read_at END, updated_at = NOW() WHERE message_id = ? `;
await trx.query(sql, [readCountDelta, readCountDelta, readCountDelta, messageId]);
await this.cache.delete(`read_summary:${messageId}`); await this.cache.delete(`read_users:${messageId}`);
} catch (error) { console.error('更新已读状态汇总失败:', error); throw error; } }
async initializeReadStatusCache(messageId, statusRecords) { try { const pipeline = this.cache.pipeline();
statusRecords.forEach(record => { const userStatusKey = `read_status:${messageId}:${record.user_id}`; pipeline.setex(userStatusKey, 3600, JSON.stringify({ isRead: record.is_read === 1, readAt: record.read_at })); });
const readCount = statusRecords.filter(r => r.is_read === 1).length; const summaryKey = `read_summary:${messageId}`; pipeline.setex(summaryKey, 300, JSON.stringify({ total_count: statusRecords.length, read_count: readCount, unread_count: statusRecords.length - readCount, last_read_at: statusRecords.find(r => r.is_read === 1)?.read_at || null }));
await pipeline.exec();
} catch (error) { console.error('初始化已读状态缓存失败:', error); } }
async updateReadStatusCache(messageId, userId, isRead, readAt = null) { try { const userStatusKey = `read_status:${messageId}:${userId}`;
await this.cache.setex(userStatusKey, 3600, JSON.stringify({ isRead: isRead, readAt: readAt }));
await this.cache.delete(`read_summary:${messageId}`); await this.cache.delete(`read_users:${messageId}`);
} catch (error) { console.error('更新已读状态缓存失败:', error); } }
async getReadStatus(messageId, userId) { try { const cacheKey = `read_status:${messageId}:${userId}`; let status = await this.cache.get(cacheKey);
if (status) { return JSON.parse(status); }
const dbStatus = await this.db.selectOne( 'message_read_status', { message_id: messageId, user_id: userId } );
if (dbStatus) { const statusData = { isRead: dbStatus.is_read === 1, readAt: dbStatus.read_at };
await this.cache.setex(cacheKey, 3600, JSON.stringify(statusData));
return statusData; }
return null;
} catch (error) { console.error('获取已读状态失败:', error); return null; } }
initializeBatchProcessor() { setInterval(() => { this.processPendingBatches(); }, this.batchTimeout); }
async processPendingBatches() { for (const [batchKey, batch] of this.pendingBatch.entries()) { if (batch.items.length >= this.batchSize || Date.now() - batch.createdAt >= this.batchTimeout) {
try { await this.executeBatch(batch); this.pendingBatch.delete(batchKey); } catch (error) { console.error('执行批处理失败:', error); } } } }
async executeBatch(batch) { switch (batch.type) { case 'mark_read': await this.executeBatchMarkRead(batch.items); break; case 'update_summary': await this.executeBatchUpdateSummary(batch.items); break; default: console.warn('未知的批处理类型:', batch.type); } }
async executeBatchMarkRead(items) { const groupedByMessage = items.reduce((groups, item) => { if (!groups[item.messageId]) { groups[item.messageId] = []; } groups[item.messageId].push(item.userId); return groups; }, {});
for (const [messageId, userIds] of Object.entries(groupedByMessage)) { await this.batchMarkAsRead([messageId], userIds); } }
async cleanupExpiredStatus(expiredThreshold) { try { const deleteStatusSql = ` DELETE mrs FROM message_read_status mrs JOIN messages m ON mrs.message_id = m.message_id WHERE m.created_at < ? `;
const statusResult = await this.db.query(deleteStatusSql, [new Date(expiredThreshold)]);
const deleteSummarySql = ` DELETE mrs FROM message_read_summary mrs JOIN messages m ON mrs.message_id = m.message_id WHERE m.created_at < ? `;
const summaryResult = await this.db.query(deleteSummarySql, [new Date(expiredThreshold)]);
console.log(`已清理${statusResult.affectedRows}条状态记录,${summaryResult.affectedRows}条汇总记录`);
} catch (error) { console.error('清理过期数据失败:', error); throw error; } } }
|