Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 22 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
use pyo3::types::{PyBytes, PyDict, PyInt, PyString};
use pyo3_async_runtimes::tokio::{future_into_py, into_future};
use pyo3_async_runtimes::tokio::{future_into_py, get_current_locals, into_future, scope};
use pyo3_stub_gen::derive::*;
use regex::Regex;
use request::{Request, RequestBuilder};
Expand All @@ -30,6 +30,7 @@ use tokio::sync::{
mpsc::{Receiver, Sender, channel},
oneshot,
};
use tokio::task::JoinSet;
use unicode_normalization::UnicodeNormalization;

use crate::middleware::Middleware;
Expand Down Expand Up @@ -547,7 +548,15 @@ impl HttpServer {
mut shutdown: ShutDownSignal,
mut request_receiver: Receiver<ProcessRequest>,
) -> PyResult<()> {
let is_async = self.is_async;
let locals = if is_async {
Some(Python::attach(get_current_locals)?)
} else {
None
};

let mut batch = Vec::with_capacity(64);
let mut tasks = JoinSet::new();
loop {
batch.clear();
tokio::select! {
Expand All @@ -556,12 +565,23 @@ impl HttpServer {
break;
}
for pr in batch.drain(..) {
pr.respond(self.is_async).await;
match locals.clone() {
Some(locals) => {
tasks.spawn(async move {
scope(locals, pr.respond(true)).await;
});
}
None => pr.respond(false).await,
}
}
},
Some(_) = tasks.join_next(), if !tasks.is_empty() => {},
_ = shutdown.wait() => break,
}
}

tasks.abort_all();
while tasks.join_next().await.is_some() {}
Ok(())
}
}
Expand Down
24 changes: 24 additions & 0 deletions tests/async_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import asyncio
import sys

from oxapy import HttpServer, Router, get


@get("/health")
async def health(_request):
return {"message": "ok"}


@get("/slow")
async def slow(_request):
await asyncio.sleep(0.5)
return {"message": "slow"}


async def main(port):
app = HttpServer(("127.0.0.1", port)).attach(Router().routes([health, slow]))
await app.async_mode().run()


if __name__ == "__main__":
asyncio.run(main(int(sys.argv[1])))
56 changes: 56 additions & 0 deletions tests/test_http_server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import socket
import subprocess
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

import pytest
import requests

from tests.utils import Multipart


Expand Down Expand Up @@ -134,3 +143,50 @@ def test_redirect_endpoint(oxapy_server):
def test_error_response(oxapy_server):
res = requests.get(f"{oxapy_server}/api/v1/error")
assert res.status_code == 500


@pytest.fixture(scope="module")
def async_server():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
proc = subprocess.Popen(
[sys.executable, str(Path(__file__).with_name("async_app.py")), str(port)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
base_url = f"http://127.0.0.1:{port}"
deadline = time.time() + 5
try:
while time.time() < deadline:
if proc.poll() is not None:
pytest.fail("async server exited during startup")
try:
if requests.get(f"{base_url}/health", timeout=0.2).status_code == 200:
break
except requests.RequestException:
pass
time.sleep(0.05)
else:
pytest.fail("async server did not start")
yield base_url
finally:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()


def test_async_handlers_run_concurrently(async_server):
def hit(_):
return requests.get(f"{async_server}/slow", timeout=15)

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=20) as pool:
responses = list(pool.map(hit, range(20)))
elapsed = time.perf_counter() - start

assert all(response.status_code == 200 for response in responses)
assert elapsed < 2.0, f"20 async handlers took {elapsed:.2f}s"
Loading