rustolio-rpc 0.1.0

An RPC extention for the HTTP-Server
Documentation
//
// SPDX-License-Identifier: MPL-2.0
//
// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

use http_body_util::BodyExt as _;
use rustolio_utils::{
    bytes::encoding::{decode_from_hyper_stream, encode_to_bytes},
    http::{self, StatusCode},
    prelude::*,
    threadsafe::Threadsafe,
};

use crate::ServerFnError;

pub async fn decode_rpc_body<B, Msg>(req: http::Request<B>) -> Result<Msg, ServerFnError>
where
    B: hyper::body::Body + Unpin + Threadsafe,
    Msg: Decode + Threadsafe,
{
    let stream = req.into_body().into_data_stream();

    let Ok(msg) = decode_from_hyper_stream::<_, _, B>(stream).await else {
        return Err(ServerFnError::http_error(
            StatusCode::BAD_REQUEST,
            "Failed to parse request body",
        ));
    };

    // let Ok(body) = req.into_body().collect().await else {
    //     return Err(ServerFnError::http_error(
    //         StatusCode::BAD_REQUEST,
    //         "Failed to parse request body",
    //     ));
    // };
    // let Ok(msg) = decode_from_bytes(body.to_bytes()) else {
    //     return Err(ServerFnError::http_error(
    //         StatusCode::BAD_REQUEST,
    //         "Failed to parse request body",
    //     ));
    // };

    Ok(msg)
}

pub fn encode_rpc_response<R, E>(res: Result<R, ServerFnError<E>>) -> http::Response
where
    R: Encode,
    E: Encode,
{
    if let Err(ServerFnError::HttpError(status, msg)) = res {
        return http::Response::builder()
            .status(status)
            .text(msg)
            .build()
            .unwrap();
    }
    let Ok(body) = encode_to_bytes(&res) else {
        return http::Response::builder()
            .status(StatusCode::INTERNAL_SERVER_ERROR)
            .text("Failed to serialize response")
            .build()
            .unwrap();
    };
    http::Response::builder().bytes(body).build().unwrap()
}