redseat-api 0.7.2

Rust client for Redseat media servers
Documentation
//! A call to a server or the cloud without its I/O: the [`Request`] to send and how to
//! read its [`Response`]. The async clients run calls through a [`crate::Transport`]
//! ([`crate::RedseatClient::run`], [`crate::CloudClient::run`]); a host that sends
//! requests itself (a WebAssembly module that cannot run async code, a binding to
//! another language) builds the same calls with the `calls` modules
//! ([`crate::server::calls`], [`crate::library::calls`], [`crate::cloud::calls`]),
//! sends [`Call::request`] and reads the answer with [`Call::parse`].
//!
//! Requests to a server carry no token: add it with [`Request::bearer`]. When
//! [`Call::parse`] fails with [`crate::ErrorKind::Unauthorized`], the token was refused:
//! get a new one ([`crate::cloud::calls::fetch_server_token`]), send the request again
//! with it, and parse that answer with the same call.

use serde::de::DeserializeOwned;

use crate::error::{Error, Result};
use crate::transport::{Request, Response};

type Read<T> = dyn Fn(Result<Response>) -> Result<T> + Send + Sync;

/// One request and how to read its answer into a `T`. Build it with a `calls` module,
/// send [`Self::request`], then [`Self::parse`] the response.
pub struct Call<T> {
    /// The request to send. Its `path` is relative to the server (or the cloud).
    pub request: Request,
    read: Box<Read<T>>,
}

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

impl<T> Call<T> {
    pub(crate) fn new(
        request: Request,
        read: impl Fn(Result<Response>) -> Result<T> + Send + Sync + 'static,
    ) -> Self {
        Call {
            request,
            read: Box::new(read),
        }
    }

    /// Reads the response the server gave, whatever its status: a status other than
    /// 2xx is read as [`Error::from_status`] (or as what the call makes of it: an
    /// expired cloud session is `None`). Can be called again, for the answer to the
    /// same request sent once more.
    pub fn parse(&self, response: Response) -> Result<T> {
        let result = if (200..300).contains(&response.status) {
            Ok(response)
        } else {
            Err(Error::from_status(
                response.status,
                Some(&self.request.path),
                &response.body,
            ))
        };
        self.read(result)
    }

    /// Reads what a [`crate::Transport`] gave for the request: a 2xx response, or the
    /// error of any other status or of a failure to send it.
    pub fn read(&self, result: Result<Response>) -> Result<T> {
        (self.read)(result)
    }

    /// The request, and the reader of its answer.
    pub(crate) fn into_parts(self) -> (Request, Box<Read<T>>) {
        (self.request, self.read)
    }

    /// The same request, its answer then turned into a `U` by `then`.
    pub(crate) fn map<U>(self, then: impl Fn(T) -> Result<U> + Send + Sync + 'static) -> Call<U>
    where
        T: 'static,
    {
        let read = self.read;
        Call::new(self.request, move |result| read(result).and_then(&then))
    }
}

impl<T: DeserializeOwned + 'static> Call<T> {
    /// A call whose answer is read as JSON.
    pub(crate) fn json(request: Request) -> Self {
        let path = request.path.clone();
        Call::new(request, move |result| {
            serde_json::from_slice(&result?.body)
                .map_err(|e| Error::malformed(format!("unexpected answer: {e}"), Some(&path)))
        })
    }
}

impl Call<()> {
    /// A call whose answer has no body to read.
    pub(crate) fn empty(request: Request) -> Self {
        Call::new(request, |result| result.map(|_| ()))
    }
}

impl Call<Vec<u8>> {
    /// A call whose answer is the body, as bytes.
    pub(crate) fn bytes(request: Request) -> Self {
        Call::new(request, |result| result.map(|response| response.body))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ErrorKind;

    fn response(status: u16, body: &str) -> Response {
        Response {
            status,
            headers: Vec::new(),
            body: body.as_bytes().to_vec(),
        }
    }

    #[test]
    fn reads_a_status_like_the_transports() {
        let call: Call<Vec<u32>> = Call::json(Request::get("/x"));
        assert_eq!(call.parse(response(200, "[1,2]")).unwrap(), vec![1, 2]);

        let refused = call.parse(response(401, r#"{"message":"expired"}"#));
        let refused = refused.unwrap_err();
        assert_eq!(refused.kind(), ErrorKind::Unauthorized);
        assert_eq!(refused.to_string(), "expired");
        assert_eq!(refused.path(), Some("/x"));

        let malformed = call.parse(response(200, "nope")).unwrap_err();
        assert_eq!(malformed.kind(), ErrorKind::MalformedResponse);
        assert_eq!(malformed.path(), Some("/x"));
        assert_eq!(
            call.read(Err(Error::transport("offline")))
                .unwrap_err()
                .kind(),
            ErrorKind::Transport
        );
    }

    #[test]
    fn maps_an_answer() {
        let call = Call::json(Request::get("/count")).map(|n: u64| Ok(n * 2));
        assert_eq!(call.parse(response(200, "21")).unwrap(), 42);
        assert!(
            Call::empty(Request::get("/"))
                .parse(response(204, ""))
                .is_ok()
        );
        assert_eq!(
            Call::bytes(Request::get("/"))
                .parse(response(200, "ab"))
                .unwrap(),
            b"ab".to_vec()
        );
    }

    #[test]
    fn never_prints_a_token() {
        let call = Call::empty(Request::get("/x").bearer("secret"));
        let printed = format!("{call:?}");
        assert!(printed.contains("/x"));
        assert!(!printed.contains("secret"));
    }
}