使用 shuttle-axum 在 Shuttle 上部署 Axum 应用:零配置 Web 服务实战指南
使用 shuttle-axum 在 Shuttle 上部署 Axum 应用:零配置 Web 服务实战指南
Axum 是 Rust 生态中广受欢迎的异步 Web 框架,而 shuttle-axum 是 Shuttle 为其提供的官方服务集成层:你只需写一个返回 Router 的异步函数,加上 #<a href="https://link.gitcode.com/i/a0013c206ce1aa39d39557799299bd5e" target="_blank">shuttle_runtime::main] 宏,就能在 Shuttle 平台上直接运行和部署,无需手写任何基础设施配置。本文以 [services/shuttle-axum/README.md 为核心骨架,结合仓库内源码逐层拆解其版本选择、工作原理与完整的上手路径,读完你即可独立完成一个 Axum 服务的本地调试与云端部署。
一、shuttle-axum 是什么
shuttle-axum 是 Shuttle 仓库中众多框架集成(Service Integration)之一,位于 services/shuttle-axum,作用是让 Axum 应用无缝接入 Shuttle 的运行时模型。
在 Shuttle 的架构中,任何可部署的服务都必须实现 Service trait(定义在 service/src/lib.rs),其核心是这样一个方法:
/// This function is run exactly once on startup of a deployment.
///
/// The passed [`SocketAddr`] receives proxied HTTP traffic from your Shuttle subdomain (or custom domain).
/// Binding to the address is only relevant if this service is an HTTP server.
async fn bind(mut self, addr: SocketAddr) -> Result<(), error::Error>;
也就是说,Shuttle 运行时会为每次部署分配一个 SocketAddr,服务方需要把自己的 HTTP 服务器绑定到这个地址上。shuttle-axum 做的正是把 axum::Router 包装起来、并实现 Service::bind,让你可以像使用普通库一样使用 Axum 的全部能力,同时自动获得 Shuttle 的资源供给、日志、部署链路。
Shuttle 支持的框架不止 Axum,还有 Actix Web、Rocket、Poem、Warp、Tower 等,完整列表见 services/README.md,其中明确指出:编写新的框架集成,只需为该框架实现 Service trait 即可。而本文主角 shuttle-axum 当前版本为 0.57.0(见 services/shuttle-axum/Cargo.toml),与整个工作区版本保持一致。
二、版本支持与 Feature 选择
原文档明确了两点版本事实:
- Axum 0.8 是默认版本;
- Axum 0.7 通过 feature flag 支持。
原文档给出的 0.7 接入配置如下(toml,ignore 代码块,需原样保留到你的 Cargo.toml):
axum = "0.7.3"
shuttle-axum = { version = "...", default-features = false, features = ["axum-0-7"] }
这里有两个关键动作:一是通过 default-features = false 关闭默认的 axum 特性,二是显式开启 axum-0-7 特性。配套地在依赖里固定你自己的 axum = "0.7.3",保证用户代码、shuttle-axum 内部与 axum 三方版本匹配。
从源码可以印证这一设计。查看 services/shuttle-axum/Cargo.toml:
[dependencies]
axum = { version = "0.8.1", optional = true }
axum-0-7 = { package = "axum", version = "0.7.3", optional = true }
shuttle-runtime = { path = "../../runtime", version = "0.57.0", default-features = false }
[features]
default = ["axum"]
axum-0-7 = ["dep:axum-0-7"]
可见 axum-0-7 本质上是对 axum 0.7.3 这个包的重新命名引入;而在 services/shuttle-axum/src/lib.rs 中,通过 cfg 完成了版本别名:
#[cfg(feature = "axum")]
pub use axum;
#[cfg(feature = "axum-0-7")]
pub use axum_0_7 as axum;
两个版本的具体对照如下:
| 场景 | 依赖写法 | 说明 |
|---|---|---|
| 默认(Axum 0.8) | shuttle-axum = "0.57.0" |
直接使用默认特性即可 |
| 需要 Axum 0.7 | axum = "0.7.3" + shuttle-axum = { version = "...", default-features = false, features = ["axum-0-7"] } |
同时关闭默认特性、开启 0.7 特性 |
三、快速开始:Hello World 示例
原文档给出的最小可运行示例为(rust,ignore):
use axum::{routing::get, Router};
async fn hello_world() -> &'static str {
"Hello, world!"
}
#[shuttle_runtime::main]
async fn axum() -> shuttle_axum::ShuttleAxum {
let router = Router::new().route("/", get(hello_world));
Ok(router.into())
}
这个示例与普通 Axum 程序相比只发生了两处变化,却蕴含了整个 Shuttle 的接入模型:
- 不再自己创建
tokio::net::TcpListener并调用axum::serve手动绑定端口——监听地址由 Shuttle 运行时注入; - 入口函数从
#[tokio::main] async fn main()换成#[shuttle_runtime::main] async fn axum(),返回值类型是shuttle_axum::ShuttleAxum。
对照仓库根目录 README.md 中的"普通 Axum vs Shuttle Axum"改写示例,二者唯一区别正是去掉了 TcpListener::bind("127.0.0.1:3000") 与 axum::serve 的手动绑定逻辑。这正是 Shuttle 的核心价值:删除所有基础设施样板代码,聚焦业务本身。
3.1 初始化项目
用 Shuttle CLI 即可生成带 Axum 模板的工程骨架(参考 runtime/README.md):
shuttle init --template axum my-axum-app
生成的 my-axum-app 是一个二进制 crate,其 Cargo.toml 中会包含以下关键依赖(同样见 runtime/README.md):
axum = "0.8.1"
shuttle-axum = "0.57.0"
shuttle-runtime = "0.57.0"
tokio = "1.28.2"
3.2 本地运行
在项目目录下执行:
shuttle run
应用会在默认端口 8000 启动,随后可用 curl 验证:
curl http://localhost:8000/
# Hello, world!
3.3 云端部署
shuttle deploy
部署完成后,服务会分配到一个 *.shuttle.app 子域名下(见 runtime/README.md):
curl https://my-axum-app-0000.shuttle.app/
# Hello, world!
四、源码解析:AxumService 与 ShuttleAxum 的底层实现
4.1 AxumService:Router 的 Shuttle 包装
services/shuttle-axum/src/lib.rs 定义了唯一的公开结构体:
/// A wrapper type for [axum::Router] so we can implement [shuttle_runtime::Service] for it.
pub struct AxumService(pub Router);
它是 axum::Router 的元组包装(tuple struct),目的是让 Router 能够实现 shuttle_runtime::Service trait——因为孤儿规则不允许为外部类型直接实现外部 trait,包装一层即可解决。
4.2 bind:服务启动的最后一公里
Service trait 的关键实现在 services/shuttle-axum/src/lib.rs:
#[shuttle_runtime::async_trait]
impl shuttle_runtime::Service for AxumService {
/// Takes the router that is returned by the user in their [shuttle_runtime::main] function
/// and binds to an address passed in by shuttle.
async fn bind(mut self, addr: SocketAddr) -> Result<(), Error> {
#[cfg(feature = "axum")]
axum::serve(
shuttle_runtime::tokio::net::TcpListener::bind(addr)
.await
.map_err(CustomError::new)?,
self.0,
)
.await
.map_err(CustomError::new)?;
#[cfg(feature = "axum-0-7")]
axum_0_7::serve(
shuttle_runtime::tokio::net::TcpListener::bind(addr)
.await
.map_err(CustomError::new)?,
self.0,
)
.await
.map_err(CustomError::new)?;
Ok(())
}
}
可以拆解为三层:
- 地址注入:
addr由 Shuttle 运行时在启动阶段通过SHUTTLE_RUNTIME_IP、SHUTTLE_RUNTIME_PORT等环境变量解析而来(见 runtime/src/rt.rs); - 监听与托管:使用
shuttle_runtime::tokio的TcpListener绑定该地址,再交由axum::serve驱动由用户返回的Router(self.0); - 错误归一:绑定与 serve 阶段的错误统一通过
CustomError::new包装。CustomError本质是anyhow::Error的类型别名(见 service/src/error.rs),最终进入service::Error的Custom变体。
注意两个 cfg 分支分别对应 0.8 与 0.7 两种 Axum 版本,与第二章的 feature 设计一一对应。
4.3 From:一行 .into()
.into()services/shuttle-axum/src/lib.rs 提供了从 Router 到 AxumService 的转换:
impl From<Router> for AxumService {
fn from(router: Router) -> Self {
Self(router)
}
}
这正是示例代码里 Ok(router.into()) 得以成立的原因。注意 Router 此处根据 feature 分别解析为 axum::Router 或 axum_0_7::Router(见同文件 L10-L13)。
4.4 ShuttleAxum:返回值类型别名
services/shuttle-axum/src/lib.rs 定义了对外暴露的返回值别名:
#[doc = include_str!("../README.md")]
pub type ShuttleAxum = Result<AxumService, Error>;
即 Result<AxumService, shuttle_runtime::Error>。Error 的定义位于 service/src/error.rs,涵盖 IO 错误、数据库错误、构建/绑定阶段 panic、字符串插值错误与自定义错误等类别。
五、#[shuttle_runtime::main]:宏展开背后的执行流程
#<a href="https://link.gitcode.com/i/f7cfc5d52a58cf35bb3e0be05b84f1f3" target="_blank">shuttle_runtime::main] 属性宏的实现位于 [codegen/src/shuttle_main.rs,它负责把用户的 main 函数改造成 Shuttle 的加载-运行模型。从源码看,展开后的代码结构为:
fn main() {
// manual expansion of #[tokio::main]
::shuttle_runtime::tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.unwrap()
.block_on(async {
::shuttle_runtime::__internals::start(
__loader,
__runner,
env!("CARGO_CRATE_NAME"),
env!("CARGO_PKG_VERSION"),
)
.await;
})
}
要点如下:
- Tokio 运行时:宏会手动展开
#<a href="https://link.gitcode.com/i/0583d26b4d7163e007fedebe2c698ca4" target="_blank">tokio::main],创建多线程运行时(见 [codegen/src/shuttle_main.rs); __loader:负责收集函数参数上的资源注解(如#[shuttle_shared_db::Postgres]),将其序列化为资源请求;__runner:负责反序列化资源供给结果、初始化资源对象(如连接池),最终调用你的业务函数;- 用户函数重命名:无论原函数名是什么(甚至可以叫
main),宏都会将其重命名为__shuttle_<原名>,避免与真实的fn main冲突(见 codegen/src/shuttle_main.rs); - 返回类型校验:宏在编译期强制要求函数返回"一等公民服务类型"或
Result<impl shuttle_service::Service, shuttle_runtime::Error>,否则直接编译报错(见 codegen/src/shuttle_main.rs),ShuttleAxum正是一等公民类型之一。
运行时侧,start 函数(runtime/src/start.rs)负责参数校验、tracing 日志初始化,随后进入 runtime/src/rt.rs 中 rt::start 的四个阶段:
- Loading / Provisioning 阶段:加载 Secrets、通过 API 供给数据库等资源(失败时返回 101/111/121/131/132 等非标准退出码);
- Resource Init 阶段:调用
runner.run,把资源转化为最终对象(失败返回 151); - Running 阶段:调用
service.bind(service_addr)启动服务,并监听 SIGTERM/SIGINT(Unix)或 Ctrl+C/Ctrl+Break(Windows)实现优雅退出(中断返回 10)。
整个调用链清晰展示了用户代码与平台运行时之间的边界:你只管返回 Router,从端口分配到资源供给全部由运行时接管。
六、进阶:为 Axum 应用接入数据库与 Secrets
6.1 一行接入 PostgreSQL
Shuttle 的"一行资源供给"在 Axum 应用中同样适用。仓库根目录 README.md 给出了完整的 Postgres 接入示例:
use axum::{routing::get, Router};
async fn hello_world() -> &'static str {
"Hello, world!"
}
#[shuttle_runtime::main]
async fn main(
#[shuttle_shared_db::Postgres] pool: sqlx::PgPool,
) -> shuttle_axum::ShuttleAxum {
pool.execute(include_str!("../schema.sql"))
.await
.expect("failed to run migrations");
let router = Router::new().route("/", get(hello_world));
Ok(router.into())
}
只需在入口函数参数上添加 #[shuttle_shared_db::Postgres] 注解,运行时就会在 __loader 阶段自动请求供给数据库,并在 __runner 阶段把 sqlx::PgPool 注入你的函数——shuttle deploy 一次即可同时上线"应用 + 数据库"。
6.2 Secrets 注入
Axum 服务同样可以读取 Shuttle 的 Secrets。在项目根目录放一个 Secrets.toml(并加入 .gitignore),然后在入口函数注入 SecretStore(参考 runtime/src/plugins.rs):
#[shuttle_runtime::main]
async fn main(
#[shuttle_runtime::Secrets] secrets: SecretStore
) -> ShuttleAxum {
// get secret defined in `Secrets.toml` file.
let secret = secrets.get("MY_API_KEY").unwrap();
let router = Router::new()
.route("/", || async move { format!("My secret is: {}", secret) });
Ok(router.into())
}
Secrets 在运行时通过 client.get_secrets 从 Shuttle API 拉取(见 runtime/src/rt.rs),并支持在资源注解字符串中以 {secrets.xxx} 形式做插值(宏展开处可见 strfmt 的调用,见 codegen/src/shuttle_main.rs)。
七、生态参照:shuttle-axum 在集成层中的位置
shuttle-axum 的实现模式并非孤例。以 services/shuttle-tower/src/lib.rs 为例,它同样定义 TowerService<T> 包装类型、实现 Service::bind(内部改用 hyper::Server::bind + tower::make::Shared),并配套 From<T> 与 ShuttleTower<T> 别名。对比可见:
| 集成层 | 包装类型 | bind 内部实现 |
|---|---|---|
| shuttle-axum | AxumService(Router) |
axum::serve(0.8/0.7 双分支) |
| shuttle-tower | TowerService<T> |
hyper::Server + tower::make::Shared |
也就是说,理解 shuttle-axum 的"包装 + bind + From + 类型别名"四件套,就等于掌握了 Shuttle 所有 Web 框架集成的通用范式,需要时也可以依照 services/README.md 的指引为自己偏好的框架编写自定义集成。
八、常见问题与排查提示
结合运行时源码,接入 shuttle-axum 时常遇以下几类问题:
-
编译报错"shuttle_runtime::main functions need to return a service":入口函数返回类型不是
ShuttleAxum这类一等公民类型。宏会对ReturnType::Default与非法类型直接 emit 编译错误(见 codegen/src/shuttle_main.rs),按提示改为-> shuttle_axum::ShuttleAxum即可。 -
本地
shuttle run时提示环境变量缺失:运行时要求SHUTTLE_ENV等变量存在(见 runtime/src/start.rs),请使用shuttle run启动而非直接cargo run。 -
遇到
--port过时参数报错:较老的命令行参数已被移除,提示信息会明确要求升级 Shuttle CLI(见 runtime/src/start.rs)。 -
版本不匹配:若使用 Axum 0.7,务必同时满足"依赖里
axum = "0.7.3"+shuttle-axum关闭默认特性并开启axum-0-7"两个条件,否则可能出现类型或版本冲突。
总结
shuttle-axum 用极小的代码量(一个包装结构体、一个 bind 实现、一个 From 转换和一个类型别名)完成了 Axum 与 Shuttle 运行时的深度对接:默认随新版 Axum 0.8,同时为既有 0.7 项目保留迁移通道;#[shuttle_runtime::main] 宏在编译期接管入口函数,运行时则在加载、供给、初始化、绑定四个阶段按部就班地启动服务。从 shuttle init --template axum 到 shuttle run 再到 shuttle deploy,你无需接触任何端口分配、TLS、反向代理或资源管理细节,这正是 Shuttle "Build & ship backends without writing any infrastructure files" 这一核心承诺在 Axum 生态中的落地体现。