jsona_util/environment/
mod.rs

1use async_trait::async_trait;
2use futures::Future;
3use time::OffsetDateTime;
4use tokio::io::{AsyncRead, AsyncWrite};
5use url::Url;
6
7use crate::util::url::to_url;
8
9#[cfg(not(target_family = "wasm"))]
10pub mod native;
11
12/// An environment in which the operations with Jsona are executed.
13///
14/// This is mostly needed for sandboxed environments such as WebAssembly.
15#[async_trait(?Send)]
16pub trait Environment: Clone + Send + Sync + 'static {
17    type Stdin: AsyncRead + Unpin;
18    type Stdout: AsyncWrite + Unpin;
19    type Stderr: AsyncWrite + Unpin;
20
21    fn now(&self) -> OffsetDateTime;
22
23    fn spawn<F>(&self, fut: F)
24    where
25        F: Future + Send + 'static,
26        F::Output: Send;
27
28    fn spawn_local<F>(&self, fut: F)
29    where
30        F: Future + 'static;
31
32    fn env_var(&self, name: &str) -> Option<String>;
33
34    fn atty_stderr(&self) -> bool;
35    fn stdin(&self) -> Self::Stdin;
36    fn stdout(&self) -> Self::Stdout;
37    fn stderr(&self) -> Self::Stderr;
38
39    async fn read_file(&self, path: &Url) -> Result<Vec<u8>, anyhow::Error>;
40
41    async fn write_file(&self, path: &Url, bytes: &[u8]) -> Result<(), anyhow::Error>;
42
43    async fn fetch_file(&self, path: &Url) -> Result<Vec<u8>, anyhow::Error>;
44
45    fn root_uri(&self) -> Option<Url>;
46
47    fn to_url(&self, path: &str) -> Option<Url> {
48        to_url(path, &self.root_uri())
49    }
50}