use std::sync::Arc;
use std::time::Duration;
use compmd_host::registry::{Client, DEFAULT_MAX_PACK_SIZE, Options, Proxy};
use compmd_host::{Bundle, FetchedBy, Manifest, Refusal, Store, refused, respond};
use tauri::http::{HeaderValue, Request, Response, StatusCode, header};
pub struct Compmd {
bundle: Option<Arc<Bundle>>,
origin: Option<String>,
store: Arc<dyn Store>,
proxy: Option<Proxy>,
}
const NO_BUNDLE: &str = "this app has no bundle: build it with @compmd/vite before the app";
pub(crate) const REGISTRY: &str = "/registry/";
const TIMEOUT: Duration = Duration::from_secs(30);
fn proxy_of(manifest: &Manifest) -> Option<Proxy> {
if manifest.fetch != FetchedBy::Host || manifest.registries.is_empty() {
return None;
}
let options = Options {
max_pack_size: manifest.max_pack_size.unwrap_or(DEFAULT_MAX_PACK_SIZE),
..Options::new(manifest.registries.clone())
};
Some(Proxy::new(options, Client::new(TIMEOUT)))
}
impl Compmd {
pub(crate) fn new(
bundle: Option<Bundle>,
origin: Option<String>,
store: Arc<dyn Store>,
) -> Self {
Self {
proxy: bundle
.as_ref()
.and_then(|bundle| proxy_of(bundle.manifest())),
bundle: bundle.map(Arc::new),
origin,
store,
}
}
#[must_use]
pub fn bundle(&self) -> Option<&Bundle> {
self.bundle.as_deref()
}
#[must_use]
pub fn origin(&self) -> Option<&str> {
self.origin.as_deref()
}
#[must_use]
pub fn store(&self) -> &dyn Store {
self.store.as_ref()
}
#[must_use]
pub fn respond<B>(&self, request: &Request<B>) -> Response<Vec<u8>> {
let path = request.uri().path();
if let (Some(proxy), Some(origin), Some(rest)) =
(&self.proxy, &self.origin, path.strip_prefix(REGISTRY))
{
let mut answer = proxy.answer(rest, &format!("{origin}{REGISTRY}"));
answer.headers_mut().insert(
header::ACCESS_CONTROL_ALLOW_ORIGIN,
HeaderValue::from_static("*"),
);
return answer;
}
self.bundle.as_ref().map_or_else(
|| {
refused(Refusal {
status: StatusCode::NOT_FOUND,
why: NO_BUNDLE,
})
},
|bundle| respond(bundle, self.store(), request),
)
}
#[cfg(feature = "processor")]
#[must_use]
pub fn packs(&self) -> Option<compmd_host::HostPacks> {
let bundle = Arc::clone(self.bundle.as_ref()?);
Some(compmd_host::HostPacks::new(bundle, Arc::clone(&self.store)))
}
}