Repository navigation
Conversation
|
Thanks so much for iterating on this! ngl im still learning so custom futures and tower trait bounds are still kinda wizardry to me lol. your version looks way cleaner and more idiomatic. Should i just close my pr so we can use yours? |
| bytes = "1.12.0" | ||
| http = "1.4.2" | ||
| http-body-util = "0.1.3" | ||
| hyper = "1.10.1" |
|
|
||
| let req_bad = Request::builder().body(Full::<Bytes>::default()).unwrap(); | ||
| let res_bad = service.ready().await?.call(req_bad).await?; | ||
| assert_eq!(res_bad.status(), StatusCode::BAD_REQUEST); |
There was a problem hiding this comment.
Probably these assertions should be in test modules? That matches the other examples.
I'd also probably add some println!s so that cargo run -p custom-future-multiple-bodies prints something, given the README guides the user to run it.
|
|
||
| impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for RequireHeader<S> | ||
| where | ||
| S: Service<Request<ReqBody>, Response = Response<ResBody>>, |
There was a problem hiding this comment.
I would probably add ResBody: http_body::Body<Data = Bytes> here, yeah, at the cost of taking the http-body = "1" dependency. That moves any error out to the middleware layer, which is clearer.
| @@ -0,0 +1,14 @@ | |||
| # Custom future with multiple bodies | |||
There was a problem hiding this comment.
Should we mention that the Either is convenient but loses the concrete error type, and that you can refer to the tower_http::limit wrapper to preserve the type?
There was a problem hiding this comment.
I dont quite understand what this means, doesnt the body stay fully preserved including the error?
There was a problem hiding this comment.
Ah sorry for the slow response.
The body itself is preserved, but the error type is erased. Either's Body impl declares type Error = Box<dyn Error + Send + Sync>. So whoever consumes the response body afterwards only sees a boxed trait object instead of, say, hyper::Error, and would have to downcast to inspect it.
Compare with tower_http::limit's ResponseBody<B>, which declares type Error = B::Error and passes through the original error untouched.
For an example this tradeoff is usually fine, I'd just like the README to mention it so readers know the alternative exists.
| pin_project! { | ||
| #[project = EnumProj] | ||
| pub enum RequireHeaderFuture<F> { | ||
| Ok{ #[pin] fut: F }, |
There was a problem hiding this comment.
nit: Future to match the repo conventions?
|
|
||
| pin_project! { | ||
| #[project = EnumProj] | ||
| pub enum RequireHeaderFuture<F> { |
There was a problem hiding this comment.
Would it be worth a doc comment pointing to how eg limit/future.rs encapsulate these types for semver safety, if used in a library? This seems fine for application usage.
There was a problem hiding this comment.
I don't particularly mind demonstrating the encapsulated pattern in general, it's not particularly more verbose, up to you.
|
|
||
| fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | ||
| match self.project() { | ||
| EnumProj::Ok { fut } => { |
There was a problem hiding this comment.
More readable as:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let res = match self.project() {
// `?` propagates an inner-service error. to turn it into a response
// instead, replace `?` with
// .unwrap_or_else(|_| rejection(StatusCode::BAD_GATEWAY, "..."))
// to convert every error, or `.or_else(..)` to convert only some and
// keep propagating the rest.
ResFutProj::Future { future } => ready!(future.poll(cx))?.map(Either::Left),
ResFutProj::MissingHeader => rejection(StatusCode::BAD_REQUEST, "missing header"),
};
Poll::Ready(Ok(res))
| } | ||
|
|
||
| #[tokio::main] | ||
| async fn main() -> Result<(), Box<dyn Error>> { |
There was a problem hiding this comment.
We need the unwrap here since we don't have Box<dyn Error>: From<Box<dyn Error + Send + Sync>>.
I'd suggest instead widening the signature to Result<(), Box<dyn Error + Send + Sync>> (or just Result<(), tower::BoxError>, which is equivalent) to avoid both the unwrap and the need to coerce explicitly to work around the missing From.
| resp.map(|body| Either::Left(body)) | ||
| } | ||
|
|
||
| fn new_err_resp<B>(status: StatusCode, body: &'static str) -> Response<ResponseBody<B>> { |
| type ResponseBody<B> = Either<B, Full<Bytes>>; | ||
|
|
||
| // some helper to go along with it | ||
| fn map_resp<B>(resp: Response<B>) -> Response<ResponseBody<B>> { |
There was a problem hiding this comment.
I don't think this really carries its weight as a helper
jlizen
left a comment
There was a problem hiding this comment.
Thanks for the contribution! looks great
This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [tower-http](https://github.com/tower-rs/tower-http) | dependencies | patch | `0.7.0` → `0.7.1` | --- ### Release Notes <details> <summary>tower-rs/tower-http (tower-http)</summary> ### [`v0.7.1`](https://github.com/tower-rs/tower-http/releases/tag/tower-http-0.7.1) [Compare Source](tower-rs/tower-http@tower-http-0.7.0...tower-http-0.7.1) #### Added - `fs`: add `ServeDir::redirect_to_trailing_slash()` to serve directory indexes directly instead of first redirecting to the trailing-slash path. The redirect remains the default ([#​728]) - `fs`: add `ignore_multi_range_requests()` to `ServeDir` and `ServeFile`, serving the full representation when a request asks for multiple byte ranges. The existing `416 Range Not Satisfiable` response remains the default ([#​727]) - `request-id`: the constructors and accessors on the request-id layers, services, and `RequestId` are now `const fn`, so they can be used in const context ([#​716]) #### Changed - `fs`: the minimum `http-range-header` requirement is now 0.4.2 ([#​661]) #### Fixed - **behavioral change:** `fs`: make `ServeDir::try_call` propagate expected filesystem I/O errors when no fallback is configured, as documented, instead of converting them to `404 Not Found` responses ([#​718]) - `decompression`: don't end the body when a data frame with no remaining bytes arrives after the decompressor reports end-of-stream. Trailers following such a frame were dropped and could not be recovered ([#​722]) - `decompression`: return a body error when a data frame with remaining bytes arrives after the decompressor reports end-of-stream, rather than silently truncating. This regressed in 0.7.0 ([#​712]) - `fs`: multipart range requests are now rejected before range validation, so they consistently return `416 Range Not Satisfiable` with a `Cannot serve multipart range requests` body instead of a generic unsatisfiable-range response ([#​661]) - `fs`: range error responses no longer carry representation headers such as `Content-Type` and `Content-Encoding` ([#​727]) - `set-header`: `SetMultipleResponseHeadersLayer` and `SetMultipleResponseHeader` are now `Clone` regardless of the response body type, matching the fix applied to the request-side types in 0.7.0 ([#​714]) [#​661]: tower-rs/tower-http#661 [#​712]: tower-rs/tower-http#712 [#​714]: tower-rs/tower-http#714 [#​716]: tower-rs/tower-http#716 [#​718]: tower-rs/tower-http#718 [#​722]: tower-rs/tower-http#722 [#​727]: tower-rs/tower-http#727 [#​728]: tower-rs/tower-http#728 #### All the changes - chore(deps): bump actions/checkout from 6 to 7 by [@​dependabot](https://github.com/dependabot)\[bot] in [#​708](tower-rs/tower-http#708) - fix(compression): reject non-empty data frames after codec is EOF by [@​seanmonstar](https://github.com/seanmonstar) in [#​712](tower-rs/tower-http#712) - Remove Clone derivations from SetMultipleResponseHeader\* types by [@​skeet70](https://github.com/skeet70) in [#​714](tower-rs/tower-http#714) - feat(request-id): Allow request-id constructor in const context by [@​tottoto](https://github.com/tottoto) in [#​716](tower-rs/tower-http#716) - fs: Avoid unnecessary conversions between SystemTime and HttpDate by [@​tottoto](https://github.com/tottoto) in [#​717](tower-rs/tower-http#717) - fs: Use HeaderValue::is_empty to check for empty values by [@​tottoto](https://github.com/tottoto) in [#​720](tower-rs/tower-http#720) - fs: Use HeaderValue::to_str for date headers by [@​tottoto](https://github.com/tottoto) in [#​721](tower-rs/tower-http#721) - chore(deps): bump taiki-e/install-action from 2 to 2.85.4 by [@​dependabot](https://github.com/dependabot)\[bot] in [#​715](tower-rs/tower-http#715) - chore(deps): bump taiki-e/install-action from 2.85.4 to 2.85.12 by [@​dependabot](https://github.com/dependabot)\[bot] in [#​723](tower-rs/tower-http#723) - docs(example)/custom future with multiple bodies by [@​Reza-Darius](https://github.com/Reza-Darius) in [#​711](tower-rs/tower-http#711) - fix(decompression): don't end the body on an empty data frame by [@​clemenslosbichler-cloud](https://github.com/clemenslosbichler-cloud) in [#​722](tower-rs/tower-http#722) - Propagate ServeDir::try_call I/O errors by [@​Boulea7](https://github.com/Boulea7) in [#​718](tower-rs/tower-http#718) - ci: Update to cargo-check-external-types 0.5.0 by [@​tottoto](https://github.com/tottoto) in [#​724](tower-rs/tower-http#724) - fix: reject multipart ranges before validation by [@​shblue21](https://github.com/shblue21) in [#​661](tower-rs/tower-http#661) - chore(deps): bump taiki-e/install-action from 2.85.12 to 2.86.3 by [@​dependabot](https://github.com/dependabot)\[bot] in [#​726](tower-rs/tower-http#726) - feat(services): configure directory redirects by [@​BreezeDelegate](https://github.com/BreezeDelegate) in [#​728](tower-rs/tower-http#728) - Allow ignoring unsupported multi-range requests by [@​BreezeDelegate](https://github.com/BreezeDelegate) in [#​727](tower-rs/tower-http#727) - chore(deps): bump taiki-e/install-action from 2.86.3 to 2.86.8 by [@​dependabot](https://github.com/dependabot)\[bot] in [#​730](tower-rs/tower-http#730) - chore(release): prepare 0.7.1 by [@​jlizen](https://github.com/jlizen) in [#​729](tower-rs/tower-http#729) #### New Contributors - [@​skeet70](https://github.com/skeet70) made their first contribution in [#​714](tower-rs/tower-http#714) - [@​Reza-Darius](https://github.com/Reza-Darius) made their first contribution in [#​711](tower-rs/tower-http#711) - [@​clemenslosbichler-cloud](https://github.com/clemenslosbichler-cloud) made their first contribution in [#​722](tower-rs/tower-http#722) - [@​Boulea7](https://github.com/Boulea7) made their first contribution in [#​718](tower-rs/tower-http#718) - [@​shblue21](https://github.com/shblue21) made their first contribution in [#​661](tower-rs/tower-http#661) - [@​BreezeDelegate](https://github.com/BreezeDelegate) made their first contribution in [#​728](tower-rs/tower-http#728) </details> --- ### Configuration 📅 **Schedule**: (UTC) - Branch creation - "before 9am on tuesday" - Automerge - At any time (no schedule defined) 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4xMzMuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjE1NS4xIiwidGFyZ2V0QnJhbmNoIjoiZGV2ZWxvcCIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiLCJyZW5vdmF0ZSJdfQ==--> Reviewed-on: https://code.futo.org/harbor/harbor/pulls/1799 Reviewed-by: Thomas de Zeeuw <[email protected]>
This PR builds on this PR, which explores idomatic solutions to dealing with multiple HTTP bodies in tower services
Motivation
@Isvane did a great job with his proposal, so i wanted to iterate on it by bringing it closer to how i solved this problem in my own project. Primarily, by introducing a custom future.
Changes
BoxBodyaliasservicetrait boundsPin Box Futurewith custom future.main()Discussion
While i think this is a decently elegant solution, it could be argued its not idiomatic if you compare how this problem is solved in
tower-http/limit.A potential foot gun im wondering about is the trait bound on
Eitherwhich states that both arms need to have the same underlyingDatatype. Right now the example leaves the response body of the inner service entirely generic, but this could lead to a nasty compile error down the road should theDatatypes mismatch.tower-http/limitimposes aBody<Data = Bytes>bound on itsBodyimplementation for it's wrapper type and im wondering whether this example should include it too, and if so, where.