use std::collections::HashMap;
use std::sync::Arc;
use alpha2_host_core::remote::{
RemoteCounts, RemoteFailure, RemoteObject, RemoteSession, SourceLocation,
};
use alpha2_host_core::requests::{MediaLocation, RemoteContentHash};
use serde_json::{Value, json};
use crate::media_policy::{media_error, refuse_unlisted};
use crate::protocol::HostError;
pub struct RemoteInputs {
session: RemoteSession,
hash: RemoteContentHash,
_cancel: crate::termination::ExportCancel,
}
pub enum Located {
Found(SourceLocation),
Offline(String),
Unsupported(String),
}
impl RemoteInputs {
pub fn for_request(
assets: &HashMap<String, MediaLocation>,
resources: &HashMap<String, HashMap<String, MediaLocation>>,
cache_bytes: u64,
hash: RemoteContentHash,
) -> Result<Option<Self>, HostError> {
let policy = crate::media_policy::current();
refuse_unlisted(&policy, assets, resources)?;
let named = assets
.values()
.chain(resources.values().flat_map(HashMap::values))
.any(|location| location.url().is_some());
if !named {
return Ok(None);
}
let cancel = crate::termination::export_cancel();
let transport = Arc::new(crate::media_fetch::MediaTransport::new(policy));
Ok(Some(Self {
session: RemoteSession::new(transport, (*cancel).clone(), cache_bytes),
hash,
_cancel: cancel,
}))
}
pub fn open(&self, source: &str, url: &str) -> Result<Arc<RemoteObject>, HostError> {
self.session
.open(url)
.map_err(|error| media_error(source, url, &error))
}
pub fn locate(&self, source: &str, url: &str) -> Result<Located, HostError> {
match self.session.open(url) {
Ok(object) => Ok(Located::Found(SourceLocation::Remote(object))),
Err(error) => match error.failure {
RemoteFailure::Offline => {
Ok(Located::Offline(alpha2_host_core::remote::shown_url(url)))
}
RemoteFailure::Empty => Ok(Located::Unsupported(error.message)),
_ => Err(media_error(source, url, &error)),
},
}
}
pub fn verifies(&self) -> bool {
self.hash == RemoteContentHash::Verify
}
pub fn counts(&self) -> RemoteCounts {
self.session.counts()
}
pub fn performance(&self) -> [(&'static str, Value); 4] {
let counts = self.counts();
[
("remoteBytes", json!(counts.bytes)),
("remoteRequests", json!(counts.requests)),
("remoteRetries", json!(counts.retries)),
("remoteReadWaitMs", json!(counts.read_wait_ms)),
]
}
}
pub fn name_source(mut error: HostError, assets: &HashMap<String, MediaLocation>) -> HostError {
let Some(details) = error.details.as_mut() else {
return error;
};
if !error.code.starts_with("MEDIA_") || details.get("source").is_some() {
return error;
}
let Some(url) = details.get("url").and_then(Value::as_str) else {
return error;
};
let mut named = assets
.iter()
.filter(|(_, location)| {
location
.url()
.is_some_and(|own| alpha2_host_core::remote::shown_url(own) == url)
})
.map(|(id, _)| id.as_str())
.collect::<Vec<_>>();
named.sort_unstable();
if let Some(first) = named.first() {
details["source"] = json!(first);
}
error
}