Skip to content

Commit

Permalink
feat(smol): add trillium_smol::UnixStream
Browse files Browse the repository at this point in the history
  • Loading branch information
jbr committed Apr 18, 2024
1 parent 9b3c99e commit 172630f
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
2 changes: 2 additions & 0 deletions smol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ signal-hook-async-std = "0.2.2"

[dev-dependencies]
env_logger = "0.11.0"
tempfile = "3.10.1"
test-harness = "0.2.0"
trillium-client = { path = "../client" }
trillium-logger = { path = "../logger" }
trillium-testing = { path = "../testing" }
Expand Down
5 changes: 5 additions & 0 deletions smol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ pub use async_net;
mod runtime;
pub use runtime::SmolRuntime;

#[cfg(unix)]
mod unix_socket_connector;
#[cfg(unix)]
pub use unix_socket_connector::UnixStream;

/**
# Runs a trillium handler in a sync context with default config
Expand Down
32 changes: 32 additions & 0 deletions smol/src/unix_socket_connector.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use crate::SmolRuntime;
use futures_lite::{AsyncRead, AsyncWrite};
use std::{io, path::Path};
use trillium_macros::{AsyncRead, AsyncWrite};
use trillium_server_common::{Connector, Transport, Url};

/// A transport that is also a connector.
///
/// Construct it with [`UnixStream::connect`]
#[derive(AsyncWrite, AsyncRead, Debug, Clone)]
pub struct UnixStream(async_net::unix::UnixStream);

impl UnixStream {
/// connect a new UnixStream
pub async fn connect(path: impl AsRef<Path>) -> io::Result<Self> {
async_net::unix::UnixStream::connect(path).await.map(Self)
}
}

impl Transport for UnixStream {}

impl Connector for UnixStream {
type Transport = Self;
type Runtime = SmolRuntime;
async fn connect(&self, _url: &Url) -> io::Result<Self::Transport> {
Ok(self.clone())
}

fn runtime(&self) -> Self::Runtime {
SmolRuntime::default()
}
}
21 changes: 21 additions & 0 deletions smol/tests/unix_stream.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#![cfg(unix)]
use test_harness::test;
use trillium_client::Client;
use trillium_smol::{config, UnixStream};
use trillium_testing::harness;

#[test(harness)]
async fn smoke() {
let temp_dir = tempfile::tempdir().unwrap();
let path = temp_dir.path().join("socket");

let handle = config().with_host(path.to_str().unwrap()).spawn("ok");
handle.info().await;

let stream = UnixStream::connect(path).await.unwrap();
let mut conn = Client::new(stream).get("http://localhost/").await.unwrap();

assert_eq!(conn.status().unwrap(), 200);
assert_eq!(conn.response_body().read_string().await.unwrap(), "ok");
handle.shut_down().await;
}

0 comments on commit 172630f

Please sign in to comment.