redseat-api 0.2.0

Rust client for Redseat media servers
Documentation
//! The `Transport` trait: how the client reaches a server. Port of `@redseat/api`
//! `transport.ts`. The HTTP implementation is [`crate::http::HttpTransport`]; WebRTC can
//! come later behind its own feature.

use std::pin::Pin;
use std::time::Duration;

use futures_util::Stream;
use serde::de::DeserializeOwned;

use crate::error::{Error, Result};

/// `Send + Sync` on native targets, nothing on wasm, where futures and JS handles are
/// single-threaded.
#[cfg(not(target_arch = "wasm32"))]
pub trait MaybeSend: Send + Sync {}
#[cfg(not(target_arch = "wasm32"))]
impl<T: Send + Sync + ?Sized> MaybeSend for T {}

/// `Send + Sync` on native targets, nothing on wasm, where futures and JS handles are
/// single-threaded.
#[cfg(target_arch = "wasm32")]
pub trait MaybeSend {}
#[cfg(target_arch = "wasm32")]
impl<T: ?Sized> MaybeSend for T {}

/// A boxed stream, `Send` on native targets.
#[cfg(not(target_arch = "wasm32"))]
pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
/// A boxed stream, `Send` on native targets.
#[cfg(target_arch = "wasm32")]
pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T>>>;

/// HTTP-like method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Method {
    Get,
    Head,
    Post,
    Put,
    Patch,
    Delete,
}

impl Method {
    /// The method name, upper case.
    pub fn as_str(self) -> &'static str {
        match self {
            Method::Get => "GET",
            Method::Head => "HEAD",
            Method::Post => "POST",
            Method::Put => "PUT",
            Method::Patch => "PATCH",
            Method::Delete => "DELETE",
        }
    }
}

/// Body of a request.
#[derive(Debug, Clone, PartialEq)]
pub enum Body {
    Json(serde_json::Value),
    /// `application/x-www-form-urlencoded`.
    Form(Vec<(String, String)>),
    Bytes {
        content_type: String,
        data: Vec<u8>,
    },
}

/// A request. `path` is relative to the transport's base URL (`/libraries`), or absolute.
#[derive(Debug, Clone, PartialEq)]
pub struct Request {
    pub method: Method,
    pub path: String,
    pub headers: Vec<(String, String)>,
    pub query: Vec<(String, String)>,
    pub body: Option<Body>,
    /// Overrides the transport's default timeout.
    pub timeout: Option<Duration>,
}

impl Request {
    pub fn new(method: Method, path: impl Into<String>) -> Self {
        Request {
            method,
            path: path.into(),
            headers: Vec::new(),
            query: Vec::new(),
            body: None,
            timeout: None,
        }
    }

    pub fn get(path: impl Into<String>) -> Self {
        Self::new(Method::Get, path)
    }

    pub fn post(path: impl Into<String>) -> Self {
        Self::new(Method::Post, path)
    }

    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    pub fn query(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.query.push((name.into(), value.into()));
        self
    }

    pub fn json(mut self, body: serde_json::Value) -> Self {
        self.body = Some(Body::Json(body));
        self
    }

    pub fn form(mut self, fields: Vec<(String, String)>) -> Self {
        self.body = Some(Body::Form(fields));
        self
    }

    /// Sets `Authorization: Bearer <token>`, replacing any previous one.
    pub fn bearer(mut self, token: &str) -> Self {
        self.headers
            .retain(|(name, _)| !name.eq_ignore_ascii_case("authorization"));
        self.headers
            .push(("Authorization".to_owned(), format!("Bearer {token}")));
        self
    }
}

/// A successful response (status 2xx). Failures come back as [`Error`].
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Response {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

impl Response {
    /// The first header with this name, ignoring case.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(n, _)| n.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }

    /// The body read as JSON.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
        serde_json::from_slice(&self.body)
            .map_err(|e| Error::malformed(format!("unexpected answer: {e}"), None))
    }
}

/// A request for a server-pushed event stream.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct EventRequest {
    pub path: String,
    pub headers: Vec<(String, String)>,
    pub query: Vec<(String, String)>,
}

/// A server event as the transport received it: name and raw `data` (JSON text).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RawEvent {
    pub event: String,
    pub data: String,
    pub id: Option<String>,
    pub retry: Option<u64>,
}

/// Stream of raw events. It ends when the server closes it; drop it to disconnect.
pub type RawEventStream = BoxStream<Result<RawEvent>>;

/// How the client reaches a server (or the cloud). Port of `RedseatTransport`.
///
/// `request` returns the response of a 2xx status and maps any other status to an
/// [`Error`] with [`Error::from_status`].
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
pub trait Transport: MaybeSend {
    async fn request(&self, request: Request) -> Result<Response>;

    /// Opens a server-pushed event stream. The protocol (SSE, DataChannel...) is a
    /// transport detail.
    async fn subscribe(&self, request: EventRequest) -> Result<RawEventStream> {
        Err(Error::Transport {
            message: "this transport does not support server events".to_owned(),
            status: None,
            path: Some(request.path),
        })
    }

    /// Stops the transport. Later calls fail.
    fn close(&self) {}

    /// The `http(s)://host:port` base of the server, when it is reachable over plain
    /// HTTP. Lets code that fetches files itself (a video player) build URLs for them,
    /// see [`crate::RedseatClient::authorized_url`]. `None` (the default) for
    /// transports that are not HTTP.
    fn http_base_url(&self) -> Option<String> {
        None
    }
}