Skip to content
v0.1.1latest release34 skills2 categories4 sub-categories79 tested scripts157 reference docsContact us

scaffold_service.rs

Helper script for rust-tokio-async-service-builder · 329 lines

Programming / Rustv1.0.0Updated OCT 21 20267 references8 scripts
scripts/scaffold_service.rs
//! Generate a minimal production-shaped axum 0.8 service: Cargo.toml + src/main.rs with shared
//! state, an AppError that maps to HTTP, health/readiness, tracing, timeout and body-limit
//! layers, a TaskTracker + CancellationToken background task, graceful shutdown and tests.
//! The output compiles, its tests pass, and it passes this skill's scanners.
//!
//! Build: rustc -O --edition 2021 scripts/scaffold_service.rs -o /tmp/scaffold_service
//! Usage: scaffold_service [--name NAME] [--file main|cargo] [--out DIR [--force]]

use std::path::Path;
use std::process::exit;

const USAGE: &str = "usage: scaffold_service [--name NAME] [--file main|cargo] [--out DIR [--force]]

Print (or write) a minimal axum 0.8 / tokio 1 service:
  Cargo.toml    axum 0.8, tokio 1, tower 0.5, tower-http 0.6, tokio-util 0.7, tracing, thiserror 2
  src/main.rs   AppState, AppError -> IntoResponse, /healthz, /readyz, /items/{id}, TraceLayer,
                TimeoutLayer, RequestBodyLimitLayer, a TaskTracker background task stopped by a
                CancellationToken, graceful shutdown on Ctrl+C/SIGTERM, oneshot router tests

options:
  --name NAME   crate name (lowercase, digits, '-' or '_'; default: my-service)
  --file F      print only `main` (src/main.rs) or `cargo` (Cargo.toml)
  --out DIR     write DIR/Cargo.toml and DIR/src/main.rs instead of printing
  --force       overwrite existing files with --out
Exit: 0 done, 2 usage error or files exist without --force.";

const CARGO: &str = r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
rust-version = "1.80"

[dependencies]
axum = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal", "time", "sync"] }
tokio-util = { version = "0.7", features = ["rt"] }
tower = "0.5"
tower-http = { version = "0.6", features = ["trace", "timeout", "limit"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

[dev-dependencies]
tokio = { version = "1", features = ["test-util"] }
tower = { version = "0.5", features = ["util"] }
"#;

const MAIN: &str = r#"//! {name}: axum 0.8 service skeleton generated by scaffold_service.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;

use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use serde::Serialize;
use tokio::net::TcpListener;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use tower::ServiceBuilder;
use tower_http::limit::RequestBodyLimitLayer;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;

/// Cheap to clone: everything shared lives behind one Arc.
#[derive(Clone)]
pub struct AppState {
    inner: Arc<Inner>,
}

struct Inner {
    ready: AtomicBool,
}

impl AppState {
    pub fn new() -> Self {
        Self { inner: Arc::new(Inner { ready: AtomicBool::new(false) }) }
    }

    pub fn set_ready(&self, ready: bool) {
        self.inner.ready.store(ready, Ordering::Release);
    }

    pub fn is_ready(&self) -> bool {
        self.inner.ready.load(Ordering::Acquire)
    }
}

impl Default for AppState {
    fn default() -> Self {
        Self::new()
    }
}

/// Every handler error. Client errors keep their message; server errors are logged, not leaked.
#[derive(Debug, thiserror::Error)]
pub enum AppError {
    #[error("{0} not found")]
    NotFound(String),
    #[error("service unavailable")]
    Unavailable,
    #[error("internal error")]
    Internal(#[source] Box<dyn std::error::Error + Send + Sync>),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let status = match &self {
            AppError::NotFound(_) => StatusCode::NOT_FOUND,
            AppError::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
            AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
        };
        if status.is_server_error() {
            tracing::error!(error = ?self, "request failed");
        }
        (status, Json(serde_json::json!({ "error": self.to_string() }))).into_response()
    }
}

#[derive(Debug, Serialize)]
pub struct Item {
    pub id: u64,
    pub name: String,
}

async fn healthz() -> &'static str {
    "ok"
}

async fn readyz(State(state): State<AppState>) -> Result<&'static str, AppError> {
    if state.is_ready() { Ok("ready") } else { Err(AppError::Unavailable) }
}

async fn get_item(Path(id): Path<u64>) -> Result<Json<Item>, AppError> {
    if id == 0 {
        return Err(AppError::NotFound(format!("item {id}")));
    }
    Ok(Json(Item { id, name: format!("item-{id}") }))
}

pub fn router(state: AppState) -> Router {
    Router::new()
        .route("/healthz", get(healthz))
        .route("/readyz", get(readyz))
        .route("/items/{id}", get(get_item))
        .layer(
            ServiceBuilder::new()
                // Outermost first. The body limit must wrap the timeout: TimeoutLayer needs a
                // `Default` response body, which RequestBodyLimitLayer's body type is not.
                .layer(TraceLayer::new_for_http())
                .layer(RequestBodyLimitLayer::new(1024 * 1024))
                .layer(TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, Duration::from_secs(10))),
        )
        .with_state(state)
}

