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
| """ 双写协调服务 - 生产级实现 保证MySQL、Milvus、MinIO三存储的数据一致性 """
import time import uuid import threading from typing import Optional, List, Dict, Any from dataclasses import dataclass, field from enum import Enum from concurrent.futures import ThreadPoolExecutor, as_completed import logging import traceback
logger = logging.getLogger(__name__)
class WriteOperation(Enum): """写操作类型""" INSERT = "insert" UPDATE = "update" DELETE = "delete" SYNC = "sync"
class ConsistencyLevel(Enum): """一致性等级""" STRONG = "strong" EVENTUAL = "eventual" CAUSAL = "causal"
@dataclass class WriteResult: """写操作结果""" success: bool operation: WriteOperation target: str data_id: str error: Optional[str] = None latency_ms: float = 0
@dataclass class DualWriteResult: """双写操作的聚合结果""" operation_id: str overall_success: bool consistency_achieved: bool results: List[WriteResult] = field(default_factory=list) compensation_needed: bool = False total_latency_ms: float = 0
class DualWriteCoordinator: """ 双写协调器 核心功能: 1. 编排多存储写入顺序 2. 处理部分失败场景 3. 触发补偿机制 4. 保证最终一致性 """ def __init__( self, mysql_client, milvus_client, minio_client, consistency_level: ConsistencyLevel = ConsistencyLevel.EVENTUAL, max_retries: int = 3, retry_delay_base: float = 1.0, enable_compensation_queue: bool = True ): self.mysql = mysql_client self.milvus = milvus_client self.minio = minio_client self.consistency_level = consistency_level self.max_retries = max_retries self.retry_delay_base = retry_delay_base self.enable_compensation_queue = enable_compensation_queue self.compensation_queue = [] self._queue_lock = threading.Lock() self.stats = { 'total_operations': 0, 'successful_operations': 0, 'compensations_triggered': 0, 'avg_latency_ms': 0, } def execute_dual_write( self, operation: WriteOperation, mysql_data: Dict = None, milvus_data: List[Dict] = None, minio_file_path: str = None, minio_file_content: bytes = None, transaction_context: Dict = None ) -> DualWriteResult: """ 执行双写操作 参数: operation: 操作类型 mysql_data: 要写入MySQL的数据字典 milvus_data: 要写入Milvus的数据列表 minio_file_path: MinIO对象路径 minio_file_content: 文件内容字节 transaction_context: 事务上下文(用于日志追踪) """ op_id = str(uuid.uuid4())[:8] start_time = time.time() logger.info(f"[{op_id}] 开始双写操作: {operation.value}") results = [] all_success = True compensation_needed = False try: if operation == WriteOperation.INSERT: results = self._execute_insert( op_id, mysql_data, milvus_data, minio_file_path, minio_file_content ) elif operation == WriteOperation.UPDATE: results = self._execute_update( op_id, mysql_data, milvus_data, minio_file_path, minio_file_content ) elif operation == WriteOperation.DELETE: results = self._execute_delete(op_id, mysql_data, milvus_data, minio_file_path) failed_targets = [r for r in results if not r.success] all_success = len(failed_targets) == 0 if not all_success: compensation_needed = True logger.warning( f"[{op_id}] 部分写入失败: " f"{[f'{r.target}({r.error})' for r in failed_targets]}" ) if self.enable_compensation_queue: self._enqueue_compensation( op_id, operation, mysql_data, milvus_data, minio_file_path, minio_file_content, failed_targets ) except Exception as e: logger.error(f"[{op_id}] 双写异常: {e}\n{traceback.format_exc()}") all_success = False compensation_needed = True results.append(WriteResult( success=False, operation=operation, target="coordinator", data_id=op_id, error=str(e) )) elapsed_ms = (time.time() - start_time) * 1000 self.stats['total_operations'] += 1 if all_success: self.stats['successful_operations'] += 1 result = DualWriteResult( operation_id=op_id, overall_success=all_success, consistency_achieved=all_success or self.consistency_level != ConsistencyLevel.STRONG, results=results, compensation_needed=compensation_needed, total_latency_ms=elapsed_ms ) logger.info( f"[{op_id}] 双写完成: success={all_success}, " f"latency={elapsed_ms:.0f}ms, targets={len(results)}" ) return result def _execute_insert( self, op_id: str, mysql_data: Dict, milvus_data: List[Dict], minio_path: str, minio_content: bytes ) -> List[WriteResult]: """ 执行插入操作(推荐顺序: MinIO → MySQL → Milvus) """ results = [] if minio_path and minio_content: result = self._safe_write( op_id, "minio", WriteOperation.INSERT, lambda: self._upload_to_minio(minio_path, minio_content), data_id=minio_path ) results.append(result) if not result.success: return results if mysql_data: result = self._safe_write( op_id, "mysql", WriteOperation.INSERT, lambda: self._insert_to_mysql(mysql_data), data_id=mysql_data.get('doc_id', '') ) results.append(result) if not result.success: if minio_path: try: self.minio.remove_object('rag-knowledge-base', minio_path) except: pass return results if milvus_data: result = self._safe_write( op_id, "milvus", WriteOperation.INSERT, lambda: self._insert_to_milvus(milvus_data), data_id=mysql_data.get('doc_id', '') if mysql_data else '' ) results.append(result) return results def _safe_write( self, op_id: str, target: str, operation: WriteOperation, write_func, data_id: str, retry: int = 0 ) -> WriteResult: """ 安全执行写操作(带重试) """ start = time.time() try: write_func() latency = (time.time() - start) * 1000 return WriteResult( success=True, operation=operation, target=target, data_id=data_id, latency_ms=latency ) except Exception as e: latency = (time.time() - start) * 1000 if retry < self.max_retries: delay = self.retry_delay_base * (2 ** retry) logger.warning( f"[{op_id}] {target} 写入失败(第{retry+1}次), " f"{delay}s后重试: {e}" ) time.sleep(delay) return self._safe_write( op_id, target, operation, write_func, data_id, retry + 1 ) else: logger.error(f"[{op_id}] {target} 写入最终失败: {e}") return WriteResult( success=False, operation=operation, target=target, data_id=data_id, error=str(e), latency_ms=latency ) def _upload_to_minio(self, path: str, content: bytes): """上传文件到MinIO""" self.minio.put_object( bucket_name="rag-knowledge-base", object_name=path, data=content, length=len(content) ) def _insert_to_mysql(self, data: Dict): """插入数据到MySQL""" sql = """ INSERT INTO documents (doc_id, title, source_type, business_tag, oss_key, status) VALUES (%s, %s, %s, %s, %s, %s) """ self.mysql.execute(sql, ( data['doc_id'], data['title'], data['source_type'], data.get('business_tag', ''), data.get('oss_key', ''), 'completed' )) def _insert_to_milvus(self, data_list: List[Dict]): """批量插入数据到Milvus""" if data_list: self.milvus.insert( collection_name="rag_vectors", data=data_list ) def _enqueue_compensation( self, op_id: str, operation: WriteOperation, mysql_data: Dict, milvus_data: List[Dict], minio_path: str, minio_content: bytes, failed_targets: List[WriteResult] ): """将失败操作加入补偿队列""" with self._queue_lock: compensation_item = { 'operation_id': op_id, 'operation': operation, 'mysql_data': mysql_data, 'milvus_data': milvus_data, 'minio_path': minio_path, 'minio_content': minio_content, 'failed_targets': [t.target for t in failed_targets], 'created_at': time.time(), 'retry_count': 0 } self.compensation_queue.append(compensation_item) self.stats['compensations_triggered'] += 1 logger.info(f"[{op_id}] 已加入补偿队列, 当前队列长度: {len(self.compensation_queue)}") def process_compensation_queue(self, max_items: int = 100): """ 处理补偿队列中的失败操作 应该由后台定时任务调用 """ with self._queue_lock: items_to_process = self.compensation_queue[:max_items] self.compensation_queue = self.compensation_queue[max_items:] processed = 0 success_count = 0 for item in items_to_process: if item['retry_count'] >= self.max_retries: logger.error( f"补偿操作达到最大重试次数, 放弃: {item['operation_id']}" ) continue item['retry_count'] += 1 try: result = self.execute_dual_write( operation=item['operation'], mysql_data=item['mysql_data'], milvus_data=item['milvus_data'], minio_file_path=item['minio_path'], minio_file_content=item['minio_content'] ) if result.overall_success: success_count += 1 logger.info(f"补偿成功: {item['operation_id']}") else: with self._queue_lock: self.compensation_queue.append(item) except Exception as e: logger.error(f"补偿执行异常: {item['operation_id']}, {e}") with self._queue_lock: self.compensation_queue.append(item) processed += 1 logger.info( f"补偿队列处理完成: 处理={processed}, 成功={success_count}, " f"剩余队列长度={len(self.compensation_queue)}" ) return {'processed': processed, 'success': success_count} def get_statistics(self) -> Dict: """获取统计信息""" return { **self.stats, 'compensation_queue_size': len(self.compensation_queue), 'success_rate': ( self.stats['successful_operations'] / max(1, self.stats['total_operations']) * 100 ) }
|