plugins/languages/rust/skills/async/SKILL.md
Rust 异步编程规范 — Tokio 1.x runtime、`async fn` in traits(stable)、async closures(Rust 1.85+ stable)、结构化并发(JoinSet / select! / spawn)、channel(mpsc / oneshot / broadcast)、tower middleware、axum 0.8 web、Pin / Send / Sync、跨 await 借用、死锁排查。编写异步服务、网络 IO、并发任务、async 死锁分析时加载。触发短语:async fn、tokio、axum、并发、死锁、Future、spawn、await、async trait、stream。
npx skillsauth add lazygophers/ccplugin rust-asyncInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
前置:rust-core、rust-memory。
#[tokio::main] // 默认 multi-thread
async fn main() -> anyhow::Result<()> { Ok(()) }
#[tokio::main(flavor = "current_thread")] // 单线程,最低开销
#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
#[tokio::test] // 测试入口
阻塞操作必须 tokio::task::spawn_blocking 隔离;纯 CPU 密集考虑独立线程池或 rayon。
async fn in traits(Rust 1.75+ stable)trait Repository: Send + Sync {
async fn find(&self, id: u64) -> anyhow::Result<Option<User>>;
async fn save(&self, u: &User) -> anyhow::Result<()>;
}
禁用 #[async_trait] 宏(除非要 dyn Trait 对象安全且 RPITIT 还不够)。
返回 impl Future + Send 自动推断;跨线程需 Send bound 时显式标注。
let fetch = async |url: String| -> anyhow::Result<String> {
reqwest::get(&url).await?.text().await.map_err(Into::into)
};
let body = fetch("https://example.com".into()).await?;
三个 trait:AsyncFn / AsyncFnMut / AsyncFnOnce,可在中间件、handler、迭代器适配中替代手写 |x| async move { ... }。
use tokio::task::JoinSet;
let mut set = JoinSet::new();
for url in urls { set.spawn(async move { fetch(url).await }); }
let mut out = Vec::new();
while let Some(res) = set.join_next().await { out.push(res?); }
JoinSet:动态任务集合,drop 自动取消。tokio::spawn:长生命周期后台任务。select!:竞争 / 超时 / 取消。futures::join_all(无错误短路、无取消)。tokio::select! {
res = work() => handle(res),
_ = tokio::time::sleep(Duration::from_secs(5)) => bail!("timeout"),
}
| Channel | 拓扑 | 场景 |
|---------|------|------|
| mpsc | 多生产-单消费 | 队列、worker pool |
| oneshot | 单值响应 | RPC 应答 |
| broadcast | 广播 | 事件总线 |
| watch | 最新值 | 配置 / 状态 |
use axum::{Router, Json, extract::{State, Path}, routing::{get, post}};
use tower_http::trace::TraceLayer;
async fn create(State(r): State<Arc<dyn Repository>>, Json(req): Json<CreateReq>)
-> Result<Json<User>, AppError>
{
Ok(Json(r.save(&req.into()).await?))
}
fn app(r: Arc<dyn Repository>) -> Router {
Router::new()
.route("/users", post(create))
.route("/users/{id}", get(get_user))
.layer(TraceLayer::new_for_http())
.with_state(r)
}
axum 0.8 路由占位符是 {id} 而非 :id。
Pin;自引用 / 手写 Future 才需要。tokio::spawn 的 Future 必须 Send + 'static → 跨 .await 不得持有非 Send(如 Rc、std::sync::MutexGuard)。tokio::sync::Mutex 才能跨 await,否则 std::sync::Mutex 必须在 await 前 drop。let value = { let g = mtx.lock().unwrap(); g.clone() }; // 释放后再 await
remote(value).await;
| AI 倾向 | 正确做法 |
|---------|---------|
| #[async_trait] | stable async fn in trait |
| block_on 嵌套 | 永远不要在 async 上下文 block_on |
| futures::join_all | JoinSet(支持取消、错误) |
| Arc<Mutex<T>> 共享 | 优先 channel / actor |
| 同步 IO 在 async fn | spawn_blocking |
| 持非 Send 跨 await | await 前 drop 或换 tokio::sync |
tokio 1.xasync fn 不用 #[async_trait]JoinSetselect!{param} 语法tools
UI/UX 与布局设计——做界面布局/结构/导航/组件/交互的设计决策。触发:做UI/UX/布局/排版/导航/组件/交互/栅格/响应式/图表选型/字体配对。按媒介路由 HTML/Web、原生 App(iOS/Android/桌面)、CLI、TUI。需后端动态系统不适用;配色/主题/色板走姊妹 skill design-color。
tools
主题与配色设计——做颜色搭配/调色板/主题/品牌色阶/暗模式的设计决策。触发:选配色/调色/主题/色板/品牌色/暗模式/对比度/色盲/UI风格。按媒介路由 HTML/Web(CSS变量)、原生App(平台token)、CLI(ANSI)、TUI(真彩/256/16降级)。保证可访问性(对比度/色盲安全)。需后端动态系统不适用;UI/UX 布局/组件/交互走姊妹 skill design-uiux。
tools
跨任意组件(plugin/skill/agent/command)的验证驱动优化循环纪律 skill。当用户要优化某个已有组件却无明确方向、或要防止改了反而更差(自评乐观偏差 / 多维同改归因失效 / 为凑分加废话膨胀)、或要把一套通用「评分→单变量改→改后验证严格更好才留否则回滚→触顶停」的纪律套到任意组件上时使用。管优化过程本身的纪律(validation gate / ratchet / 独立验证 / 触顶停),不评单组件深度(交 skill-dev),不查插件接线(交 plugin-dev)。仅手动 /optimize-any 触发。
data-ai
两层规则记忆 (基于 .skein/spec)。planning 时 recall 召回相关规则、task finish 后 sediment 沉淀学习 + prune 自动精简过期/重复/断链规则。core 常驻硬规 + recall 按需召回, 经判定门自动写盘 (不逐次问用户)。产出 .skein/spec 下 core/recall 规则文件 + index。另支持空仓 bootstrap 播种规则基线、记忆大面积失效 (大重构/换栈) 时 reconstruct 可逆归档后按项目类型分型重建、maintain 手动体检 (超预算/stale/断链/重复/废弃, --apply 自动修复)、auto-fix (Stop hook 写 .pending-fix 标记 → main 派 skein-specer bg 跑 maintain --apply 全自动修, 断链只报告)。