Skip to content

Commit

Permalink
feat!: introduce ServerConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
jbr committed Jun 25, 2024
1 parent 81ad587 commit b368b94
Show file tree
Hide file tree
Showing 74 changed files with 2,360 additions and 2,290 deletions.
14 changes: 2 additions & 12 deletions api/tests/disconnect-body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,20 +100,10 @@ async fn establish_server(handler: impl Handler) -> (ServerHandle, impl AsyncWri

let handle = trillium_testing::config().with_port(0).spawn(handler);
let info = handle.info().await;
let port = info.tcp_socket_addr().map_or_else(
|| {
info.listener_description()
.split(":")
.nth(1)
.unwrap()
.parse()
.unwrap()
},
|x| x.port(),
);
let url = info.state::<url::Url>().unwrap();

let client = ArcedConnector::new(client_config())
.connect(&format!("http://localhost:{port}").parse().unwrap())
.connect(url)
.await
.unwrap();
(handle, client)
Expand Down
10 changes: 9 additions & 1 deletion async-std/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ impl RuntimeTrait for AsyncStdRuntime {
fn block_on<Fut: Future>(&self, fut: Fut) -> Fut::Output {
async_std::task::block_on(fut)
}

#[cfg(unix)]
fn hook_signals(
&self,
signals: impl IntoIterator<Item = i32>,
) -> impl Stream<Item = i32> + Send + 'static {
signal_hook_async_std::Signals::new(signals).unwrap()
}
}

