use crate::AnalyzeError;
use std::future::Future;
use std::pin::Pin;
#[cfg(not(target_arch = "wasm32"))]
mod tokio_runtime;
#[cfg(target_arch = "wasm32")]
mod wasm_runtime;
#[cfg(not(target_arch = "wasm32"))]
pub use tokio_runtime::TokioRuntime;
#[cfg(target_arch = "wasm32")]
pub use wasm_runtime::WasmRuntime;
#[cfg(not(target_arch = "wasm32"))]
pub type DefaultRuntime = TokioRuntime;
#[cfg(target_arch = "wasm32")]
pub type DefaultRuntime = WasmRuntime;
#[derive(Debug, Clone)]
pub struct FetchResult {
pub url: String,
pub status: u16,
pub body: String,
pub headers: Vec<(String, String)>,
}
#[cfg(not(target_arch = "wasm32"))]
pub trait AsyncRuntime: Send + Sync + 'static {
fn fetch_url(
&self,
url: &str,
) -> Pin<Box<dyn Future<Output = Result<FetchResult, AnalyzeError>> + Send + '_>>;
fn check_url(
&self,
url: &str,
) -> Pin<Box<dyn Future<Output = Result<bool, AnalyzeError>> + Send + '_>>;
fn fetch_batch(
&self,
urls: Vec<String>,
) -> Pin<Box<dyn Future<Output = Vec<Result<FetchResult, AnalyzeError>>> + Send + '_>>;
fn spawn<F>(&self, future: F)
where
F: Future<Output = ()> + Send + 'static;
fn runtime_name(&self) -> &'static str;
}
#[cfg(target_arch = "wasm32")]
pub trait AsyncRuntime: 'static {
fn fetch_url(
&self,
url: &str,
) -> Pin<Box<dyn Future<Output = Result<FetchResult, AnalyzeError>> + '_>>;
fn check_url(
&self,
url: &str,
) -> Pin<Box<dyn Future<Output = Result<bool, AnalyzeError>> + '_>>;
fn fetch_batch(
&self,
urls: Vec<String>,
) -> Pin<Box<dyn Future<Output = Vec<Result<FetchResult, AnalyzeError>>> + '_>>;
fn spawn<F>(&self, future: F)
where
F: Future<Output = ()> + 'static;
fn runtime_name(&self) -> &'static str;
}
pub fn create_default_runtime() -> DefaultRuntime {
DefaultRuntime::default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_runtime_creation() {
let runtime = create_default_runtime();
#[cfg(not(target_arch = "wasm32"))]
assert_eq!(runtime.runtime_name(), "tokio");
#[cfg(target_arch = "wasm32")]
assert_eq!(runtime.runtime_name(), "wasm");
}
}