Skip to content

Commit adba649

Browse files
committed
Revamp Tide, dropping Extractors and simplifying the framework
This commit reworks Tide, with the goal of reducing the total number of concepts in the framework. The key new idea is to remove the notion of `Extractor`s, which in turn allows us to remove or simplify several other concepts in Tide. We'll first lay out the new design, and then discuss the tradeoffs made in this simplification. Here's a full list of the concepts in Tide after this commit: | Concept | Description | | ----- | ----------- | | `App` | Builder for Tide applications | | `Route` | Builder for an individual route | | `Endpoint` | Trait for actual endpoints | | `Context` | The request context for an endpoint | | `IntoResponse` | A trait for converting into a `Response` | | `Middleware` | A trait for Tide middleware | Previously, the `Endpoint` trait was treated as a somewhat magical internal abstraction, and we used a macro to provide `Endpoint` implementations for actual endpoints (with varying numbers of extractor arguments). In this commit, an `Endpoint` is just an asynchronous function from a `Context` to a `Response`: ```rust pub trait Endpoint<AppData>: Send + Sync + 'static { /// The async result of `call`. type Fut: Future<Output = Response> + Send + 'static; /// Invoke the endpoint. fn call(&self, cx: Context<AppData>) -> Self::Fut; } ``` For convenience, this trait is implemented for async functions that return any value that implements `IntoResponse`: ```rust impl<AppData, F, Fut> Endpoint<AppData> for F where F: Fn(Context<AppData>) -> Fut, Fut: Future Fut::Output: IntoResponse, // ... ``` This implementation is in contrast to the macro-generated implementations we previously had, which allowed endpoints with varying numbers of `Extractor` arguments. The intent is for endpoints to perform their own extraction directly on the `Context`, as we'll see next. The `Context` type contains all of the request and middleware context an endpoint operates on. You can think of it as wrapping an `http_service::Request` with some additional data. It's easiest to understand `Context` through the APIs it provides. First, we have methods for getting basic http request information, mirroring the `http` APIs: ```rust impl<AppData> Context<AppData> { pub fn method(&self) -> &Method; pub fn uri(&self) -> &Uri; pub fn version(&self) -> Version; pub fn headers(&self) -> &HeaderMap; } ``` The context also has a handle to application data, which typically would store database connection pools and other "application-global" state. This API replaces the old `AppData` extractor: ```rust impl<AppData> Context<AppData> { pub fn app_data(&self) -> &AppData { &self.app_data } } ``` Similarly, we provide a *direct* API for extracting any "route parameters" (i.e. placeholders in the route URL), replacing the need for `NamedSegment` and the like: ```rust impl<AppData> Context<AppData> { pub fn route_param(&self, key: &str) -> Option<&str>; } ``` Basic body extraction is likewise built in via `Context` methods, replacing the `Str`, `Bytes`, and `Json` extractors: ```rust impl<AppData> Context<AppData> { pub async fn body_bytes(&mut self) -> std::io::Result<Vec<u8>>; pub async fn body_string(&mut self) -> std::io::Result<String>; pub async fn body_json<T: serde::de::DeserializeOwned>(&mut self) -> std::io::Result<T>; } ``` Looking at the [message database example](https://github.com/rustasync/tide/blob/master/examples/messages.rs#L44), we previously had endpoints like this: ```rust async fn new_message(mut db: AppData<Database>, msg: body::Json<Message>) -> String { db.insert(msg.clone()).to_string() } async fn set_message( mut db: AppData<Database>, id: head::Path<usize>, msg: body::Json<Message>, ) -> Result<(), StatusCode> { if db.set(*id, msg.clone()) { Ok(()) } else { Err(StatusCode::NOT_FOUND) } } ``` These endpoints would now be written something like this (where `Error` is intended as a general error type, convertible into a response): ```rust async fn new_message(cx: Context<Database>) -> Result<String, Error> { let msg = await!(cx.body_json())?; cx.app_data().insert(msg).to_string() } async fn set_message(cx: Context<Database>) -> Result<(), Error> { let msg = await!(cx.body_json())?; if cx.app_data().set(cx.route_param("id"), msg) { Ok(()) } else { Err(StatusCode::NOT_FOUND) } } ``` The endpoint code is a bit more verbose, but also arguably easier to follow, since the extraction (and error handling) is more clear. In addition, the basic extraction approach is *more discoverable*, since it operates via normal methods on `Context`. Part of the idea of the old `Extractor` trait was that Tide would provide an *extensible* system of extractors; you could always introduce new types that implement `Extractor`. But now most of the existing extractors are built-in `Context` methods. How do we recover extensibility? Easy: we use Rust's ability to extend existing types with new methods, via traits! (Note: this is directly inspired by the Gotham framework). Let's say we want to provide cookie extraction. Previously, we'd have a `Cookies` type that you could use as an endpoint argument for extraction. Now, instead, we can introduce a `Cookies` *trait* that's used to extend `Context` with new APIs: ```rust trait Cookies { fn cookies(&self) -> CookieJar; } impl<AppData> Cookies for Context<AppData> { ... } ``` This pattern is called an "extension trait" -- a trait whose sole purpose is to extend an existing type with new methods. There are several nice properties of this approach: - The resulting extraction API is just a direct and natural as the built-in ones: just a method call on the `Context` object. - The methods that are available on `Context` are controlled by what traits are in scope. In other words, if you want to use a custom extractor from the ecosystem, you just bring its trait into scope, and then the method is available. That makes it easy to build a robust ecosystem around a small set of core Tide APIs. One of the major benefits of moving extraction into the endpoint body, rather than via `Extractor` arguments, is that it's much simpler to provide configuration. For example, we could easily provide a customized json body extractor that limited the maximum size of the body or other such options: ```rust impl<AppData> Context<AppData> { pub async fn body_json_cfg<T: serde::de::DeserializeOwned>(&mut self, cfg: JsonConfig) -> std::io::Result<T>; } ``` As a result, we can drop much of the complexity in `App` around configuration. Following the spirit of the changes to extractors, response generation for non-standard Rust types is now just done via a free function: ```rust mod response { pub fn json<T: serde::Serialize>(t: T) -> Response { ... } } ``` As before, there's a top-level `App` type for building up a Tide application. However, the API has been drastically simplified: - It no longer provides a configuration system, since extractors can now be configured directly. - It no longer allows for the middleware list to be customized per route; instead, middleware is set up only at the top level. These simplifications make the programming model much easier to understand; previously, there were inconsistencies between the way that middleware nesting and configuration nesting worked. The hope is that we can get away with this much simpler, top-level model. When actually adding routes via `at`, you get a `Route` object (which used to be `Resource`). This object now provides a *builder-style* API for adding endpoints, allowing you to chain several endpoints. Altogether, this means we can drop nested routing as well. The middleware trait is more or less as it was before, adjusted to use `Context` objects and otherwise slightly cleaned up. This commit also switches to using the route-recognizer crate, rather than the path-table crate, as the underlying routing mechanism. In addition to being more efficient, route-recognizer provides a more intuitive semantics for "ambiguous" routing situations. See issue #12 and issue #141 for more details.
1 parent d14e8f8 commit adba649

36 files changed

+984
-2268
lines changed

Cargo.toml

+4-1
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@ version = "0.0.5"
1515
[dependencies]
1616
cookie = "0.11"
1717
futures-preview = "0.3.0-alpha.13"
18+
fnv = "1.0.6"
1819
http = "0.1"
1920
http-service = "0.1.4"
20-
path-table = "1.0.0"
2121
pin-utils = "0.1.0-alpha.4"
22+
route-recognizer = "0.1.12"
2223
serde = "1.0.80"
2324
serde_derive = "1.0.80"
2425
serde_json = "1.0.32"
@@ -46,3 +47,5 @@ basic-cookies = "0.1.3"
4647
juniper = "0.10.0"
4748
structopt = "0.2.14"
4849
http-service-mock = "0.1.0"
50+
serde = "1.0.80"
51+
serde_derive = "1.0.80"

examples/body_types.rs

+24-29
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,51 @@
1-
#![feature(async_await, futures_api)]
1+
#![feature(async_await, futures_api, await_macro)]
22

33
#[macro_use]
44
extern crate serde_derive;
5-
use tide::body;
5+
6+
use tide::{
7+
error::ResultExt,
8+
forms::{self, ExtractForms},
9+
response, App, Context, EndpointResult,
10+
};
611

712
#[derive(Serialize, Deserialize, Clone, Debug)]
813
struct Message {
914
author: Option<String>,
1015
contents: String,
1116
}
1217

13-
async fn echo_string(msg: body::Str) -> String {
14-
println!("String: {}", *msg);
15-
format!("{}", *msg)
16-
}
17-
18-
async fn echo_string_lossy(msg: body::StrLossy) -> String {
19-
println!("String: {}", *msg);
20-
format!("{}", *msg)
21-
}
22-
23-
async fn echo_vec(msg: body::Bytes) -> Vec<u8> {
24-
println!("Vec<u8>: {:?}", *msg);
25-
msg.to_vec()
26-
}
27-
28-
async fn echo_bytes(msg: body::Bytes) -> body::Bytes {
29-
println!("Bytes: {:?}", *msg);
18+
async fn echo_string(mut cx: Context<()>) -> String {
19+
let msg = await!(cx.body_string()).unwrap();
20+
println!("String: {}", msg);
3021
msg
3122
}
3223

33-
async fn echo_json(msg: body::Json<Message>) -> body::Json<Message> {
34-
println!("JSON: {:?}", *msg);
35-
24+
async fn echo_bytes(mut cx: Context<()>) -> Vec<u8> {
25+
let msg = await!(cx.body_bytes()).unwrap();
26+
println!("Bytes: {:?}", msg);
3627
msg
3728
}
3829

39-
async fn echo_form(msg: body::Form<Message>) -> body::Form<Message> {
40-
println!("Form: {:?}", *msg);
30+
async fn echo_json(mut cx: Context<()>) -> EndpointResult {
31+
let msg = await!(cx.body_json()).client_err()?;
32+
println!("JSON: {:?}", msg);
33+
Ok(response::json(msg))
34+
}
4135

42-
msg
36+
async fn echo_form(mut cx: Context<()>) -> EndpointResult {
37+
let msg = await!(cx.body_form())?;
38+
println!("Form: {:?}", msg);
39+
Ok(forms::form(msg))
4340
}
4441

4542
fn main() {
46-
let mut app = tide::App::new(());
43+
let mut app = App::new(());
4744

4845
app.at("/echo/string").post(echo_string);
49-
app.at("/echo/string_lossy").post(echo_string_lossy);
50-
app.at("/echo/vec").post(echo_vec);
5146
app.at("/echo/bytes").post(echo_bytes);
5247
app.at("/echo/json").post(echo_json);
5348
app.at("/echo/form").post(echo_form);
5449

55-
app.serve();
50+
app.serve("127.0.0.1:8000").unwrap();
5651
}

examples/catch_all.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
#![feature(async_await, futures_api)]
22

3-
async fn echo_path(path: tide::head::Path<String>) -> String {
4-
format!("Your path is: {}", *path)
3+
use tide::Context;
4+
5+
async fn echo_path(cx: Context<()>) -> String {
6+
let path: String = cx.param("path").unwrap();
7+
format!("Your path is: {}", path)
58
}
69

710
fn main() {
811
let mut app = tide::App::new(());
9-
app.at("/echo_path").nest(|router| {
10-
router.at("*").get(echo_path);
11-
});
12-
13-
app.serve();
12+
app.at("/echo_path/:path*").get(echo_path);
13+
app.serve("127.0.0.1:8000").unwrap();
1414
}

examples/cli_parsing.rs

-48
This file was deleted.

examples/computed_values.rs

-38
This file was deleted.

examples/configuration.rs

-34
This file was deleted.

examples/cookie_extractor.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,15 @@
11
#![feature(async_await, futures_api)]
22

3-
use tide::Cookies;
3+
use tide::{cookies::ExtractCookies, Context};
44

55
/// Tide will use the the `Cookies`'s `Extract` implementation to build this parameter.
66
///
7-
async fn hello_cookies(cookies: Cookies) -> String {
8-
format!("hello cookies: {:?}", cookies)
7+
async fn hello_cookies(mut cx: Context<()>) -> String {
8+
format!("hello cookies: {:?}", cx.cookie("hello"))
99
}
1010

1111
fn main() {
1212
let mut app = tide::App::new(());
1313
app.at("/").get(hello_cookies);
14-
15-
let address = "127.0.0.1:8000".to_owned();
16-
println!("Server is listening on http://{}", address);
17-
app.serve();
14+
app.serve("127.0.0.1:8000").unwrap();
1815
}

examples/default_handler.rs

-13
This file was deleted.

examples/default_headers.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ fn main() {
1111
.header("X-Server", "Tide"),
1212
);
1313

14-
app.at("/").get(async || "Hello, world!");
14+
app.at("/").get(async move |_| "Hello, world!");
1515

16-
app.serve();
16+
app.serve("127.0.0.1:8000").unwrap();
1717
}

examples/graphql.rs

+15-17
Original file line numberDiff line numberDiff line change
@@ -3,26 +3,26 @@
33
//
44
// [the Juniper book]: https://graphql-rust.github.io/
55

6-
#![feature(async_await, futures_api)]
6+
#![feature(async_await, futures_api, await_macro)]
77

88
use http::status::StatusCode;
99
use juniper::graphql_object;
1010
use std::sync::{atomic, Arc};
11-
use tide::{body, App, AppData, IntoResponse, Response};
11+
use tide::{error::ResultExt, response, App, Context, EndpointResult};
1212

13-
// First, we define `Context` that holds accumulator state. This is accessible as App data in
13+
// First, we define `Data` that holds accumulator state. This is accessible as App data in
1414
// Tide, and as executor context in Juniper.
1515
#[derive(Clone, Default)]
16-
struct Context(Arc<atomic::AtomicIsize>);
16+
struct Data(Arc<atomic::AtomicIsize>);
1717

18-
impl juniper::Context for Context {}
18+
impl juniper::Context for Data {}
1919

2020
// We define `Query` unit struct here. GraphQL queries will refer to this struct. The struct itself
2121
// doesn't have any associated data (and there's no need to do so), but instead it exposes the
2222
// accumulator state from the context.
2323
struct Query;
2424

25-
graphql_object!(Query: Context |&self| {
25+
graphql_object!(Query: Data |&self| {
2626
// GraphQL integers are signed and 32 bits long.
2727
field accumulator(&executor) -> i32 as "Current value of the accumulator" {
2828
executor.context().0.load(atomic::Ordering::Relaxed) as i32
@@ -33,7 +33,7 @@ graphql_object!(Query: Context |&self| {
3333
// `Query`, but it provides the way to "mutate" the accumulator state.
3434
struct Mutation;
3535

36-
graphql_object!(Mutation: Context |&self| {
36+
graphql_object!(Mutation: Data |&self| {
3737
field add(&executor, by: i32) -> i32 as "Add given value to the accumulator." {
3838
executor.context().0.fetch_add(by as isize, atomic::Ordering::Relaxed) as i32 + by
3939
}
@@ -45,23 +45,21 @@ type Schema = juniper::RootNode<'static, Query, Mutation>;
4545

4646
// Finally, we'll bridge between Tide and Juniper. `GraphQLRequest` from Juniper implements
4747
// `Deserialize`, so we use `Json` extractor to deserialize the request body.
48-
async fn handle_graphql(
49-
ctx: AppData<Context>,
50-
query: body::Json<juniper::http::GraphQLRequest>,
51-
) -> Response {
52-
let response = query.execute(&Schema::new(Query, Mutation), &ctx);
48+
async fn handle_graphql(mut cx: Context<Data>) -> EndpointResult {
49+
let query: juniper::http::GraphQLRequest = await!(cx.body_json()).client_err()?;
50+
let response = query.execute(&Schema::new(Query, Mutation), cx.app_data());
5351
let status = if response.is_ok() {
5452
StatusCode::OK
5553
} else {
5654
StatusCode::BAD_REQUEST
5755
};
58-
body::Json(response).with_status(status).into_response()
56+
let mut resp = response::json(response);
57+
*resp.status_mut() = status;
58+
Ok(resp)
5959
}
6060

6161
fn main() {
62-
let mut app = App::new(Context::default());
63-
62+
let mut app = App::new(Data::default());
6463
app.at("/graphql").post(handle_graphql);
65-
66-
app.serve();
64+
app.serve("127.0.0.1:8000").unwrap();
6765
}

examples/hello.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
fn main() {
44
let mut app = tide::App::new(());
5-
app.at("/").get(async || "Hello, world!");
6-
7-
app.serve();
5+
app.at("/").get(async move |_| "Hello, world!");
6+
app.serve("127.0.0.1:8000").unwrap();
87
}

0 commit comments

Comments
 (0)