mirror of https://github.com/stjepang/smol
Compare commits
44 Commits
Author | SHA1 | Date |
---|---|---|
dependabot[bot] | 641326b54f | |
dependabot[bot] | bc7a85d170 | |
dependabot[bot] | f8f5a4af67 | |
John Nunley | 490c4c6e64 | |
John Nunley | f3054c3537 | |
John Nunley | 5b505fc26d | |
John Nunley | d37bf58d8d | |
dependabot[bot] | b1c9f8743e | |
dependabot[bot] | bdc061956a | |
John Nunley | 75c8dcedfa | |
John Nunley | 19ca79660f | |
dependabot[bot] | f337143aba | |
dependabot[bot] | 19a6a3faaa | |
dependabot[bot] | 1beb26f5d1 | |
dependabot[bot] | d1da833155 | |
Alex Touchet | f0cd8e37d9 | |
Taiki Endo | 8d8879df0f | |
Taiki Endo | 7e95fff0bf | |
John Nunley | 86dad666a1 | |
dependabot[bot] | 2ca5cd505b | |
imarkov | 5d51de0bd5 | |
dependabot[bot] | 084a207cf1 | |
Taiki Endo | 8a67449e06 | |
Taiki Endo | c428a2b225 | |
John Nunley | 35b45aa3da | |
dependabot[bot] | 14d27a94c5 | |
Taiki Endo | 4604978cf0 | |
dependabot[bot] | b35cafc04b | |
Taiki Endo | ef89385fcb | |
dependabot[bot] | 5ceeb1598b | |
Taiki Endo | bf64d51914 | |
dependabot[bot] | b2a51bb937 | |
dependabot[bot] | 678f70de25 | |
Taiki Endo | c65906cac8 | |
Taiki Endo | b2a5e69394 | |
Taiki Endo | be21c2f968 | |
dependabot[bot] | 9e13aecceb | |
John Nunley | 36e085f9fa | |
dependabot[bot] | f5c45807c2 | |
dependabot[bot] | faee9a8ca5 | |
dependabot[bot] | 0ae00dac77 | |
dependabot[bot] | fc6acf23c9 | |
Taiki Endo | 4b16219609 | |
Taiki Endo | 3022d23f27 |
|
@ -0,0 +1,9 @@
|
|||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: cargo
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
commit-message:
|
||||
prefix: ''
|
||||
labels: []
|
|
@ -1,16 +1,29 @@
|
|||
name: CI
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
schedule:
|
||||
- cron: '0 2 * * *'
|
||||
- cron: '0 2 * * 0'
|
||||
|
||||
env:
|
||||
RUSTFLAGS: -D warnings
|
||||
CARGO_INCREMENTAL: 0
|
||||
CARGO_NET_GIT_FETCH_WITH_CLI: true
|
||||
CARGO_NET_RETRY: 10
|
||||
CARGO_TERM_COLOR: always
|
||||
RUST_BACKTRACE: 1
|
||||
RUSTFLAGS: -D warnings
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
RUSTUP_MAX_RETRIES: 10
|
||||
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
jobs:
|
||||
test:
|
||||
|
@ -21,7 +34,7 @@ jobs:
|
|||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
rust: [nightly, beta, stable]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
# --no-self-update is necessary because the windows environment cannot self-update rustup.exe.
|
||||
run: rustup update ${{ matrix.rust }} --no-self-update && rustup default ${{ matrix.rust }}
|
||||
|
@ -36,10 +49,10 @@ jobs:
|
|||
strategy:
|
||||
matrix:
|
||||
# When updating this, the reminder to update the minimum supported
|
||||
# Rust version in Cargo.toml.
|
||||
rust: ['1.47']
|
||||
# Rust version in Cargo.toml and README.md.
|
||||
rust: ['1.63']
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
run: rustup update ${{ matrix.rust }} && rustup default ${{ matrix.rust }}
|
||||
- run: cargo build
|
||||
|
@ -47,7 +60,7 @@ jobs:
|
|||
clippy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
run: rustup update stable
|
||||
- run: cargo clippy --all-features --all-targets
|
||||
|
@ -55,15 +68,20 @@ jobs:
|
|||
fmt:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: Install Rust
|
||||
run: rustup update stable
|
||||
- run: cargo fmt --all --check
|
||||
|
||||
security_audit:
|
||||
permissions:
|
||||
checks: write
|
||||
contents: read
|
||||
issues: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions-rs/audit-check@v1
|
||||
- uses: actions/checkout@v4
|
||||
# https://github.com/rustsec/audit-check/issues/2
|
||||
- uses: rustsec/audit-check@master
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
|
|
@ -1,5 +1,8 @@
|
|||
name: Release
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
|
@ -10,7 +13,7 @@ jobs:
|
|||
if: github.repository_owner == 'smol-rs'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- uses: taiki-e/create-gh-release-action@v1
|
||||
with:
|
||||
changelog: CHANGELOG.md
|
||||
|
|
|
@ -1,3 +1,8 @@
|
|||
# Version 2.0.0
|
||||
|
||||
- **Breaking:** Bump subcrates to their newest major versions. (#277, #280, #281, #282, #283)
|
||||
- Run the `async-process` driver on the executor. (#284)
|
||||
|
||||
# Version 1.3.0
|
||||
|
||||
- Remove the dependency on the `once_cell` crate to restore the MSRV. (#241)
|
||||
|
|
39
Cargo.toml
39
Cargo.toml
|
@ -2,11 +2,11 @@
|
|||
name = "smol"
|
||||
# When publishing a new version:
|
||||
# - Update CHANGELOG.md
|
||||
# - Create "v1.x.y" git tag
|
||||
version = "1.3.0"
|
||||
# - Create "v2.x.y" git tag
|
||||
version = "2.0.0"
|
||||
authors = ["Stjepan Glavina <stjepang@gmail.com>"]
|
||||
edition = "2018"
|
||||
rust-version = "1.47"
|
||||
rust-version = "1.63"
|
||||
description = "A small and fast async runtime"
|
||||
license = "Apache-2.0 OR MIT"
|
||||
repository = "https://github.com/smol-rs/smol"
|
||||
|
@ -15,40 +15,45 @@ categories = ["asynchronous", "concurrency", "network-programming"]
|
|||
exclude = ["/.*"]
|
||||
|
||||
[dependencies]
|
||||
async-channel = "1.4.2"
|
||||
async-channel = "2.0.0"
|
||||
async-executor = "1.5.0"
|
||||
async-fs = "1.3.0"
|
||||
async-io = "1.12.0"
|
||||
async-lock = "2.6.0"
|
||||
async-net = "1.4.3"
|
||||
async-process = "1.6.0"
|
||||
async-fs = "2.0.0"
|
||||
async-io = "2.1.0"
|
||||
async-lock = "3.0.0"
|
||||
async-net = "2.0.0"
|
||||
blocking = "1.3.0"
|
||||
futures-lite = "1.11.0"
|
||||
futures-lite = "2.0.0"
|
||||
|
||||
[target.'cfg(not(target_os = "espidf"))'.dependencies]
|
||||
async-process = "2.0.0"
|
||||
|
||||
[dev-dependencies]
|
||||
anyhow = "1"
|
||||
async-dup = "1"
|
||||
async-h1 = "2"
|
||||
async-native-tls = "0.4"
|
||||
async-tungstenite = { version = "0.17", features = ["async-native-tls"] }
|
||||
async-native-tls = "0.5"
|
||||
async-tungstenite = { version = "0.25", features = ["async-native-tls"] }
|
||||
ctrlc = "3"
|
||||
doc-comment = "0.3"
|
||||
futures = "0.3"
|
||||
http = "0.2"
|
||||
http = "1.1"
|
||||
http-body-util = "0.1.0"
|
||||
http-types = "2"
|
||||
hyper = { version = "0.14", default-features = false, features = ["client", "http1", "server", "stream"] }
|
||||
hyper = { version = "1.0", default-features = false, features = ["client", "http1", "server"] }
|
||||
macro_rules_attribute = "0.2.0"
|
||||
native-tls = "0.2"
|
||||
scraper = "0.13"
|
||||
scraper = "0.19"
|
||||
signal-hook = "0.3"
|
||||
smol-hyper = "0.1.0"
|
||||
smol-macros = "0.1.0"
|
||||
surf = { version = "2", default-features = false, features = ["h1-client"] }
|
||||
tempfile = "3"
|
||||
tokio = { version = "1", default-features = false, features = ["rt-multi-thread"] }
|
||||
tungstenite = "0.17"
|
||||
url = "2"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dev-dependencies]
|
||||
inotify = { version = "0.10", default-features = false }
|
||||
nix = "0.24"
|
||||
rustix = "0.38"
|
||||
timerfd = "1"
|
||||
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
|
|
12
README.md
12
README.md
|
@ -1,6 +1,6 @@
|
|||
# smol
|
||||
|
||||
[![Build](https://github.com/smol-rs/smol/workflows/Build%20and%20test/badge.svg)](
|
||||
[![Build](https://github.com/smol-rs/smol/actions/workflows/ci.yml/badge.svg)](
|
||||
https://github.com/smol-rs/smol/actions)
|
||||
[![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)](
|
||||
https://github.com/smol-rs/smol)
|
||||
|
@ -8,8 +8,10 @@ https://github.com/smol-rs/smol)
|
|||
https://crates.io/crates/smol)
|
||||
[![Documentation](https://docs.rs/smol/badge.svg)](
|
||||
https://docs.rs/smol)
|
||||
[![Chat](https://img.shields.io/discord/701824908866617385.svg?logo=discord)](
|
||||
https://discord.gg/x6m5Vvt)
|
||||
[![Chat](https://img.shields.io/matrix/smol-rs%3Amatrix.org)](
|
||||
https://matrix.to/#/#smol-rs:matrix.org)
|
||||
|
||||
<img src="https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png" alt="kitty" width="100px" style="float: left;" />
|
||||
|
||||
A small and fast async runtime.
|
||||
|
||||
|
@ -99,6 +101,10 @@ Another useful tool for making certificates is [mkcert].
|
|||
|
||||
[mkcert]: https://github.com/FiloSottile/mkcert
|
||||
|
||||
## MSRV Policy
|
||||
|
||||
The Minimum Supported Rust Version (MSRV) of this crate is **1.63**. As a **tentative** policy, the MSRV will not advance past the [current Rust version provided by Debian Stable](https://packages.debian.org/stable/rust/rustc). At the time of writing, this version of Rust is *1.63*. However, the MSRV may be advanced further in the event of a major ecosystem shift or a security vulnerability.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under either of
|
||||
|
|
Binary file not shown.
After Width: | Height: | Size: 112 KiB |
Binary file not shown.
After Width: | Height: | Size: 117 KiB |
|
@ -6,175 +6,139 @@
|
|||
//! cargo run --example hyper-client
|
||||
//! ```
|
||||
|
||||
use std::net::Shutdown;
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::convert::TryInto;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use anyhow::{bail, Context as _, Error, Result};
|
||||
use anyhow::{bail, Context as _, Result};
|
||||
use async_native_tls::TlsStream;
|
||||
use http::Uri;
|
||||
use hyper::{Body, Client, Request, Response};
|
||||
use smol::{io, prelude::*, Async};
|
||||
use http_body_util::{BodyStream, Empty};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::{Request, Response};
|
||||
use macro_rules_attribute::apply;
|
||||
use smol::{io, net::TcpStream, prelude::*, Executor};
|
||||
use smol_hyper::rt::FuturesIo;
|
||||
use smol_macros::main;
|
||||
|
||||
/// Sends a request and fetches the response.
|
||||
async fn fetch(req: Request<Body>) -> Result<Response<Body>> {
|
||||
Ok(Client::builder()
|
||||
.executor(SmolExecutor)
|
||||
.build::<_, Body>(SmolConnector)
|
||||
.request(req)
|
||||
.await?)
|
||||
}
|
||||
async fn fetch(
|
||||
ex: &Executor<'static>,
|
||||
req: Request<Empty<&'static [u8]>>,
|
||||
) -> Result<Response<Incoming>> {
|
||||
// Connect to the HTTP server.
|
||||
let io = {
|
||||
let host = req.uri().host().context("cannot parse host")?;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
smol::block_on(async {
|
||||
// Create a request.
|
||||
let req = Request::get("https://www.rust-lang.org").body(Body::empty())?;
|
||||
|
||||
// Fetch the response.
|
||||
let resp = fetch(req).await?;
|
||||
println!("{:#?}", resp);
|
||||
|
||||
// Read the message body.
|
||||
let body = resp
|
||||
.into_body()
|
||||
.try_fold(Vec::new(), |mut body, chunk| {
|
||||
body.extend_from_slice(&chunk);
|
||||
Ok(body)
|
||||
})
|
||||
.await?;
|
||||
println!("{}", String::from_utf8_lossy(&body));
|
||||
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawns futures.
|
||||
#[derive(Clone)]
|
||||
struct SmolExecutor;
|
||||
|
||||
impl<F: Future + Send + 'static> hyper::rt::Executor<F> for SmolExecutor {
|
||||
fn execute(&self, fut: F) {
|
||||
smol::spawn(async { drop(fut.await) }).detach();
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects to URLs.
|
||||
#[derive(Clone)]
|
||||
struct SmolConnector;
|
||||
|
||||
impl hyper::service::Service<Uri> for SmolConnector {
|
||||
type Response = SmolStream;
|
||||
type Error = Error;
|
||||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
|
||||
|
||||
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, uri: Uri) -> Self::Future {
|
||||
Box::pin(async move {
|
||||
let host = uri.host().context("cannot parse host")?;
|
||||
|
||||
match uri.scheme_str() {
|
||||
Some("http") => {
|
||||
let socket_addr = {
|
||||
let host = host.to_string();
|
||||
let port = uri.port_u16().unwrap_or(80);
|
||||
smol::unblock(move || (host.as_str(), port).to_socket_addrs())
|
||||
.await?
|
||||
.next()
|
||||
.context("cannot resolve address")?
|
||||
};
|
||||
let stream = Async::<TcpStream>::connect(socket_addr).await?;
|
||||
Ok(SmolStream::Plain(stream))
|
||||
}
|
||||
Some("https") => {
|
||||
// In case of HTTPS, establish a secure TLS connection first.
|
||||
let socket_addr = {
|
||||
let host = host.to_string();
|
||||
let port = uri.port_u16().unwrap_or(443);
|
||||
smol::unblock(move || (host.as_str(), port).to_socket_addrs())
|
||||
.await?
|
||||
.next()
|
||||
.context("cannot resolve address")?
|
||||
};
|
||||
let stream = Async::<TcpStream>::connect(socket_addr).await?;
|
||||
let stream = async_native_tls::connect(host, stream).await?;
|
||||
Ok(SmolStream::Tls(stream))
|
||||
}
|
||||
scheme => bail!("unsupported scheme: {:?}", scheme),
|
||||
match req.uri().scheme_str() {
|
||||
Some("http") => {
|
||||
let stream = {
|
||||
let port = req.uri().port_u16().unwrap_or(80);
|
||||
TcpStream::connect((host, port)).await?
|
||||
};
|
||||
SmolStream::Plain(stream)
|
||||
}
|
||||
Some("https") => {
|
||||
// In case of HTTPS, establish a secure TLS connection first.
|
||||
let stream = {
|
||||
let port = req.uri().port_u16().unwrap_or(443);
|
||||
TcpStream::connect((host, port)).await?
|
||||
};
|
||||
let stream = async_native_tls::connect(host, stream).await?;
|
||||
SmolStream::Tls(stream)
|
||||
}
|
||||
scheme => bail!("unsupported scheme: {:?}", scheme),
|
||||
}
|
||||
};
|
||||
|
||||
// Spawn the HTTP/1 connection.
|
||||
let (mut sender, conn) = hyper::client::conn::http1::handshake(FuturesIo::new(io)).await?;
|
||||
ex.spawn(async move {
|
||||
if let Err(e) = conn.await {
|
||||
println!("Connection failed: {:?}", e);
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
|
||||
// Get the result
|
||||
let result = sender.send_request(req).await?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[apply(main!)]
|
||||
async fn main(ex: &Executor<'static>) -> Result<()> {
|
||||
// Create a request.
|
||||
let url: hyper::Uri = "https://www.rust-lang.org".try_into()?;
|
||||
let req = Request::builder()
|
||||
.header(
|
||||
hyper::header::HOST,
|
||||
url.authority().unwrap().clone().as_str(),
|
||||
)
|
||||
.uri(url)
|
||||
.body(Empty::new())?;
|
||||
|
||||
// Fetch the response.
|
||||
let resp = fetch(ex, req).await?;
|
||||
println!("{:#?}", resp);
|
||||
|
||||
// Read the message body.
|
||||
let body: Vec<u8> = BodyStream::new(resp.into_body())
|
||||
.try_fold(Vec::new(), |mut body, chunk| {
|
||||
if let Some(chunk) = chunk.data_ref() {
|
||||
body.extend_from_slice(chunk);
|
||||
}
|
||||
Ok(body)
|
||||
})
|
||||
}
|
||||
.await?;
|
||||
println!("{}", String::from_utf8_lossy(&body));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A TCP or TCP+TLS connection.
|
||||
enum SmolStream {
|
||||
/// A plain TCP connection.
|
||||
Plain(Async<TcpStream>),
|
||||
Plain(TcpStream),
|
||||
|
||||
/// A TCP connection secured by TLS.
|
||||
Tls(TlsStream<Async<TcpStream>>),
|
||||
Tls(TlsStream<TcpStream>),
|
||||
}
|
||||
|
||||
impl hyper::client::connect::Connection for SmolStream {
|
||||
fn connected(&self) -> hyper::client::connect::Connected {
|
||||
hyper::client::connect::Connected::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl tokio::io::AsyncRead for SmolStream {
|
||||
impl AsyncRead for SmolStream {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut tokio::io::ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
buf: &mut [u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => {
|
||||
Pin::new(s)
|
||||
.poll_read(cx, buf.initialize_unfilled())
|
||||
.map_ok(|size| {
|
||||
buf.advance(size);
|
||||
})
|
||||
}
|
||||
SmolStream::Tls(s) => {
|
||||
Pin::new(s)
|
||||
.poll_read(cx, buf.initialize_unfilled())
|
||||
.map_ok(|size| {
|
||||
buf.advance(size);
|
||||
})
|
||||
}
|
||||
SmolStream::Plain(stream) => Pin::new(stream).poll_read(cx, buf),
|
||||
SmolStream::Tls(stream) => Pin::new(stream).poll_read(cx, buf),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl tokio::io::AsyncWrite for SmolStream {
|
||||
impl AsyncWrite for SmolStream {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => Pin::new(s).poll_write(cx, buf),
|
||||
SmolStream::Tls(s) => Pin::new(s).poll_write(cx, buf),
|
||||
SmolStream::Plain(stream) => Pin::new(stream).poll_write(cx, buf),
|
||||
SmolStream::Tls(stream) => Pin::new(stream).poll_write(cx, buf),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(stream) => Pin::new(stream).poll_close(cx),
|
||||
SmolStream::Tls(stream) => Pin::new(stream).poll_close(cx),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => Pin::new(s).poll_flush(cx),
|
||||
SmolStream::Tls(s) => Pin::new(s).poll_flush(cx),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => {
|
||||
s.get_ref().shutdown(Shutdown::Write)?;
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
SmolStream::Tls(s) => Pin::new(s).poll_close(cx),
|
||||
SmolStream::Plain(stream) => Pin::new(stream).poll_flush(cx),
|
||||
SmolStream::Tls(stream) => Pin::new(stream).poll_flush(cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -13,24 +13,54 @@
|
|||
//!
|
||||
//! Refer to `README.md` to see how to the TLS certificate was generated.
|
||||
|
||||
use std::net::{Shutdown, TcpListener, TcpStream};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use anyhow::{Error, Result};
|
||||
use anyhow::Result;
|
||||
use async_native_tls::{Identity, TlsAcceptor, TlsStream};
|
||||
use hyper::service::{make_service_fn, service_fn};
|
||||
use hyper::{Body, Request, Response, Server};
|
||||
use smol::{future, io, prelude::*, Async};
|
||||
use http_body_util::Full;
|
||||
use hyper::body::Incoming;
|
||||
use hyper::service::service_fn;
|
||||
use hyper::{Request, Response};
|
||||
use macro_rules_attribute::apply;
|
||||
use smol::{future, io, prelude::*, Async, Executor};
|
||||
use smol_hyper::rt::{FuturesIo, SmolTimer};
|
||||
use smol_macros::main;
|
||||
|
||||
/// Serves a request and returns a response.
|
||||
async fn serve(req: Request<Body>, host: String) -> Result<Response<Body>> {
|
||||
println!("Serving {}{}", host, req.uri());
|
||||
Ok(Response::new(Body::from("Hello from hyper!")))
|
||||
async fn serve(req: Request<Incoming>) -> Result<Response<Full<&'static [u8]>>> {
|
||||
println!("Serving {}", req.uri());
|
||||
Ok(Response::new(Full::new("Hello from hyper!".as_bytes())))
|
||||
}
|
||||
|
||||
/// Handle a new client.
|
||||
async fn handle_client(client: Async<TcpStream>, tls: Option<TlsAcceptor>) -> Result<()> {
|
||||
// Wrap it in TLS if necessary.
|
||||
let client = match &tls {
|
||||
None => SmolStream::Plain(client),
|
||||
Some(tls) => {
|
||||
// In case of HTTPS, establish a secure TLS connection.
|
||||
SmolStream::Tls(tls.accept(client).await?)
|
||||
}
|
||||
};
|
||||
|
||||
// Build the server.
|
||||
hyper::server::conn::http1::Builder::new()
|
||||
.timer(SmolTimer::new())
|
||||
.serve_connection(FuturesIo::new(client), service_fn(serve))
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Listens for incoming connections and serves them.
|
||||
async fn listen(listener: Async<TcpListener>, tls: Option<TlsAcceptor>) -> Result<()> {
|
||||
async fn listen(
|
||||
ex: &Arc<Executor<'static>>,
|
||||
listener: Async<TcpListener>,
|
||||
tls: Option<TlsAcceptor>,
|
||||
) -> Result<()> {
|
||||
// Format the full host address.
|
||||
let host = &match tls {
|
||||
None => format!("http://{}", listener.get_ref().local_addr()?),
|
||||
|
@ -38,86 +68,42 @@ async fn listen(listener: Async<TcpListener>, tls: Option<TlsAcceptor>) -> Resul
|
|||
};
|
||||
println!("Listening on {}", host);
|
||||
|
||||
// Start a hyper server.
|
||||
Server::builder(SmolListener::new(&listener, tls))
|
||||
.executor(SmolExecutor)
|
||||
.serve(make_service_fn(move |_| {
|
||||
let host = host.clone();
|
||||
async { Ok::<_, Error>(service_fn(move |req| serve(req, host.clone()))) }
|
||||
}))
|
||||
.await?;
|
||||
loop {
|
||||
// Wait for a new client.
|
||||
let (client, _) = listener.accept().await?;
|
||||
|
||||
Ok(())
|
||||
// Spawn a task to handle this connection.
|
||||
ex.spawn({
|
||||
let tls = tls.clone();
|
||||
async move {
|
||||
if let Err(e) = handle_client(client, tls).await {
|
||||
println!("Error while handling client: {}", e);
|
||||
}
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
#[apply(main!)]
|
||||
async fn main(ex: &Arc<Executor<'static>>) -> Result<()> {
|
||||
// Initialize TLS with the local certificate, private key, and password.
|
||||
let identity = Identity::from_pkcs12(include_bytes!("identity.pfx"), "password")?;
|
||||
let tls = TlsAcceptor::from(native_tls::TlsAcceptor::new(identity)?);
|
||||
|
||||
// Start HTTP and HTTPS servers.
|
||||
smol::block_on(async {
|
||||
let http = listen(Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?, None);
|
||||
let https = listen(
|
||||
Async::<TcpListener>::bind(([127, 0, 0, 1], 8001))?,
|
||||
Some(tls),
|
||||
);
|
||||
future::try_zip(http, https).await?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Spawns futures.
|
||||
#[derive(Clone)]
|
||||
struct SmolExecutor;
|
||||
|
||||
impl<F: Future + Send + 'static> hyper::rt::Executor<F> for SmolExecutor {
|
||||
fn execute(&self, fut: F) {
|
||||
smol::spawn(async { drop(fut.await) }).detach();
|
||||
}
|
||||
}
|
||||
|
||||
/// Listens for incoming connections.
|
||||
struct SmolListener<'a> {
|
||||
tls: Option<TlsAcceptor>,
|
||||
incoming: Pin<Box<dyn Stream<Item = io::Result<Async<TcpStream>>> + Send + 'a>>,
|
||||
}
|
||||
|
||||
impl<'a> SmolListener<'a> {
|
||||
fn new(listener: &'a Async<TcpListener>, tls: Option<TlsAcceptor>) -> Self {
|
||||
Self {
|
||||
incoming: Box::pin(listener.incoming()),
|
||||
tls,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl hyper::server::accept::Accept for SmolListener<'_> {
|
||||
type Conn = SmolStream;
|
||||
type Error = Error;
|
||||
|
||||
fn poll_accept(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context,
|
||||
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
|
||||
let stream = smol::ready!(self.incoming.as_mut().poll_next(cx)).unwrap()?;
|
||||
|
||||
let stream = match &self.tls {
|
||||
None => SmolStream::Plain(stream),
|
||||
Some(tls) => {
|
||||
// In case of HTTPS, start establishing a secure TLS connection.
|
||||
let tls = tls.clone();
|
||||
SmolStream::Handshake(Box::pin(async move {
|
||||
tls.accept(stream).await.map_err(|err| {
|
||||
println!("Failed to establish secure TLS connection: {:#?}", err);
|
||||
io::Error::new(io::ErrorKind::Other, Box::new(err))
|
||||
})
|
||||
}))
|
||||
}
|
||||
};
|
||||
|
||||
Poll::Ready(Some(Ok(stream)))
|
||||
}
|
||||
let http = listen(
|
||||
ex,
|
||||
Async::<TcpListener>::bind(([127, 0, 0, 1], 8000))?,
|
||||
None,
|
||||
);
|
||||
let https = listen(
|
||||
ex,
|
||||
Async::<TcpListener>::bind(([127, 0, 0, 1], 8001))?,
|
||||
Some(tls),
|
||||
);
|
||||
future::try_zip(http, https).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A TCP or TCP+TLS connection.
|
||||
|
@ -127,83 +113,44 @@ enum SmolStream {
|
|||
|
||||
/// A TCP connection secured by TLS.
|
||||
Tls(TlsStream<Async<TcpStream>>),
|
||||
|
||||
/// A TCP connection that is in process of getting secured by TLS.
|
||||
#[allow(clippy::type_complexity)]
|
||||
Handshake(Pin<Box<dyn Future<Output = io::Result<TlsStream<Async<TcpStream>>>> + Send>>),
|
||||
}
|
||||
|
||||
impl hyper::client::connect::Connection for SmolStream {
|
||||
fn connected(&self) -> hyper::client::connect::Connected {
|
||||
hyper::client::connect::Connected::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl tokio::io::AsyncRead for SmolStream {
|
||||
impl AsyncRead for SmolStream {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut tokio::io::ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
loop {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => {
|
||||
return Pin::new(s)
|
||||
.poll_read(cx, buf.initialize_unfilled())
|
||||
.map_ok(|size| {
|
||||
buf.advance(size);
|
||||
});
|
||||
}
|
||||
SmolStream::Tls(s) => {
|
||||
return Pin::new(s)
|
||||
.poll_read(cx, buf.initialize_unfilled())
|
||||
.map_ok(|size| {
|
||||
buf.advance(size);
|
||||
});
|
||||
}
|
||||
SmolStream::Handshake(f) => {
|
||||
let s = smol::ready!(f.as_mut().poll(cx))?;
|
||||
*self = SmolStream::Tls(s);
|
||||
}
|
||||
}
|
||||
buf: &mut [u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
match &mut *self {
|
||||
Self::Plain(s) => Pin::new(s).poll_read(cx, buf),
|
||||
Self::Tls(s) => Pin::new(s).poll_read(cx, buf),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl tokio::io::AsyncWrite for SmolStream {
|
||||
impl AsyncWrite for SmolStream {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
loop {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => return Pin::new(s).poll_write(cx, buf),
|
||||
SmolStream::Tls(s) => return Pin::new(s).poll_write(cx, buf),
|
||||
SmolStream::Handshake(f) => {
|
||||
let s = smol::ready!(f.as_mut().poll(cx))?;
|
||||
*self = SmolStream::Tls(s);
|
||||
}
|
||||
}
|
||||
match &mut *self {
|
||||
Self::Plain(s) => Pin::new(s).poll_write(cx, buf),
|
||||
Self::Tls(s) => Pin::new(s).poll_write(cx, buf),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match &mut *self {
|
||||
Self::Plain(s) => Pin::new(s).poll_close(cx),
|
||||
Self::Tls(s) => Pin::new(s).poll_close(cx),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => Pin::new(s).poll_flush(cx),
|
||||
SmolStream::Tls(s) => Pin::new(s).poll_flush(cx),
|
||||
SmolStream::Handshake(_) => Poll::Ready(Ok(())),
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
match &mut *self {
|
||||
SmolStream::Plain(s) => {
|
||||
s.get_ref().shutdown(Shutdown::Write)?;
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
SmolStream::Tls(s) => Pin::new(s).poll_close(cx),
|
||||
SmolStream::Handshake(_) => Poll::Ready(Ok(())),
|
||||
Self::Plain(s) => Pin::new(s).poll_close(cx),
|
||||
Self::Tls(s) => Pin::new(s).poll_close(cx),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
#[cfg(target_os = "linux")]
|
||||
fn main() -> std::io::Result<()> {
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::io::AsFd;
|
||||
|
||||
use inotify::{EventMask, Inotify, WatchMask};
|
||||
use smol::{io, Async};
|
||||
|
@ -34,15 +35,16 @@ fn main() -> std::io::Result<()> {
|
|||
|
||||
smol::block_on(async {
|
||||
// Watch events in the current directory.
|
||||
let mut inotify = Async::new(Inotify::init()?)?;
|
||||
inotify.get_mut().add_watch(".", WatchMask::ALL_EVENTS)?;
|
||||
let mut inotify = Inotify::init()?;
|
||||
let source = Async::new(inotify.as_fd().try_clone_to_owned()?)?;
|
||||
inotify.watches().add(".", WatchMask::ALL_EVENTS)?;
|
||||
println!("Watching for filesystem events in the current directory...");
|
||||
println!("Try opening a file to trigger some events.");
|
||||
println!();
|
||||
|
||||
// Wait for events in a loop and print them on the screen.
|
||||
loop {
|
||||
for event in inotify.read_with_mut(read_op).await? {
|
||||
for event in source.read_with(|_| read_op(&mut inotify)).await? {
|
||||
println!("{:?}", event);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -8,7 +8,6 @@
|
|||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn main() -> std::io::Result<()> {
|
||||
use std::os::unix::io::AsRawFd;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use smol::{io, Async};
|
||||
|
@ -22,7 +21,7 @@ fn main() -> std::io::Result<()> {
|
|||
|
||||
// When the OS timer fires, a 64-bit integer can be read from it.
|
||||
Async::new(timer)?
|
||||
.read_with(|t| nix::unistd::read(t.as_raw_fd(), &mut [0u8; 8]).map_err(io::Error::from))
|
||||
.read_with(|t| rustix::io::read(t, &mut [0u8; 8]).map_err(io::Error::from))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -18,7 +18,7 @@ use std::task::{Context, Poll};
|
|||
|
||||
use anyhow::{bail, Context as _, Result};
|
||||
use async_native_tls::{Certificate, TlsConnector, TlsStream};
|
||||
use async_tungstenite::WebSocketStream;
|
||||
use async_tungstenite::{tungstenite, WebSocketStream};
|
||||
use futures::sink::{Sink, SinkExt};
|
||||
use smol::{prelude::*, Async};
|
||||
use tungstenite::handshake::client::Response;
|
||||
|
|
|
@ -18,7 +18,7 @@ use std::task::{Context, Poll};
|
|||
|
||||
use anyhow::{Context as _, Result};
|
||||
use async_native_tls::{Identity, TlsAcceptor, TlsStream};
|
||||
use async_tungstenite::WebSocketStream;
|
||||
use async_tungstenite::{tungstenite, WebSocketStream};
|
||||
use futures::sink::{Sink, SinkExt};
|
||||
use smol::{future, prelude::*, Async};
|
||||
use tungstenite::Message;
|
||||
|
|
|
@ -8,41 +8,112 @@
|
|||
|
||||
#[cfg(windows)]
|
||||
fn main() -> std::io::Result<()> {
|
||||
use std::ops::Deref;
|
||||
use std::os::windows::io::{AsRawSocket, AsSocket, BorrowedSocket};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use smol::{io, prelude::*, Async, Unblock};
|
||||
use smol::{future, prelude::*, Async, Unblock};
|
||||
use std::io;
|
||||
use tempfile::tempdir;
|
||||
use uds_windows::{UnixListener, UnixStream};
|
||||
|
||||
// n.b.: notgull: uds_windows does not support I/O safety yet, hence the wrapper types
|
||||
|
||||
struct UnixListener(uds_windows::UnixListener);
|
||||
|
||||
impl From<uds_windows::UnixListener> for UnixListener {
|
||||
fn from(ul: uds_windows::UnixListener) -> Self {
|
||||
Self(ul)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for UnixListener {
|
||||
type Target = uds_windows::UnixListener;
|
||||
|
||||
fn deref(&self) -> &uds_windows::UnixListener {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsSocket for UnixListener {
|
||||
fn as_socket(&self) -> BorrowedSocket<'_> {
|
||||
unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
|
||||
}
|
||||
}
|
||||
|
||||
struct UnixStream(uds_windows::UnixStream);
|
||||
|
||||
impl From<uds_windows::UnixStream> for UnixStream {
|
||||
fn from(ul: uds_windows::UnixStream) -> Self {
|
||||
Self(ul)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for UnixStream {
|
||||
type Target = uds_windows::UnixStream;
|
||||
|
||||
fn deref(&self) -> &uds_windows::UnixStream {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl AsSocket for UnixStream {
|
||||
fn as_socket(&self) -> BorrowedSocket<'_> {
|
||||
unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
|
||||
}
|
||||
}
|
||||
|
||||
impl io::Read for UnixStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
io::Read::read(&mut self.0, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl io::Write for UnixStream {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
io::Write::write(&mut self.0, buf)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
io::Write::flush(&mut self.0)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl async_io::IoSafe for UnixStream {}
|
||||
|
||||
async fn client(addr: PathBuf) -> io::Result<()> {
|
||||
// Connect to the address.
|
||||
let stream = Async::new(UnixStream::connect(addr)?)?;
|
||||
let stream = Async::new(UnixStream::from(uds_windows::UnixStream::connect(addr)?))?;
|
||||
println!("Connected to {:?}", stream.get_ref().peer_addr()?);
|
||||
|
||||
// Pipe the stream to stdout.
|
||||
let mut stdout = Unblock::new(std::io::stdout());
|
||||
io::copy(&stream, &mut stdout).await?;
|
||||
futures_lite::io::copy(stream, &mut stdout).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
let dir = tempdir()?;
|
||||
let path = dir.path().join("socket");
|
||||
|
||||
smol::block_on(async {
|
||||
future::block_on(async {
|
||||
// Create a listener.
|
||||
let listener = Async::new(UnixListener::bind(&path)?)?;
|
||||
let listener = Async::new(UnixListener::from(uds_windows::UnixListener::bind(&path)?))?;
|
||||
println!("Listening on {:?}", listener.get_ref().local_addr()?);
|
||||
|
||||
// Spawn a client task.
|
||||
let task = smol::spawn(client(path));
|
||||
future::try_zip(
|
||||
async {
|
||||
// Accept the client.
|
||||
let (stream, _) = listener.read_with(|l| l.accept()).await?;
|
||||
println!("Accepted a client");
|
||||
|
||||
// Accept the client.
|
||||
let (stream, _) = listener.read_with(|l| l.accept()).await?;
|
||||
println!("Accepted a client");
|
||||
|
||||
// Send a message, drop the stream, and wait for the client.
|
||||
Async::new(stream)?.write_all(b"Hello!\n").await?;
|
||||
task.await?;
|
||||
// Send a message, drop the stream, and wait for the client.
|
||||
Async::new(UnixStream::from(stream))?
|
||||
.write_all(b"Hello!\n")
|
||||
.await?;
|
||||
Ok(())
|
||||
},
|
||||
client(path),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
|
|
15
src/lib.rs
15
src/lib.rs
|
@ -31,6 +31,12 @@
|
|||
//! [examples]: https://github.com/smol-rs/smol/tree/master/examples
|
||||
//! [get-request]: https://github.com/smol-rs/smol/blob/master/examples/get-request.rs
|
||||
|
||||
#![doc(
|
||||
html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
|
||||
)]
|
||||
#![doc(
|
||||
html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
|
||||
)]
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
|
||||
|
||||
|
@ -46,10 +52,11 @@ pub use {
|
|||
};
|
||||
|
||||
#[doc(inline)]
|
||||
pub use {
|
||||
async_channel as channel, async_fs as fs, async_lock as lock, async_net as net,
|
||||
async_process as process,
|
||||
};
|
||||
pub use {async_channel as channel, async_fs as fs, async_lock as lock, async_net as net};
|
||||
|
||||
#[cfg(not(target_os = "espidf"))]
|
||||
#[doc(inline)]
|
||||
pub use async_process as process;
|
||||
|
||||
mod spawn;
|
||||
pub use spawn::spawn;
|
||||
|
|
|
@ -49,7 +49,11 @@ pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static
|
|||
.expect("cannot spawn executor thread");
|
||||
}
|
||||
|
||||
Executor::new()
|
||||
// Prevent spawning another thread by running the process driver on this thread.
|
||||
let ex = Executor::new();
|
||||
#[cfg(not(target_os = "espidf"))]
|
||||
ex.spawn(async_process::driver()).detach();
|
||||
ex
|
||||
})
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue