Moving from axum or actix-web
Move an existing axum or actix-web app onto Ulo one route at a time, with Ulo as the host's fallback service, and a contract test that diffs old and new answers.
An existing axum or actix-web service does not have to be rewritten in one change. The app mounts behind the host router as its fallback service: routes the host still owns keep answering from the host, and everything else reaches Ulo. A route moves by deleting the host handler and adding a controller method with the same path.
This recipe compiled against ulo 0.1.0-alpha.3, axum 0.8.9 and actix-web 4.20.0. The axum version was run: the contract test below drives real requests over TCP against the old handlers and the new controller, and the host binary was started, queried and stopped with SIGTERM (exit 0). The actix version was compiled, and the same requests were run against it once with a throwaway harness that is not reproduced here.
It builds on examples/21-http-in-axum.
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
ulo-http-axum = "=0.1.0-alpha.3"
ulo-http-hyper = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
axum = { version = "0.8", features = ["tokio", "http1", "json"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "io-util"] }
serde = { version = "1", features = ["derive"] }ulo-http-hyper is needed only by the last step. The actix section lists its own dependencies.
The service being moved
Two routes under /notes and one /health, all axum. host_only() is the router the service serves today.
use std::sync::{Arc, Mutex};
use axum::Router;
use axum::extract::{Path, State};
use axum::http::{HeaderValue, StatusCode, header::LOCATION};
use axum::response::IntoResponse;
use axum::routing::{get, post};
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
pub struct Note {
pub id: u32,
pub title: String,
}
#[derive(Deserialize)]
pub struct NewNote {
pub title: String,
}
/// The routes as they were written for axum, before any of them moves.
pub mod host_routes {
use super::*;
pub type Store = Arc<Mutex<Vec<Note>>>;
pub fn seeded() -> Store {
Arc::new(Mutex::new(vec![Note { id: 1, title: "first".into() }]))
}
async fn find(State(store): State<Store>, Path(id): Path<u32>) -> Result<axum::Json<Note>, (StatusCode, String)> {
let all = store.lock().unwrap();
all.iter().find(|note| note.id == id).cloned().map(axum::Json).ok_or((StatusCode::NOT_FOUND, format!("no note {id}")))
}
async fn create(State(store): State<Store>, axum::Json(new): axum::Json<NewNote>) -> impl IntoResponse {
let mut all = store.lock().unwrap();
let note = Note { id: all.len() as u32 + 1, title: new.title };
all.push(note.clone());
let location = HeaderValue::from_str(&format!("/notes/{}", note.id)).unwrap();
(StatusCode::CREATED, [(LOCATION, location)], axum::Json(note))
}
pub fn routes() -> Router<Store> {
Router::new().route("/notes/{id}", get(find)).route("/notes", post(create))
}
}
/// The host as it was: every route is axum's.
pub fn host_only() -> Router {
Router::new().route("/health", get(|| async { "axum is up" })).merge(host_routes::routes().with_state(host_routes::seeded()))
}Step 1: mount Ulo as the fallback
An app with no controllers goes behind the router with fallback_service. Embedded::new() sets no nested_at, so the app sees every path whole. axum matches its own routes first and hands the rest to the app.
/// The host unchanged, with an app that has no controllers behind it as the fallback.
pub mod fallback_only {
use axum::Router;
use ulo::{App, AppBuilder, module};
use ulo_http_axum::{Embedded, Handle};
#[module]
pub struct EmptyModule;
pub fn builder() -> AppBuilder {
App::builder(EmptyModule)
}
pub fn embedded() -> Embedded {
Embedded::new()
}
pub fn router(app: &Handle) -> Router {
super::host_only().fallback_service(app.service())
}
}The host binary builds the router before listen() and passes the server future to run, which owns shutdown (see Embedding).
use notes_host::axum_host::moved;
use ulo_runtime_tokio::{Tokio, shutdown_signal};
#[tokio::main]
async fn main() -> Result<(), ulo::BoxError> {
let server = moved::embedded();
let embedded = server.handle();
let app = moved::builder().runtime(Tokio::current()).wire()?.connect().await?.bind(server).listen().await?;
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
let host = axum::serve(listener, moved::router(&embedded));
ulo_http_axum::run(app, &embedded, host, shutdown_signal()).await?;
Ok(())
}Nothing a client can observe changes for the routes axum matches. The same request set sent to host_only() and to this router differs in two answers, both misses axum did not match: an unknown path and a path with a trailing slash. Each was an empty 404 and is now the app's 404 problem document. A wrong method on an axum route, DELETE /health, is still axum's 405, byte for byte.
The step 3 harness pointed at this router, with every difference left unlisted, reports exactly those two cases.
Step 2: move one route into a controller
GET /notes/{id} and POST /notes become methods on a #[controller]. The handlers keep their paths, and the host deletes its own copies. The host's /health stays.
/// The same routes, with `/notes` answered by the ulo app.
pub mod moved {
use std::sync::Mutex;
use axum::Router;
use axum::routing::get;
use ulo::{App, AppBuilder, Dep, controller, handlers, injectable, module};
use ulo_http::{Classify, Created, Json, Path};
use ulo_http_axum::{Embedded, Handle};
use super::{NewNote, Note};
#[derive(Debug, Classify)]
#[classify(not_found)]
pub struct NoteNotFound(pub u32);
impl std::fmt::Display for NoteNotFound {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "no note {}", self.0)
}
}
impl std::error::Error for NoteNotFound {}
pub struct Notes {
all: Mutex<Vec<Note>>,
}
#[injectable]
impl Notes {
fn new() -> Self {
Notes { all: Mutex::new(vec![Note { id: 1, title: "first".into() }]) }
}
}
#[controller]
pub struct NotesController {
notes: Dep<Notes>,
}
#[handlers]
impl NotesController {
#[ulo_http::get("/notes/{id}")]
fn find(&self, Path(id): Path<u32>) -> Result<Json<Note>, NoteNotFound> {
let all = self.notes.all.lock().unwrap();
all.iter().find(|note| note.id == id).cloned().map(Json).ok_or(NoteNotFound(id))
}
#[ulo_http::post("/notes")]
fn create(&self, Json(new): Json<NewNote>) -> Created<Json<Note>> {
let mut all = self.notes.all.lock().unwrap();
let note = Note { id: all.len() as u32 + 1, title: new.title };
all.push(note.clone());
Created::at(format!("/notes/{}", note.id), Json(note))
}
}
#[module(providers = [Notes], controllers = [NotesController])]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}
/// No `nested_at`: the app answers as the fallback and sees the path whole.
pub fn embedded() -> Embedded {
Embedded::new()
}
pub fn router(app: &Handle) -> Router {
Router::new().route("/health", get(|| async { "axum is up" })).fallback_service(app.service())
}
}Each handler is written as in any Ulo app. Json and Path in ulo_http replace axum's extractors of the same names, Created::at replaces the (StatusCode::CREATED, [(LOCATION, ..)], Json(..)) tuple, and a domain error that derives Classify replaces a (StatusCode, String) return. See Built-in extractors and Error handling.
One route per change keeps each diff reviewable. After a route moves, delete its handler from host_routes and its entry in the host router, and extend the test.
Step 3: a contract test
A moved route should answer as the old one did, and every place it does not should be written down. The test starts the old router and the new one on port 0, sends the same requests to both, and diffs status, every header except date, and the body. Each case lists the fields it is known to differ in. An empty list asserts byte-identical answers, and an unlisted difference fails the test.
use std::collections::{BTreeMap, BTreeSet};
use std::future::pending;
use std::net::SocketAddr;
use notes_host::axum_host::{host_only, moved};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use ulo::Signal;
use ulo_runtime_tokio::Tokio;
struct Wire {
status: u16,
headers: BTreeMap<String, String>,
body: String,
}
async fn send(addr: SocketAddr, method: &str, path: &str, content_type: Option<&str>, body: &[u8]) -> Wire {
let mut head = format!("{method} {path} HTTP/1.1\r\nhost: example\r\nconnection: close\r\n");
if let Some(content_type) = content_type {
head.push_str(&format!("content-type: {content_type}\r\ncontent-length: {}\r\n", body.len()));
}
head.push_str("\r\n");
let mut stream = TcpStream::connect(addr).await.unwrap();
stream.write_all(head.as_bytes()).await.unwrap();
// A server may answer 413 and close before the whole body is written.
let _ = stream.write_all(body).await;
let mut raw = Vec::new();
let _ = stream.read_to_end(&mut raw).await;
let text = String::from_utf8_lossy(&raw);
let (head, body) = text.split_once("\r\n\r\n").expect("a reply with a head");
let mut lines = head.split("\r\n");
let status = lines.next().unwrap().split(' ').nth(1).unwrap().parse().unwrap();
let headers = lines
.filter_map(|line| line.split_once(':'))
.map(|(name, value)| (name.trim().to_ascii_lowercase(), value.trim().to_owned()))
.collect();
Wire { status, headers, body: body.to_owned() }
}
/// The fields that differ: `status`, `body` and `header:<name>`. `date` is the host's clock.
fn diff(old: &Wire, new: &Wire) -> Vec<String> {
let mut differs = Vec::new();
if old.status != new.status {
differs.push("status".to_owned());
}
if old.body != new.body {
differs.push("body".to_owned());
}
let names: BTreeSet<_> = old.headers.keys().chain(new.headers.keys()).filter(|name| *name != "date").collect();
for name in names {
if old.headers.get(name) != new.headers.get(name) {
differs.push(format!("header:{name}"));
}
}
differs.sort();
differs
}
/// One request, and the differences the move is known to make. An empty list means the two
/// answers are byte-identical apart from `date`.
struct Case {
name: &'static str,
method: &'static str,
path: &'static str,
content_type: Option<&'static str>,
body: Vec<u8>,
listed: &'static [&'static str],
}
/// Plain text or an empty body from axum, a problem document from the app.
const PROBLEM: &[&str] = &["body", "header:content-length", "header:content-type"];
fn cases() -> Vec<Case> {
let json = Some("application/json");
let case = |name, method, path, content_type, body: &[u8], listed| Case { name, method, path, content_type, body: body.to_vec(), listed };
vec![
case("find", "GET", "/notes/1", None, b"", &[]),
case("create", "POST", "/notes", json, br#"{"title":"second"}"#, &[]),
case("find, missing", "GET", "/notes/99", None, b"", PROBLEM),
case("find, id not a number", "GET", "/notes/abc", None, b"", PROBLEM),
case("find, trailing slash", "GET", "/notes/1/", None, b"", &["body", "header:content-length", "header:content-type", "status"]),
case("find, wrong method", "DELETE", "/notes/1", None, b"", &["body", "header:allow", "header:content-length", "header:content-type"]),
case("create, truncated json", "POST", "/notes", json, br#"{"title":"#, PROBLEM),
case("create, missing field", "POST", "/notes", json, b"{}", PROBLEM),
case("create, wrong content type", "POST", "/notes", Some("text/plain"), b"x", &["body", "header:accept", "header:content-length", "header:content-type"]),
case("create, 3 MiB body", "POST", "/notes", json, &vec![b' '; 3 << 20], PROBLEM),
case("host route", "GET", "/health", None, b"", &[]),
case("host route, wrong method", "DELETE", "/health", None, b"", &[]),
]
}
async fn serve_old() -> SocketAddr {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, host_only()).await });
addr
}
async fn serve_new() -> SocketAddr {
let server = moved::embedded();
let embedded = server.handle();
let app = moved::builder().runtime(Tokio::current()).wire().unwrap().connect().await.unwrap().bind(server).listen().await.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let serve = axum::serve(listener, moved::router(&embedded));
tokio::spawn(async move { ulo_http_axum::run(app, &embedded, serve, pending::<Signal>()).await });
addr
}
#[tokio::test]
async fn the_moved_routes_answer_as_the_old_ones_did_except_where_listed() {
let (old, new) = (serve_old().await, serve_new().await);
let mut unexpected = Vec::new();
for case in cases() {
let a = send(old, case.method, case.path, case.content_type, &case.body).await;
let b = send(new, case.method, case.path, case.content_type, &case.body).await;
let differs = diff(&a, &b);
if differs != case.listed {
unexpected.push(format!("{}: differs in {differs:?}, listed {:?}", case.name, case.listed));
}
}
assert!(unexpected.is_empty(), "{unexpected:#?}");
}The test asserts both directions: it fails on a difference a case does not list, and listing a difference that no longer occurs fails too, since the lists compare for equality. Deleting PROBLEM from the find, missing case produced find, missing: differs in ["body", "header:content-length", "header:content-type"], listed [].
When a listed difference is a decision rather than a side effect, replace the listing with a handler that reproduces the old answer.
Step 4: retire the host
When the last host route has moved, /health becomes a controller and the app binds its own server.
/// No host: `/health` is a ulo route and ulo's own server owns the socket.
pub mod retired {
use ulo::{App, AppBuilder, controller, handlers, module};
use ulo_http_hyper::Server;
use super::moved::{Notes, NotesController};
#[controller]
pub struct HealthController;
#[handlers]
impl HealthController {
#[ulo_http::get("/health")]
fn health(&self) -> &'static str {
"axum is up"
}
}
#[module(providers = [Notes], controllers = [NotesController, HealthController])]
pub struct AppModule;
pub fn builder() -> AppBuilder {
App::builder(AppModule)
}
pub fn server(addr: &str) -> Server {
Server::new(addr)
}
}use notes_host::axum_host::retired;
use ulo_runtime_tokio::{Tokio, shutdown_signal};
#[tokio::main]
async fn main() -> Result<(), ulo::BoxError> {
let app = retired::builder().runtime(Tokio::current()).wire()?.connect().await?.bind(retired::server("127.0.0.1:3000")).listen().await?;
app.serve(shutdown_signal()).await?;
Ok(())
}The same request set sent to the fallback-mounted app and to this one differs in a single answer: DELETE /health, which was axum's empty 405 and is now the app's 405 problem document. Every moved route answers identically, because the same controller serves both. The axum, tower and host-adapter dependencies leave Cargo.toml. See Hyper for the server's settings, which replace the host's.
What changes when a route moves
Each row was observed by the contract test on axum, or read in the source at the cited path. The actix column holds only what differed in the actix run.
| Behaviour | axum 0.8, before | Ulo, after | Evidence |
|---|---|---|---|
| Error body | text/plain text, or empty | application/problem+json with type, title, status and detail | run; ulo-http/src/render.rs:89 |
| Miss on a path the host does not route | empty 404 | the app's problem 404, no route matches this path | run (step 1) |
| Trailing slash | /notes/1/ is 404 | /notes/1/ answers as /notes/1, 200. Request and route paths are canonicalised and no redirect is sent | run; ulo-http/src/router/pattern.rs:2, :366 |
| Wrong method | 405 with Allow: GET,HEAD, empty body | 405 with Allow: GET, HEAD, OPTIONS and a problem body | run; ulo-http/src/miss.rs (MethodNotAllowed), render.rs:216 |
| Extractor failure statuses | 400 bad path, 400 bad JSON, 422 missing field, 415 wrong content type, 413 over the limit | the same five statuses, with problem bodies. 415 adds Accept: application/json | run; ulo-http/src/extract/body.rs:21 |
| Two body extractors in one handler | runtime behaviour of the host | compile error: note and raw both consume the body; a handler reads the body once | run (cargo check); body.rs:38 |
| Body limit | axum's DefaultBodyLimit; a 3 MiB body was 413 | Embedded::max_body(bytes), 2 MiB unset; a route overrides it with #[meta(MaxBody(..))]. A DefaultBodyLimit of 10 MiB on the host router did not lift it: a 3 MiB body was still 413 at 2097152 bytes | run; ulo-http/src/embed.rs:489 |
| Path parameter syntax | /{id}, and /{*rest} for a tail | {id} and {*rest}. :id is a literal segment, and Path<u32> on it is refused when listen() runs: a single value on a route with 0 parameters. A brace inside a segment ({id:\d+}) is refused | run (listen error); pattern.rs:440, ulo-http/src/router/mod.rs:136 |
axum 0.7 and earlier wrote /:id and /*rest, so a service on that line meets the :id row.
actix-web
The mount is App::default_service(scope("", &embedded)), which answers what no actix service matched. scope returns an HttpServiceFactory, and run takes the HttpServer. The controller and module are the ones above.
ulo-http-actix = "=0.1.0-alpha.3"
actix-web = { version = "4", default-features = false, features = ["macros"] }use std::sync::Mutex;
use actix_web::error::ErrorNotFound;
use actix_web::http::header::LOCATION;
use actix_web::{App, HttpResponse, HttpServer, get, post, web};
use crate::axum_host::{NewNote, Note};
/// The routes as they were written for actix-web, before any of them moves.
pub mod host_routes {
use super::*;
pub struct Store(pub Mutex<Vec<Note>>);
pub fn seeded() -> web::Data<Store> {
web::Data::new(Store(Mutex::new(vec![Note { id: 1, title: "first".into() }])))
}
#[get("/notes/{id}")]
async fn find(store: web::Data<Store>, id: web::Path<u32>) -> actix_web::Result<web::Json<Note>> {
let all = store.0.lock().unwrap();
all.iter().find(|note| note.id == *id).cloned().map(web::Json).ok_or_else(|| ErrorNotFound(format!("no note {id}")))
}
#[post("/notes")]
async fn create(store: web::Data<Store>, new: web::Json<NewNote>) -> HttpResponse {
let mut all = store.0.lock().unwrap();
let note = Note { id: all.len() as u32 + 1, title: new.into_inner().title };
all.push(note.clone());
HttpResponse::Created().insert_header((LOCATION, format!("/notes/{}", note.id))).json(note)
}
pub fn routes(cfg: &mut web::ServiceConfig) {
cfg.service(find).service(create);
}
}
async fn health() -> &'static str {
"actix is up"
}
/// The host as it was: every route is actix's. Returns the address it listens on.
pub fn host_only() -> std::io::Result<std::net::SocketAddr> {
let store = host_routes::seeded();
let server = HttpServer::new(move || App::new().app_data(store.clone()).route("/health", web::get().to(health)).configure(host_routes::routes))
.workers(1)
.bind(("127.0.0.1", 0))?;
let addr = server.addrs()[0];
tokio::spawn(server.run());
Ok(addr)
}
/// `/notes` answered by the ulo app, mounted as actix's default service: it answers what no actix
/// route matched. The app sees the path whole.
pub async fn after() -> Result<std::net::SocketAddr, ulo::BoxError> {
use ulo_http_actix::{Embedded, run, scope};
use ulo_runtime_tokio::Tokio;
let server = Embedded::new();
let embedded = server.handle();
let app = crate::axum_host::moved::builder().runtime(Tokio::current()).wire()?.connect().await?.bind(server).listen().await?;
let host = {
let embedded = embedded.clone();
HttpServer::new(move || App::new().route("/health", web::get().to(health)).default_service(scope("", &embedded)))
.workers(1)
.bind(("127.0.0.1", 0))?
};
let addr = host.addrs()[0];
tokio::spawn(run(app, &embedded, host, std::future::pending::<ulo::Signal>()));
Ok(addr)
}before() is the service as it is, and after() mounts the app behind it. Both return the bound address.
The adapter declares what actix cannot do (ulo-http-actix/src/lib.rs, read), and listen fails startup when a handler needs one of them:
- No WebSocket gateways on the HTTP port, and no upgrades.
- No host extensions reach the app. A value in actix's request store crosses through an
Embedded::forwardcopy. web::scopeleaves the path whole, so the app strips thenested_atprefix itself. A fallback mount has no prefix.- A call whose peer closed the connection before the response head runs to its answer, since actix gives a handler no signal of the close. The app observes the disconnect at the response body's next failed write.
- A request whose head is still arriving at the drain gets a closed connection, not the app's 503. An HTTP/2 connection is reset at the stop deadline with no GOAWAY.
Running the contract requests against the actix pair showed what differs from axum:
| Behaviour | actix-web 4, before | Ulo, after |
|---|---|---|
Wrong method on a host route (DELETE /health) | actix's 405 with Allow: GET | the app's 404 problem document, no Allow: the method guard falls through to the default service |
| Bad path value | 404 | 400 |
| JSON missing a field | 400 | 422 |
| Wrong content type | 400 | 415 |
| 3 MiB JSON body | 413, text | 413, problem document |
| Trailing slash, unknown path, missing note, truncated JSON | as for axum | as for axum |
The first row appears as soon as the app is mounted: a host route that rejects a method hands the request to the app. The adapter's docs say App::service(scope("", &embedded)) mounts the app ahead of the services registered after it, so it is not the fallback. Use default_service.
Failure modes
- A request the host receives before
listen()finishes is answered 503. Build the router beforelisten()and serve it after. - Two shutdown owners.
runattaches the host's graceful stop to the app's drain. Do not give the host a second signal. - A handler reading
Dep<ClientAddr>on axum is refused at startup unless the router is served withinto_make_service_with_connect_info::<SocketAddr>(), the app is wrapped inHostLayer, and the server says.peer_addr(true). See axum. - With
nest_service("/api", ..)the app also needsEmbedded::nested_at("/api").examples/21-http-in-axumdoes both. - The host's own limits (TLS, HTTP/2 settings, header timeout) have no method on
Embedded; they stay on the host until step 4, then move to the server. See Limits.
References
- Embedding, the host table and
Embeddedsettings - axum and actix-web
- Built-in extractors
- Error handling
- Limits
- Hyper