Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update to http 1.0 and hyper 1.1 on hard mode #7

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 108 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion crates/twirp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,15 @@ reqwest = { version = "0.11", features = ["default", "gzip", "json"], optional =
url = { version = "2.5", optional = true }

# For the server feature
hyper = { version = "0.14", features = ["full"], optional = true }
bytes = "1.5"
http-body-util = "0.1"
hyper = { version = "1.1", features = ["full"], optional = true }
hyper-util = { version = "0.1", features = ["tokio"] }
pin-project-lite = "0.2"

# For the test-support feature
async-trait = { version = "0.1", optional = true }
tokio = { version = "1.33", features = [], optional = true }

[dev-dependencies]
tokio = { version = "1.33", features = ["rt", "macros"] }
112 changes: 112 additions & 0 deletions crates/twirp/src/body.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use std::fmt::{self, Debug, Formatter};
use std::pin::Pin;
use std::task::{Context, Poll};

use bytes::Bytes;
use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::BodyExt;
use hyper::body::Frame;

use crate::GenericError;

type BoxBody = UnsyncBoxBody<Bytes, GenericError>;

pin_project_lite::pin_project! {
/// Generic body type (like `axum::body::Body`).
pub struct Body {
#[pin]
inner: BoxBody
}
}

impl Debug for Body {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Body").finish()
}
}

impl From<Bytes> for Body {
fn from(bytes: Bytes) -> Self {
Body {
inner: BoxBody::new(http_body_util::Full::new(bytes).map_err(|err| match err {})),
}
}
}

impl From<Vec<u8>> for Body {
fn from(bytes: Vec<u8>) -> Self {
Bytes::from(bytes).into()
}
}

impl From<String> for Body {
fn from(text: String) -> Self {
Bytes::from(text).into()
}
}

impl From<&'static str> for Body {
fn from(text: &'static str) -> Self {
Bytes::from(text).into()
}
}

impl Body {
/// Create a new Body that wraps another `http::body::Body`.
pub fn new<B>(body: B) -> Self
where
B: hyper::body::Body<Data = Bytes> + Send + 'static,
B::Error: Into<GenericError>,
{
Body {
inner: BoxBody::new(body.map_err(|err| err.into())),
}
}

pub fn empty() -> Self {
Self::new(http_body_util::Empty::new())
}

pub(crate) fn protobuf<T>(message: &T) -> Self
where
T: prost::Message,
{
serialize_proto_message(message).into()
}

pub(crate) fn json<T>(data: &T) -> Result<Self, serde_json::Error>
where
T: serde::Serialize,
{
let json = serde_json::to_string(&data)?;
Ok(json.into())
}
}

pub(crate) fn serialize_proto_message<T>(m: &T) -> Vec<u8>
where
T: prost::Message,
{
let len = m.encoded_len();
let mut data = Vec::with_capacity(len);
m.encode(&mut data)
.expect("can only fail if buffer does not have capacity");
assert_eq!(data.len(), len);
data
}

impl hyper::body::Body for Body {
/// Values yielded by the `Body`.
type Data = bytes::Bytes;

/// The error type this `Body` might generate.
type Error = GenericError;

/// Attempt to pull out the next data buffer of this stream.
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
self.project().inner.poll_frame(cx)
}
}
8 changes: 4 additions & 4 deletions crates/twirp/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::sync::Arc;

use async_trait::async_trait;
use hyper::header::{InvalidHeaderValue, CONTENT_TYPE};
use hyper::StatusCode;
use reqwest::header::{InvalidHeaderValue, CONTENT_TYPE};
use reqwest::StatusCode;
use thiserror::Error;
use url::Url;

use crate::headers::{CONTENT_TYPE_JSON, CONTENT_TYPE_PROTOBUF};
use crate::{to_proto_body, TwirpErrorResponse};
use crate::{body, TwirpErrorResponse};

#[derive(Debug, Error)]
pub enum ClientError {
Expand Down Expand Up @@ -146,7 +146,7 @@ impl Client {
.http_client
.post(url)
.header(CONTENT_TYPE, CONTENT_TYPE_PROTOBUF)
.body(to_proto_body(body))
.body(body::serialize_proto_message(&body))
.build()?;

// Create and execute the middleware handlers
Expand Down
6 changes: 4 additions & 2 deletions crates/twirp/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

use std::collections::HashMap;

use hyper::{header, Body, Response, StatusCode};
use hyper::{header, Response, StatusCode};
use serde::{Deserialize, Serialize, Serializer};

use crate::Body;

// Alias for a generic error
pub type GenericError = Box<dyn std::error::Error + Send + Sync>;
pub type GenericError = Box<dyn std::error::Error + Send + Sync + 'static>;

macro_rules! twirp_error_codes {
(
Expand Down
14 changes: 2 additions & 12 deletions crates/twirp/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#[cfg(feature = "client")]
pub mod client;

mod body;
pub mod error;
pub mod headers;
pub mod server;

#[cfg(any(test, feature = "test-support"))]
pub mod test;

pub use body::Body;
pub use client::{Client, ClientBuilder, ClientError, Middleware, Next, Result};
pub use error::*; // many constructors like `invalid_argument()`
pub use server::{serve, Router, Timings};
Expand All @@ -17,15 +19,3 @@ pub use reqwest;

// Re-export `url so that the generated code works without additional dependencies beyond just the `twirp` crate.
pub use url;

pub(crate) fn to_proto_body<T>(m: T) -> hyper::Body
where
T: prost::Message,
{
let len = m.encoded_len();
let mut data = Vec::with_capacity(len);
m.encode(&mut data)
.expect("can only fail if buffer does not have capacity");
assert_eq!(data.len(), len);
hyper::Body::from(data)
}
Loading