impl AsyncStdRuntime {
Expand Down Expand Up @@ -81,6 +89,6 @@ impl AsyncStdRuntime {

impl From<AsyncStdRuntime> for Runtime {
fn from(value: AsyncStdRuntime) -> Self {
Runtime::new(value)
Runtime::from_trait_impl(value)
}
}
18 changes: 6 additions & 12 deletions async-std/src/server/tcp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{AsyncStdRuntime, AsyncStdTransport};
use async_std::net::{TcpListener, TcpStream};
use std::{env, io::Result};
use std::io::Result;
use trillium::Info;
use trillium_server_common::Server;

Expand All @@ -22,24 +22,18 @@ impl Server for AsyncStdServer {
type Runtime = AsyncStdRuntime;
type Transport = AsyncStdTransport<TcpStream>;

const DESCRIPTION: &'static str = concat!(
" (",
env!("CARGO_PKG_NAME"),
" v",
env!("CARGO_PKG_VERSION"),
")"
);

async fn accept(&mut self) -> Result<Self::Transport> {
self.0.accept().await.map(|(t, _)| t.into())
}

fn listener_from_tcp(tcp: std::net::TcpListener) -> Self {
fn from_tcp(tcp: std::net::TcpListener) -> Self {
Self(tcp.into())
}

fn info(&self) -> Info {
self.0.local_addr().unwrap().into()
fn init(&self, info: &mut Info) {
if let Ok(socket_addr) = self.0.local_addr() {
info.insert_state(socket_addr);
}
}

fn runtime() -> Self::Runtime {
Expand Down
49 changes: 16 additions & 33 deletions async-std/src/server/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ use crate::{AsyncStdRuntime, AsyncStdTransport};
use async_std::{
net::{TcpListener, TcpStream},
os::unix::net::{UnixListener, UnixStream},
stream::StreamExt,
};
use std::{env, io::Result};
use std::io::Result;
use trillium::{log_error, Info};
use trillium_server_common::{
Binding::{self, *},
Server, Swansong,
Server,
};

/// Tcp/Unix Trillium server adapter for Async-Std
Expand Down Expand Up @@ -41,31 +40,6 @@ impl Server for AsyncStdServer {
type Runtime = AsyncStdRuntime;
type Transport = Binding<AsyncStdTransport<TcpStream>, AsyncStdTransport<UnixStream>>;

const DESCRIPTION: &'static str = concat!(
" (",
env!("CARGO_PKG_NAME"),
" v",
env!("CARGO_PKG_VERSION"),
")"
);

async fn handle_signals(swansong: Swansong) {
use signal_hook::consts::signal::*;
use signal_hook_async_std::Signals;

let signals = Signals::new([SIGINT, SIGTERM, SIGQUIT]).unwrap();
let mut signals = signals.fuse();
while signals.next().await.is_some() {
if swansong.state().is_shutting_down() {
eprintln!("\nSecond interrupt, shutting down harshly");
std::process::exit(1);
} else {
println!("\nShutting down gracefully.\nControl-C again to force.");
swansong.shut_down();
}
}
}

async fn accept(&mut self) -> Result<Self::Transport> {
match &self.0 {
Tcp(t) => t
Expand All @@ -80,18 +54,27 @@ impl Server for AsyncStdServer {
}
}

fn listener_from_tcp(tcp: std::net::TcpListener) -> Self {
fn from_tcp(tcp: std::net::TcpListener) -> Self {
Self(Tcp(tcp.into()))
}

fn listener_from_unix(tcp: std::os::unix::net::UnixListener) -> Self {
fn from_unix(tcp: std::os::unix::net::UnixListener) -> Self {
Self(Unix(tcp.into()))
}

fn info(&self) -> Info {
fn init(&self, info: &mut Info) {
match &self.0 {
Tcp(t) => t.local_addr().unwrap().into(),
Unix(u) => u.local_addr().unwrap().into(),
Tcp(t) => {
if let Ok(socket_addr) = t.local_addr() {
info.insert_state(socket_addr);
}
}

Unix(u) => {
if let Ok(socket_addr) = u.local_addr() {
info.insert_state(socket_addr);
}
}
}
}

Expand Down
20 changes: 13 additions & 7 deletions aws-lambda/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use lamedh_runtime::{Context, Handler as AwsHandler};
use std::{future::Future, pin::Pin, sync::Arc};
use tokio::runtime;
use trillium::{Conn, Handler};
use trillium_http::{Conn as HttpConn, Synthetic};
use trillium_http::{Conn as HttpConn, ServerConfig, Synthetic};

mod context;
pub use context::LambdaConnExt;
Expand All @@ -32,14 +32,19 @@ mod response;
use response::{AlbMultiHeadersResponse, AlbResponse, LambdaResponse};

#[derive(Debug)]
struct HandlerWrapper<H>(Arc<H>);
struct HandlerWrapper<H>(Arc<H>, Arc<ServerConfig>);

impl<H: Handler> AwsHandler<LambdaRequest, LambdaResponse> for HandlerWrapper<H> {
type Error = std::io::Error;
type Fut = Pin<Box<dyn Future<Output = Result<LambdaResponse, Self::Error>> + Send + 'static>>;

fn call(&mut self, request: LambdaRequest, context: Context) -> Self::Fut {
Box::pin(handler_fn(request, context, Arc::clone(&self.0)))
Box::pin(handler_fn(
request,
context,
Arc::clone(&self.0),
Arc::clone(&self.1),
))
}
}

Expand All @@ -52,17 +57,18 @@ async fn handler_fn(
request: LambdaRequest,
context: Context,
handler: Arc<impl Handler>,
server_config: Arc<ServerConfig>,
) -> std::io::Result<LambdaResponse> {
match request {
LambdaRequest::Alb(request) => {
let mut conn = request.into_conn().await;
let mut conn = request.into_conn().await.with_server_config(server_config);
conn.state_mut().insert(LambdaContext::new(context));
let conn = run_handler(conn, handler).await;
Ok(LambdaResponse::Alb(AlbResponse::from_conn(conn).await))
}

LambdaRequest::AlbMultiHeaders(request) => {
let mut conn = request.into_conn().await;
let mut conn = request.into_conn().await.with_server_config(server_config);
conn.state_mut().insert(LambdaContext::new(context));
let conn = run_handler(conn, handler).await;
Ok(LambdaResponse::AlbMultiHeaders(
Expand All @@ -75,9 +81,9 @@ async fn handler_fn(
///
/// This function will poll pending until the server shuts down.
pub async fn run_async(mut handler: impl Handler) {
let mut info = "aws lambda".into();
let mut info = ServerConfig::default().into();
handler.init(&mut info).await;
lamedh_runtime::run(HandlerWrapper(Arc::new(handler)))
lamedh_runtime::run(HandlerWrapper(Arc::new(handler), Arc::new(info.into())))
.await
.unwrap()
}
Expand Down
7 changes: 4 additions & 3 deletions client/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::{Conn, IntoUrl, Pool, USER_AGENT};
use std::{fmt::Debug, sync::Arc, time::Duration};
use trillium_http::{
transport::BoxedTransport, HeaderName, HeaderValues, Headers, KnownHeaderName, Method,
ReceivedBodyState, Version::Http1_1,
ReceivedBodyState, TypeSet, Version::Http1_1,
};
use trillium_server_common::{
url::{Origin, Url},
Expand Down Expand Up @@ -76,9 +76,9 @@ impl Client {
method!(patch, Patch);

/// builds a new client from this `Connector`
pub fn new(config: impl Connector) -> Self {
pub fn new(connector: impl Connector) -> Self {
Self {
config: ArcedConnector::new(config),
config: ArcedConnector::new(connector),
pool: None,
base: None,
default_headers: Arc::new(default_request_headers()),
Expand Down Expand Up @@ -167,6 +167,7 @@ impl Client {
timeout: self.timeout,
http_version: Http1_1,
max_head_length: 8 * 1024,
state: TypeSet::new(),
}
}

Expand Down
Loading

0 comments on commit b368b94

Please sign in to comment.