From 3ffa8c41f7b5990c661fbdcc791f0bbc80e7eeea Mon Sep 17 00:00:00 2001 From: xiaoxixi Date: Tue, 28 Apr 2026 22:13:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(storage):=20=E6=B7=BB=E5=8A=A0=E5=86=99?= =?UTF-8?q?=E5=85=A5=E9=87=8D=E8=AF=95=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/storage/mod.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/storage/mod.rs b/src/storage/mod.rs index bf54ec8..7c59c4c 100644 --- a/src/storage/mod.rs +++ b/src/storage/mod.rs @@ -5,6 +5,7 @@ pub mod message; pub use error::StorageError; use sqlx::{Pool, Row, Sqlite, SqlitePool}; +use tokio::time::{sleep, Duration}; use std::path::Path; pub struct Storage { @@ -334,4 +335,29 @@ impl Storage { .await?; Ok(()) } + + /// 追加消息,带重试逻辑 + /// 重试 3 次(100/200/300ms 退避),仍失败返回错误 + pub async fn append_message_with_retry( + &self, + session_id: &str, + msg: &crate::storage::message::MessageMeta, + ) -> Result { + let delays = [100, 200, 300]; + + for (i, delay) in delays.iter().enumerate() { + match self.append_message(session_id, msg).await { + Ok(seq) => return Ok(seq), + Err(e) if i < delays.len() - 1 => { + sleep(Duration::from_millis(*delay)).await; + tracing::warn!("Storage write failed, retrying: {}", e); + } + Err(e) => { + tracing::error!("Storage write failed after retries: {}", e); + return Err(e); + } + } + } + unreachable!() + } }