1use std::collections::BTreeMap;
11use std::future::{Future, ready};
12use std::io;
13use std::pin::pin;
14use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
15use std::task::{Context, Poll, Waker};
16
17use rig_core::wasm_compat::WasmCompatSend;
18
19use crate::SessionError;
20
21#[derive(Debug, thiserror::Error)]
23pub enum LogWriteError {
24 #[error("the log changed since it was read")]
27 Changed,
28 #[error(transparent)]
30 Io(#[from] io::Error),
31}
32
33impl From<LogWriteError> for io::Error {
34 fn from(error: LogWriteError) -> Self {
37 match error {
38 LogWriteError::Changed => io::Error::other(LogWriteError::Changed.to_string()),
39 LogWriteError::Io(error) => error,
40 }
41 }
42}
43
44pub trait Files: Send + Sync + 'static {
54 fn write_file(&self, name: &str, bytes: &[u8]) -> io::Result<()>;
57
58 fn append_file(&self, name: &str, bytes: &[u8]) -> io::Result<()>;
61
62 fn read_file(&self, name: &str) -> io::Result<Vec<u8>>;
64
65 fn remove_file(&self, name: &str) -> io::Result<()>;
67
68 fn files(&self) -> io::Result<Vec<String>>;
70}
71
72pub trait Store: Files {
79 fn logs(&self) -> io::Result<Vec<String>>;
81
82 fn read_log(&self, name: &str) -> io::Result<Vec<u8>>;
84
85 fn append_log(&self, name: &str, len: u64, bytes: &[u8]) -> Result<(), LogWriteError>;
96
97 fn replace_log(&self, name: &str, len: u64, bytes: &[u8]) -> Result<(), LogWriteError>;
103
104 fn destroy(&self) -> io::Result<()>;
107}
108
109pub trait AsyncStore {
134 fn read_log_async(
136 &self,
137 name: &str,
138 ) -> impl Future<Output = io::Result<Vec<u8>>> + WasmCompatSend;
139
140 fn append_log_async(
143 &self,
144 name: &str,
145 len: u64,
146 bytes: &[u8],
147 ) -> impl Future<Output = Result<(), LogWriteError>> + WasmCompatSend;
148
149 fn replace_log_async(
152 &self,
153 name: &str,
154 len: u64,
155 bytes: &[u8],
156 ) -> impl Future<Output = Result<(), LogWriteError>> + WasmCompatSend;
157
158 fn read_file_async(
160 &self,
161 name: &str,
162 ) -> impl Future<Output = io::Result<Vec<u8>>> + WasmCompatSend;
163
164 fn write_file_async(
166 &self,
167 name: &str,
168 bytes: &[u8],
169 ) -> impl Future<Output = io::Result<()>> + WasmCompatSend;
170}
171
172impl<S: Store + ?Sized> AsyncStore for S {
174 fn read_log_async(
175 &self,
176 name: &str,
177 ) -> impl Future<Output = io::Result<Vec<u8>>> + WasmCompatSend {
178 ready(self.read_log(name))
179 }
180
181 fn append_log_async(
182 &self,
183 name: &str,
184 len: u64,
185 bytes: &[u8],
186 ) -> impl Future<Output = Result<(), LogWriteError>> + WasmCompatSend {
187 ready(self.append_log(name, len, bytes))
188 }
189
190 fn replace_log_async(
191 &self,
192 name: &str,
193 len: u64,
194 bytes: &[u8],
195 ) -> impl Future<Output = Result<(), LogWriteError>> + WasmCompatSend {
196 ready(self.replace_log(name, len, bytes))
197 }
198
199 fn read_file_async(
200 &self,
201 name: &str,
202 ) -> impl Future<Output = io::Result<Vec<u8>>> + WasmCompatSend {
203 ready(self.read_file(name))
204 }
205
206 fn write_file_async(
207 &self,
208 name: &str,
209 bytes: &[u8],
210 ) -> impl Future<Output = io::Result<()>> + WasmCompatSend {
211 ready(self.write_file(name, bytes))
212 }
213}
214
215macro_rules! forward {
218 ($($pointer:ident),*) => {$(
219 impl<S: Files + ?Sized> Files for $pointer<S> {
220 fn write_file(&self, name: &str, bytes: &[u8]) -> io::Result<()> {
221 (**self).write_file(name, bytes)
222 }
223
224 fn append_file(&self, name: &str, bytes: &[u8]) -> io::Result<()> {
225 (**self).append_file(name, bytes)
226 }
227
228 fn read_file(&self, name: &str) -> io::Result<Vec<u8>> {
229 (**self).read_file(name)
230 }
231
232 fn remove_file(&self, name: &str) -> io::Result<()> {
233 (**self).remove_file(name)
234 }
235
236 fn files(&self) -> io::Result<Vec<String>> {
237 (**self).files()
238 }
239 }
240
241 impl<S: Store + ?Sized> Store for $pointer<S> {
242 fn logs(&self) -> io::Result<Vec<String>> {
243 (**self).logs()
244 }
245
246 fn read_log(&self, name: &str) -> io::Result<Vec<u8>> {
247 (**self).read_log(name)
248 }
249
250 fn append_log(&self, name: &str, len: u64, bytes: &[u8]) -> Result<(), LogWriteError> {
251 (**self).append_log(name, len, bytes)
252 }
253
254 fn replace_log(&self, name: &str, len: u64, bytes: &[u8]) -> Result<(), LogWriteError> {
255 (**self).replace_log(name, len, bytes)
256 }
257
258 fn destroy(&self) -> io::Result<()> {
259 (**self).destroy()
260 }
261 }
262 )*};
263}
264
265forward!(Arc, Box);
266
267pub(crate) fn now<T>(
271 work: impl Future<Output = Result<T, SessionError>>,
272) -> Result<T, SessionError> {
273 match pin!(work).poll(&mut Context::from_waker(Waker::noop())) {
274 Poll::Ready(output) => output,
275 Poll::Pending => Err(io::Error::other("a local store's call did not finish").into()),
276 }
277}
278
279pub fn check_name(name: &str) -> io::Result<()> {
295 let bad = |part: &str| matches!(part, "" | "." | "..") || part.contains('\\');
296 if name.split('/').any(bad) {
297 let why = format!("{name:?} is no name in a session");
298 return Err(io::Error::new(io::ErrorKind::InvalidInput, why));
299 }
300 Ok(())
301}
302
303pub fn check_log_name(name: &str) -> io::Result<()> {
316 check_name(name)?;
317 if name.contains('/') {
318 let why = format!("{name:?} is no log name");
319 return Err(io::Error::new(io::ErrorKind::InvalidInput, why));
320 }
321 Ok(())
322}
323
324#[derive(Clone, Default)]
327pub struct MemoryStore(Arc<Mutex<Memory>>);
328
329#[derive(Default)]
330struct Memory {
331 logs: BTreeMap<String, Vec<u8>>,
332 files: BTreeMap<String, Vec<u8>>,
333}
334
335impl MemoryStore {
336 fn memory(&self) -> MutexGuard<'_, Memory> {
337 self.0.lock().unwrap_or_else(PoisonError::into_inner)
338 }
339}
340
341fn not_found() -> io::Error {
342 io::ErrorKind::NotFound.into()
343}
344
345impl Files for MemoryStore {
346 fn write_file(&self, name: &str, bytes: &[u8]) -> io::Result<()> {
347 check_name(name)?;
348 self.memory().files.insert(name.to_owned(), bytes.to_vec());
349 Ok(())
350 }
351
352 fn append_file(&self, name: &str, bytes: &[u8]) -> io::Result<()> {
353 check_name(name)?;
354 let mut memory = self.memory();
355 let file = memory.files.entry(name.to_owned()).or_default();
356 file.extend_from_slice(bytes);
357 Ok(())
358 }
359
360 fn read_file(&self, name: &str) -> io::Result<Vec<u8>> {
361 check_name(name)?;
362 self.memory().files.get(name).cloned().ok_or_else(not_found)
363 }
364
365 fn remove_file(&self, name: &str) -> io::Result<()> {
366 check_name(name)?;
367 self.memory().files.remove(name);
368 Ok(())
369 }
370
371 fn files(&self) -> io::Result<Vec<String>> {
372 Ok(self.memory().files.keys().cloned().collect())
373 }
374}
375
376impl Store for MemoryStore {
377 fn logs(&self) -> io::Result<Vec<String>> {
378 Ok(self.memory().logs.keys().cloned().collect())
379 }
380
381 fn read_log(&self, name: &str) -> io::Result<Vec<u8>> {
382 check_log_name(name)?;
383 self.memory().logs.get(name).cloned().ok_or_else(not_found)
384 }
385
386 fn append_log(&self, name: &str, len: u64, bytes: &[u8]) -> Result<(), LogWriteError> {
387 check_log_name(name)?;
388 let mut memory = self.memory();
389 if memory.logs.get(name).map_or(0, Vec::len) as u64 != len {
390 return Err(LogWriteError::Changed);
391 }
392 let log = memory.logs.entry(name.to_owned()).or_default();
393 log.extend_from_slice(bytes);
394 Ok(())
395 }
396
397 fn replace_log(&self, name: &str, len: u64, bytes: &[u8]) -> Result<(), LogWriteError> {
398 check_log_name(name)?;
399 let mut memory = self.memory();
400 if memory.logs.get(name).map_or(0, Vec::len) as u64 != len {
401 return Err(LogWriteError::Changed);
402 }
403 memory.logs.insert(name.to_owned(), bytes.to_vec());
404 Ok(())
405 }
406
407 fn destroy(&self) -> io::Result<()> {
408 *self.memory() = Memory::default();
409 Ok(())
410 }
411}
412
413pub const PLUGINS: &str = "plugins/";
415
416pub struct PluginFiles(pub Arc<dyn Files>);
419
420impl Files for PluginFiles {
421 fn write_file(&self, name: &str, bytes: &[u8]) -> io::Result<()> {
422 self.0.write_file(&format!("{PLUGINS}{name}"), bytes)
423 }
424
425 fn append_file(&self, name: &str, bytes: &[u8]) -> io::Result<()> {
426 self.0.append_file(&format!("{PLUGINS}{name}"), bytes)
427 }
428
429 fn read_file(&self, name: &str) -> io::Result<Vec<u8>> {
430 self.0.read_file(&format!("{PLUGINS}{name}"))
431 }
432
433 fn remove_file(&self, name: &str) -> io::Result<()> {
434 self.0.remove_file(&format!("{PLUGINS}{name}"))
435 }
436
437 fn files(&self) -> io::Result<Vec<String>> {
438 let files = self.0.files()?.into_iter();
439 let within = files.filter_map(|name| Some(name.strip_prefix(PLUGINS)?.to_owned()));
440 Ok(within.collect())
441 }
442}