redseat-api 0.1.0

Rust client for Redseat media servers
Documentation
//! HTTP + SSE transport, with reqwest and rustls. Port of `@redseat/api-http`
//! `http-transport.ts` and `client.ts`, with the address choice of `direct.ts`.

use std::sync::PoisonError;
use std::sync::RwLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use futures_util::StreamExt;

use crate::cloud::CloudServer;
use crate::direct::{ProbeOptions, probe_candidates_with, server_candidates};
use crate::error::{Error, Result};
use crate::sse::decode_event_stream;
use crate::transport::{Body, EventRequest, Method, RawEventStream, Request, Response, Transport};

/// Default request timeout (TS: 30 s).
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// How [`HttpTransport::connect`] picks a server address.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectOptions {
    /// The URL that worked last time, cached by the app: tried first.
    pub preferred_url: Option<String>,
    pub probe: ProbeOptions,
    /// Request timeout.
    pub timeout: Duration,
}

impl Default for ConnectOptions {
    fn default() -> Self {
        ConnectOptions {
            preferred_url: None,
            probe: ProbeOptions::default(),
            timeout: DEFAULT_TIMEOUT,
        }
    }
}

/// [`Transport`] over HTTP(S).
pub struct HttpTransport {
    client: reqwest::Client,
    base_url: RwLock<String>,
    timeout: Duration,
    closed: AtomicBool,
}

impl std::fmt::Debug for HttpTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpTransport")
            .field("base_url", &self.base_url())
            .finish_non_exhaustive()
    }
}

fn http_client() -> Result<reqwest::Client> {
    reqwest::Client::builder()
        .build()
        .map_err(|e| Error::transport(format!("HTTP client: {e}")))
}

fn map_reqwest_error(error: reqwest::Error, path: &str) -> Error {
    let path = Some(path.to_owned());
    let message = error.to_string();
    if error.is_timeout() {
        Error::Timeout { message, path }
    } else if error.is_decode() {
        Error::MalformedResponse { message, path }
    } else if error.is_builder() {
        Error::Transport {
            message,
            status: None,
            path,
        }
    } else {
        Error::Network { message, path }
    }
}

fn reqwest_method(method: Method) -> reqwest::Method {
    match method {
        Method::Get => reqwest::Method::GET,
        Method::Head => reqwest::Method::HEAD,
        Method::Post => reqwest::Method::POST,
        Method::Put => reqwest::Method::PUT,
        Method::Patch => reqwest::Method::PATCH,
        Method::Delete => reqwest::Method::DELETE,
    }
}

/// `GET <url>/ping`: true when it answers with a success.
async fn ping(client: &reqwest::Client, url: &str, timeout: Duration) -> bool {
    client
        .get(format!("{url}/ping"))
        .timeout(timeout)
        .send()
        .await
        .is_ok_and(|response| response.status().is_success())
}

/// The base URL to reach `server` at: the first of its direct addresses and custom
/// domain to answer `/ping` (see [`crate::direct`]), else its `url`.
pub async fn resolve_server_url(server: &CloudServer, options: &ConnectOptions) -> Result<String> {
    let candidates = server_candidates(server, options.preferred_url.as_deref());
    if !candidates.is_empty() {
        let client = http_client()?;
        let timeout = options.probe.timeout;
        let winner = probe_candidates_with(&candidates, options.probe, |candidate| {
            let client = client.clone();
            let url = candidate.url.clone();
            async move { ping(&client, &url, timeout).await }
        })
        .await;
        if let Some(winner) = winner {
            return Ok(winner.url);
        }
    }
    if !server.url.is_empty() {
        let port = server.port.map(|p| format!(":{p}")).unwrap_or_default();
        return Ok(format!("https://{}{port}", server.url));
    }
    Err(Error::Network {
        message: format!(
            "server {} is unreachable: none of its addresses answered",
            server.name.as_deref().unwrap_or(&server.id)
        ),
        path: None,
    })
}

impl HttpTransport {
    /// A transport to `base_url` (`https://host:port`).
    pub fn new(base_url: &str) -> Result<Self> {
        Self::with_timeout(base_url, DEFAULT_TIMEOUT)
    }

