diff options
author | Ferris Tseng <ferristseng@fastmail.fm> | 2021-02-22 20:42:21 -0500 |
---|---|---|
committer | Ferris Tseng <ferristseng@fastmail.fm> | 2021-02-22 20:42:21 -0500 |
commit | cc0131c9c6bea175853c995768fc817b5b066be7 (patch) | |
tree | 0f3f11c7c3a7bd52aaf1fb647901c0f44e1f9b9d | |
parent | 7dddbde3a1abcb96b75aa4636a07498193f7c551 (diff) |
add hyper backend
-rw-r--r-- | ipfs-api-backend-hyper/Cargo.toml | 26 | ||||
-rw-r--r-- | ipfs-api-backend-hyper/src/backend.rs | 132 | ||||
-rw-r--r-- | ipfs-api-backend-hyper/src/error.rs | 43 | ||||
-rw-r--r-- | ipfs-api-backend-hyper/src/lib.rs | 14 |
4 files changed, 215 insertions, 0 deletions
diff --git a/ipfs-api-backend-hyper/Cargo.toml b/ipfs-api-backend-hyper/Cargo.toml new file mode 100644 index 0000000..9ebd7d0 --- /dev/null +++ b/ipfs-api-backend-hyper/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "ipfs-api-backend-hyper" +description = "Hyper implementation of IPFS HTTP API" +authors = ["Ferris Tseng <ferristseng@fastmail.fm>"] +edition = "2018" +documentation = "https://docs.rs/ipfs-api" +repository = "https://github.com/ferristseng/rust-ipfs-api" +keywords = ["ipfs"] +categories = ["filesystem", "web-programming"] +version = "0.1.0" +readme = "../README.md" +license = "MIT OR Apache-2.0" + +[dependencies] +async-trait = "0.1" +bytes = "1.0" +futures = "0.3" +http = "0.2" +hyper = { version = "0.14", features = ["http1", "http2", "client"] } +hyper-multipart-rfc7578 = "0.5" +hyper-tls = "0.5" +ipfs-api-prelude = { version = "0.1.0", path = "../ipfs-api-prelude" } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +serde_urlencoded = "0.7" +thiserror = "1.0" diff --git a/ipfs-api-backend-hyper/src/backend.rs b/ipfs-api-backend-hyper/src/backend.rs new file mode 100644 index 0000000..047fbb6 --- /dev/null +++ b/ipfs-api-backend-hyper/src/backend.rs @@ -0,0 +1,132 @@ +use crate::error::Error; +use async_trait::async_trait; +use bytes::Bytes; +use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt}; +use http::{ + header::{HeaderName, HeaderValue}, + uri::Scheme, + StatusCode, Uri, +}; +use hyper::{ + body, + client::{self, Builder, HttpConnector}, +}; +use hyper_tls::HttpsConnector; +use ipfs_api_prelude::{ApiRequest, Backend, TryFromUri}; +use serde::Serialize; + +pub struct HyperBackend { + base: Uri, + client: client::Client<HttpsConnector<HttpConnector>, hyper::Body>, +} + +impl Default for HyperBackend { + fn default() -> Self { + Self::from_ipfs_config() + .unwrap_or_else(|| Self::from_host_and_port(Scheme::HTTP, "localhost", 5001).unwrap()) + } +} + +impl TryFromUri for HyperBackend { + fn build_with_base_uri(base: Uri) -> Self { + let client = Builder::default() + .pool_max_idle_per_host(0) + .build(HttpsConnector::new()); + + HyperBackend { base, client } + } +} + +#[async_trait(?Send)] +impl Backend for HyperBackend { + type HttpRequest = http::Request<hyper::Body>; + + type HttpResponse = http::Response<hyper::Body>; + + type MultipartForm = multipart::client::multipart::Form<'static>; + + type Error = Error; + + fn build_base_request<Req>( + &self, + req: &Req, + form: Option<Self::MultipartForm>, + ) -> Result<Self::HttpRequest, Error> + where + Req: ApiRequest, + { + req.absolute_url(&self.base).and_then(move |url| { + let builder = http::Request::builder(); + let builder = builder.method(Req::METHOD.clone()).uri(url); + + let req = if let Some(form) = form { + form.set_body_convert::<hyper::Body, multipart::client::multipart::Body>(builder) + } else { + builder.body(hyper::Body::empty()) + }; + + req.map_err(From::from) + }) + } + + fn get_header<'a>(res: &'a Self::HttpResponse, key: HeaderName) -> Option<&'a HeaderValue> { + res.headers().get(key) + } + + async fn request_raw<Req>( + &self, + req: Req, + form: Option<Self::MultipartForm>, + ) -> Result<(StatusCode, Bytes), Self::Error> + where + Req: ApiRequest + Serialize, + { + let req = self.build_base_request(&req, form)?; + let res = self.client.request(req).await?; + let status = res.status(); + let body = body::to_bytes(res.into_body()).await?; + + Ok((status, body)) + } + + fn response_to_byte_stream( + res: Self::HttpResponse, + ) -> Box<dyn Stream<Item = Result<Bytes, Self::Error>> + Unpin> { + Box::new(res.into_body().err_into()) + } + + fn request_stream<Res, F, OutStream>( + &self, + req: Self::HttpRequest, + process: F, + ) -> Box<dyn Stream<Item = Result<Res, Self::Error>> + Unpin> + where + OutStream: Stream<Item = Result<Res, Self::Error>> + Unpin, + F: 'static + Fn(Self::HttpResponse) -> OutStream, + { + let stream = self + .client + .request(req) + .err_into() + .map_ok(move |res| { + match res.status() { + StatusCode::OK => process(res).right_stream(), + // If the server responded with an error status code, the body + // still needs to be read so an error can be built. This block will + // read the entire body stream, then immediately return an error. + // + _ => body::to_bytes(res.into_body()) + .boxed() + .map(|maybe_body| match maybe_body { + Ok(body) => Err(Self::process_error_from_body(body)), + Err(e) => Err(e.into()), + }) + .into_stream() + .left_stream(), + } + }) + .try_flatten_stream(); + + Box::new(stream) + } +} diff --git a/ipfs-api-backend-hyper/src/error.rs b/ipfs-api-backend-hyper/src/error.rs new file mode 100644 index 0000000..9db1959 --- /dev/null +++ b/ipfs-api-backend-hyper/src/error.rs @@ -0,0 +1,43 @@ +// Copyright 2019 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +use std::string::FromUtf8Error; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + #[error("api returned error `{0}`")] + Api(ipfs_api_prelude::ApiError), + + #[error("hyper client error `{0}`")] + Client(#[from] hyper::Error), + + #[error("http error `{0}`")] + Http(#[from] http::Error), + + #[error("json parse error `{0}`")] + Parse(#[from] serde_json::Error), + + #[error("utf8 decoding error `{0}`")] + ParseUtf8(#[from] FromUtf8Error), + + #[error("uri error `{0}`")] + Url(#[from] http::uri::InvalidUri), + + #[error("url encoding error `{0}`")] + EncodeUrl(#[from] serde_urlencoded::ser::Error), + + #[error("ipfs client error `{0}`")] + IpfsClientError(#[from] ipfs_api_prelude::Error), +} + +impl From<ipfs_api_prelude::ApiError> for Error { + fn from(err: ipfs_api_prelude::ApiError) -> Self { + Error::Api(err) + } +} diff --git a/ipfs-api-backend-hyper/src/lib.rs b/ipfs-api-backend-hyper/src/lib.rs new file mode 100644 index 0000000..276d34a --- /dev/null +++ b/ipfs-api-backend-hyper/src/lib.rs @@ -0,0 +1,14 @@ +// Copyright 2019 rust-ipfs-api Developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. +// + +extern crate hyper_multipart_rfc7578 as multipart; + +mod backend; +mod error; + +pub use crate::{backend::HyperBackend as IpfsApi, error::Error}; |