/// Resolves on Ctrl+C or SIGTERM and cancels `token` so background tasks stop too.
async fn shutdown_signal(token: CancellationToken) {
    let ctrl_c = async {
        if let Err(err) = tokio::signal::ctrl_c().await {
            tracing::error!(error = %err, "cannot listen for Ctrl+C");
        }
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut sig) => {
                sig.recv().await;
            }
            Err(err) => tracing::error!(error = %err, "cannot listen for SIGTERM"),
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        _ = ctrl_c => {}
        _ = terminate => {}
    }
    tracing::info!("shutdown signal received");
    token.cancel();
}

fn spawn_background(tracker: &TaskTracker, token: CancellationToken) {
    tracker.spawn(async move {
        let mut tick = tokio::time::interval(Duration::from_secs(60));
        loop {
            tokio::select! {
                _ = token.cancelled() => break,
                _ = tick.tick() => tracing::debug!("background tick"),
            }
        }
        tracing::info!("background task stopped");
    });
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,tower_http=info".into()),
        )
        .init();

    let token = CancellationToken::new();
    let tracker = TaskTracker::new();
    spawn_background(&tracker, token.child_token());

    let state = AppState::new();
    let addr = std::env::var("BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:3000".to_string());
    let listener = TcpListener::bind(&addr).await?;
    tracing::info!(%addr, "listening");
    state.set_ready(true);

    axum::serve(listener, router(state.clone()))
        .with_graceful_shutdown(shutdown_signal(token.clone()))
        .await?;

    // Drain: stop accepting work, then give background tasks a bounded time to finish.
    state.set_ready(false);
    token.cancel();
    tracker.close();
    if tokio::time::timeout(Duration::from_secs(10), tracker.wait()).await.is_err() {
        tracing::warn!("background tasks did not stop within 10s");
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::{to_bytes, Body};
    use axum::http::Request;
    use tower::ServiceExt; // oneshot

    async fn call(app: Router, uri: &str) -> (StatusCode, String) {
        let res = app.oneshot(Request::get(uri).body(Body::empty()).expect("request")).await.expect("infallible");
        let status = res.status();
        let body = to_bytes(res.into_body(), 64 * 1024).await.expect("body");
        (status, String::from_utf8_lossy(&body).into_owned())
    }

    #[tokio::test]
    async fn healthz_is_ok() {
        assert_eq!(call(router(AppState::new()), "/healthz").await, (StatusCode::OK, "ok".into()));
    }

    #[tokio::test]
    async fn readyz_follows_state() {
        let state = AppState::new();
        assert_eq!(call(router(state.clone()), "/readyz").await.0, StatusCode::SERVICE_UNAVAILABLE);
        state.set_ready(true);
        assert_eq!(call(router(state), "/readyz").await.0, StatusCode::OK);
    }

    #[tokio::test]
    async fn missing_item_is_json_404() {
        let (status, body) = call(router(AppState::new()), "/items/0").await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert!(body.contains("item 0 not found"), "{body}");
    }

    #[tokio::test(start_paused = true)]
    async fn background_task_stops_on_cancel() {
        let (tracker, token) = (TaskTracker::new(), CancellationToken::new());
        spawn_background(&tracker, token.clone());
        token.cancel();
        tracker.close();
        tokio::time::timeout(Duration::from_secs(1), tracker.wait()).await.expect("task stopped");
    }
}
"#;

fn die(msg: &str) -> ! {
    eprintln!("error: {msg}");
    exit(2);
}

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.iter().any(|a| a == "-h" || a == "--help") {
        println!("{USAGE}");
        return;
    }
    let (mut name, mut file, mut out, mut force) = ("my-service".to_string(), None, None, false);
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let mut val = || it.next().cloned().unwrap_or_else(|| die(&format!("{a} needs a value")));
        match a.as_str() {
            "--name" => name = val(),
            "--file" => file = Some(val()),
            "--out" => out = Some(val()),
            "--force" => force = true,
            other => die(&format!("unknown argument {other}\n\n{USAGE}")),
        }
    }
    let valid = name.chars().next().is_some_and(|c| c.is_ascii_lowercase())
        && name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
    if !valid {
        die(&format!("--name must be lowercase letters, digits, '-' or '_', got '{name}'"));
    }
    let cargo = CARGO.replace("{name}", &name);
    let main = MAIN.replace("{name}", &name);
    match (out, file.as_deref()) {
        (Some(dir), _) => {
            let targets = [(Path::new(&dir).join("Cargo.toml"), cargo), (Path::new(&dir).join("src/main.rs"), main)];
            if !force {
                if let Some((p, _)) = targets.iter().find(|(p, _)| p.exists()) {
                    die(&format!("{} exists; pass --force to overwrite", p.display()));
                }
            }
            for (p, text) in &targets {
                if let Some(parent) = p.parent() {
                    std::fs::create_dir_all(parent).unwrap_or_else(|e| die(&format!("cannot create {}: {e}", parent.display())));
                }
                std::fs::write(p, text).unwrap_or_else(|e| die(&format!("cannot write {}: {e}", p.display())));
                println!("wrote {}", p.display());
            }
        }
        (None, Some("main")) => print!("{main}"),
        (None, Some("cargo")) => print!("{cargo}"),
        (None, Some(other)) => die(&format!("--file must be main or cargo, got '{other}'")),
        (None, None) => print!("# Cargo.toml\n{cargo}\n// src/main.rs\n{main}"),
    }
}
More in Rust

rust-borrow-checker-error-explainer

Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.

rust-cargo-workspace-designer

Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.

rust-error-handling-thiserror-anyhow-designer

Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.

rust-lifetime-annotation-advisor

Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.

rust-trait-design-reviewer

Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.

rust-unsafe-block-auditor

Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.