    pub fn with_timeout(base_url: &str, timeout: Duration) -> Result<Self> {
        Ok(HttpTransport {
            client: http_client()?,
            base_url: RwLock::new(normalize_base(base_url)?),
            timeout,
            closed: AtomicBool::new(false),
        })
    }

    /// A transport to `server`, at the address [`resolve_server_url`] picks.
    pub async fn connect(server: &CloudServer, options: ConnectOptions) -> Result<Self> {
        let base_url = resolve_server_url(server, &options).await?;
        Self::with_timeout(&base_url, options.timeout)
    }

    pub fn base_url(&self) -> String {
        self.base_url
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Switches to another address, for example after the network changed.
    pub fn set_base_url(&self, base_url: &str) -> Result<()> {
        let base_url = normalize_base(base_url)?;
        *self
            .base_url
            .write()
            .unwrap_or_else(PoisonError::into_inner) = base_url;
        Ok(())
    }

    fn url(&self, path: &str, query: &[(String, String)]) -> Result<url::Url> {
        let absolute = if path.starts_with("http://") || path.starts_with("https://") {
            path.to_owned()
        } else {
            let slash = if path.starts_with('/') { "" } else { "/" };
            format!("{}{slash}{path}", self.base_url())
        };
        let mut url = url::Url::parse(&absolute).map_err(|e| Error::Transport {
            message: format!("invalid URL {absolute}: {e}"),
            status: None,
            path: Some(path.to_owned()),
        })?;
        if !query.is_empty() {
            url.query_pairs_mut().extend_pairs(query);
        }
        Ok(url)
    }

    fn check_open(&self, path: &str) -> Result<()> {
        if self.closed.load(Ordering::Relaxed) {
            return Err(Error::Transport {
                message: "HTTP transport is closed".to_owned(),
                status: None,
                path: Some(path.to_owned()),
            });
        }
        Ok(())
    }
}

fn normalize_base(base_url: &str) -> Result<String> {
    let trimmed = base_url.trim_end_matches('/');
    url::Url::parse(trimmed)
        .map_err(|e| Error::transport(format!("invalid URL {base_url}: {e}")))?;
    Ok(trimmed.to_owned())
}

async fn error_of(response: reqwest::Response, path: &str) -> Error {
    let status = response.status().as_u16();
    let body = response
        .bytes()
        .await
        .map(|b| b.to_vec())
        .unwrap_or_default();
    Error::from_status(status, Some(path), &body)
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
impl Transport for HttpTransport {
    async fn request(&self, request: Request) -> Result<Response> {
        self.check_open(&request.path)?;
        let path = request.path.clone();
        let url = self.url(&request.path, &request.query)?;
        let mut builder = self
            .client
            .request(reqwest_method(request.method), url)
            .timeout(request.timeout.unwrap_or(self.timeout));
        for (name, value) in &request.headers {
            builder = builder.header(name, value);
        }
        builder = match request.body {
            None => builder,
            Some(Body::Json(value)) => builder
                .header("Content-Type", "application/json")
                .body(value.to_string()),
            Some(Body::Form(fields)) => builder
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body(
                    url::form_urlencoded::Serializer::new(String::new())
                        .extend_pairs(fields)
                        .finish(),
                ),
            Some(Body::Bytes { content_type, data }) => {
                builder.header("Content-Type", content_type).body(data)
            }
        };

        let response = builder
            .send()
            .await
            .map_err(|e| map_reqwest_error(e, &path))?;
        if !response.status().is_success() {
            return Err(error_of(response, &path).await);
        }
        let status = response.status().as_u16();
        let headers = response
            .headers()
            .iter()
            .filter_map(|(name, value)| {
                Some((name.as_str().to_owned(), value.to_str().ok()?.to_owned()))
            })
            .collect();
        let body = response
            .bytes()
            .await
            .map_err(|e| map_reqwest_error(e, &path))?
            .to_vec();
        Ok(Response {
            status,
            headers,
            body,
        })
    }

    async fn subscribe(&self, request: EventRequest) -> Result<RawEventStream> {
        self.check_open(&request.path)?;
        let path = request.path.clone();
        let url = self.url(&request.path, &request.query)?;
        // No timeout: the stream stays open.
        let mut builder = self
            .client
            .get(url)
            .header("Accept", "text/event-stream")
            .header("Cache-Control", "no-cache");
        for (name, value) in &request.headers {
            builder = builder.header(name, value);
        }
        let response = builder
            .send()
            .await
            .map_err(|e| map_reqwest_error(e, &path))?;
        if !response.status().is_success() {
            return Err(error_of(response, &path).await);
        }
        let chunks = response
            .bytes_stream()
            .map(move |chunk| chunk.map_err(|e| map_reqwest_error(e, &path)));
        Ok(Box::pin(decode_event_stream(Box::pin(chunks))))
    }

    fn close(&self) {
        self.closed.store(true, Ordering::Relaxed);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::serve_http as serve;

    #[tokio::test]
    async fn sends_requests_and_maps_statuses() {
        let (address, mut heads) = serve(
            "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 7\r\nconnection: close\r\n\r\n[1,2,3]",
        )
        .await;
        let transport = HttpTransport::new(&format!("http://{address}/")).unwrap();
        let response = transport
            .request(
                Request::get("/libraries/x/medias")
                    .query("filter", "{\"a\":1}")
                    .bearer("tok"),
            )
            .await
            .unwrap();
        assert_eq!(response.json::<Vec<u8>>().unwrap(), vec![1, 2, 3]);
        assert_eq!(response.header("Content-Type"), Some("application/json"));
        let head = heads.recv().await.unwrap();
        assert!(head.starts_with("GET /libraries/x/medias?filter=%7B%22a%22%3A1%7D HTTP/1.1"));
        assert!(head.to_lowercase().contains("authorization: bearer tok"));

        let (address, _) =
            serve("HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
                .await;
        let transport = HttpTransport::new(&format!("http://{address}")).unwrap();
        let error = transport.request(Request::get("/x")).await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Unauthorized);
        assert_eq!(error.path(), Some("/x"));
    }

    #[tokio::test]
    async fn streams_server_events() {
        let (address, mut heads) = serve(
            "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\nevent: heartbeat\ndata: {}\n\nevent: medias\ndata: {\"medias\":{\"library\":\"l\",\"medias\":[]}}\n\nevent: tags\ndata: {}",
        )
        .await;
        let transport = HttpTransport::new(&format!("http://{address}")).unwrap();
        let events: Vec<_> = transport
            .subscribe(EventRequest {
                path: "/sse".into(),
                query: vec![("libraries".into(), "l".into())],
                ..Default::default()
            })
            .await
            .unwrap()
            .collect()
            .await;
        let names: Vec<_> = events
            .iter()
            .map(|e| e.as_ref().unwrap().event.as_str())
            .collect();
        assert_eq!(names, vec!["heartbeat", "medias", "tags"]);
        let head = heads.recv().await.unwrap();
        assert!(head.starts_with("GET /sse?libraries=l HTTP/1.1"));
        assert!(head.to_lowercase().contains("accept: text/event-stream"));
    }

    #[tokio::test]
    async fn a_closed_transport_refuses_requests() {
        let transport = HttpTransport::new("http://127.0.0.1:9").unwrap();
        transport.close();
        let error = transport.request(Request::get("/x")).await.unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Transport);
    }

    #[tokio::test]
    async fn falls_back_to_the_server_url_when_no_candidate_answers() {
        let server = CloudServer {
            id: "srv".into(),
            name: None,
            url: "media.example.org".into(),
            port: Some(8443),
            local: None,
            direct: None,
            domain: None,
            member: None,
        };
        let url = resolve_server_url(&server, &ConnectOptions::default())
            .await
            .unwrap();
        assert_eq!(url, "https://media.example.org:8443");

        let unreachable = CloudServer {
            url: String::new(),
            ..server
        };
        let error = resolve_server_url(&unreachable, &ConnectOptions::default())
            .await
            .unwrap_err();
        assert_eq!(error.kind(), crate::ErrorKind::Network);
    }
}