Skip to main content

orch/store/cluster/
storage.rs

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