Skip to content

Commit ac0abd3

Browse files
committed
Erase type on server state and place in Arc<State> any hashmap
1 parent 41afeb9 commit ac0abd3

26 files changed

+247
-306
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ serde = "1.0.117"
5050
serde_json = "1.0.59"
5151
routefinder = "0.5.0"
5252
regex = "1.5.5"
53+
hashbrown = "0.12.3"
5354

5455
[dev-dependencies]
5556
async-std = { version = "1.6.5", features = ["unstable", "attributes"] }

examples/graphql.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::sync::{Arc, RwLock};
22

33
use juniper::{http::graphiql, http::GraphQLRequest, RootNode};
44
use lazy_static::lazy_static;
5-
use tide::{http::mime, Body, Redirect, Request, RequestState, Response, Server, StatusCode};
5+
use tide::{http::mime, Body, Redirect, Request, Response, Server, StatusCode};
66

77
#[derive(Clone)]
88
struct User {
@@ -76,7 +76,7 @@ lazy_static! {
7676

7777
async fn handle_graphql(mut request: Request) -> tide::Result {
7878
let query: GraphQLRequest = request.body_json().await?;
79-
let response = query.execute(&SCHEMA, request.state());
79+
let response = query.execute(&SCHEMA, request.state::<State>());
8080
let status = if response.is_ok() {
8181
StatusCode::Ok
8282
} else {
@@ -105,9 +105,3 @@ async fn main() -> std::io::Result<()> {
105105
app.listen("0.0.0.0:8080").await?;
106106
Ok(())
107107
}
108-
109-
impl RequestState<State> for Request {
110-
fn state(&self) -> &State {
111-
self.ext::<State>().unwrap()
112-
}
113-
}

examples/middleware.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::sync::Arc;
33

44
use tide::http::mime;
55
use tide::utils::{After, Before};
6-
use tide::{Middleware, Next, Request, RequestState, Response, Result, StatusCode};
6+
use tide::{Middleware, Next, Request, Response, Result, StatusCode};
77

88
#[derive(Debug)]
99
struct User {
@@ -24,7 +24,7 @@ impl UserDatabase {
2424
// application state. Because it depends on a specific request state,
2525
// it would likely be closely tied to a specific application
2626
async fn user_loader(mut request: Request, next: Next) -> Result {
27-
if let Some(user) = request.state().find_user().await {
27+
if let Some(user) = request.state::<UserDatabase>().find_user().await {
2828
tide::log::trace!("user loaded", {user: user.name});
2929
request.set_ext(user);
3030
Ok(next.run(request).await)
@@ -125,9 +125,3 @@ async fn main() -> Result<()> {
125125
app.listen("127.0.0.1:8080").await?;
126126
Ok(())
127127
}
128-
129-
impl RequestState<UserDatabase> for Request {
130-
fn state(&self) -> &UserDatabase {
131-
self.ext::<UserDatabase>().unwrap()
132-
}
133-
}

examples/state.rs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
use std::sync::atomic::{AtomicU32, Ordering};
22
use std::sync::Arc;
33

4-
use tide::RequestState;
5-
64
#[derive(Clone)]
75
struct State {
86
value: Arc<AtomicU32>,
@@ -22,21 +20,15 @@ async fn main() -> tide::Result<()> {
2220
let mut app = tide::with_state(State::new());
2321
app.with(tide::log::LogMiddleware::new());
2422
app.at("/").get(|req: tide::Request| async move {
25-
let state = req.state();
23+
let state = req.state::<State>();
2624
let value = state.value.load(Ordering::Relaxed);
2725
Ok(format!("{}\n", value))
2826
});
2927
app.at("/inc").get(|req: tide::Request| async move {
30-
let state = req.state();
28+
let state = req.state::<State>();
3129
let value = state.value.fetch_add(1, Ordering::Relaxed) + 1;
3230
Ok(format!("{}\n", value))
3331
});
3432
app.listen("127.0.0.1:8080").await?;
3533
Ok(())
3634
}
37-
38-
impl RequestState<State> for tide::Request {
39-
fn state(&self) -> &State {
40-
self.ext::<State>().unwrap()
41-
}
42-
}

examples/upload.rs

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::sync::Arc;
55
use async_std::{fs::OpenOptions, io};
66
use tempfile::TempDir;
77
use tide::prelude::*;
8-
use tide::{Body, Request, RequestState, Response, StatusCode};
8+
use tide::{Body, Request, Response, StatusCode};
99

1010
#[derive(Clone)]
1111
struct TempDirState {
@@ -24,12 +24,6 @@ impl TempDirState {
2424
}
2525
}
2626

27-
impl RequestState<TempDirState> for Request {
28-
fn state(&self) -> &TempDirState {
29-
self.ext::<TempDirState>().unwrap()
30-
}
31-
}
32-
3327
#[async_std::main]
3428
async fn main() -> Result<(), IoError> {
3529
// tide::log::start();
@@ -44,7 +38,7 @@ async fn main() -> Result<(), IoError> {
4438
app.at(":file")
4539
.put(|req: Request| async move {
4640
let path = req.param("file")?;
47-
let state = req.state();
41+
let state = req.state::<TempDirState>();
4842
let fs_path = state.path().join(path);
4943

5044
let file = OpenOptions::new()
@@ -64,7 +58,7 @@ async fn main() -> Result<(), IoError> {
6458
})
6559
.get(|req: Request| async move {
6660
let path = req.param("file")?;
67-
let fs_path = req.state().path().join(path);
61+
let fs_path = req.state::<TempDirState>().path().join(path);
6862

6963
if let Ok(body) = Body::from_file(fs_path).await {
7064
Ok(body.into())

src/endpoint.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::{Middleware, Request, Response};
1111
/// This trait is automatically implemented for `Fn` types, and so is rarely implemented
1212
/// directly by Tide users.
1313
///
14-
/// In practice, endpoints are functions that take a `Request<State>` as an argument and
14+
/// In practice, endpoints are functions that take a `Request` as an argument and
1515
/// return a type `T` that implements `Into<Response>`.
1616
///
1717
/// # Examples

src/lib.rs

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ mod response_builder;
7777
mod route;
7878
mod router;
7979
mod server;
80+
mod state;
8081

8182
pub mod convert;
8283
pub mod listener;
@@ -97,8 +98,8 @@ pub use request::Request;
9798
pub use response::Response;
9899
pub use response_builder::ResponseBuilder;
99100
pub use route::Route;
100-
pub use server::RequestState;
101101
pub use server::Server;
102+
pub use state::State;
102103

103104
pub use http_types::{self as http, Body, Error, Status, StatusCode};
104105

@@ -117,7 +118,7 @@ pub use http_types::{self as http, Body, Error, Status, StatusCode};
117118
/// # Ok(()) }) }
118119
/// ```
119120
#[must_use]
120-
pub fn new() -> server::Server<()> {
121+
pub fn new() -> server::Server {
121122
Server::new()
122123
}
123124

@@ -131,7 +132,7 @@ pub fn new() -> server::Server<()> {
131132
/// # use async_std::task::block_on;
132133
/// # fn main() -> Result<(), std::io::Error> { block_on(async {
133134
/// #
134-
/// use tide::{Request, RequestState};
135+
/// use tide::{Request};
135136
///
136137
/// /// The shared application state.
137138
/// #[derive(Clone)]
@@ -144,22 +145,16 @@ pub fn new() -> server::Server<()> {
144145
/// name: "Nori".to_string()
145146
/// };
146147
///
147-
/// impl RequestState<State> for Request {
148-
/// fn state(&self) -> &State {
149-
/// self.ext::<State>().unwrap()
150-
/// }
151-
/// }
152-
///
153148
/// // Initialize the application with state.
154149
/// let mut app = tide::with_state(state);
155150
/// app.at("/").get(|req: Request| async move {
156-
/// Ok(format!("Hello, {}!", &req.state().name))
151+
/// Ok(format!("Hello, {}!", &req.state::<State>().name))
157152
/// });
158153
/// app.listen("127.0.0.1:8080").await?;
159154
/// #
160155
/// # Ok(()) }) }
161156
/// ```
162-
pub fn with_state<State>(state: State) -> server::Server<State>
157+
pub fn with_state<State>(state: State) -> server::Server
163158
where
164159
State: Clone + Send + Sync + 'static,
165160
{

src/listener/concurrent_listener.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,11 @@ use futures_util::stream::{futures_unordered::FuturesUnordered, StreamExt};
3333
///```
3434
3535
#[derive(Default)]
36-
pub struct ConcurrentListener<State> {
37-
listeners: Vec<Box<dyn Listener<State>>>,
36+
pub struct ConcurrentListener {
37+
listeners: Vec<Box<dyn Listener>>,
3838
}
3939

40-
impl<State: Clone + Send + Sync + 'static> ConcurrentListener<State> {
40+
impl ConcurrentListener {
4141
/// creates a new ConcurrentListener
4242
pub fn new() -> Self {
4343
Self { listeners: vec![] }
@@ -59,7 +59,7 @@ impl<State: Clone + Send + Sync + 'static> ConcurrentListener<State> {
5959
/// ```
6060
pub fn add<L>(&mut self, listener: L) -> io::Result<()>
6161
where
62-
L: ToListener<State>,
62+
L: ToListener,
6363
{
6464
self.listeners.push(Box::new(listener.to_listener()?));
6565
Ok(())
@@ -78,19 +78,16 @@ impl<State: Clone + Send + Sync + 'static> ConcurrentListener<State> {
7878
/// # Ok(()) }) }
7979
pub fn with_listener<L>(mut self, listener: L) -> Self
8080
where
81-
L: ToListener<State>,
81+
L: ToListener,
8282
{
8383
self.add(listener).expect("Unable to add listener");
8484
self
8585
}
8686
}
8787

8888
#[async_trait::async_trait]
89-
impl<State> Listener<State> for ConcurrentListener<State>
90-
where
91-
State: Clone + Send + Sync + 'static,
92-
{
93-
async fn bind(&mut self, app: Server<State>) -> io::Result<()> {
89+
impl Listener for ConcurrentListener {
90+
async fn bind(&mut self, app: Server) -> io::Result<()> {
9491
for listener in self.listeners.iter_mut() {
9592
listener.bind(app.clone()).await?;
9693
}
@@ -118,13 +115,13 @@ where
118115
}
119116
}
120117

121-
impl<State> Debug for ConcurrentListener<State> {
118+
impl Debug for ConcurrentListener {
122119
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
123120
write!(f, "{:?}", self.listeners)
124121
}
125122
}
126123

127-
impl<State> Display for ConcurrentListener<State> {
124+
impl Display for ConcurrentListener {
128125
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
129126
let string = self
130127
.listeners

src/listener/failover_listener.rs

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,12 @@ use crate::listener::ListenInfo;
3434
///}
3535
///```
3636
#[derive(Default)]
37-
pub struct FailoverListener<State> {
38-
listeners: Vec<Option<Box<dyn Listener<State>>>>,
37+
pub struct FailoverListener {
38+
listeners: Vec<Option<Box<dyn Listener>>>,
3939
index: Option<usize>,
4040
}
4141

42-
impl<State> FailoverListener<State>
43-
where
44-
State: Clone + Send + Sync + 'static,
45-
{
42+
impl FailoverListener {
4643
/// creates a new FailoverListener
4744
pub fn new() -> Self {
4845
Self {
@@ -69,7 +66,7 @@ where
6966
/// ```
7067
pub fn add<L>(&mut self, listener: L) -> io::Result<()>
7168
where
72-
L: ToListener<State>,
69+
L: ToListener,
7370
{
7471
self.listeners.push(Some(Box::new(listener.to_listener()?)));
7572
Ok(())
@@ -88,19 +85,16 @@ where
8885
/// # Ok(()) }) }
8986
pub fn with_listener<L>(mut self, listener: L) -> Self
9087
where
91-
L: ToListener<State>,
88+
L: ToListener,
9289
{
9390
self.add(listener).expect("Unable to add listener");
9491
self
9592
}
9693
}
9794

9895
#[async_trait::async_trait]
99-
impl<State> Listener<State> for FailoverListener<State>
100-
where
101-
State: Clone + Send + Sync + 'static,
102-
{
103-
async fn bind(&mut self, app: Server<State>) -> io::Result<()> {
96+
impl Listener for FailoverListener {
97+
async fn bind(&mut self, app: Server) -> io::Result<()> {
10498
for (index, listener) in self.listeners.iter_mut().enumerate() {
10599
let listener = listener.as_deref_mut().expect("bind called twice");
106100
match listener.bind(app.clone()).await {
@@ -148,13 +142,13 @@ where
148142
}
149143
}
150144

151-
impl<State> Debug for FailoverListener<State> {
145+
impl Debug for FailoverListener {
152146
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
153147
write!(f, "{:?}", self.listeners)
154148
}
155149
}
156150

157-
impl<State> Display for FailoverListener<State> {
151+
impl Display for FailoverListener {
158152
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
159153
let string = self
160154
.listeners

src/listener/mod.rs

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,11 @@ pub(crate) use unix_listener::UnixListener;
3535
/// implement at least one [`ToListener`](crate::listener::ToListener) that
3636
/// outputs your Listener type.
3737
#[async_trait]
38-
pub trait Listener<State>: Debug + Display + Send + Sync + 'static
39-
where
40-
State: Send + Sync + 'static,
41-
{
38+
pub trait Listener: Debug + Display + Send + Sync + 'static {
4239
/// Bind the listener. This starts the listening process by opening the
4340
/// necessary network ports, but not yet accepting incoming connections. This
4441
/// method must be called before `accept`.
45-
async fn bind(&mut self, app: Server<State>) -> io::Result<()>;
42+
async fn bind(&mut self, app: Server) -> io::Result<()>;
4643

4744
/// Start accepting incoming connections. This method must be called only
4845
/// after `bind` has succeeded.
@@ -54,12 +51,8 @@ where
5451
}
5552

5653
#[async_trait]
57-
impl<L, State> Listener<State> for Box<L>
58-
where
59-
L: Listener<State>,
60-
State: Send + Sync + 'static,
61-
{
62-
async fn bind(&mut self, app: Server<State>) -> io::Result<()> {
54+
impl<L: Listener> Listener for Box<L> {
55+
async fn bind(&mut self, app: Server) -> io::Result<()> {
6356
self.as_mut().bind(app).await
6457
}
6558

0 commit comments

Comments
 (0)