1#![expect(
2 clippy::result_large_err,
3 reason = "openraft's trait methods return its own StorageError, so its size is not ours to change"
4)]
5
6use std::collections::BTreeMap;
7use std::error;
8use std::fmt;
9use std::fmt::Debug;
10use std::fmt::Formatter;
11use std::io;
12use std::io::Cursor;
13use std::ops::{Bound, RangeBounds};
14use std::path::Path;
15
16use openraft::storage::{LogState, RaftLogReader, RaftSnapshotBuilder, Snapshot};
17use openraft::{
18 BasicNode, Entry, EntryPayload, LogId, OptionalSend, RaftLogId, RaftStorage, SnapshotMeta,
19 StorageError, StorageIOError, StoredMembership, Vote,
20};
21use serde::de::DeserializeOwned;
22use serde::{Deserialize, Serialize};
23use sqlx::sqlite::SqliteJournalMode;
24use sqlx::sqlite::{SqliteConnectOptions, SqlitePool, SqlitePoolOptions};
25use sqlx::{Acquire, SqliteConnection};
26
27use super::{NodeId, Reply, TypeConfig};
28use crate::store::{TaskStore, kv, replica, tasks};
29
30type Err = StorageError<NodeId>;
31
32const APPLIED_KEY: &str = "raft:applied";
33const MEMBERSHIP_KEY: &str = "raft:membership";
34
35fn io<E: error::Error + 'static>(e: E) -> Err {
36 StorageIOError::read(&e).into()
37}
38
39#[expect(
40 clippy::needless_pass_by_value,
41 reason = "map_err passes the error by value"
42)]
43fn io_any(e: anyhow::Error) -> Err {
44 io(io::Error::other(format!("{e:#}")))
45}
46
47#[derive(Serialize, Deserialize)]
49struct SnapshotData {
50 last_applied: Option<LogId<NodeId>>,
51 membership: StoredMembership<NodeId, BasicNode>,
52 tasks: Vec<serde_json::Value>,
53 tables: BTreeMap<String, Vec<serde_json::Value>>,
54 kv: Vec<kv::Row>,
55}
56
57#[derive(Serialize, Deserialize)]
58struct StoredSnapshot {
59 meta: SnapshotMeta<NodeId, BasicNode>,
60 data: Vec<u8>,
61}
62
63#[derive(Clone)]
69pub struct RaftStore {
70 log: SqlitePool,
71 store: TaskStore,
72}
73
74impl Debug for RaftStore {
75 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
76 f.debug_struct("RaftStore")
77 .field("log", &self.log)
78 .finish_non_exhaustive()
79 }
80}
81
82impl RaftStore {
83 pub async fn open(raft_db: &Path, store: TaskStore) -> anyhow::Result<Self> {
84 let options = SqliteConnectOptions::new()
85 .filename(raft_db)
86 .journal_mode(SqliteJournalMode::Wal)
87 .create_if_missing(true);
88 let log = SqlitePoolOptions::new()
89 .max_connections(1)
90 .connect_with(options)
91 .await?;
92 sqlx::query(
93 "CREATE TABLE IF NOT EXISTS log (idx INTEGER PRIMARY KEY, entry TEXT NOT NULL);
94 CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);",
95 )
96 .execute(&log)
97 .await?;
98 Ok(Self { log, store })
99 }
100
101 async fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, Err> {
102 let v: Option<(String,)> = sqlx::query_as("SELECT value FROM meta WHERE key = ?")
103 .bind(key)
104 .fetch_optional(&self.log)
105 .await
106 .map_err(io)?;
107 v.map(|(s,)| serde_json::from_str(&s).map_err(io))
108 .transpose()
109 }
110
111 async fn put<T: Serialize>(&self, key: &str, value: &T) -> Result<(), Err> {
112 let s = serde_json::to_string(value).map_err(io)?;
113 sqlx::query("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)")
114 .bind(key)
115 .bind(s)
116 .execute(&self.log)
117 .await
118 .map_err(io)?;
119 Ok(())
120 }
121
122 async fn state_get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, Err> {
123 let v = self.store.kv_get(key).await.map_err(io_any)?;
124 v.map(|s| serde_json::from_str(&s).map_err(io)).transpose()
125 }
126}
127
128async fn state_put<T: Serialize>(
129 conn: &mut SqliteConnection,
130 now: &str,
131 key: &str,
132 value: &T,
133) -> Result<(), Err> {
134 let s = serde_json::to_string(value).map_err(io)?;
135 kv::set(conn, now, key, &s).await.map_err(io_any)
136}
137
138impl RaftLogReader<TypeConfig> for RaftStore {
139 async fn try_get_log_entries<RB: RangeBounds<u64> + Clone + Debug + OptionalSend>(
140 &mut self,
141 range: RB,
142 ) -> Result<Vec<Entry<TypeConfig>>, Err> {
143 let start = match range.start_bound() {
144 Bound::Included(&s) => s,
145 Bound::Excluded(&s) => s + 1,
146 Bound::Unbounded => 0,
147 };
148 let end = match range.end_bound() {
149 Bound::Included(&e) => e.saturating_add(1),
150 Bound::Excluded(&e) => e,
151 Bound::Unbounded => u64::MAX,
152 };
153 let rows: Vec<(String,)> =
155 sqlx::query_as("SELECT entry FROM log WHERE idx >= ? AND idx < ? ORDER BY idx")
156 .bind(i64::try_from(start).unwrap_or(i64::MAX))
157 .bind(i64::try_from(end).unwrap_or(i64::MAX))
158 .fetch_all(&self.log)
159 .await
160 .map_err(io)?;
161 rows.into_iter()
162 .map(|(s,)| serde_json::from_str(&s).map_err(io))
163 .collect()
164 }
165}
166
167impl RaftSnapshotBuilder<TypeConfig> for RaftStore {
168 async fn build_snapshot(&mut self) -> Result<Snapshot<TypeConfig>, Err> {
169 let (tables, tasks, kv) = self.store.snapshot_rows().await.map_err(io_any)?;
170
171 let snap = SnapshotData {
172 tables,
173 last_applied: self.state_get(APPLIED_KEY).await?,
174 membership: self.state_get(MEMBERSHIP_KEY).await?.unwrap_or_default(),
175 tasks,
176 kv,
177 };
178 let data = serde_json::to_vec(&snap).map_err(io)?;
179 let last = snap.last_applied;
180 let meta = SnapshotMeta {
181 last_log_id: last,
182 last_membership: snap.membership,
183 snapshot_id: last
184 .map(|l| format!("{}-{}", l.leader_id, l.index))
185 .unwrap_or_default(),
186 };
187 self.put(
188 "snapshot",
189 &StoredSnapshot {
190 meta: meta.clone(),
191 data: data.clone(),
192 },
193 )
194 .await?;
195 Ok(Snapshot {
196 meta,
197 snapshot: Box::new(Cursor::new(data)),
198 })
199 }
200}
201
202impl RaftStorage<TypeConfig> for RaftStore {
203 type LogReader = Self;
204 type SnapshotBuilder = Self;
205
206 async fn save_vote(&mut self, vote: &Vote<NodeId>) -> Result<(), Err> {
207 self.put("vote", vote).await
208 }
209
210 async fn read_vote(&mut self) -> Result<Option<Vote<NodeId>>, Err> {
211 self.get("vote").await
212 }
213
214 async fn save_committed(&mut self, committed: Option<LogId<NodeId>>) -> Result<(), Err> {
215 self.put("committed", &committed).await
216 }
217
218 async fn read_committed(&mut self) -> Result<Option<LogId<NodeId>>, Err> {
219 Ok(self
220 .get::<Option<LogId<NodeId>>>("committed")
221 .await?
222 .flatten())
223 }
224
225 async fn get_log_state(&mut self) -> Result<LogState<TypeConfig>, Err> {
226 let purged = self.get::<Option<LogId<NodeId>>>("purged").await?.flatten();
227 let last: Option<(String,)> =
228 sqlx::query_as("SELECT entry FROM log ORDER BY idx DESC LIMIT 1")
229 .fetch_optional(&self.log)
230 .await
231 .map_err(io)?;
232 let last = match last {
233 Some((s,)) => Some(
234 *serde_json::from_str::<Entry<TypeConfig>>(&s)
235 .map_err(io)?
236 .get_log_id(),
237 ),
238 None => purged,
239 };
240 Ok(LogState {
241 last_purged_log_id: purged,
242 last_log_id: last,
243 })
244 }
245
246 async fn get_log_reader(&mut self) -> Self::LogReader {
247 self.clone()
248 }
249
250 async fn append_to_log<I>(&mut self, entries: I) -> Result<(), Err>
251 where
252 I: IntoIterator<Item = Entry<TypeConfig>> + OptionalSend,
253 {
254 let rows = entries
255 .into_iter()
256 .map(|e| {
257 Ok((
258 i64::try_from(e.log_id.index).map_err(io)?,
259 serde_json::to_string(&e).map_err(io)?,
260 ))
261 })
262 .collect::<Result<Vec<_>, Err>>()?;
263 let mut tx = self.log.begin().await.map_err(io)?;
264 for (idx, s) in rows {
265 sqlx::query("INSERT OR REPLACE INTO log (idx, entry) VALUES (?, ?)")
266 .bind(idx)
267 .bind(s)
268 .execute(&mut *tx)
269 .await
270 .map_err(io)?;
271 }
272
273 tx.commit().await.map_err(io)
274 }
275
276 async fn delete_conflict_logs_since(&mut self, log_id: LogId<NodeId>) -> Result<(), Err> {
277 sqlx::query("DELETE FROM log WHERE idx >= ?")
278 .bind(i64::try_from(log_id.index).map_err(io)?)
279 .execute(&self.log)
280 .await
281 .map_err(io)?;
282 Ok(())
283 }
284
285 async fn purge_logs_upto(&mut self, log_id: LogId<NodeId>) -> Result<(), Err> {
286 self.put("purged", &Some(log_id)).await?;
287 sqlx::query("DELETE FROM log WHERE idx <= ?")
288 .bind(i64::try_from(log_id.index).map_err(io)?)
289 .execute(&self.log)
290 .await
291 .map_err(io)?;
292 Ok(())
293 }
294
295 async fn last_applied_state(
296 &mut self,
297 ) -> Result<(Option<LogId<NodeId>>, StoredMembership<NodeId, BasicNode>), Err> {
298 Ok((
299 self.state_get(APPLIED_KEY).await?,
300 self.state_get(MEMBERSHIP_KEY).await?.unwrap_or_default(),
301 ))
302 }
303
304 async fn apply_to_state_machine(
305 &mut self,
306 entries: &[Entry<TypeConfig>],
307 ) -> Result<Vec<Reply>, Err> {
308 let mut tx = self.store.begin_write().await.map_err(io)?;
309 let mut out = Vec::with_capacity(entries.len());
310 for e in entries {
311 let reply = match &e.payload {
312 EntryPayload::Blank => Reply::Done,
313 EntryPayload::Normal(req) => {
314 let mut sp = tx.begin().await.map_err(io)?;
316 match req.cmd.clone().apply(&mut sp, &req.now, true).await {
317 Ok(reply) => {
318 sp.commit().await.map_err(io)?;
319 reply
320 }
321 Err(err) => {
322 sp.rollback().await.map_err(io)?;
323 Reply::Err(format!("{err:#}"))
324 }
325 }
326 }
327 EntryPayload::Membership(m) => {
328 let stored = StoredMembership::new(Some(e.log_id), m.clone());
329 state_put(&mut tx, "", MEMBERSHIP_KEY, &stored).await?;
330 Reply::Done
331 }
332 };
333 state_put(&mut tx, "", APPLIED_KEY, &e.log_id).await?;
334 out.push(reply);
335 }
336
337 tx.commit().await.map_err(io)?;
338 Ok(out)
339 }
340
341 async fn get_snapshot_builder(&mut self) -> Self::SnapshotBuilder {
342 self.clone()
343 }
344
345 async fn begin_receiving_snapshot(&mut self) -> Result<Box<Cursor<Vec<u8>>>, Err> {
346 Ok(Box::new(Cursor::new(Vec::new())))
347 }
348
349 async fn install_snapshot(
350 &mut self,
351 meta: &SnapshotMeta<NodeId, BasicNode>,
352 snapshot: Box<Cursor<Vec<u8>>>,
353 ) -> Result<(), Err> {
354 let data = snapshot.into_inner();
355 let snap: SnapshotData = serde_json::from_slice(&data).map_err(io)?;
356 let mut tx = self.store.begin_write().await.map_err(io)?;
357 tasks::replace_replicated(&mut tx, &snap.tasks)
358 .await
359 .map_err(io_any)?;
360 for table in replica::TABLES {
361 let rows = snap
362 .tables
363 .get(table)
364 .map(Vec::as_slice)
365 .unwrap_or_default();
366 replica::replace_table(&mut tx, table, rows)
367 .await
368 .map_err(io_any)?;
369 }
370 kv::replace_replicated(&mut tx, &snap.kv)
371 .await
372 .map_err(io_any)?;
373 state_put(&mut tx, "", APPLIED_KEY, &meta.last_log_id).await?;
374 state_put(&mut tx, "", MEMBERSHIP_KEY, &meta.last_membership).await?;
375 tx.commit().await.map_err(io)?;
376 self.put(
377 "snapshot",
378 &StoredSnapshot {
379 meta: meta.clone(),
380 data,
381 },
382 )
383 .await
384 }
385
386 async fn get_current_snapshot(&mut self) -> Result<Option<Snapshot<TypeConfig>>, Err> {
387 let s: Option<StoredSnapshot> = self.get("snapshot").await?;
388 Ok(s.map(|s| Snapshot {
389 meta: s.meta,
390 snapshot: Box::new(Cursor::new(s.data)),
391 }))
392 }
393}