multicast_codemode_local/
store.rs1use std::fs::OpenOptions;
2use std::path::Path;
3use std::sync::Mutex;
4
5use async_trait::async_trait;
6use multicast_codemode::{
7 ArtifactRef, ArtifactStore, ExecutionCheckpoint, ExecutionState, RuntimeStore, Snippet,
8};
9use rusqlite::{Connection, OptionalExtension, params};
10use serde::{Serialize, de::DeserializeOwned};
11use serde_json::Value;
12use sha2::{Digest, Sha256};
13
14pub struct DurableStore {
20 connection: Mutex<Connection>,
21}
22
23impl DurableStore {
24 pub fn open(path: impl AsRef<Path>) -> Result<Self, String> {
26 let path = path.as_ref();
27 if path.as_os_str().is_empty() || path == Path::new(":memory:") {
28 return Err("Durable store requires a file database".into());
29 }
30 let mut options = OpenOptions::new();
31 options.create(true).truncate(false).read(true).write(true);
32 #[cfg(unix)]
33 {
34 use std::os::unix::fs::OpenOptionsExt;
35 options.mode(0o600);
36 }
37 drop(options.open(path).map_err(error)?);
38 let connection = Connection::open(path).map_err(error)?;
39 connection
40 .busy_timeout(std::time::Duration::ZERO)
41 .map_err(error)?;
42 connection
43 .execute_batch(
44 "PRAGMA locking_mode=EXCLUSIVE; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
45 BEGIN EXCLUSIVE;
46 CREATE TABLE IF NOT EXISTS records (
47 kind TEXT NOT NULL, key TEXT NOT NULL, owner TEXT NOT NULL,
48 data BLOB NOT NULL, PRIMARY KEY(kind, key, owner));
49 CREATE TABLE IF NOT EXISTS checkpoints (
50 id TEXT PRIMARY KEY, identity TEXT NOT NULL, heap BLOB NOT NULL);
51 COMMIT;",
52 )
53 .map_err(|e| {
54 format!("Durable store ownership unavailable or initialization failed: {e}")
55 })?;
56 Ok(Self {
57 connection: Mutex::new(connection),
58 })
59 }
60
61 fn get<T: DeserializeOwned>(
62 &self,
63 kind: &str,
64 key: &str,
65 owner: &str,
66 ) -> Result<Option<T>, String> {
67 let data: Option<Vec<u8>> = self
68 .connection
69 .lock()
70 .map_err(error)?
71 .query_row(
72 "SELECT data FROM records WHERE kind=?1 AND key=?2 AND owner=?3",
73 params![kind, key, owner],
74 |row| row.get(0),
75 )
76 .optional()
77 .map_err(error)?;
78 data.map(|bytes| serde_json::from_slice(&bytes).map_err(error))
79 .transpose()
80 }
81
82 fn put<T: Serialize>(
83 &self,
84 kind: &str,
85 key: &str,
86 owner: &str,
87 value: &T,
88 ) -> Result<(), String> {
89 let data = serde_json::to_vec(value).map_err(error)?;
90 self.connection
91 .lock()
92 .map_err(error)?
93 .execute(
94 "INSERT OR REPLACE INTO records VALUES (?1, ?2, ?3, ?4)",
95 params![kind, key, owner, data],
96 )
97 .map_err(error)?;
98 Ok(())
99 }
100
101 fn list<T: DeserializeOwned>(&self, kind: &str) -> Result<Vec<T>, String> {
102 let connection = self.connection.lock().map_err(error)?;
103 let mut statement = connection
104 .prepare("SELECT data FROM records WHERE kind=?1 ORDER BY key")
105 .map_err(error)?;
106 statement
107 .query_map([kind], |row| row.get::<_, Vec<u8>>(0))
108 .map_err(error)?
109 .map(|row| serde_json::from_slice(&row.map_err(error)?).map_err(error))
110 .collect()
111 }
112
113 fn checkpoint(&self, id: &str) -> Result<Option<ExecutionCheckpoint>, String> {
114 let row: Option<(String, Vec<u8>)> = self
115 .connection
116 .lock()
117 .map_err(error)?
118 .query_row(
119 "SELECT identity, heap FROM checkpoints WHERE id=?1",
120 [id],
121 |row| Ok((row.get(0)?, row.get(1)?)),
122 )
123 .optional()
124 .map_err(error)?;
125 Ok(row.map(|(identity, bytes)| ExecutionCheckpoint { identity, bytes }))
126 }
127
128 pub(crate) fn save_checkpoint(
129 &self,
130 id: &str,
131 identity: &str,
132 heap: &[u8],
133 ) -> Result<(), String> {
134 self.connection
135 .lock()
136 .map_err(error)?
137 .execute(
138 "INSERT OR REPLACE INTO checkpoints VALUES (?1, ?2, ?3)",
139 params![id, identity, heap],
140 )
141 .map_err(error)?;
142 Ok(())
143 }
144}
145
146#[async_trait]
147impl RuntimeStore for DurableStore {
148 async fn workflow_identity(&self) -> Result<String, String> {
149 if let Some(id) = self.get::<String>("workflow_identity", "id", "")? {
150 return Ok(id);
151 }
152 let mut bytes = [0u8; 24];
153 getrandom::fill(&mut bytes).map_err(error)?;
154 let id = bytes.iter().map(|b| format!("{b:02x}")).collect::<String>();
155 self.put("workflow_identity", "id", "", &id)?;
156 Ok(id)
157 }
158 async fn get_workflows(&self) -> Result<Option<serde_json::Value>, String> {
159 self.get("workflows", "catalog", "")
160 }
161 async fn put_workflows(&self, catalog: &serde_json::Value) -> Result<(), String> {
162 self.put("workflows", "catalog", "", catalog)
163 }
164 async fn get_checkpoint(&self, id: &str) -> Result<Option<ExecutionCheckpoint>, String> {
165 self.checkpoint(id)
166 }
167 async fn put_checkpoint(
168 &self,
169 id: &str,
170 checkpoint: &ExecutionCheckpoint,
171 ) -> Result<(), String> {
172 self.save_checkpoint(id, &checkpoint.identity, &checkpoint.bytes)
173 }
174 async fn get_execution(&self, id: &str) -> Result<Option<ExecutionState>, String> {
175 self.get("execution", id, "")
176 }
177 async fn put_execution(&self, value: &ExecutionState) -> Result<(), String> {
178 self.put("execution", &value.id, "", value)
179 }
180 async fn list_executions(&self) -> Result<Vec<ExecutionState>, String> {
181 self.list("execution")
182 }
183 async fn delete_execution(&self, id: &str) -> Result<(), String> {
184 let mut connection = self.connection.lock().map_err(error)?;
185 let tx = connection.transaction().map_err(error)?;
186 tx.execute("DELETE FROM records WHERE (kind='execution' AND key=?1) OR (kind='artifact' AND owner=?1)", [id]).map_err(error)?;
187 tx.execute("DELETE FROM checkpoints WHERE id=?1", [id])
188 .map_err(error)?;
189 tx.commit().map_err(error)
190 }
191 async fn get_snippet(&self, name: &str) -> Result<Option<Snippet>, String> {
192 self.get("snippet", name, "")
193 }
194 async fn put_snippet(&self, value: &Snippet) -> Result<(), String> {
195 self.put("snippet", &value.name, "", value)
196 }
197 async fn list_snippets(&self) -> Result<Vec<Snippet>, String> {
198 self.list("snippet")
199 }
200 async fn delete_snippet(&self, name: &str) -> Result<bool, String> {
201 self.connection
202 .lock()
203 .map_err(error)?
204 .execute(
205 "DELETE FROM records WHERE kind='snippet' AND key=?1",
206 [name],
207 )
208 .map(|count| count > 0)
209 .map_err(error)
210 }
211}
212
213#[async_trait]
214impl ArtifactStore for DurableStore {
215 async fn put(&self, execution_id: &str, value: &Value) -> Result<ArtifactRef, String> {
216 let data = serde_json::to_vec(value).map_err(error)?;
217 let id = format!(
218 "{:x}",
219 Sha256::digest([execution_id.as_bytes(), &data].concat())
220 );
221 self.put("artifact", &id, execution_id, value)?;
222 Ok(ArtifactRef {
223 id,
224 execution_id: execution_id.into(),
225 bytes: data.len(),
226 preview: String::from_utf8_lossy(&data).chars().take(256).collect(),
227 })
228 }
229 async fn get(&self, execution_id: &str, artifact_id: &str) -> Result<Option<Value>, String> {
230 self.get("artifact", artifact_id, execution_id)
231 }
232 async fn delete_execution(&self, execution_id: &str) -> Result<(), String> {
233 self.connection
234 .lock()
235 .map_err(error)?
236 .execute(
237 "DELETE FROM records WHERE kind='artifact' AND owner=?1",
238 [execution_id],
239 )
240 .map_err(error)?;
241 Ok(())
242 }
243}
244
245fn error(value: impl std::fmt::Display) -> String {
246 value.to_string()
247}