-
Notifications
You must be signed in to change notification settings - Fork 0
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
Port miniserve to async #17
Open
willcrichton
wants to merge
3
commits into
00-chat-route-b
Choose a base branch
from
01-async-await-a
base: 00-chat-route-b
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,6 @@ | ||
[workspace] | ||
members = ["crates/*"] | ||
resolver = "2" | ||
|
||
[workspace.dependencies] | ||
tokio = { version = "1.39.2", default-features = false } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,7 @@ | ||
#![warn(clippy::pedantic)] | ||
|
||
use std::{ | ||
collections::HashMap, | ||
io::{self}, | ||
net::{TcpListener, TcpStream}, | ||
sync::Arc, | ||
thread, | ||
}; | ||
use std::{collections::HashMap, future::Future, io, pin::Pin, sync::Arc}; | ||
use tokio::net::{TcpListener, TcpStream}; | ||
|
||
/// Re-export for library clients. | ||
pub use http; | ||
|
@@ -32,15 +27,26 @@ pub enum Content { | |
pub type Response = Result<Content, http::StatusCode>; | ||
|
||
/// Trait alias for functions that can handle requests and return responses. | ||
pub trait Handler: Fn(Request) -> Response + Send + Sync + 'static {} | ||
pub trait Handler: Fn(Request) -> Self::Future + Send + Sync + 'static { | ||
type Future: Future<Output = Response> + Send + Sync + 'static; | ||
} | ||
|
||
impl<F, H> Handler for H | ||
where | ||
F: Future<Output = Response> + Send + Sync + 'static, | ||
H: Fn(Request) -> F + Send + Sync + 'static, | ||
{ | ||
type Future = F; | ||
} | ||
|
||
impl<F> Handler for F where F: Fn(Request) -> Response + Send + Sync + 'static {} | ||
type ErasedHandler = | ||
Box<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send + Sync>> + Send + Sync>; | ||
|
||
/// The main server data structure. | ||
#[derive(Default)] | ||
pub struct Server { | ||
/// Map from a route path (e.g., "/foo") to a handler function for that route. | ||
routes: HashMap<String, Box<dyn Handler>>, | ||
routes: HashMap<String, ErasedHandler>, | ||
} | ||
|
||
impl Server { | ||
|
@@ -55,7 +61,12 @@ impl Server { | |
/// Adds a new route to the server. | ||
#[must_use] | ||
pub fn route<H: Handler>(mut self, route: impl Into<String>, handler: H) -> Self { | ||
self.routes.insert(route.into(), Box::new(handler)); | ||
let handler = Arc::new(handler); | ||
let erased = Box::new(move |req| { | ||
let handler_ref = Arc::clone(&handler); | ||
Box::pin(handler_ref(req)) as Pin<Box<dyn Future<Output = Response> + Send + Sync>> | ||
}); | ||
self.routes.insert(route.into(), erased); | ||
self | ||
} | ||
|
||
|
@@ -66,21 +77,22 @@ impl Server { | |
/// # Panics | ||
/// | ||
/// Panics if `127.0.0.1:3000` is not available. | ||
pub fn run(self) { | ||
let listener = | ||
TcpListener::bind("127.0.0.1:3000").expect("Failed to connect to 127.0.0.1:3000"); | ||
pub async fn run(self) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Note that the |
||
let listener = TcpListener::bind("127.0.0.1:3000") | ||
.await | ||
.expect("Failed to connect to 127.0.0.1:3000"); | ||
let this = Arc::new(self); | ||
for stream in listener.incoming().flatten() { | ||
let this_ref = Arc::clone(&this); | ||
thread::spawn(move || { | ||
let _ = this_ref.handle(&stream); | ||
}); | ||
loop { | ||
if let Ok((stream, _)) = listener.accept().await { | ||
let this_ref = Arc::clone(&this); | ||
tokio::spawn(async move { | ||
let _ = this_ref.handle(stream).await; | ||
}); | ||
} | ||
} | ||
} | ||
|
||
fn handle(&self, stream: &TcpStream) -> io::Result<()> { | ||
protocol::handle(stream, |route, request| { | ||
self.routes.get(route).map(move |handler| handler(request)) | ||
}) | ||
async fn handle(&self, stream: TcpStream) -> io::Result<()> { | ||
protocol::handle(stream, &|route| self.routes.get(route)).await | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Take a close look at the change to the
Handler
trait. Previously, a handler was a function that took a request and returned a response. Now, a handler is a function that takes a request and returns a future which eventually returns a response.