rust-backend
GitHub指导编写和修改 Static Web Server 的 Rust 代码,涵盖模块、异步及错误处理。强调严格遵循 CI 标准的验证流程,包括格式化、Clippy 检查、测试及文档生成,并指出构建陷阱与代码规范。
触发场景
安装
npx skills add static-web-server/static-web-server --skill rust-backend -g -y
SKILL.md
Frontmatter
{
"name": "rust-backend",
"description": "Write or modify Rust code in the Static Web Server (SWS) project — modules, types, error handling, async code, hyper responses, feature-gated code, and the local commands that mirror CI. Use when editing anything under src\/, adding a module or dependency, or getting clippy\/fmt\/test\/rustdoc to pass."
}
Rust Backend Coding Standards
Load this skill before editing Rust source. For architecture, pipeline order, and the config-option recipe, see design/SKILL.md. For review criteria, see code-quality/SKILL.md.
When to load: editing any file under src/, adding a module or dependency, changing error handling or async code, or fixing a CI failure in lint, fmt, tests, or docs.
Verify Like CI
Run these before declaring a change done. They match .github/workflows/devel.yml.
# Format (CI runs exactly this)
cargo fmt --all -- --check tests/*.rs
# Clippy: lib/bin, then tests. Repeat for each feature set CI checks
cargo clippy --features all -- -D warnings
cargo clippy --features all --tests -- -D warnings
cargo clippy --no-default-features -- -D warnings
cargo clippy --no-default-features --tests -- -D warnings
# Tests
cargo test --features all
cargo test --no-default-features
# Rustdoc (nightly) — catches broken intra-doc links and missing docs
cargo +nightly rustdoc --lib -Zrustdoc-map --features all \
--config "build.rustflags=[\"--cfg\", \"tokio_unstable\"]" \
-Zhost-config -Ztarget-applies-to-host \
--config "host.rustflags=[\"--cfg\", \"tokio_unstable\"]" \
--config "build.rustdocflags=[\"--cfg\", \"docsrs\", \"--cfg\", \"docsrs\", \"--cfg\", \"tokio_unstable\", \"-Z\", \"unstable-options\", \"--cap-lints\", \"warn\", \"--extern-html-root-takes-precedence\"]" \
-Zunstable-options -- --document-private-items
FIPS (--no-default-features --features all-fips) needs cmake, golang, and libclang; run it only when touching TLS provider code.
Tooling Pitfalls
- Never use
--all-features: it enablestls-ringandtls-fipstogether andsrc/tls.rsfails withcompile_error!. Use--features all. (make lintstill uses--all-features; do not rely on it) RUSTFLAGSreplaces.cargo/config.tomlflags: the config sets--cfg tokio_unstable. If the shell exportsRUSTFLAGS(e.g.-L native=...for musl),--features allfails withcannot find function default_runtime_collector in crate tokio_metrics_collector. Fix:RUSTFLAGS="$RUSTFLAGS --cfg tokio_unstable" cargo .... ChangingRUSTFLAGSalso forces a full rebuild--no-default-featuresis the strict build: unused imports, dead code, and unused variables that only exist under a feature surface here. Run it whenever you add#[cfg(feature = ...)]
Crate-Level Lints
src/lib.rs sets:
#![deny(missing_docs)] // every pub item, field, and variant needs a `///` doc comment
#![forbid(unsafe_code)]
#![deny(warnings)]
#![deny(rust_2018_idioms)]
#![deny(dead_code)]
Integration test files under tests/ repeat forbid(unsafe_code), deny(warnings), deny(rust_2018_idioms), and deny(dead_code).
Source files begin with the SPDX header:
// SPDX-License-Identifier: MIT OR Apache-2.0
// This file is part of Static Web Server.
// See https://static-web-server.net/ for more information
// Copyright (C) 2019-present Jose Quintana <joseluisq.net>
Error Handling
- Types:
crate::Result<T>(anyhow::Result) andcrate::Error(anyhow::Error) fromsrc/error.rs, which also re-exportsContext,anyhow!, andbail! - HTTP-level failures: file-serving functions return
Result<T, StatusCode>.static_files::handle()returnsResult<StaticFileResponse, StatusCode>;handler.rsturns the status into an error page viaerror_page::error_response() - Context on startup errors:
fallible().with_context(|| format!("unable to read {}", path.display()))?. Startup errors abort with a readable message; request-path errors become status codes - No
unwrap()/expect()in production code: use?,ok_or_else, or a match. Tests may unwrap - Log at the boundary: modules return errors;
handler.rsanderror_page.rslog them. Usetracingmacros (error!,warn!,debug!,trace!), notprintln! - Avoid:
Stringas an error type,Box<dyn Error>, silently discarding aResult
Async and HTTP
- Runtime:
tokiomulti-threaded. Never callblock_onin async context. Usetokio::task::spawn_blockingfor CPU-heavy or blocking work - HTTP:
hyperv1 +hyper-util+http-body-util.service.rsadaptsRequestHandlertohyper::service::Service - Bodies:
crate::body::BodyisBoxBody<Bytes, io::Error>. Build withbody::empty(),body::full(bytes), orbody::stream(s). Stream files; buffer only small generated responses (health, error pages, listings) - Static header values: define
static NAME: HeaderValue = HeaderValue::from_static("...")and.clone()it (seecontrol_headers.rs,security_headers.rs) - Method helpers: use
MethodExt(is_allowed,is_head,is_options) fromcrate::exts::http
Feature Module Pattern
Each feature module follows the same shape so server/opts.rs and handler.rs stay uniform:
/// Initializes <feature>.
pub(crate) fn init(enabled: bool, handler_opts: &mut RequestHandlerOpts) {
handler_opts.my_feature = enabled;
tracing::info!(enabled, "my feature");
}
/// Pre-processing: return `Some` to short-circuit the request.
pub(crate) fn pre_process<T>(
opts: &RequestHandlerOpts,
req: &Request<T>,
) -> Option<Result<Response<Body>, Error>> { /* ... */ }
/// Post-processing: always return the (possibly modified) response.
pub(crate) fn post_process<T>(
opts: &RequestHandlerOpts,
req: &Request<T>,
resp: Response<Body>,
) -> Result<Response<Body>, Error> { /* ... */ }
Keep the testable logic in a plain function (e.g. append_headers(uri, &mut resp), auto(method, headers, level, resp)) that unit tests and benches/ call directly.
Feature-Gated Code
- Gate the module in
lib.rswith#[cfg(feature = "x")]and#[cfg_attr(docsrs, doc(cfg(feature = "x")))] - Gate every field, constructor entry, and use site.
RequestHandlerOptsis built in three places: itsDefaultimpl (handler.rs),server/opts.rs, andtesting.rs - Compression code gates on
any(feature = "compression", feature = "compression-gzip", feature = "compression-brotli", feature = "compression-zstd", feature = "compression-deflate")— copy the existing block - Provide a
#[cfg(not(feature = "x"))]fallback value when a caller needs one (seewill_serve_fallbackinhandler.rs)
File System
- The root is canonicalized once in
server/opts.rs(unless--use-relative-root); virtual-host roots are canonicalized insettings/. Never canonicalize the base per request - Request paths pass through
fs::path::sanitize_path()thenstatic_files::security::enforce(). Seesecurity/SKILL.mdbefore touching either fs/meta.rs(try_metadata,try_file_open,try_metadata_with_html_suffix) maps any metadata or open failure toStatusCode::NOT_FOUNDand logs the cause atdebug/trace- Prefer
&Pathover&PathBufin new signatures, andimpl AsRef<Path>for new public APIs
Code Style
rustfmtdefaults. No commented-out code; git keeps history- Derive
DebugandCloneon config/option types;#[must_use]on pure functions whose result must be used - No global mutable state (
static mut,Mutexin astatic). Shared config isArc<RequestHandlerOpts>; per-thread caches usethread_local!(see the containment cache instatic_files/security.rs) - Regex: the crate uses
regex-lite, notregex. Globs useglobset. Placeholder replacement usesaho-corasick - Extract nested conditionals into named functions; prefer
let ... elseandif let ... &&chains (edition 2024) over deep nesting
Dependencies
- Check binary-size impact before adding a crate:
cargo build --release --features allbefore/after, comparetarget/release/static-web-server. Over 100KB requires a feature flag or replacing existing functionality - Use
default-features = falseand enable only needed features cargo auditruns in CI (.github/workflows/audit.yml)
版本历史
-
a1500d4
当前 2026-10-20 05:08
更新触发条件以包含修复 CI 失败;新增工具使用陷阱说明(如避免 --all-features);细化 crate 级 lint 配置及 FIPS 构建要求。
- 21dc11b 2026-08-20 17:42


