<rss version="2.0"><channel><title>Rust.cc</title><link>https://rust.cc</link><description>This Is Rust Crustacean Community RSS feed.</description><item><title>nanobot-rs：Rust 实现的本地 AI Agent 运行时</title><link>https://rustcc.cn/article?id=5703dd2f-1043-4d2c-835b-137cec34b343</link><description><![CDATA[<p>nanobot 是纯 Rust 编写的轻量级本地 Agent 运行时，主打本地部署、多渠道接入、多模型兼容，适合快速搭建可扩展的 AI 智能体应用。</p>
<p>参考了知名的 openclaw/nanobot</p>
<p>主要供自用和学习，平时只占用 10多 MB 内存，适合个人跑几个 bot 玩</p>
<p><strong>核心能力</strong></p>
<p>支持 CLI 交互式 / 单轮对话，开箱即用</p>
<p>原生适配 Anthropic、OpenAI 兼容全系模型，可无缝切换 DeepSeek 等主流大模型</p>
<p>自带丰富工具集：文件操作、Shell 执行、网页抓取、子代理、定时任务、MCP/ACP 能力</p>
<p>本地会话持久化、记忆管理、心跳守护，轻量化无依赖</p>
<p>多渠道接入：CLI、Telegram、飞书</p>
<p><strong>项目特点</strong></p>
<p>极简配置，一行命令快速启动本地 AI 对话</p>
<p>完善 CI/CD 支持，跨 Linux/macOS/Windows 编译打包</p>
<p>规范版本管理与自动 Changelog，结构清晰易二次开发</p>
<p>适合 AI Agent 学习研究、私人本地智能体、业务轻量化机器人搭建</p>
<p>主打轻量化、高性能，欢迎大家 star、提 issue、PR 贡献代码～</p>
]]></description><pubDate>2026-05-29 13:49:01</pubDate></item><item><title>【Rust日报】2026-05-29 Rust 1.96.0 发布，稳定 core::range 新类型与 assert_matches!</title><link>https://rustcc.cn/article?id=9765251a-a3f9-4424-be9c-1f2c82338b1b</link><description><![CDATA[<h2>Rust 1.96.0 发布，稳定 core::range 新类型与 assert_matches!</h2>
<p>Rust 官方团队正式发布 1.96.0 稳定版，包含多项语言和标准库更新。</p>
<p><strong>新 Range 类型（core::range）</strong></p>
<p>许多用户期望 Range 及相关 <code>core::ops</code> 类型是 Copy 的，但原来它们直接实现了 Iterator，同时实现 Iterator 和 Copy 是一个 footgun，因此一直回避。RFC 3550 提出了一组替代 Range 类型，这些类型实现 IntoIterator 而非 Iterator，因此也可以是 Copy。相关类型现已稳定：</p>
<ul>
<li><code>core::range::Range</code>、<code>core::range::RangeFrom</code>、<code>core::range::RangeInclusive</code> 及关联迭代器</li>
<li>新的 RangeInclusive 将字段公开，避免了旧版本中暴露迭代器耗尽状态的问题</li>
<li>公共 API 建议使用 <code>impl RangeBounds</code>，同时接受新旧两种 Range 类型</li>
</ul>
<p><strong>新断言宏 assert_matches!</strong></p>
<p>新增 <code>assert_matches!</code> 和 <code>debug_assert_matches!</code>，断言某个值是否匹配给定模式，失败时输出 Debug 表示，便于诊断失败原因。注意：因与同名第三方 crate 冲突，这两个宏未加入标准前置导入，需手动 <code>use core::assert_matches</code> 引入。</p>
<p><strong>WebAssembly 目标变更</strong></p>
<p>WebAssembly 目标不再向链接器传递 <code>--allow-undefined</code>，未定义符号现在会变成链接错误而非自动转为 "env" 模块的 WebAssembly 导入。此变更已在 1.96 生效。</p>
<p><strong>两个 Cargo 安全修复</strong></p>
<ul>
<li>CVE-2026-5223（中危）：Cargo 错误处理第三方注册表 crate tarball 中的符号链接，允许恶意 crate 覆盖同一注册表中另一个 crate 的源代码；1.96 起拒绝提取 tarball 中任何符号链接。crates.io 用户不受影响。</li>
<li>CVE-2026-5222（低危）：URL 规范化后的认证处理问题。</li>
</ul>
<p>升级：<code>rustup update stable</code></p>
<p>原文链接：https://blog.rust-lang.org/2026/05/28/Rust-1.96.0/</p>
<h2>在越狱 Kindle 上运行 Rust（和 Slint）</h2>
<p>作者成功在第 7 代 Kindle Paperwhite 上运行 Rust 程序，实现了图形界面显示和触摸交互，初衷是将 Kindle 用作床头时钟，后续计划开发 Home Assistant 仪表板。</p>
<p>核心技术路径：使用 <code>cargo-zigbuild</code> 交叉编译到 <code>armv7-unknown-linux-musleabihf</code>；选用 Slint GUI 库，软件渲染后通过内存映射写入 <code>/dev/fb0</code> 刷新电子墨水屏；触摸输入则从 <code>/dev/input/event1</code> 读取 Linux 多点触控事件并转换为 Slint 事件。充分利用了 Linux "一切皆文件"的设计哲学。</p>
<p>作者已将 Slint Kindle 后端开源：https://github.com/sverrejb/slint-kindle-backend</p>
<p>原文链接：https://sverre.me/blog/rust-on-kindle/</p>
<h2>Rust 将拯救 Linux 免受 AI 威胁——Greg Kroah-Hartman</h2>
<p>Linux 稳定内核维护者 Greg Kroah-Hartman 在 Rust Week 大会上指出：最新 AI 漏洞检测程序发现了大量严重的 Linux 安全漏洞（Dirty Frag、Copy Fail、Fragnesia 等），内核团队如今每天要发布约 13 个 CVE。大多数漏洞源于 C 语言的内存管理问题——未检查的指针解引用、忘记解锁、内存泄漏等。</p>
<p>Rust 可在编译时捕获这些错误，强制执行锁的获取与释放，预计可直接消除约 60% 的内核漏洞，减轻维护者负担。此外，即使 Rust 消失，它已促使内核 C 代码引入了 guards 和作用域锁等新模式。</p>
<p>原文链接：https://www.zdnet.com/article/rust-will-save-linux-from-ai-says-greg-kroah-hartman/</p>
<h2>Agari：用 Rust 和 Bevy 开发日本立直麻将游戏的一年</h2>
<p>作者用 Rust + Bevy 历时一年开发了一款日本立直麻将游戏，起因是现有在线平台 AI 弱、界面风格难以被朋友接受、且需要持续联网。</p>
<p>技术方案：先开发 Rust 计分库 <code>agari</code>（日语"上がり"，胡牌），再基于此构建游戏。Bevy 引擎适合场景简单、渲染负载轻的麻将游戏；采用 3D 桌面设计 + 长焦压缩视角，使远近玩家牌张大小接近；多人联机采用主机权威 + 锁步同步架构，并实现了断线重连系统。</p>
<p>设计目标：离线可玩、无账号、无抽卡、可配置 AI 风格、界面简洁（无动漫元素）。</p>
<p>原文链接：https://agari.app/devlog/building-agari/</p>
<hr>
<p>From Rust中文社区 Mike</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-05-29 01:12:15</pubDate></item><item><title>Velotype 0.5.0 已发布：Outline 解析与渲染、Workspace 模式、Mermaid和LaTeX渲染等功能已初步实现</title><link>https://rustcc.cn/article?id=76efd4d9-c027-4c72-be1f-895cbf75a364</link><description><![CDATA[<p>Velotype 项目在过去 2 周左右的时间内共计进行了 59 次 commit 并 Close 了 28 个 issue，获得了 300+ Star 并有 2 位出色的 contributor 加入了 velotype 的开发。这些都超出了我对项目早期的预期！</p>
<p>同时，过去的 2 周时间里，velotype 有以下更新：</p>
<ul>
<li>实现对 Mermaid 和 LaTeX 的渲染支持，并在后续迭代中不断修复已知问题和进行改进</li>
</ul>
<p><img src="https://img.cdn1.vip/i/6a17e49ccd5a5_1779950748.webp" alt="p1"></p>
<ul>
<li>支持了 Dark/Light 明暗双主题色(默认暗色主题)，构建了偏好设置页面，支持按键自定义等</li>
</ul>
<p><img src="https://img.cdn1.vip/i/6a17e51fb075e_1779950879.webp" alt="p2"></p>
<ul>
<li>支持了更多的 markdown 语法并优化了底层渲染逻辑</li>
</ul>
<p>并在 <code>v0.5.0</code> 版本中通过对 md 文件 <code>Hx</code> 标题的解析与渲染，构建了大纲解析，同时初步完成了 Workspace 模式，支持一些简易使用的快捷功能，Workspace 面板中会解析并渲染当前打开的 md 文件所在的根路径下的文件 Tree，如果存在其它 md 文件，单击即可快速替换当前编辑的文件，提供了一些便捷和编辑氛围。更多的功能将在后续不断完善。</p>
<p><img src="https://img.cdn1.vip/i/6a17e564d5d98_1779950948.webp" alt="p3"></p>
<p>Velotype 项目地址：https://github.com/manyougz/velotype ，如果觉得对您有帮助，不妨给项目一颗 star，十分感谢！同时也欢迎参与到 velotype 的开发中！</p>
<blockquote>
<p>注意！目前 Velotype 项目依旧处于早期开发状态，还有许多的潜在问题待修复和功能待完善。</p>
</blockquote>
]]></description><pubDate>2026-05-28 06:54:20</pubDate></item><item><title>【Rust日报】2026-05-28 SQLx 0.9.0 发布：新增 sqlx.toml 与更严格 SQL 安全机制</title><link>https://rustcc.cn/article?id=e7b83f3b-49eb-4ff4-ac8c-d9c541abc406</link><description><![CDATA[<h2>SQLx 0.9.0 发布：新增 sqlx.toml 与更严格 SQL 安全机制</h2>
<h3>重要公告</h3>
<p><strong>新的 GitHub 组织</strong></p>
<ul>
<li>SQLx 仓库将转移到新的 GitHub 组织：https://github.com/transact-rs/</li>
<li>原因：SQLx 已不再由 LaunchBadge, LLC. 拥有和维护，现在由核心作者集体所有</li>
<li>这一变更使所有权更加明确，并允许邀请外部协作者</li>
</ul>
<p><strong>移除 Cargo.lock 跟踪</strong></p>
<ul>
<li>Git 不再跟踪 Cargo.lock 文件</li>
<li>CI 将默认使用所有依赖项的最新版本进行测试</li>
<li><code>cargo install --locked sqlx-cli</code> 将不再工作</li>
<li>需要可重现构建的用户应维护自己的 lockfile</li>
</ul>
<h3>版本亮点</h3>
<p><strong>新增运行时支持</strong></p>
<ul>
<li>支持 smol 和 async-global-executor 运行时，作为已弃用的 async-std 的继任者</li>
</ul>
<p><strong>sqlx.toml 配置文件</strong></p>
<ul>
<li>新增配置文件支持，便于实现多数据库或多租户设置</li>
<li>允许全局类型覆盖，简化自定义类型和第三方库的使用</li>
</ul>
<p>原文链接：https://github.com/transact-rs/</p>
<h2>Edge Python：13000行 Rust 打造的 WASM Python 编译器</h2>
<p>作者分享了一个用 13000 行纯 Rust（<code>no_std</code>）代码写成的 Python 编译器项目 <code>Edge Python</code>，目标是把 Python 子集编译成约 170KB 的 WASM 模块，在浏览器、Cloudflare Workers、Wasmtime 等环境里运行。</p>
<h3>项目亮点</h3>
<ul>
<li><strong>异步模型很特别</strong>：把调度器移进虚拟机，允许挂起点从普通 <code>def</code> 或模块顶层触发，而不必让 <code>async/await</code> 污染整条调用链</li>
<li><strong>结构化并发内建</strong>：提供 <code>gather</code>、<code>with_timeout</code>、<code>run</code>、<code>cancel</code> 等原语，并支持确定性虚拟时钟，方便测试并发逻辑</li>
<li><strong>编译器实现很硬核</strong>：字节码采用 SSA 版本化并在控制流汇合点使用 Phi 节点，解析器则是手写 Pratt parser 直接生成字节码</li>
<li><strong>面向真实场景</strong>：项目已经拿到赞助，希望在客户端执行数千行 Python 代码，以降低延迟和算力成本</li>
</ul>
<p>这个项目既有“编译器玩具变真项目”的传播性，也有相当扎实的技术含量，放在今天的 Rust 生态里很吸睛。</p>
<p>原文链接：https://www.reddit.com/r/rust/comments/1tou27c/13k_lines_of_rust_later_from_toy_compiler_to/</p>
<h2>Pingora - Cloudflare 开源的高性能网络代理框架</h2>
<h3>项目简介</h3>
<p>Pingora 是一个用 Rust 语言开发的框架，用于构建快速、可靠和可编程的网络系统。该项目已经过实战检验，多年来每秒处理超过 4000 万次互联网请求。</p>
<h3>核心特性</h3>
<ul>
<li><strong>异步 Rust 架构</strong>：提供快速可靠的 HTTP 1/2 端到端代理</li>
<li><strong>多 TLS 支持</strong>：支持 OpenSSL、BoringSSL、s2n-tls 或 rustls（实验性）</li>
<li><strong>协议支持</strong>：支持 gRPC 和 WebSocket 代理</li>
<li><strong>平滑重载</strong>：支持优雅的服务重启</li>
<li><strong>灵活的负载均衡</strong>：可自定义负载均衡和故障转移策略</li>
<li><strong>可观测性</strong>：支持多种监控工具</li>
</ul>
<h3>使用场景</h3>
<ul>
<li><strong>安全优先</strong>：相比 C/C++ 服务，Pingora 提供更好的内存安全性</li>
<li><strong>性能敏感</strong>：快速高效的性能表现</li>
<li><strong>高度定制</strong>：提供高度可编程的 API 接口</li>
</ul>
<h3>主要组件</h3>
<ul>
<li><strong>pingora-core</strong>：定义协议、功能和基本特性</li>
<li><strong>pingora-proxy</strong>：构建 HTTP 代理的逻辑和 API</li>
</ul>
<p>原文链接：https://github.com/cloudflare/pingora</p>
<h2>Current - 基于浏览器的文件分享工具</h2>
<p>作者向 Rust 社区分享了自己开发的新工具 <code>Current</code>。</p>
<h3>关键要点</h3>
<p><strong>项目介绍：</strong></p>
<ul>
<li>这是一个基于浏览器的文件分享 Web 应用</li>
<li>使用 <strong>iroh</strong> 库及其点对点（P2P）网络功能构建</li>
<li>主要用途是在设备之间传输文件</li>
</ul>
<p><strong>目标场景：</strong></p>
<ul>
<li>专门设计用于创意团队成员之间传输大型视频文件</li>
<li>也可用于其他文件传输需求</li>
</ul>
<p><strong>开发状态：</strong></p>
<ul>
<li>这是开发者使用 iroh 构建的多个工具中第一个准备公开分享的项目</li>
<li>开发者希望获得社区对工具本身和技术文档写作方面的反馈</li>
</ul>
<p>原文链接：https://www.reddit.com/r/rust/comments/1tpend9/building_current_a_browserbased_file_sharing_tool/</p>
<p>--</p>
<p>From 日报小组 Mike</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-05-28 01:09:40</pubDate></item><item><title>【Rust日报】2026-05-27 speakrs - 快速 Rust 说话人分离工具</title><link>https://rustcc.cn/article?id=0e6c3cfe-2024-47cc-b30b-03d06cf36680</link><description><![CDATA[<h2>speakrs - 快速 Rust 说话人分离工具</h2>
<p><code>speakrs</code> 是一个用 Rust 实现的高速说话人分离（speaker diarization）工具，目标是在保持接近 pyannote 精度的同时，把吞吐量拉到非常高的水平。</p>
<h3>核心亮点</h3>
<ul>
<li><strong>性能很猛</strong>：在 VoxConverse dev 数据集上，speakrs CoreML 版本 DER 为 <strong>7.1%</strong>，实时倍速达到 <strong>529x</strong>；对比之下，pyannote 在同平台的 DER 为 <strong>7.2%</strong>，实时倍速约 <strong>24x</strong></li>
<li><strong>纯 Rust 实现</strong>：完整覆盖 pyannote community-1 风格流程，包括分段、powerset 解码、重叠添加聚合、二值化、嵌入、PLDA 和 VBx 聚类</li>
<li><strong>无需 Python 运行时</strong>：推理基于 ONNX Runtime 或原生 CoreML，适合更轻量的部署路径</li>
</ul>
<h3>主要特性</h3>
<ul>
<li><strong>多种执行模式</strong>：支持 <code>cpu</code>、<code>coreml</code>、<code>coreml-fast</code>、<code>cuda</code>、<code>cuda-fast</code></li>
<li><strong>接口直接</strong>：既能处理音频，也能输出说话人分段结果</li>
<li><strong>支持后台批处理</strong>：可多线程异步处理音频文件</li>
<li><strong>适合离线环境</strong>：支持从本地目录加载模型</li>
</ul>
<p>对做语音处理、会议转录、多说话人场景分析的 Rust 开发者来说，这是个很值得关注的新项目。</p>
<p>原文链接：https://github.com/avencera/speakrs</p>
<h2>BoquilaHUB v0.5 版本发布</h2>
<p>BoquilaHUB 是一个面向生物声学场景的 Rust 工具，这次 v0.5 更新重点把音频与嵌入能力、GUI 体验和模型支持都往前推了一步。</p>
<h3>主要更新内容</h3>
<ul>
<li><strong>新增音频能力</strong>：加入生物声学分类、音频播放和频谱图可视化</li>
<li><strong>GUI 重做</strong>：多个可视化工具重新设计，图像、视频、实时源和音频文件浏览体验更顺手</li>
<li><strong>实时源增强</strong>：新增可调缓冲区，可以回看之前错过的内容</li>
<li><strong>模型扩展</strong>：支持 Perch 2、BioClip 2 等更多模型，也可从 <code>boquila.org/hub</code> 获取更多模型</li>
</ul>
<h3>底层实现变化</h3>
<ul>
<li>从手动操作图像缓冲区，转向使用 <strong>egui</strong> 做绘制，交互性更强</li>
<li>集成 <strong>egui plots</strong> 处理频谱图展示</li>
<li>通过 <code>AIOutput</code> 枚举，简化新增输出类型时的代码路径</li>
</ul>
<p>如果后续 Rust 在科研工具、音视频分析和边缘侧 AI 推理场景继续出圈，这类项目会越来越有代表性。</p>
<p>原文链接：https://boquila.org/hub</p>
<h2>rproc - Linux 资源与进程监控工具</h2>
<p>rproc 是一款受 Windows 11 任务管理器启发的 Linux 资源与进程监控工具，使用 Rust 和 egui 构建，目标是给 Linux 用户一个更直观、更现代的系统监控体验。</p>
<h3>主要功能</h3>
<ul>
<li><strong>进程管理</strong>：监控 CPU、内存、磁盘 I/O、线程和状态，并支持排序、筛选和终止进程</li>
<li><strong>性能总览</strong>：提供 CPU（全局及单核）、内存、磁盘、网络和 GPU 的实时图表</li>
<li><strong>启动项管理</strong>：查看 XDG 自动启动项和已启用的 systemd 单元</li>
<li><strong>服务管理</strong>：可管理 systemctl 的系统和用户服务单元</li>
<li><strong>可调刷新率</strong>：适合不同机器和使用习惯</li>
</ul>
<h3>一个挺实用的细节</h3>
<p>rproc 会维护一个 <strong>60 样本滚动窗口</strong>，并把历史写到 <code>~/.cache/rproc/history.bin</code>。就算 GUI 完全退出，再次打开时也能直接看到最近一分钟的系统活动，而不用重新等待图表“热起来”。</p>
<p>这是个很典型的 Rust 桌面工具项目：功能明确、体验导向，而且把系统层细节做得很认真。</p>
<p>原文链接：https://github.com/Trystan-SA/rproc</p>
<h2>Theta - AI Agent 配置管理工具</h2>
<p>Theta 是一个用 Rust 编写的命令行工具，用来管理基于 theta-spec 标准定义的 AI Agent 配置，思路很像“给 Agent 世界做一个包管理器”。</p>
<h3>核心功能</h3>
<ul>
<li><strong>统一配置管理</strong>：集中管理规则、工具、技能等 Agent 资源</li>
<li><strong>多平台支持</strong>：面向 Claude Code、Codex CLI、GitHub Copilot、Cursor 等主流 AI 编程助手</li>
<li><strong>解析与锁定</strong>：读取 <code>theta.toml</code>，解析、锁定、物化并转换配置到指定平台</li>
</ul>
<h3>命令结构</h3>
<ul>
<li><strong>生命周期管理</strong>：<code>init</code>、<code>check</code>、<code>lock</code>、<code>sync</code>、<code>cast</code></li>
<li><strong>依赖管理</strong>：<code>add</code> / <code>rm rule|tool|skill|subagent</code></li>
<li><strong>检查工具</strong>：<code>describe</code>、<code>list</code>、<code>tree</code></li>
</ul>
<h3>为什么值得看</h3>
<ul>
<li>架构灵感来自 <code>uv</code></li>
<li>实现了以清单为中心的 <strong>theta-spec</strong> 标准</li>
<li>使用三层 Git 缓存架构和确定性锁文件设计</li>
<li>支持从现有 AI 助手平台导入配置</li>
</ul>
<p>AI 编程助手生态最近越来越碎，这类“统一描述、统一同步、统一转换”的工具，后面很可能会变成团队协作里的刚需。</p>
<p>原文链接：https://github.com/tamarillo-ai/theta</p>
<p>--</p>
<p>From 日报小组 Mike</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-05-27 01:08:20</pubDate></item><item><title>求职-rust开发</title><link>https://rustcc.cn/article?id=4afe2604-9c5b-4054-8aac-7dbf2b91c836</link><description><![CDATA[<p>5年以上Golang后端SaaS系统开发经验，并在近一年深度投入Rust中间件、嵌入式软件及音视频领域的研发工作。上家公司做商超的，主要是提供ai识别和计价上位机软件。主要是 rust FFI 调用算法动态库然后编译成dll给上位机使用以及嵌入式软件开发，采用rv1126b板子，在板子上开发ai识别系统。</p>
]]></description><pubDate>2026-05-26 12:08:55</pubDate></item><item><title>如何提高编译速度？</title><link>https://rustcc.cn/article?id=207c4da3-30a9-4dfa-bb01-99f8edfef071</link><description><![CDATA[<p>我有一个<code>vibe coding</code>的前后端一体项目，改一个<code>askama</code>模板文件，整个项目重编译，无法得到即时的反馈。</p>
<p>我尝试过拆crate，拆成：core / models / services / middleware / web，但是无论拆得多细，最后这个<code>web crate</code>编译速度就是很慢很慢，而且体感上和未拆分的大单体编译速度没啥区别。</p>
<p><strong>有没有什么办法提高最后这个crate的编译速度呢？</strong></p>
<p>注：现在也就是个后台管理系统的雏形，Rust 不算注释共 5500 行，html 有1千多行，算上各种 spec 文档也不到1万行。我的CPU是：<code>Intel(R) Core(TM) i7-14700，28线程</code>。</p>
<p>拆分前：</p>
<pre><code>src/
├── main.rs                 # 启动入口：pool, migrate, seed, routes, serve
├── config.rs               # 环境变量解析
├── db/
│   ├── mod.rs              # pool 初始化
│   └── migrations/         # sqlx migration SQL
├── middleware/
│   ├── auth.rs             # JWT 认证（Cookie + Bearer 双模式）
│   └── csrf.rs             # CSRF 校验
├── models/
│   ├── user.rs
│   ├── role.rs
│   ├── menu.rs
│   ├── dept.rs
│   └── log.rs
├── handlers/
│   ├── pages/              # 页面路由（完整 HTML）
│   │   ├── auth.rs         # GET/POST /login 等
│   │   ├── dashboard.rs    # GET /
│   │   ├── user.rs         # GET /users, /users/new, /users/{id}/edit
│   │   ├── role.rs         # GET /roles, /roles/new, /roles/{id}/edit
│   │   ├── dept.rs         # GET /depts
│   │   ├── menu.rs         # GET /menus, /menus/new, /menus/{id}/edit
│   │   └── log.rs          # GET /logs
│   └── fragments/          # HTML 片段路由（HTMX 调用）
│       ├── user.rs         # GET /users/table, POST /users, DELETE /users/{id}
│       ├── role.rs         # ...
│       ├── dept.rs
│       ├── menu.rs
│       └── log.rs          # GET /logs/table
├── services/               # 业务逻辑
│   ├── auth.rs
│   ├── user.rs
│   ├── role.rs
│   ├── menu.rs
│   ├── dept.rs
│   └── log.rs
└── templates/              # Askama 模板
    ├── layouts/
    │   └── main.html       # 基模板（navbar + sidebar + content）
    ├── partials/
    │   ├── navbar.html
    │   ├── sidebar.html
    │   ├── pagination.html
    │   ├── confirm-modal.html
    │   └── toast.html (Phase 1 inline JS in main.html)
    ├── auth/
    │   ├── login.html
    │   ├── forgot_password.html   (延后)
    │   └── reset_password.html    (延后)
    ├── profile/
    │   └── password.html
    ├── users/
    │   ├── list.html
    │   ├── form.html
    │   └── table_fragment.html
    ├── roles/
    │   ├── list.html
    │   └── form.html
    ├── depts/
    │   └── list.html
    ├── menus/
    │   ├── list.html
    │   └── form.html
    ├── logs/
    │   └── list.html
    ├── dashboard.html
    └── errors/
        ├── 401.html
        ├── 403.html
        ├── 404.html
        └── 500.html

静态资源：`static/css/tailwind.css`、`static/js/htmx.min.js`、`static/img/*`
</code></pre>
<p>拆分后：</p>
<pre><code>[workspace]
members = [
    "crates/core",
    "crates/models",
    "crates/services",
    "crates/middleware",
    "crates/web",
]
</code></pre>
]]></description><pubDate>2026-05-26 03:44:53</pubDate></item><item><title>【Rust日报】2026-05-26 TrapDoor 跨生态供应链攻击曝光</title><link>https://rustcc.cn/article?id=937572a4-f57d-482c-ad32-aa8bb611e752</link><description><![CDATA[<h2>TrapDoor 跨生态供应链攻击曝光</h2>
<p>Socket 安全研究人员披露了一起名为 TrapDoor 的大规模供应链攻击活动，影响范围横跨 npm、PyPI 和 Crates.io 三大软件包生态。</p>
<h3>事件要点</h3>
<ul>
<li><strong>波及范围很广</strong>：已识别出 34 个以上恶意软件包，以及 384+ 个相关版本与工件</li>
<li><strong>Rust 生态也在范围内</strong>：Crates.io 侧的攻击主要借助恶意 <code>build.rs</code> 脚本实施</li>
<li><strong>主要攻击目标</strong>：加密货币、DeFi、Solana、Sui、Move、AI/机器学习相关开发者</li>
<li><strong>重点窃取内容</strong>：SSH 密钥、加密钱包、AWS 凭证、GitHub 令牌、浏览器配置、环境变量与本地开发配置</li>
</ul>
<h3>传播与持久化方式</h3>
<ul>
<li>npm 包通过 <code>postinstall</code> 执行共享恶意载荷</li>
<li>PyPI 包在导入时拉取并执行远程 JavaScript</li>
<li>攻击者还会植入 <code>.cursorrules</code>、<code>CLAUDE.md</code>、Git hook、Shell hook、systemd 服务、cron 任务与 SSH 配置等持久化后门</li>
</ul>
<p>这次事件再次提醒 Rust 开发者：即便使用的是 crates.io，也不能忽视供应链安全，尤其要留意构建脚本、依赖来源与本地开发环境中的异常文件。</p>
<p>原文链接：https://socket.dev/blog/trapdoor-crypto-stealer-npm-pypi-crates</p>
<h2>CubeCL 0.20.0 发布：跨平台内核框架重大更新</h2>
<p>CubeCL 0.20.0 正式发布。这一版本继续强化“单一代码库覆盖多种硬件后端”的路线，重点放在 CPU 运行时重构、自动调优和 GPU 高级特性的补齐上。</p>
<h3>这次更新值得关注的点</h3>
<ul>
<li><strong>CPU 后端大改</strong>：重写 CPU 实现，引入更完整的延迟执行系统与多流能力</li>
<li><strong>内核融合补齐</strong>：补上早期版本缺失的 kernel fusion 支持</li>
<li><strong>性能持续拉升</strong>：通过缓存对齐、内存访问优化和自动调优，在部分场景里表现优于 libtorch</li>
<li><strong>GPU 能力增强</strong>：新增 TMA 与 inline PTX 等能力，进一步逼近现代硬件上限</li>
<li><strong>保持可移植性</strong>：同一套优化思路尽量在 GPU 与 CPU 之间保持一致</li>
</ul>
<p>对于做高性能计算、推理框架或异构后端抽象的 Rust 开发者来说，这个版本的演进方向相当值得跟进。</p>
<p>原文链接：https://www.reddit.com/r/rust/comments/1tn7waw/cubecl_0200_is_here_crossplatform_kernels_for/</p>
<h2>snarf：Rust 结构体缓存行伪共享检测工具</h2>
<p>snarf 是一个面向 Rust 的结构体缓存行伪共享检测工具，用来发现原子字段或其他竞争字段是否落在同一缓存行上，从而提前暴露潜在的性能陷阱。</p>
<h3>工具亮点</h3>
<ul>
<li><strong>聚焦伪共享问题</strong>：可识别 <code>Atomic*</code>、<code>Cell</code>、<code>RefCell</code>、<code>UnsafeCell</code> 等字段与其他字段共享缓存行的情况</li>
<li><strong>支持递归检测</strong>：像 <code>Option&lt;AtomicU64&gt;</code>、<code>Arc&lt;Mutex&lt;AtomicU64&gt;&gt;</code> 这类嵌套场景也能覆盖</li>
<li><strong>输出方式灵活</strong>：支持普通输出、JSON、GitHub Actions 注释等格式</li>
<li><strong>适合接入 CI</strong>：可配合 <code>--warn-only</code>、<code>--strict</code> 等参数按团队需求使用</li>
</ul>
<h3>使用方式</h3>
<ul>
<li>安装：<code>cargo install cargo-snarf</code></li>
<li>运行：<code>cargo snarf</code></li>
<li>目前需要 nightly Rust，以便读取精确的类型大小与字段偏移信息</li>
</ul>
<p>这是个很实用的小工具，尤其适合并发密集型项目做结构体布局自检。</p>
<p>原文链接：https://github.com/cong-or/snarf</p>
<h2>AIRE：用于交互式应用的实时音频引擎</h2>
<p>作者在业余时间开发 2D 游戏时，因为现有音频库无法满足需求，索性自己做了一个面向交互式应用的实时音频引擎 AIRE。</p>
<h3>当前能力</h3>
<ul>
<li><strong>多格式支持</strong>：可播放 WAV、OGG、FLAC 和 MP3</li>
<li><strong>流式播放</strong>：支持从磁盘流式读取大型音频文件</li>
<li><strong>实时控制</strong>：可在运行时调节音量、声像以及暂停 / 恢复 / 停止播放</li>
<li><strong>合成能力</strong>：内置多种带限振荡器波形，并支持 ADSR 包络</li>
<li><strong>线程友好</strong>：与音频线程之间采用无锁通信方式</li>
</ul>
<h3>后续方向</h3>
<p>作者希望它未来不只是“播放声音”，而是能进一步理解运行环境，先补齐基础的 2D 空间音频，再逐步探索更动态的声学效果与混响能力。</p>
<p>原文链接：https://github.com/Breijen/aire</p>
<p>--</p>
<p>From 日报小组 Mike</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-05-26 01:07:17</pubDate></item><item><title>再一次试图绕过孤儿规则，named impl 草案</title><link>https://rustcc.cn/article?id=9930a967-9904-4038-9993-3595264d6dbf</link><description><![CDATA[<h1>Rust named impl 草案</h1>
<p>目的很明确，绕过 rust 的孤儿规则。<br>
应该比参考链接的方案写法更流利，读法更自然，且语法更完善。</p>
<h2>概述</h2>
<pre><code>// struct trait 默认 impl, 与当前版本2024相同
pub struct Struct1&lt;T&gt;(T);
pub trait Trait1 {
    fn trait1_fn(&amp;self);
}
impl&lt;T&gt; Trait1 for Struct1&lt;T&gt; {
    fn trait1_fn(&amp;self) {
        println!("default impl");
    }
}

// 新增 named-impl 定义, 可定义在任意 crate
// 下面的 ST1 在 Type Namespace 中
pub impl&lt;T&gt; Trait1 for Struct1&lt;T&gt; use ST1 {
    fn trait1_fn(&amp;self) {
        println!("named impl ST1");
    }
}

// 禁止使用 default 命名 named-impl
pub impl Clone for i32 use default {} // ❌

// 像 struct 和 trait 一样用 use 导入, 也可写全名 mod1::ST1
use mod1::{Struct1, Trait1, ST1};

// 类型定义
type Struct1Generic = Struct1&lt;i32&gt;;
// 泛型类型, 默认推导为下一行的 Struct1&lt;i32, _ use default&gt;

type Struct1Default = Struct1&lt;i32, _ use default&gt;;
//具体类型, 与当前版本2024 Struct1 行为完全相同, 不使用任何 named-impl
//此处 default 为弱关键字 weak keyword

type Struct1WithST1 = Struct1&lt;i32, Trait1 use ST1&gt;;
//具体类型, 布局与 Struct1 相同, 作为 Trait1 时使用 ST1 的实现， 默认省略了最后的 _ use default

// 实现重叠与优先级规则
type ComplexType = Struct1&lt;i64,
    From&lt;i32&gt; use mod2::Struct1Fromi32,
    From&lt;_: Add&gt; use default,
    From&lt;_&gt; use StructFrom, 
    Trait1 use ST1
&gt;;
// 多个 named-impl 泛型参数, trait 之间可以有重叠overlap
// 作为 From&lt;i32&gt; 时使用 Struct1Fromi32 , 作为 From&lt;&amp;str&gt; 时使用 StructFrom
// 从左到右找到第一个匹配的trait(use 前)后, 使用对应的实现

// 有不同 impl 就不是同一类型
assert!(TypeId::of::&lt;Struct1Default&gt;() != TypeId::of::&lt;Struct1WithST1&gt;());


// 类型转换
let s = Struct1(1); // 默认推导为 Struct1&lt;i32, _ use default&gt;
let mut s_ref_named: &amp;Struct1&lt;i32, Trait1 use ST1&gt; = &amp;s; // ✅ 类型转换
let s_ref_default = s_ref_named as &amp;Struct1&lt;i32, _ use default&gt;; // ✅ 多向互转
s_ref_named = s_ref_default; // ❌ 禁止没有显式类型的自动转换

let s4 = Struct1(4); // 默认推导为 Struct1&lt;i32, _ use default&gt;
let s5: Struct1&lt;i32, Trait1 use ST1&gt; = s4; // move 加类型转换

let vs: Vec&lt;Struct1&lt;i32&gt;&gt; = vec![]; // 默认推导为 Vec&lt;Struct1&lt;i32, _ use default&gt;&gt;
let vs1: &amp;Vec&lt;Struct1&lt;i32, Trait1 use ST1&gt;&gt; = &amp;vs; // 类型定义中任意位置的 Struct1
let vs2: &amp;Vec&lt;Struct1&lt;i32, _ use default&gt;&gt; = vs1;


// 最终使用
// 任意 T: Trait1 的 T 均可使用 Struct1&lt;i32, _ use default&gt; 和 Struct1&lt;i32, Trait1 use ST1&gt; 来类型实例化

// 1. 直接调用
s5.trait1_fn();

// 2. UFCS
&lt;Struct1&lt;i32&gt; as Trait1 use ST1&gt;::trait1_fn(&amp;s5);

// 3. 泛型函数
fn use_trait1&lt;T: Trait1&gt;(a: &amp;T) {
    a.trait1_fn();
}

use_trait1(s_ref_default); // default impl
use_trait1(s_ref_named); // named impl ST1

// 4. 泛型类型
pub struct Struct2&lt;'a, T: Trait1&gt;(&amp;'a T);
impl Struct2&lt;'a, T: Trait1&gt; {
    pub fn use_inner(&amp;self) {
        self.0.trait1_fn();
    }
}

let s21 = Struct2(s_ref_default);
s21.use_inner(); //  default impl

let s22 = Struct2(s_ref_named);
s22.use_inner(); // named impl ST1


// trait object
let mut dyn_trait1: &amp;dyn Trait1;

dyn_trait1 = s_ref_named;
dyn_trait1.use_inner(); // named impl ST1

dyn_trait1 = s_ref_default;
dyn_trait1.use_inner(); //  default impl


// impl trait
// 1. 参数位置的 impl trait 仅为泛型参数的简写
fn use_trait1(a: &amp;impl Trait1) {
    a.trait1_fn();
}
use_trait1(s_ref_default); // default impl
use_trait1(s_ref_named); // named impl ST1

// 2. 返回值位置的 impl trait
fn return_trait1() -&gt; impl Trait1 {
    let s4 = Struct1(4); // 默认推导为 Struct1&lt;i32, _ use default&gt;
    return s4 as Struct1&lt;i32, Trait1 use ST1&gt;; // move 加类型转换
}

</code></pre>
<h2>禁止规则</h2>
<ol>
<li><code>Copy</code>, <code>Drop</code>, <code>Send</code>, <code>Sync</code>, <code>Unpin</code> 等必须禁止 named-impl .</li>
</ol>
<pre><code>#[disable_named_impl(all)]
pub trait Copy {}
</code></pre>
<p><code>#[disable_named_impl(all)]</code> 可供外部代码使用, 可置于 trait struct enum 等</p>
<ol start="2">
<li><code>Hash</code> <code>PartialOrd</code> 等至少在有默认实现时禁止 named-impl .</li>
</ol>
<pre><code>#[disable_named_impl(exist_default)]
pub trait Hash {}
</code></pre>
<p><code>#[disable_named_impl(exist_default)]</code> 可供外部代码使用, 可置于 trait struct enum 等</p>
<h2>扩展用法</h2>
<ol>
<li>
<p>对外部类型实现外部trait , 绕过孤儿规则</p>
</li>
<li>
<p>编译期代理，或函数装饰器
java.lang.reflect.Proxy , Python Decorator</p>
</li>
</ol>
<pre><code>impl fmt::Display for i32 use ProxyDisplay {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {
        write!(f, "before ")?;
        (self as &amp;i32&lt;Display use default&gt;).fmt(f)?;
        write!(f, " after")?;
        Ok(())
    }
}

// 通用代理, 但可能因为递归写不出
impl&lt;T: Display&gt; fmt::Display for T use ProxyDisplayDefault {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {
        write!(f, "before ")?;
        (self as &amp;T&lt;Display use default&gt;).fmt(f)?;
        write!(f, " after")?;
        Ok(())
    }
}
</code></pre>
<ol start="3">
<li>特化, 偏特化</li>
</ol>
<pre><code>// 实现重叠与优先级规则
type ComplexType = Struct1&lt;i64,
    From&lt;i32&gt; use Struct1Fromi32,
    From&lt;_: Add&gt; use default,
    From&lt;_&gt; use StructFrom, 
    Trait1 use ST1
&gt;;
// 多个 named-impl 泛型参数, trait 之间可以有重叠overlap
// 作为 From&lt;i32&gt; 时使用 Struct1Fromi32 , 作为 From&lt;&amp;str&gt; 时使用 StructFrom
// 从左到右找到第一个匹配的trait(use 前)后, 使用对应的实现
</code></pre>
<h2>类型隐式泛型, 可选</h2>
<ol>
<li>泛型约束可为 struct enum</li>
</ol>
<pre><code>#[derive(Default)]
struct Struct1;
impl Trait1 for Struct1 {};
impl Trait1 for Struct1 use TS1 {};
fn use_struct1&lt;T: Struct1&gt;() {
    T::default().trait1_fn();
}

use_struct1&lt;Struct1&lt;_ use default&gt;&gt;();
use_struct1&lt;Struct1&lt;Trait1 use TS1&gt;&gt;();
</code></pre>
<ol start="2">
<li>类型隐式泛型, 函数参数和返回值都变成泛型</li>
</ol>
<ul>
<li>优点: 旧式函数可自动用于带 named-impl 的类型</li>
<li>缺点: unsound , 破坏函数原意</li>
</ul>
<pre><code>fn use_struct1(s: &amp;Struct1) {
    s.trait1_fn();
}
// 自动翻译为
fn use_struct1&lt;T: Struct1&gt;(s: &amp;T) {
    s.trait1_fn();
}
</code></pre>
<ul>
<li>问题代码1 多 Struct1 只能为同一类型</li>
<li>问题代码2 参数 i32 变泛型后, 破坏函数内部与参数无关的 i32, 如有 Add 或 PartialEq 等将完全破坏逻辑</li>
</ul>
<h2>简化语法</h2>
<ol>
<li>named-impl 选择参数简化</li>
</ol>
<pre><code>type Struct1Default = Struct1&lt;i32, use default&gt;;
type Struct1WithST1 = Struct1&lt;i32, use ST1&gt;;
type ComplexType = Struct1&lt;i64, use Struct1Fromi32&lt;i32&gt;, use StructFrom&lt;_&gt;, use ST1&gt;;
// trait的类型可以推导得到, 泛型参数在 impl name 之后
</code></pre>
<h2>替代语法</h2>
<ol>
<li>用 <code>as</code> 而不是 <code>use</code></li>
</ol>
<pre><code>pub impl&lt;T&gt; Trait1 for Struct1&lt;T&gt; as ST1 {
    fn trait1_fn(&amp;self) {
        println!("named impl ST1");
    }
}
type Struct1Default = Struct1&lt;i32, _ as default&gt;;
type Struct1WithST1 = Struct1&lt;i32, Trait1 as ST1&gt;;

&lt;Struct1&lt;i32&gt; as Trait1 as ST1&gt;::trait1_fn(&amp;s5);
</code></pre>
<ol start="2">
<li>named-impl 选择参数用 <code>+</code> 追加在类型之后</li>
</ol>
<pre><code>type Struct1Default = Struct1&lt;i32&gt; + _ use default;
type Struct1WithST1 = Struct1&lt;i32&gt; + Trait1 use ST1;
type ComplexType = Struct1&lt;i64&gt; + From&lt;i32&gt; use Struct1Fromi32 + From&lt;_&gt; use StructFrom + Trait1 use ST1;
</code></pre>
<h2>trait继承问题</h2>
<ol>
<li>类型膨胀</li>
<li>subtrait 的 named-impl 是否是否可以选定其 super trait 的实现</li>
<li>更复杂的 upcasting</li>
</ol>
<pre><code>trait T1 {}
trait T2 : T1 {}

struct S;
impl T1 for S {}
impl T2 for S {}

impl T1 for S as T1S3 {}
impl T2 for S as T2S3 {} // 是否可以在此处限制必须使用 T1S3 ?

// 坏消息: 类型膨胀
// 好消息：不是自动生成的4种类型，不写就不会存在（不管是编译时还是运行时）
let s1: S&lt;_ use default&gt; = S;
let s2: S&lt;T1 use T1S3&gt; = S;
let s3: S&lt;T2 use T2S3&gt; = S; // 如果有限制, 则自动推导为下一个
let s4: S&lt;T1 use T1S3, T2 use T2S3&gt; = S;
</code></pre>
<h2>兼容性破坏</h2>
<ol>
<li>FFI 边界</li>
<li>dylib 导出函数</li>
<li>所有假设 trait object 数据指针相同则判断为同一对象的代码出错</li>
</ol>
<pre><code>fn is_same(a: &amp;dyn T1, b: &amp;dyn T1) -&gt; bool {
	let (ptr_a, vt_a) = unsafe { transmute::&lt;_, (usize, usize)&gt;(a) }
	let (ptr_b, vt_b) = unsafe { transmute::&lt;_, (usize, usize)&gt;(b) }
	return ptr_a == ptr_b;
}
</code></pre>
<h2>否定性实现 negative-impls</h2>
<ol>
<li><a href="https://doc.rust-lang.org/unstable-book/language-features/negative-impls.html" rel="noopener noreferrer">negative-impls</a> 不能用于 named-impl</li>
</ol>
<pre><code>pub impl !Trait1 for i32 use NegTrait1 {} // ❌
</code></pre>
<ol start="2">
<li>当存在 negative-impls 时, 禁止有重叠overlap的 named-impl</li>
</ol>
<pre><code>#![feature(negative_impls)]
trait DerefMut { }
impl&lt;T: ?Sized&gt; !DerefMut for &amp;T { }

impl DerefMut for &amp;i32 use DerefMutForI32 {} // ❌
</code></pre>
<h2>参考</h2>
<ul>
<li>https://internals.rust-lang.org/t/pre-rfc-selectable-trait-implementations/23829 最接近, 但没有名字</li>
<li>https://internals.rust-lang.org/t/looking-for-rfc-coauthors-on-named-impls/6275</li>
<li>https://internals.rust-lang.org/t/named-impls-and-impl-generics/22158</li>
<li>https://internals.rust-lang.org/t/pre-rfc-scoped-impl-trait-for-type/19923 理论最完善</li>
</ul>
]]></description><pubDate>2026-05-25 16:30:12</pubDate></item><item><title>【Rust日报】2026-05-25 Wild 0.9.0 版本发布</title><link>https://rustcc.cn/article?id=d8fabba9-b39b-473a-a341-21df3b001988</link><description><![CDATA[<h2>Wild 0.9.0 版本发布</h2>
<p>David Lattimore 于 2026年5月24日发布了 Wild 链接器的 0.9.0 版本。这是自1月以来的首次更新。</p>
<h3>主要功能更新</h3>
<p><strong>链接器脚本支持</strong></p>
<ul>
<li>多位开发者在 GSoC 2026（谷歌编程之夏）前期对链接器脚本支持做了大量工作</li>
<li>Vishruth Thimmaiah 被选中通过 GSoC 继续开发此功能</li>
<li>目标是实现对 Linux 内核模块甚至内核本身的链接支持</li>
</ul>
<p><strong>平台移植工作</strong></p>
<ul>
<li>Mac (Mach-O) 移植：由 Martin Liška 主导</li>
<li>Wasm 移植：由 Kei Akiyama 作为 GSoC 项目主导（这是 Kei 第二年参与 Wild 项目的 GSoC）</li>
</ul>
<p><strong>链接器插件 LTO 支持</strong></p>
<ul>
<li>新增基本的 LTO（链接时优化）支持</li>
<li>主要用于 C、C++ 或混合语言项目</li>
<li>链接速度不会更快，甚至可能稍慢，但方便用户无需切换链接器</li>
</ul>
<p><strong>调试信息压缩</strong></p>
<ul>
<li>现在支持输出压缩的调试信息</li>
<li>支持 zlib 和 zstd 压缩格式</li>
</ul>
<p>原文链接：https://davidlattimore.github.io/posts/2026/05/24/wild-update-0.9.0.html</p>
<h2>Floo v0.10 发布 - Rust 终端工作区管理工具</h2>
<h3>项目简介</h3>
<p><strong>floo</strong> 是一个基于 ratatui 构建的终端用户界面（TUI）程序，旨在帮助开发者快速切换和管理工作区，减少手动操作的负担。可通过 <code>cargo install floo</code> 从 crates.io 安装。</p>
<h3>解决的痛点</h3>
<p>作者使用终端中心化的工作流程（neovim），每次启动电脑时需要重复执行以下操作：</p>
<ul>
<li>在终端中 cd 到项目目录</li>
<li>打开 tmux 会话</li>
<li>加载环境变量</li>
<li>在不同窗口中打开编辑器和运行命令</li>
</ul>
<h3>核心功能</h3>
<ul>
<li><strong>自动目录切换</strong>：选择项目（fireplace）时自动 cd 到工作区</li>
<li><strong>环境变量加载</strong>：自动加载 .env 或 .envrc 文件</li>
<li><strong>自定义操作脚本</strong>：通过在项目根目录放置 <code>.floo</code> 脚本来定义自定义工作流</li>
<li><strong>tmux 集成</strong>：内置模板可自动配置和打开 tmux 会话</li>
<li><strong>项目笔记</strong>：支持为每个项目快速记录笔记</li>
</ul>
<h3>优势</h3>
<ul>
<li>节省大量重复性手动操作</li>
</ul>
<p>原文链接：https://www.reddit.com/r/rust/comments/1tma7ro/floo_v010_released/</p>
<h2>OpenMLS - Rust实现的MLS协议库</h2>
<p>OpenMLS是消息层安全协议(MLS, Messaging Layer Security)的Rust实现，遵循RFC 9420规范。这是一个软件库，可作为需要端到端加密消息的应用程序的构建模块。</p>
<h3>主要特点</h3>
<ul>
<li><strong>安全易用的接口</strong>：隐藏底层加密操作的复杂性</li>
<li><strong>端到端加密</strong>：为消息传递提供安全保障</li>
</ul>
<h3>支持的密码套件</h3>
<ul>
<li>MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 (强制实现)</li>
<li>MLS_128_DHKEMP256_AES128GCM_SHA256_P256</li>
<li>MLS_128_DHKEMX25519_CHACHA20POLY1305_SHA256_Ed25519</li>
</ul>
<h3>支持的平台</h3>
<p><strong>完全支持（构建和测试）：</strong></p>
<ul>
<li>x86_64-unknown-linux-gnu</li>
<li>x86_64-pc-windows-msvc</li>
<li>aarch64-apple-darwin</li>
<li>aarch64-unknown-linux-gnu</li>
</ul>
<p><strong>部分支持（仅构建）：</strong></p>
<ul>
<li>iOS、Android、WebAssembly等多个平台</li>
</ul>
<p>原文链接：https://github.com/openmls/openmls</p>
<h2>Scena 1.5.1 发布</h2>
<p>Scena 是一个 Rust 原生的 3D 渲染器，专注于场景图、glTF/GLB 格式、PBR 材质、浏览器演示、本地渲染和无头图像生成。</p>
<h3>主要特点</h3>
<ul>
<li><strong>简化的 API 设计</strong>：使开发者能够用简洁的 Rust 代码实现常见的 3D 查看器功能</li>
<li><strong>多种渲染路径</strong>：支持原生渲染、无头渲染、WebGL2 和 WebGPU</li>
<li><strong>材质系统</strong>：提供命名的 PBR 材质预设</li>
<li><strong>模型支持</strong>：完整的 glTF/GLB 文件加载能力</li>
<li><strong>环境照明</strong>：内置工作室照明和环境预设</li>
</ul>
<h3>1.5.1 版本重点更新</h3>
<ul>
<li>浏览器渲染的公开展示平台</li>
<li>命名 PBR 材质预设功能</li>
<li>glTF/GLB 加载优化</li>
<li>工业/数字孪生场景的连接器配对功能</li>
<li>通过预计算 HDR 照明和更小的 WASM 包提升浏览器启动速度</li>
</ul>
<h3>资源链接</h3>
<ul>
<li><strong>在线演示</strong>：https://scena-demo.pages.dev/</li>
<li><strong>Crate 地址</strong>：https://crates.io/crates/scena</li>
</ul>
<p>原文链接：https://scena-demo.pages.dev/</p>
<p>--</p>
<p>From 日报小组 Mike</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-05-25 01:11:25</pubDate></item><item><title>A high-performance async Rust implementation of KCP - A Fast and Reliable ARQ Protocol built on top of Tokio.</title><link>https://rustcc.cn/article?id=29969d7b-6ba8-4f9e-908c-4004a893fee0</link><description><![CDATA[<p>https://github.com/leihuxi/rust-kcp
A high-performance async Rust implementation of KCP - A Fast and Reliable ARQ Protocol built on top of Tokio.</p>
<p>Features
Async-First Design: Built from ground up for async/await with Tokio integration
Zero-Copy: Efficient buffer management using the bytes crate
Lock-Free Buffer Pool: High-performance memory management with crossbeam
Connection-Oriented: High-level connection abstractions (KcpStream, KcpListener)
Protocol Compatible: Compatible with original C KCP implementation
Observability: Integrated tracing and metrics support
Memory Efficient: Object pooling and buffer reuse
Multiple Performance Modes: Normal, Fast, Turbo, Gaming presets
Installation
Add this to your Cargo.toml:</p>
<p>[dependencies]
kcp-tokio = "0.4"
tokio = { version = "1.0", features = ["full"] }
Quick Start
Client
use kcp_tokio::{KcpConfig, KcpStream};
use tokio::io::{AsyncReadExt, AsyncWriteExt};</p>
<p>#[tokio::main]
async fn main() -&gt; Result&lt;(), Box&gt; {
let config = KcpConfig::new().fast_mode();
let mut stream = KcpStream::connect("127.0.0.1:12345".parse()?, config).await?;</p>
<pre><code>// Send data
stream.write_all(b"Hello, KCP!").await?;

// Receive response
let mut buffer = [0u8; 1024];
let n = stream.read(&amp;mut buffer).await?;
println!("Received: {}", String::from_utf8_lossy(&amp;buffer[..n]));

Ok(())
</code></pre>
<p>}
Server
use kcp_tokio::{KcpConfig, KcpListener};
use tokio::io::{AsyncReadExt, AsyncWriteExt};</p>
<p>#[tokio::main]
async fn main() -&gt; Result&lt;(), Box&gt; {
let config = KcpConfig::realtime();
let mut listener = KcpListener::bind("127.0.0.1:12345".parse()?, config).await?;</p>
<pre><code>println!("Server listening on 127.0.0.1:12345");

while let Ok((mut stream, addr)) = listener.accept().await {
    println!("New connection from {}", addr);
    tokio::spawn(async move {
        let mut buf = [0u8; 1024];
        while let Ok(n) = stream.read(&amp;mut buf).await {
            if n == 0 { break; }
            let _ = stream.write_all(&amp;buf[..n]).await;
        }
    });
}

Ok(())
</code></pre>
<p>}
Architecture
┌─────────────────────────────────────────────────────────────┐
│                    Application Layer                         │
│              (User code using KcpStream/KcpListener)         │
├─────────────────────────────────────────────────────────────┤
│                    High-Level API Layer                      │
│                  KcpStream    KcpListener                    │
│           (AsyncRead/AsyncWrite, TCP-like interface)         │
├─────────────────────────────────────────────────────────────┤
│                    Protocol Core Layer                       │
│                       KcpEngine                              │
│        (ARQ logic, congestion control, retransmission)       │
├─────────────────────────────────────────────────────────────┤
│                    Common Layer                              │
│         KcpSegment, KcpHeader, BufferPool, Constants         │
├─────────────────────────────────────────────────────────────┤
│                    Transport Layer                           │
│          Generic Transport trait (UDP default)               │
└─────────────────────────────────────────────────────────────┘
Configuration
Performance Presets
// Gaming - ultra-low latency (3ms update interval)
let config = KcpConfig::gaming();</p>
<p>// Real-time communication (8ms update interval)
let config = KcpConfig::realtime();</p>
<p>// File transfer - high throughput
let config = KcpConfig::file_transfer();</p>
<p>// Testing with packet loss simulation
let config = KcpConfig::testing(0.1); // 10% packet loss
Performance Modes
Mode	Update Interval	Resend	Congestion Control	Use Case
Normal	40ms	0	Yes	General purpose
Fast	8ms	2	Yes	Low latency
Turbo	4ms	1	No	Maximum speed
Gaming	3ms	1	No	Real-time games
Custom Configuration
use std::time::Duration;</p>
<p>let config = KcpConfig::new()
.fast_mode()
.window_size(128, 128)
.mtu(1400)
.connect_timeout(Duration::from_secs(10))
.keep_alive(Some(Duration::from_secs(30)))
.stream_mode(true);
Examples</p>
<h1>Run performance test server</h1>
<p>cargo run --example perf_test_server -- 127.0.0.1:12345 gaming</p>
<h1>Run performance test client</h1>
<p>cargo run --example perf_test_client -- 127.0.0.1:12345</p>
<h1>Run simple echo example</h1>
<p>cargo run --example simple_echo
Testing</p>
<h1>Run all tests</h1>
<p>cargo test</p>
<h1>Run resilience tests (packet loss, reorder, concurrent connections)</h1>
<p>cargo test --test resilience_test</p>
<h1>Run benchmarks</h1>
<p>cargo bench</p>
<h1>Run with logging</h1>
<p>RUST_LOG=debug cargo test -- --nocapture</p>
<h1>Run clippy</h1>
<p>cargo clippy --all-targets -- --deny clippy::all
Documentation
Detailed documentation is available in the doc/ directory:</p>
<p>Document	Description
ARCHITECTURE.md	System architecture and design
MODULES.md	Module reference and APIs
USAGE.md	Usage guide and examples
TESTING.md	Testing guide
Performance
KCP provides significant latency improvements over TCP:</p>
<p>30-40% lower latency in typical network conditions
Better performance on lossy networks
Configurable trade-offs between latency and bandwidth
Optimizations in this Implementation
Actor-based lock-free architecture: KcpEngine runs in a single dedicated tokio task, eliminating Arc&lt;Mutex&lt;&gt;&gt; contention
Generic Transport trait: Associated Addr type with RPITIT — zero heap allocation on hot path (no Pin&lt;Box&gt;)
DashMap for packet routing: Listener uses lock-free concurrent hashmap on the hot path
Lock-free buffer pools: crossbeam::queue::ArrayQueue for zero-allocation fast path
BTreeMap receive buffer: O(log n) insertion for out-of-order packets (vs O(n) linear scan)
Zero-copy segment encoding: Flush avoids cloning segments, encodes by reference
Cached timestamps: Single syscall per input() call instead of 3+
Pre-allocated buffers: VecDeque::with_capacity based on window sizes, avoiding grow overhead on send burst
Zero-copy packet handling with bytes crate
Grouped state structs for better cache locality
Configurable update intervals (3-40ms)
Batch ACK processing
Use Cases
Gaming: Ultra-low latency for real-time multiplayer
VoIP/Video: Real-time communication
Live Streaming: Low-latency data delivery
File Transfer: Reliable bulk data transfer
IoT: Efficient communication for constrained devices
Compatibility
Protocol: Compatible with original C KCP
Rust: Edition 2021, stable toolchain
Tokio: 1.0+
License
MIT License - see LICENSE file.</p>
<p>Contributing
Contributions are welcome! Please feel free to submit a Pull Request.</p>
<p>Resources
Original KCP Protocol
KCP Protocol Documentation
Tokio Documentation
Benchmarks
Criterion benchmarks measure engine-level throughput and latency:</p>
<p>cargo bench
Benchmark	Description
engine_throughput	10/100/500 x 1KB messages
engine_small_messages	1000 x 64B messages
engine_large_message	Single 16KB/64KB message fragmentation + reassembly
Version History
v0.4.0: Extract kcp-core as standalone protocol crate, restructure source layout (src/ → kcp/, flatten async_kcp/)
v0.3.7: Fix ACK window/UNA fields, generic Transport trait with RPITIT, resilience tests, criterion benchmarks
v0.3.4: Engine refactoring, lock-free buffer pools, documentation
v0.3.3: Performance optimizations, sub-millisecond latency
v0.3.1: Full async support, comprehensive configuration
v0.2.x: Performance improvements and bug fixes
v0.1.x: Initial implementation</p>
]]></description><pubDate>2026-05-11 07:11:35</pubDate></item><item><title>mace：又一个嵌入式 key-value 存储</title><link>https://rustcc.cn/article?id=e2ec9976-8f93-4c2e-b63e-5d4419f55631</link><description><![CDATA[<p>mace 是一个 Rust 实现的嵌入式 KV 引擎，结合了 B+ 树的读性能和 LSM 树的写吞吐，在读多写少和扫描场景下有明显的性能优势。</p>
<hr>
<h2>核心能力</h2>
<ul>
<li><strong>混合架构</strong>：兼顾 B+ 树读速与 LSM 树写吞吐</li>
<li><strong>MVCC 并发</strong>：非阻塞的并发读写</li>
<li><strong>闪存优化</strong>：面向 SSD/NVMe 的 log-structured 设计</li>
<li><strong>大值分离</strong>：独立 Blob 存储，减少写放大</li>
<li><strong>ACID 事务</strong>：完整的事务支持</li>
</ul>
<hr>
<h2>性能数据</h2>
<table>
<thead>
<tr>
<th>场景</th>
<th>吞吐量提升</th>
</tr>
</thead>
<tbody>
<tr>
<td>随机读</td>
<td>2.4x</td>
</tr>
<tr>
<td>范围扫描</td>
<td>3.5x</td>
</tr>
<tr>
<td>读 heavy 混合负载</td>
<td>2.3x</td>
</tr>
<tr>
<td>写 heavy 混合负载</td>
<td>0.76x</td>
</tr>
</tbody>
</table>
<blockquote>
<p>注：以上为与 RocksDB 对比的中位数倍数。</p>
</blockquote>
<hr>
<h2>适用场景</h2>
<ul>
<li>需要高并发读写的嵌入式服务（尤其是 mixed/read-heavy 负载）</li>
<li>写入吞吐敏感的本地存储层（中小 value 场景优势更明显）</li>
<li>混合读写 + 扫描的业务</li>
<li>需要本地事务和 MVCC 的 Rust 应用</li>
</ul>
<hr>
<h2>地址</h2>
<ul>
<li>源码：<a href="https://github.com/abbycin/mace" rel="noopener noreferrer">https://github.com/abbycin/mace</a></li>
<li>Benchmark 脚本：<a href="https://github.com/abbycin/kv_bench" rel="noopener noreferrer">https://github.com/abbycin/kv_bench（scale 分支）</a></li>
</ul>
<blockquote>
<p>mace 还在非常早期的阶段，目前还在努力提升稳定性以及对特定workload进行优化...</p>
</blockquote>
<p><strong>0.0.29 版更新</strong></p>
<table>
<thead>
<tr>
<th>Workload</th>
<th align="right">Mace胜OPS</th>
<th align="right">OPS中位数比 (Mace/RocksDB)</th>
<th align="right">Mace胜p99</th>
<th align="right">p99中位数比 (Mace/RocksDB)</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>W1</code> (95R/5U, uniform)</td>
<td align="right">16 / 16</td>
<td align="right"><strong>2.3x</strong></td>
<td align="right">5 / 16</td>
<td align="right"><strong>1.0x</strong></td>
</tr>
<tr>
<td><code>W2</code> (95R/5U, zipf)</td>
<td align="right">16 / 16</td>
<td align="right"><strong>1.5x</strong></td>
<td align="right">11 / 16</td>
<td align="right"><strong>0.5x</strong></td>
</tr>
<tr>
<td><code>W3</code> (50R/50U)</td>
<td align="right">15 / 16</td>
<td align="right"><strong>1.4x</strong></td>
<td align="right">9 / 16</td>
<td align="right"><strong>0.5x</strong></td>
</tr>
<tr>
<td><code>W4</code> (5R/95U)</td>
<td align="right">12 / 16</td>
<td align="right"><strong>1.3x</strong></td>
<td align="right">7 / 16</td>
<td align="right"><strong>1.0x</strong></td>
</tr>
<tr>
<td><code>W5</code> (70R/25U/5S)</td>
<td align="right">15 / 16</td>
<td align="right"><strong>2.1x</strong></td>
<td align="right">16 / 16</td>
<td align="right"><strong>0.2x</strong></td>
</tr>
<tr>
<td><code>W6</code> (100% scan)</td>
<td align="right">16 / 16</td>
<td align="right"><strong>4.6x</strong></td>
<td align="right">15 / 16</td>
<td align="right"><strong>0.2x</strong></td>
</tr>
</tbody>
</table>
]]></description><pubDate>2026-03-09 11:56:39</pubDate></item><item><title>🌱 Rudis 0.4.0 发布，一个高性能内存数据库</title><link>https://rustcc.cn/article?id=682d0f5e-15ec-4138-aff6-d045fb529a7e</link><description><![CDATA[<p>项目介绍：</p>
<p>Rudis 是一个采用 Rust 语言编写得高性能键值存储系统，旨在利用 Rust 语言的优势来重新复现 Rudis 的核心功能，以满足用户对高性能、可靠性和安全性的需求，同时保证与 Rudis API 的兼容。</p>
<p>跨平台，兼容 windows、linux 系统架构。 兼容 字符串、集合、哈希、列表、有序集合数据结构。 提供 rdb 与 aof 机制以支持数据备份和恢复。 拥有卓越的处理速度和即时响应能力。 兼容 Rudis 的命令和协议规范。</p>
<p>欢迎在 GitHub 上关注我们的项目发展轨迹：</p>
<p>👉 https://github.com/lunar-landing/rudis</p>
<p>更新日志：</p>
<ul>
<li>新增 List 数据结构 Blpop、Brpop 命名。</li>
<li>新增 Hash 数据结构 HSCAN 命令，支持 MATCH 和 COUNT 参数。</li>
<li>新增 String 数据结构 SETEX、PSETEX、SETNX、SETBIT、GETBIT、BITCOUNT、BITOP 命令。</li>
<li>新增 Set 数据结构 SRANDMEMBER、SDIFFSTORE、SINTERSTORE、SMOVE 命令。</li>
<li>新增 HyperLogLog 数据结构及 PFADD、PFCOUNT、PFMERGE 命令。</li>
<li>重构 SortedSet 底层实现，采用 HashMap + SkipList 架构提升性能，并支持 bincode 序列化。</li>
<li>修复 SETEX/PSETEX 过期记录清理逻辑以及系统时间倒退导致的 RDB 调度 Panic 问题。</li>
</ul>
]]></description><pubDate>2026-02-03 03:12:19</pubDate></item><item><title>我做了一个独立开发者行情板，想试着对抗一次内卷</title><link>https://rustcc.cn/article?id=7a4bcdcd-4650-425b-92a4-6ef65838534b</link><description><![CDATA[<h1>接私活这几年，我发现我们根本不知道「合理报价」是多少</h1>
<p>这几年接私活、做外包、做独立项目，有一个问题一直困扰我：</p>
<blockquote>
<p><strong>我们其实不知道一个项目「合理的价格」是多少。</strong></p>
</blockquote>
<p>不是技术难度不知道，而是——<br>
你不知道别人真实成交是多少，只能靠猜、靠平台最低价、靠「听说」。</p>
<p>需求方会说：</p>
<blockquote>
<p>「别人比你便宜一半。」</p>
</blockquote>
<p>开发者只能纠结：</p>
<blockquote>
<p>「我是报高了，还是别人报低了？」</p>
</blockquote>
<p>时间久了，就变成大家都在往下试探，<br>
<strong>内卷不是某个人的选择，而是信息不透明的结果。</strong></p>
<hr>
<h2>我已经做了什么</h2>
<p>我先从自己开始。</p>
<p>我把自己这几年做过的一些真实项目整理出来，包括：</p>
<ul>
<li>项目类型</li>
<li>实际成交价格</li>
<li>大概工期</li>
<li>是否反复改需求</li>
<li>是否包含售后</li>
</ul>
<p>做成了一个 <strong>独立开发者行情板</strong>。</p>
<p>目前一共 <strong>23 个案例</strong>：</p>
<ul>
<li>大部分是我自己的真实成交</li>
<li>少部分是朋友的</li>
<li>也有几个是匿名提交的</li>
</ul>
<p>我不回避这个事实：<br>
<strong>数据现在还很少，而且并不「漂亮」。</strong></p>
<p>但它至少是真实的。</p>
<hr>
<h2>为什么我需要更多人，而不是「更多数据」</h2>
<p>我一个人的案例，其实没什么意义。</p>
<p>但如果有：</p>
<ul>
<li>50 个</li>
<li>100 个</li>
<li>200 个</li>
</ul>
<p>来自不同背景、不同技术栈、不同城市的真实案例，<br>
至少可以做到一件事：</p>
<blockquote>
<p><strong>让后来的人，在报价时有一个不被平台最低价绑架的参考。</strong></p>
</blockquote>
<p>你不需要证明你多厉害，<br>
也不需要报一个「体面」的价格，<br>
<strong>真实比好看重要。</strong></p>
<hr>
<h2>关于匿名和安全</h2>
<p>我知道大家最担心什么，所以我一开始就做了两件事：</p>
<ul>
<li>提供 <strong>匿名提交</strong></li>
<li>不要求任何可追溯身份信息</li>
</ul>
<p>目前有两个入口：</p>
<p><a href="https://test-cigsro9bfq3z.feishu.cn/share/base/form/shrcnoJFwnYGX1E8NKW6qjpNJ6X?from=navigation" rel="noopener noreferrer">飞书表单</a>
<a href="https://market.fxlogo.site" rel="noopener noreferrer">行情板网站</a></p>
<p>不署名、不展示来源、不做商业售卖。<br>
你可以只写你愿意写的字段。</p>
<hr>
<h2>说一句更远一点的想法（不画饼）</h2>
<p>行情板不是终点。</p>
<p>我真正想做的，是一个 <strong>不竞价、不抽佣、不负责售后</strong> 的撮合平台，<br>
只做一件事：</p>
<blockquote>
<p><strong>把预算真实的需求方，和愿意按合理价格做事的开发者，匹配到一起。</strong></p>
</blockquote>
<p>行情板只是前战，是定价共识的基础。<br>
如果连「合理价格区间」都没有，<br>
任何撮合都会退化成比谁便宜。</p>
<p>我不确定这条路能走多远，<br>
但至少想先试一次。</p>
<hr>
<h2>最后</h2>
<p>如果你愿意贡献一个案例：</p>
<ul>
<li>成功的</li>
<li>失败的</li>
<li>觉得自己报低了的</li>
<li>或者被压价压得很难受的</li>
</ul>
<p>都可以。</p>
<p>如果你不想提交，也没关系，<br>
<strong>至少希望这个东西能让你下次报价时，心里多一点底气。</strong></p>
]]></description><pubDate>2026-02-02 10:25:00</pubDate></item><item><title>低成本 AI 赋能首选！算纽 GPUNexus 聚合全球算力，MaaS 服务直达业务核心</title><link>https://rustcc.cn/article?id=d599b7f7-9c0b-4fe6-8396-133b85abbe30</link><description><![CDATA[<p>算纽GPUNexus定位全球 GPU 资源智能调度枢纽，致力于构建低成本、高弹性的下一代分布式 AI 计算生态。我们的核心服务模式：</p>
<ul>
<li>
<p>算力层聚合：广泛接入全球闲散 GPU 算力资源，通过标准化调度技术实现算力的统一管理与高效利用；</p>
</li>
<li>
<p>服务层赋能：在聚合算力之上深度部署 MaaS 模型服务，客户无需投入高昂成本搭建算力与模型架构，只需通过简洁的大模型接口，即可按需调用 AI 能力，快速赋能业务创新。</p>
</li>
</ul>
<p>算纽（GPUNexus）打通算力资源与模型应用的壁垒，让 AI 服务更便捷、更普惠。</p>
<h1>2. 产品形态</h1>
<h2>2.1. 算力资产分享</h2>
<p>算纽算力资产分享产品，核心打破算力孤岛，依托智能调度技术，实现各类计算资源一键接入、整合与统一调度，激活分散算力价值。</p>
<p>产品支持全场景接入，覆盖算力中心、企业服务器等专业设备及个人电脑、手机等终端，实现“云-边-端”全域覆盖。无论闲置算力拥有方（企业/机构/个人）还是算力需求方，均可通过平台精准匹配、高效流转。</p>
<p>无需复杂配置即可快速上线，智能调度实现供需实时匹配，既提升算力利用率，又帮助需求方降本、分享方变现，构建互利共赢的算力生态。</p>
<h2>2.2. MAAS服务</h2>
<p>算纽 MaaS服务，一站式整合30 余款主流开源大模型矩阵，囊括 DeepSeek、Qwen、GLM、Kimi、MiniMax 等明星模型，深度覆盖编程开发、学术研究与论文创作、数学推理、视觉处理与多模态交互、对话与长文本处理五大核心场景。</p>
<h2>2.3. 开发者套餐</h2>
<p>算纽开发者套餐，专为学生、独立开发者及中小团队量身定制，以超高性价比解锁顶级大模型编程能力，让每一份开发需求都能高效落地。</p>
<p>套餐核心优势直击开发痛点：成本颠覆性降低，计费低至传统tokens计费的一折，大幅压缩开发成本；模型自由切换，无需冗余购买多平台会员，一键直达GLM-4.7、MiniMax-M2.1、Kimi-K2三大顶级编程模型，最新最强的模型能力随心选；高效创作不等待，生成速度媲美同类高级套餐，助力快速完成代码编写、调试、优化等核心工作。</p>
<p>更有7天免费体验限时开启！零成本即可抢先体验顶级模型的强悍编程能力，轻松开启高效开发新体验。</p>
<p>​</p>
<ul>
<li>官方网址：<a href="https://gpunexus.com/signup?aff=c1xh" rel="noopener noreferrer">https://gpunexus.com/</a></li>
<li>咨询电话：010-53650986</li>
<li>联系邮箱：data@chengfangtech.com</li>
</ul>
]]></description><pubDate>2026-01-14 02:18:35</pubDate></item><item><title>helix-kanban 终端内的多窗口看板</title><link>https://rustcc.cn/article?id=56234088-880c-4fc8-8281-726abca68b8a</link><description><![CDATA[<h1>Kanban</h1>
<p>一个终端看板应用，灵感来自 <a href="https://helix-editor.com/" rel="noopener noreferrer">Helix 编辑器</a>的键位设计。</p>
<h2>预览</h2>
<p><img src="https://raw.githubusercontent.com/menzil/helix-kanban/master/screenshoot.png" alt="Kanban TUI 截图"></p>
<h2>特性</h2>
<ul>
<li>📁 <strong>基于文件存储</strong> - 使用 Markdown 文件和 TOML 配置，易于版本控制</li>
<li>🎯 <strong>多项目支持</strong> - 支持全局项目和本地项目（<code>.kanban/</code>）</li>
<li>⌨️  <strong>Helix 风格键位</strong> - 符合直觉的键盘快捷键</li>
<li>🪟 <strong>窗口管理</strong> - 支持垂直/水平分屏，同时查看多个项目，自动保存和恢复工作区布局</li>
<li>🎨 <strong>现代 TUI</strong> - 基于 ratatui 的美观终端界面</li>
<li>📝 <strong>Markdown 支持</strong> - 任务使用 Markdown 格式，支持外部编辑器</li>
<li>🔍 <strong>任务预览</strong> - 内置预览和外部预览工具支持</li>
<li>⚙️  <strong>自动配置</strong> - 首次运行自动检测编辑器和预览器</li>
</ul>
<h2>安装</h2>
<h3>从 crates.io 安装</h3>
<pre><code>cargo install helix-kanban
</code></pre>
<h3>从源码构建</h3>
<pre><code>git clone https://github.com/menzil/helix-kanban.git
cd helix-kanban
cargo build --release
</code></pre>
<h2>快速开始</h2>
<p>首次运行会显示欢迎对话框，自动检测系统编辑器和 Markdown 预览器：</p>
<pre><code>hxk
</code></pre>
<h3>输入法切换（macOS）</h3>
<p>为了更好的输入体验，在正常模式下自动切换到英文输入法，在对话框模式（如创建/编辑任务）时保持用户的输入法。</p>
<p><strong>推荐安装 im-select 工具：</strong></p>
<pre><code># 使用 Homebrew 安装
brew install im-select

# 或者使用 curl 安装
curl -Ls https://raw.githubusercontent.com/daipeihust/im-select/master/install_mac.sh | sh
</code></pre>
<blockquote>
<p>注意：如果不安装 im-select，程序仍可正常运行，只是不会自动切换输入法。</p>
</blockquote>
<h3>配置管理</h3>
<p>查看当前配置：</p>
<pre><code>hxk config show
</code></pre>
<p>设置编辑器：</p>
<pre><code>hxk config editor nvim
hxk config editor "code --wait"
</code></pre>
<p>设置 Markdown 预览器：</p>
<pre><code>hxk config viewer glow
hxk config viewer "open -a Marked 2"
</code></pre>
<h2>键位绑定</h2>
<h3>基础导航</h3>
<table>
<thead>
<tr>
<th>键位</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>j</code> / <code>↓</code></td>
<td>下一个任务</td>
</tr>
<tr>
<td><code>k</code> / <code>↑</code></td>
<td>上一个任务</td>
</tr>
<tr>
<td><code>h</code> / <code>←</code></td>
<td>左边的列</td>
</tr>
<tr>
<td><code>l</code> / <code>→</code></td>
<td>右边的列</td>
</tr>
<tr>
<td><code>q</code></td>
<td>退出程序</td>
</tr>
<tr>
<td><code>ESC</code></td>
<td>取消/返回</td>
</tr>
<tr>
<td><code>:</code></td>
<td>命令模式</td>
</tr>
<tr>
<td><code>?</code></td>
<td>显示帮助</td>
</tr>
<tr>
<td><code>Space</code></td>
<td>打开命令菜单</td>
</tr>
</tbody>
</table>
<h3>任务操作</h3>
<table>
<thead>
<tr>
<th>键位</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>a</code></td>
<td>创建新任务</td>
</tr>
<tr>
<td><code>e</code></td>
<td>编辑任务标题</td>
</tr>
<tr>
<td><code>E</code></td>
<td>用外部编辑器编辑任务</td>
</tr>
<tr>
<td><code>v</code></td>
<td>预览任务（TUI 内）</td>
</tr>
<tr>
<td><code>V</code></td>
<td>用外部工具预览任务</td>
</tr>
<tr>
<td><code>d</code></td>
<td>删除任务</td>
</tr>
<tr>
<td><code>H</code></td>
<td>任务移到左列</td>
</tr>
<tr>
<td><code>L</code></td>
<td>任务移到右列</td>
</tr>
<tr>
<td><code>J</code></td>
<td>任务在列内下移</td>
</tr>
<tr>
<td><code>K</code></td>
<td>任务在列内上移</td>
</tr>
</tbody>
</table>
<h3>项目管理</h3>
<table>
<thead>
<tr>
<th>键位</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>n</code></td>
<td>新建本地项目 [L]</td>
</tr>
<tr>
<td><code>N</code></td>
<td>新建全局项目 [G]</td>
</tr>
<tr>
<td><code>Space f</code></td>
<td>快速切换项目</td>
</tr>
<tr>
<td><code>Space p o</code></td>
<td>打开项目</td>
</tr>
<tr>
<td><code>Space p n</code></td>
<td>创建新项目</td>
</tr>
<tr>
<td><code>Space p d</code></td>
<td>删除项目</td>
</tr>
<tr>
<td><code>Space p r</code></td>
<td>重命名项目</td>
</tr>
<tr>
<td><code>Space r</code></td>
<td>重新加载当前项目</td>
</tr>
<tr>
<td><code>Space R</code></td>
<td>重新加载所有项目</td>
</tr>
</tbody>
</table>
<h3>窗口管理</h3>
<table>
<thead>
<tr>
<th>键位</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>Space w w</code></td>
<td>下一个窗口</td>
</tr>
<tr>
<td><code>Space w v</code></td>
<td>垂直分屏</td>
</tr>
<tr>
<td><code>Space w s</code></td>
<td>水平分屏</td>
</tr>
<tr>
<td><code>Space w q</code></td>
<td>关闭窗口</td>
</tr>
<tr>
<td><code>Space w h</code></td>
<td>聚焦左面板</td>
</tr>
<tr>
<td><code>Space w l</code></td>
<td>聚焦右面板</td>
</tr>
<tr>
<td><code>Space w j</code></td>
<td>聚焦下面板</td>
</tr>
<tr>
<td><code>Space w k</code></td>
<td>聚焦上面板</td>
</tr>
</tbody>
</table>
<h3>命令模式</h3>
<p>按 <code>:</code> 进入命令模式，支持的命令：</p>
<ul>
<li><code>:q</code> / <code>:quit</code> - 退出应用</li>
<li><code>:open</code> / <code>:po</code> - 打开项目</li>
<li><code>:new</code> / <code>:pn</code> - 创建新项目（全局）</li>
<li><code>:new-local</code> / <code>:pnl</code> - 创建新项目（本地）</li>
<li><code>:add</code> / <code>:tn</code> - 创建新任务</li>
<li><code>:edit</code> / <code>:te</code> - 编辑任务</li>
<li><code>:view</code> / <code>:tv</code> - 预览任务</li>
<li><code>:reload</code> / <code>:r</code> / <code>:refresh</code> - 重新加载当前项目</li>
<li><code>:reload-all</code> / <code>:ra</code> / <code>:refresh-all</code> - 重新加载所有项目</li>
<li><code>:vsplit</code> / <code>:sv</code> - 垂直分屏</li>
<li><code>:hsplit</code> / <code>:sh</code> - 水平分屏</li>
<li><code>:help</code> / <code>:h</code> - 显示帮助</li>
</ul>
<h2>数据存储</h2>
<h3>全局项目</h3>
<p>全局项目存储在 <code>~/.kanban/projects/</code> 目录下。</p>
<h3>本地项目</h3>
<p>在任何目录下按 <code>n</code> 创建本地项目，会在当前目录的 <code>.kanban/</code> 下存储：</p>
<pre><code>your-project/
├── .kanban/
│   └── kanban-project/
│       ├── .kanban.toml
│       ├── todo/
│       ├── doing/
│       └── done/
└── ... (你的其他文件)
</code></pre>
<h3>项目结构</h3>
<pre><code>project-name/
├── .kanban.toml          # 项目配置
├── todo/                 # Todo 任务
│   ├── 001.md
│   └── 002.md
├── doing/                # 进行中任务
│   └── 003.md
└── done/                 # 完成的任务
    └── 004.md
</code></pre>
<h3>任务文件格式</h3>
<p>任务以 Markdown 格式存储：</p>
<pre><code># 任务标题

created: 2025-12-10T10:30:00+08:00
priority: high

任务的详细描述内容...

## 子任务

- [ ] 子任务 1
- [x] 子任务 2
</code></pre>
<h3>配置文件</h3>
<p>应用配置存储在 <code>~/.kanban/config.toml</code>：</p>
<pre><code>editor = "nvim"
markdown_viewer = "glow"

# 隐藏的全局项目列表（软删除）
hidden_projects = ["old-project", "archived-project"]
</code></pre>
<h3>工作区状态保存</h3>
<p>应用会自动保存窗口布局和工作状态，下次启动时恢复：</p>
<p><strong>保存内容</strong>：</p>
<ul>
<li>分屏结构（垂直/水平分割）</li>
<li>每个窗格打开的项目</li>
<li>当前选中的列和任务</li>
<li>聚焦的窗格</li>
</ul>
<p><strong>保存位置</strong>：</p>
<ul>
<li>全局工作区：<code>~/.kanban/workspace.toml</code> - 在任何目录启动时使用</li>
<li>本地工作区：<code>.kanban/workspace.toml</code> - 在项目目录下启动时优先使用</li>
</ul>
<p><strong>使用场景</strong>：</p>
<ul>
<li>经常需要同时查看多个项目？设置好分屏布局后，下次启动自动恢复</li>
<li>在不同项目目录工作？每个目录都有自己独立的工作区布局</li>
<li>想要重置布局？使用命令 <code>:reset-layout</code> 恢复默认单窗格</li>
</ul>
<p><strong>示例工作区配置</strong> (<code>workspace.toml</code>)：</p>
<pre><code># 自动生成，通常无需手动编辑
focused_pane = 2
next_pane_id = 4

[[panes]]
id = 0
type = "horizontal_split"
left = 1
right = 2

[[panes]]
id = 1
type = "leaf"
project = "work-project"
selected_column = 1
selected_task_index = 0

[[panes]]
id = 2
type = "leaf"
project = "personal-project"
selected_column = 0
selected_task_index = 2
</code></pre>
<h2>开发</h2>
<pre><code># 运行开发版本
cargo run

# 运行测试
cargo test

# 构建 release 版本
cargo build --release
</code></pre>
<h2>致谢</h2>
<ul>
<li>键位设计灵感来自 <a href="https://helix-editor.com/" rel="noopener noreferrer">Helix Editor</a></li>
<li>UI 框架使用 <a href="https://github.com/ratatui-org/ratatui" rel="noopener noreferrer">ratatui</a></li>
</ul>
<h2>许可证</h2>
<p>MIT OR Apache-2.0</p>
]]></description><pubDate>2025-12-11 10:37:54</pubDate></item><item><title>使用 Rust 宏实现基于 Sea-ORM 的乐观锁样板代码自动化</title><link>https://rustcc.cn/article?id=1e3818da-3c6a-46eb-89ab-3e3144fc362c</link><description><![CDATA[<p>在昨天的文章中，我们讨论了乐观锁（Optimistic Locking）作为高并发场景下保证数据一致性的重要手段。但乐观锁的实现，尤其是基于版本号（Version）或时间戳（Updated At）的 <strong>CAS (Compare-and-Swap)</strong> 模式，往往需要在应用的每个 Repository 中重复编写大量的样板代码。</p>
<p>今天的核心主题是：如何利用 <strong>Rust 过程宏</strong>的强大能力，将这些繁琐的持久化逻辑自动化，让开发者只需声明字段，即可获得健壮的乐观锁支持。</p>
<hr>
<h2>宏架构：分治与协作</h2>
<p>实现一个完整的、自动化的乐观锁流程，需要宏在两个不同的代码层面进行注入和协作：</p>
<ol>
<li><strong>数据变更层</strong> (<code>ActiveModelBehavior</code>)：负责在数据写入数据库前，自动管理版本号 (<code>version</code>) 和时间戳 (<code>updated_at</code>) 的递增/更新。</li>
<li><strong>持久化操作层</strong> (<code>Repository::save</code>)：负责实现核心的原子更新逻辑，即 <strong>CAS 检查</strong>。</li>
</ol>
<h3>Part 1: ActiveModel 的预处理钩子 (<code>before_save</code>)</h3>
<p>这是我们实现乐观锁的第一步：确保在更新操作中，版本号能够正确地 <strong>自增</strong>。</p>
<p>我们通过宏注入或修改 <code>sea-orm::ActiveModelBehavior</code> Trait 的 <code>before_save</code> 钩子。</p>
<p><strong>宏注入逻辑概览：</strong></p>
<pre><code>// 宏片段：insert_active_model_behavior_impl 的核心逻辑
if need_version {
    let version_stmt = quote! {
        if insert {
            // 插入 (insert=true) 时，版本号初始化为 1
            self.version = Set(1);
        } else if self.is_changed() {
            // 更新 (insert=false) 且模型有业务字段变化时，版本号自增
            let current_version = match self.version {
                Set(v) =&gt; *v,
                _ =&gt; 0,
            };
            self.version = Set(current_version + 1);
        }
    };
}
// updated_at 逻辑类似：非插入且 is_changed 时设置为当前时间
</code></pre>
<p><strong>关键成果：</strong>
当我们在 Repository 中执行更新操作时，<code>ActiveModel</code> 已经通过 <code>before_save</code> 确保了两个重要事实：</p>
<ol>
<li>它携带着我们从数据库中读出的 <strong>旧版本号</strong>。</li>
<li>它将尝试写入的 <code>version</code> 值，是 <strong>旧版本号 + 1</strong>。</li>
</ol>
<hr>
<h3>Part 2: Repository 的原子 CAS 更新 (<code>save</code> 方法)</h3>
<p>这是乐观锁实现的核心战场，由 <code>fn create_tenant_save_impl</code> 宏片段生成。其逻辑必须严格遵循 <strong>三步走</strong> 策略，以处理成功、冲突和首次插入三种情况。</p>
<h4>Step 1: 原子 UPDATE (Compare-and-Swap)</h4>
<p>我们使用 <code>sea-orm</code> 的 <code>update_many</code> 配合 <code>filter</code> 条件，来实现原子性检查。</p>
<p>我们从聚合根 (<code>entity</code>) 中取出 <strong>旧版本</strong>（即 <code>current_version</code>），并将其作为 <code>WHERE</code> 子句的一部分。</p>
<pre><code>// 宏片段：create_tenant_save_impl 的核心 CAS 逻辑

// 从聚合获取当前版本（即期望的旧版本）
let current_version = entity_model.#optimistic_lock_field_ident();

// 1) 原子 UPDATE（带 version CAS）
let res = models::Entity::update_many()
    #id_filters // 主键和 TenantId 过滤
    // ⬇️ 核心：只有当数据库中的版本号等于旧版本号时，才允许更新 ⬇️
    .filter(models::Column::#optimistic_lock_col_ident.eq(current_version)) 
    .set(update_model.clone())
    .exec(&amp;conn)
    .await?;

if res.rows_affected &gt; 0 {
    // 成功！说明版本匹配，且更新成功写入
    // ... 事件处理并返回 Ok(())
    return Ok(());
}
</code></pre>
<p>如果 <code>rows_affected &gt; 0</code>，任务圆满完成。如果 <code>rows_affected == 0</code>，则进入下一步判断。</p>
<h4>Step 2 &amp; 3: 冲突检测与首次插入</h4>
<p>如果 CAS 更新失败（<code>rows_affected == 0</code>），我们需要区分是 <strong>版本冲突</strong>（记录存在但版本号不匹配）还是 <strong>首次插入</strong>（记录根本不存在）。</p>
<pre><code>// 2) UPDATE 未命中，检查记录是否存在
if models::Entity::find()
    #id_filters // 仅按主键和 TenantId 查找
    .one(&amp;conn)
    .await?
    .is_some()
{
    // 记录存在，但 Step 1 未命中 -&gt; 乐观锁冲突！
    return Err(#crate_root::domain::RepositoryError::optimistic_lock_error(
        "Optimistic lock conflict: Version mismatch".to_string(),
    ));
}

// 3) 记录不存在，执行首次插入
let insert_model: models::Model = entity_model.clone().try_into()?;
let mut active_model = insert_model.into_active_model();
active_model.insert(&amp;conn).await?;
// ... 事件处理并返回 Ok(())
</code></pre>
<h3>Talk is cheap, show me the code</h3>
<h4>before_save</h4>
<pre><code>fn insert_active_model_behavior_impl(input: &amp;mut ItemMod, model_config: &amp;ModelConfig) {
  let Some((_, items)) = &amp;mut input.content else {
      return;
  };

  let mut has_active_model_behavior = false;
  for item in items.iter_mut() {
      if let syn::Item::Impl(item_impl) = item
          &amp;&amp; let Some((_, path, _)) = &amp;item_impl.trait_
          &amp;&amp; path.segments.last().unwrap().ident == "ActiveModelBehavior"
      {
          has_active_model_behavior = true;
          break;
      }
  }

  if !has_active_model_behavior {
      let active_model_behavior_impl = quote! {
          #[async_trait]
          impl ActiveModelBehavior for ActiveModel {
              async fn before_save&lt;C&gt;(mut self, db: &amp;C, insert: bool) -&gt; Result&lt;Self, DbErr&gt;
              where
                  C: ConnectionTrait,
              {
                  Ok(self)
              }
          }
      };
      items.push(parse_quote!(#active_model_behavior_impl));
  }

  for item in items.iter_mut() {
      if let syn::Item::Impl(item_impl) = item
          &amp;&amp; let Some((_, path, _)) = &amp;item_impl.trait_
          &amp;&amp; path.segments.last().unwrap().ident == "ActiveModelBehavior"
      {
          let mut has_before_save = false;
          for item in item_impl.items.iter_mut() {
              if let syn::ImplItem::Fn(method) = item
                  &amp;&amp; method.sig.ident == "before_save"
              {
                  has_before_save = true;
                  break;
              }
          }

          if !has_before_save {
              let before_save_method = quote! {
                  async fn before_save&lt;C&gt;(mut self, db: &amp;C, insert: bool) -&gt; Result&lt;Self, DbErr&gt;
                  where
                      C: ConnectionTrait,
                  {
                      Ok(self)
                  }
              };
              item_impl.items.push(parse_quote!(#before_save_method));
          }

          let need_created_at = model_config
              .fields
              .iter()
              .any(|f| f.ident.as_ref().unwrap() == "created_at");
          let need_updated_at = model_config
              .fields
              .iter()
              .any(|f| f.ident.as_ref().unwrap() == "updated_at");

          let need_version = model_config
              .fields
              .iter()
              .any(|f| f.ident.as_ref().unwrap() == "version");

          if !(need_created_at || need_updated_at || need_version) {
              return;
          }

          for item in item_impl.items.iter_mut() {
              if let syn::ImplItem::Fn(method) = item
                  &amp;&amp; method.sig.ident == "before_save"
              {
                  let mut stmts = Vec::new();
                  stmts.push(quote! {
                      let now = chrono::Utc::now();
                  });

                  if need_created_at {
                      let created_at_stmt = quote! {
                          if insert {
                              self.created_at = Set(now);
                          }
                      };
                      stmts.push(created_at_stmt);
                  }
                  if need_updated_at {
                      let updated_at_stmt = quote! {
                          if insert {
                              self.updated_at = Set(now);
                          } else if self.is_changed() {
                              self.updated_at = Set(now);
                          }
                      };
                      stmts.push(updated_at_stmt);
                  }

                  if need_version {
                      let version_stmt = quote! {
                          if insert {
                              self.version = Set(1);
                          } else if self.is_changed() {
                              let current_version = match self.version {
                              Set(v) =&gt; *v,
                              _ =&gt; 0,
                          };
                              self.version = Set(current_version + 1);
                          }
                      };
                      stmts.push(version_stmt);
                  }

                  let stmts = parse_quote!({#(#stmts)*});

                  // 插入到方法体的开头
                  method.block.stmts.insert(0, stmts);
              }
          }
      }
  }
}

</code></pre>
<p>宏生成的代码示例</p>
<pre><code> impl ActiveModelBehavior for ActiveModel {
        #[allow(
            elided_named_lifetimes,
            clippy::async_yields_async,
            clippy::diverging_sub_expression,
            clippy::let_unit_value,
            clippy::needless_arbitrary_self_type,
            clippy::no_effect_underscore_binding,
            clippy::shadow_same,
            clippy::type_complexity,
            clippy::type_repetition_in_bounds,
            clippy::used_underscore_binding
        )]
        fn before_save&lt;'life0, 'async_trait, C&gt;(
            self,
            db: &amp;'life0 C,
            insert: bool,
        ) -&gt; ::core::pin::Pin&lt;
            Box&lt;
                dyn ::core::future::Future&lt;Output = Result&lt;Self, DbErr&gt;&gt;
                    + ::core::marker::Send
                    + 'async_trait,
            &gt;,
        &gt;
        where
            C: ConnectionTrait,
            C: 'async_trait,
            'life0: 'async_trait,
            Self: 'async_trait,
        {
            Box::pin(async move {
                if let ::core::option::Option::Some(__ret) =
                    ::core::option::Option::None::&lt;Result&lt;Self, DbErr&gt;&gt;
                {
                    #[allow(unreachable_code)]
                    return __ret;
                }
                let mut __self = self;
                let insert = insert;
                let __ret: Result&lt;Self, DbErr&gt; = {
                    {
                        let now = chrono::Utc::now();
                        if insert {
                            __self.created_at = Set(now);
                        }
                        if insert {
                            __self.updated_at = Set(now);
                        } else if __self.is_changed() {
                            __self.updated_at = Set(now);
                        }
                    }
                    Ok(__self)
                };
                #[allow(unreachable_code)]
                __ret
            })
        }
    }
</code></pre>
<h4>Repository::save</h4>
<pre><code>fn create_tenant_save_impl(
    crate_root: &amp;Path,
    aggregate: &amp;Path,
    args: &amp;RepositoryStructArgs,
    id_filters: &amp;TokenStream,
) -&gt; TokenStream {
    // 若指定了乐观锁字段，准备字段名/Column ident
    let optimistic_lock_field = args.optimistic_lock_field.as_ref().map(|lit| {
        let optimistic_lock_field_name = lit.value();
        let optimstic_lock_field_ident = new_id(&amp;optimistic_lock_field_name); // 用于 ActiveModel/Model 字段访问
        let optimistic_lock_col_ident = new_id(&amp;to_pascal_case(&amp;optimistic_lock_field_name)); // 用于 models::Column::Xxx
        (
            optimistic_lock_field_name,
            optimstic_lock_field_ident,
            optimistic_lock_col_ident,
        )
    });

    // 根据是否指定乐观锁字段，生成 save 的实现
    if let Some((
        optimistic_lock_field_name,
        optimistic_lock_field_ident,
        optimistic_lock_col_ident,
    )) = optimistic_lock_field
    {
        if optimistic_lock_field_name == "version" {
            quote! {
                async fn save(
                    &amp;self,
                    txn: &amp;mut TC,
                    entity: &amp;mut #crate_root::domain::EventSourcedEntity&lt;#aggregate&gt;,
                ) -&gt; Result&lt;(), #crate_root::domain::RepositoryError&gt; {
                    use #crate_root::domain::SeaOrmModelUpdater;
                    use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter};
                    use sea_orm::ActiveValue::Set;

                    let conn = txn.get_connection();
                    let entity_model: &amp;#aggregate = entity;

                    let id = entity_model.id();
                    let tenant_id = entity_model.tenant_id();

                    // 从聚合获取当前版本与期望旧版本
                    let current_version = entity_model.#optimistic_lock_field_ident();

                    // 构造用于原子更新的 ActiveModel（只写回必要列）
                    let mut update_model = models::Model::from(entity_model.clone()).into_active_model();

                    // 1) 原子 UPDATE（带 version CAS）
                    let res = models::Entity::update_many()
                        #id_filters
                        .filter(models::Column::TenantId.eq(*tenant_id))
                        .filter(models::Column::#optimistic_lock_col_ident.eq(current_version))
                        .set(update_model.clone())
                        .exec(&amp;conn)
                        .await?;

                    if res.rows_affected &gt; 0 {
                        entity.move_event_to_context(txn);
                        return Ok(());
                    }

                    // 2) UPDATE 未命中，检查记录是否存在（按主键 + tenant）
                    if models::Entity::find()
                        #id_filters
                        .filter(models::Column::TenantId.eq(*tenant_id))
                        .one(&amp;conn)
                        .await?
                        .is_some()
                    {
                        return Err(#crate_root::domain::RepositoryError::optimistic_lock_error(
                            "Optimistic lock conflict: Version mismatch".to_string(),
                        ));
                    }

                    // 3) 记录不存在，插入数据
                    let insert_model: models::Model = entity_model.clone().try_into()?;
                    let mut active_model = insert_model.into_active_model();
                    active_model.insert(&amp;conn).await?;
                    entity.move_event_to_context(txn);
                    Ok(())
                }
            }
        } else {
            // treat as timestamp update_at
            quote! {
                async fn save(
                    &amp;self,
                    txn: &amp;mut TC,
                    entity: &amp;mut #crate_root::domain::EventSourcedEntity&lt;#aggregate&gt;,
                ) -&gt; Result&lt;(), #crate_root::domain::RepositoryError&gt; {
                    use #crate_root::domain::SeaOrmModelUpdater;
                    use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter};
                    use sea_orm::ActiveValue::Set;
                    use chrono::Utc;

                    let conn = txn.get_connection();
                    let entity_model: &amp;#aggregate = entity;

                    let id = entity_model.id();
                    let tenant_id = entity_model.tenant_id();

                    // 读取实体携带的旧时间戳与准备新的时间戳
                    let current_ts = entity_model.#optimistic_lock_field_ident();

                    // 构造用于原子更新的 ActiveModel
                    let mut update_model = models::Model::from(entity_model.clone()).into_active_model();

                    // 1) 原子 UPDATE（带 updated_at CAS）
                    let res = models::Entity::update_many()
                        #id_filters
                        .filter(models::Column::TenantId.eq(*tenant_id))
                        .filter(models::Column::#optimistic_lock_col_ident.eq(current_ts))
                        .set(update_model.clone())
                        .exec(&amp;conn)
                        .await?;

                    if res.rows_affected &gt; 0 {
                        entity.move_event_to_context(txn);
                        return Ok(());
                    }

                    // 2) UPDATE 未命中，检查记录是否存在
                    if models::Entity::find()
                        #id_filters
                        .filter(models::Column::TenantId.eq(*tenant_id))
                        .one(&amp;conn)
                        .await?
                        .is_some()
                    {
                        return Err(#crate_root::domain::RepositoryError::optimistic_lock_error(
                            "Optimistic lock conflict".to_string(),
                        ));
                    }

                    // 3) 记录不存在，直接插入数据
                    let insert_model: models::Model = entity_model.clone().try_into()?;
                    let mut active_model = insert_model.into_active_model();

                    active_model.insert(&amp;conn).await?;
                    entity.move_event_to_context(txn);
                    Ok(())
                }
            }
        }
    } else {
        // no optimistic lock field -&gt; simple update/insert behavior (原始实现)
        quote! {
            async fn save(
                &amp;self,
                txn: &amp;mut TC,
                entity: &amp;mut #crate_root::domain::EventSourcedEntity&lt;#aggregate&gt;,
            ) -&gt; Result&lt;(), #crate_root::domain::RepositoryError&gt; {
                use #crate_root::domain::SeaOrmModelUpdater;
                use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter};

                let conn = txn.get_connection();

                let entity_model: &amp;#aggregate = entity;

                let id = entity_model.id();
                let tenant_id = entity_model.tenant_id();

                if let Some(mut model) = models::Entity::find()
                    #id_filters
                    .filter(models::Column::TenantId.eq(*tenant_id))
                    .one(&amp;conn)
                    .await?
                {
                    if &amp;model.tenant_id != tenant_id {
                        return Err(#crate_root::domain::RepositoryError::mapping_error(
                            format!(
                                "Tenant ID mismatch: expected {}, found {}, id: {}",
                                tenant_id, model.tenant_id, id
                            ),
                        ));
                    }

                    // 更新逻辑
                    model.update_from_aggregate_root(entity_model).await?;

                    let active_model = model.into_active_model();
                    active_model.update(&amp;conn).await?;
                } else {
                    // 创建新记录
                    let model: models::Model = entity_model.clone().try_into()?;
                    let active_model = model.into_active_model();
                    active_model.insert(&amp;conn).await?;
                }

                entity.move_event_to_context(txn);
                Ok(())
            }
        }
    }
}

</code></pre>
<p>宏生成的代码示例</p>
<pre><code>  async fn save(
        &amp;self,
        txn: &amp;mut TC,
        entity: &amp;mut core_common::domain::EventSourcedEntity&lt;TenantUser&gt;,
    ) -&gt; Result&lt;(), core_common::domain::RepositoryError&gt; {
        use core_common::domain::SeaOrmModelUpdater;
        use sea_orm::{
            ActiveModelTrait, ColumnTrait, EntityTrait, IntoActiveModel, QueryFilter,
        };
        use sea_orm::ActiveValue::Set;
        use chrono::Utc;
        let conn = txn.get_connection();
        let entity_model: &amp;TenantUser = entity;
        let id = entity_model.id();
        let current_ts = entity_model.update_at();
        let mut update_model = models::Model::from(entity_model.clone())
            .into_active_model();
        let res = models::Entity::update_many()
            .filter(models::Column::Id.eq((id.tenant_id(), id.user_id())))
            .filter(models::Column::UpdateAt.eq(current_ts))
            .set(update_model.clone())
            .exec(&amp;conn)
            .await?;
        if res.rows_affected &gt; 0 {
            entity.move_event_to_context(txn);
            return Ok(());
        }
        if models::Entity::find()
            .filter(models::Column::Id.eq((id.tenant_id(), id.user_id())))
            .one(&amp;conn)
            .await?
            .is_some()
        {
            return Err(
                core_common::domain::RepositoryError::optimistic_lock_error(
                    "Optimistic lock conflict".to_string(),
                ),
            );
        }
        let insert_model: models::Model = entity_model.clone().try_into()?;
        let mut active_model = insert_model.into_active_model();
        active_model.insert(&amp;conn).await?;
        entity.move_event_to_context(txn);
        Ok(())
    }
</code></pre>
<h3>兼容性处理</h3>
<p>宏的另一个优势是其灵活性。它能根据字段名称自动适配不同的乐观锁策略：</p>
<ul>
<li>如果检测到字段为 <code>"version"</code>，则执行版本号的 CAS 逻辑。</li>
<li>如果检测到其他时间戳字段如 <code>"updated_at"</code>，则执行基于时间戳的 CAS 逻辑。</li>
</ul>
<hr>
<h2>结论</h2>
<p>通过将 <code>before_save</code> 中的版本递增逻辑，与 <code>Repository::save</code> 中的原子 CAS 检查完美结合，我们使用 Rust 过程宏实现了一个 <strong>高内聚、低耦合</strong> 的乐观锁基础设施。</p>
<p>开发者现在可以专注于业务逻辑，而将并发控制的复杂性和样板代码完全交给宏来处理。这不仅极大地提高了开发效率，同时也确保了底层持久化操作的健壮性和一致性。</p>
]]></description><pubDate>2025-11-18 12:33:36</pubDate></item><item><title>避开数据竞态：Rust SeaORM 中的乐观锁与 Upsert 模式实践</title><link>https://rustcc.cn/article?id=7436f49b-1862-4226-90cf-b517cf0d1902</link><description><![CDATA[<p>在构建高并发的后端服务时，确保数据的最终一致性是至关重要的。特别是当业务逻辑需要执行 <strong>"更新或插入 (Upsert)"</strong> 这种复合操作时，传统的 “先查询，后更新” 模式极易陷入并发陷阱。<br>
本文将深入探讨为什么简单的操作会引发竞态条件，并介绍如何在 Rust 的 SeaORM 框架中，使用 <strong>版本号（<code>i32</code>）</strong> 实现一个健壮的 <strong>原子化乐观锁 Upsert</strong> 流程。</p>
<hr>
<h2>一、乐观锁：不是不锁，而是“巧”锁</h2>
<p>数据库的并发控制主要分为悲观锁和乐观锁。</p>
<ul>
<li><strong>悲观锁（Pessimistic Locking）：</strong> 假设冲突一定会发生。在读取数据时就对数据行进行锁定，直到事务完成。</li>
<li><strong>乐观锁（Optimistic Locking）：</strong> 假设冲突很少发生。在整个事务过程中不锁定资源，而是通过检查数据是否被修改来确认。</li>
</ul>
<p>乐观锁的核心思想是：<strong>通过一次原子性的操作来检查并修改数据，而不是依赖两次独立的数据库操作。</strong></p>
<hr>
<h2>二、没有锁的陷阱：丢失更新的竞态条件</h2>
<p>让我们以一个 <code>version: i32</code> 字段为例，来看看缺乏原子性操作会导致什么问题。</p>
<h3>场景：多人同时更新同一条记录</h3>
<ol>
<li><strong>查询（事务 A/B）：</strong> 事务 A 和事务 B 都读取了 ID=1 的记录，其 <code>version</code> 都为 <strong><code>1</code></strong>。</li>
<li><strong>更新（事务 B 提交）：</strong> 事务 B 完成修改，执行 <strong>无版本检查</strong> 的 <code>UPDATE</code> 语句，数据库中的 <code>version</code> 变为 <code>2</code>。</li>
<li><strong>更新（事务 A 提交）：</strong> 事务 A 完成修改，也执行 <strong>无版本检查</strong> 的 <code>UPDATE</code> 语句。</li>
</ol>
<p><strong>结果：</strong> 事务 B 的业务变更被事务 A 的修改覆盖，导致 <strong>丢失更新（Lost Update）</strong> 的竞态条件。</p>
<h3>乐观锁的解决之道：单次原子操作</h3>
<p>要解决这个问题，必须让 <strong>“检查旧版本”</strong> 和 <strong>“设置新值”</strong> 成为一个原子操作，即在 <code>UPDATE</code> 语句中加入版本过滤条件：</p>
<pre><code>UPDATE records
SET title = '新标题', version = version + 1
WHERE id = 1 AND version = 1; -- 关键：只有旧版本为 1 时才允许更新
</code></pre>
<p>在 SeaORM 中，我们使用 <code>update_many()</code> 配合 <code>filter()</code> 来构造这个原子操作，并通过检查 <code>rows_affected</code> 来判断操作是否成功。</p>
<hr>
<h2>三、Upsert 流程的抉择：先 Update 再 Insert 的优势</h2>
<p>实现 Upsert 功能主要有两种策略：<strong>“先 Update 再 Insert”</strong> 和 <strong>“先 Insert 再 Update”</strong>。在涉及<strong>乐观锁</strong>的业务中，<strong>“先 Update 再 Insert”</strong> 模式是更优的选择。</p>
<h3>1. 模式一：先 Update 再 Insert（推荐）</h3>
<p>这种模式总是优先处理最常见的情况：<strong>更新现有记录</strong>。</p>
<p><strong>优势分析：</strong></p>
<ul>
<li><strong>天然支持乐观锁：</strong> 乐观锁检查（<code>WHERE version = ?</code>）直接集成在 <code>UPDATE</code> 语句中，利用了数据库的原子性，保证了在单次操作中完成检查和修改。</li>
<li><strong>高效处理更新：</strong> 在高并发的更新场景中，大部分操作都是更新。这种模式只需执行一次成功的 <code>UPDATE</code> 就能完成任务，避免了不必要的 <code>INSERT</code> 尝试。</li>
</ul>
<h3>2. 模式二：先 Insert 再 Update</h3>
<p><strong>流程：</strong> 尝试 <code>INSERT</code> $\to$ 如果失败（主键冲突），执行 <code>UPDATE</code>。</p>
<p><strong>劣势分析：</strong></p>
<ul>
<li><strong>乐观锁实现复杂：</strong> 如果 <code>INSERT</code> 失败，转到 <code>UPDATE</code> 时，必须确保 <code>UPDATE</code> 操作是带有乐观锁检查的，这增加了流程的复杂性。</li>
<li><strong>高更新场景效率低：</strong> 如果大部分操作是更新，这种模式会强制执行一次注定会失败的 <code>INSERT</code> 操作（抛出主键冲突错误），然后再执行一次 <code>UPDATE</code>，浪费了数据库资源。</li>
</ul>
<h3>总结：选择 “先 Update 再 Insert” 的理由</h3>
<p>在处理带有乐观锁的聚合根持久化时，<strong>“先 Update 再 Insert”</strong> 模式是首选方案。它能够利用 <code>UPDATE</code> 的原子性高效地处理最常见的<strong>更新</strong>操作，并<strong>天然地</strong>将乐观锁检查与数据库写操作绑定。</p>
<hr>
<h2>四、SeaORM 中的 Upsert 流程：UPDATE $\to$ FIND $\to$ INSERT</h2>
<p>基于 <strong>“先 Update 再 Insert”</strong> 的策略，我们构建一个清晰的 <strong>"原子 UPDATE + FIND + INSERT"</strong> 三步流程，以可靠地处理成功更新、并发冲突和成功插入三种情况。</p>
<h3>核心实现代码</h3>
<pre><code>// 假设 entity.version 是更新后的新版本，expected_old_version = entity.version - 1
async fn save&lt;T: TransactionContext&gt;(
    &amp;self,
    callback: &amp;mut EventSourcedEntity&lt;Callback&gt;,
    txn: &amp;mut T,
) -&gt; Result&lt;(), RepositoryError&gt; {
    let conn = txn.get_connection();
    let entity: &amp;Callback = callback;
    let id = entity.channel.0.clone(); 
    let expected_old_version = entity.version - 1; 

    // 准备 ActiveModel，设置新的 version
    let mut active_model_for_update: ActiveModel = entity.clone().into_active_model();
    active_model_for_update.version = Set(entity.version); 

    // ----------------------------------------------------
    // 第一步：尝试原子 UPDATE（带乐观锁）
    // ----------------------------------------------------
    let res = callback_model::Entity::update_many()
        .set(active_model_for_update)
        .filter(callback_model::Column::Channel.eq(id.clone())) 
        .filter(callback_model::Column::Version.eq(expected_old_version)) // 乐观锁检查
        .exec(conn)
        .await?;

    if res.rows_affected &gt; 0 {
        // 更新成功：影响行数 &gt; 0，说明乐观锁条件满足。
        callback.move_event_to_context(txn);
        return Ok(());
    }

    // ----------------------------------------------------
    // 第二步：UPDATE 失败。使用 FIND 检查记录是否存在（判断是否为并发冲突）
    // ----------------------------------------------------
    if callback_model::Entity::find_by_id(id.clone())
        .one(conn)
        .await?
        .is_some()
    {
        // 记录存在。UPDATE 失败且记录存在，必然是版本不匹配，即并发冲突。
        return Err(RepositoryError::optimistic_lock_error(
            "Optimistic lock conflict: Record exists, but old version did not match."
        ));
    }

    // ----------------------------------------------------
    // 第三步：记录不存在，尝试 INSERT
    // ----------------------------------------------------
    let active_model_for_insert: ActiveModel = entity.clone().into_active_model();
    
    active_model_for_insert.insert(conn).await
        .map_err(|e| {
             // 如果 INSERT 失败，则视为并发冲突（在 FIND 之后被其他事务插入）。
             match e {
                 DbErr::RecordNotInserted | DbErr::Custom(_) =&gt; RepositoryError::optimistic_lock_error(
                    "Concurrency conflict: Record inserted after non-existence check."
                 ),
                 _ =&gt; e.into(),
            }
        })?;

    callback.move_event_to_context(txn);
    Ok(())
}
</code></pre>
<hr>
<h2>结论：告别竞态，拥抱原子性</h2>
<p>通过本文的分析和实践，我们可以得出以下关键结论：</p>
<ol>
<li><strong>乐观锁是高并发的基石：</strong> 放弃“先查后改”的传统模式，将<strong>版本检查</strong>与<strong>数据修改</strong>集成到一次原子性的 <code>UPDATE</code> 操作中，是避免丢失更新等竞态条件的根本方法。</li>
<li><strong>选择正确的 Upsert 策略：</strong> <strong>“先 Update 再 Insert”</strong> 模式凭借其对乐观锁的天然支持和对更新操作的高效处理，成为处理聚合根持久化的首选。</li>
<li><strong>利用数据库的原子性：</strong> 无论是通过检查 <code>rows_affected</code>，还是依赖主键约束错误来区分更新失败的原因，都是在充分利用数据库底层机制来确保数据一致性。</li>
</ol>
<p>在您的 Rust DDD/CQRS 架构中，将这种原子化逻辑封装进仓储（Repository）层的 <code>save()</code> 方法中，是确保数据完整性和系统高可用性的关键。</p>
]]></description><pubDate>2025-11-18 12:33:11</pubDate></item><item><title>with_err_location：让 Rust 错误处理更智能的过程宏</title><link>https://rustcc.cn/article?id=2650d510-e3ee-4f14-9284-5927ea273e91</link><description><![CDATA[<p>在 Rust 错误处理中，我们经常需要记录错误发生的位置信息以便调试。虽然 <code>snafu</code> 库提供了强大的错误处理能力，但手动为每个错误变体添加位置字段和工厂方法仍然繁琐且容易出错。本文介绍一个自定义的过程宏 <code>#[with_err_location]</code>，它可以自动化这些重复工作，让错误处理更加优雅和高效。</p>
<h2>问题背景</h2>
<p>使用 <code>snafu</code> 进行错误处理时，我们通常需要：</p>
<ol>
<li>为每个错误变体手动添加 <code>location</code> 字段</li>
<li>添加相应的属性（<code>#[snafu(implicit)]</code>、<code>#[serde(skip)]</code>）</li>
<li>为复杂的 source 字段添加 <code>#[snafu(source(false))]</code></li>
<li>手动实现工厂方法来创建错误实例</li>
</ol>
<p>这导致了大量的样板代码：</p>
<pre><code>#[derive(Debug, Serialize, Snafu)]
#[serde(tag = "type")]
pub enum ApiError {
    #[serde(rename = "validate_error")]
    ValidateError {
        message: String,
        #[serde(skip)]
        #[snafu(implicit)]
        location: snafu::Location,
    },
    
    #[serde(rename = "internal_error")]
    InternalError {
        message: String,
        #[serde(skip)]
        #[snafu(source(false))]
        source: Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;,
        #[serde(skip)]
        #[snafu(implicit)]
        location: snafu::Location,
    },
}

impl ApiError {
    #[track_caller]
    pub fn validate_error(message: String) -&gt; Self {
        ApiError::ValidateError {
            message,
            location: GenerateImplicitData::generate(),
        }
    }
    
    #[track_caller]
    pub fn internal_error(message: String) -&gt; Self {
        ApiError::InternalError {
            message,
            source: None,
            location: GenerateImplicitData::generate(),
        }
    }
    
    #[track_caller]
    pub fn internal_error_with_source(message: String, source: Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;) -&gt; Self {
        ApiError::InternalError {
            message,
            source,
            location: GenerateImplicitData::generate(),
        }
    }
}
</code></pre>
<h2>解决方案：<code>#[with_err_location]</code> 宏</h2>
<p><code>#[with_err_location]</code> 宏可以自动化所有这些工作，让您只需要定义核心的错误结构：</p>
<pre><code>#[with_err_location]
#[derive(Debug, Serialize, Snafu)]
#[serde(tag = "type")]
pub enum ApiError {
    #[serde(rename = "validate_error")]
    ValidateError {
        message: String,
    },
    
    #[serde(rename = "internal_error")]
    InternalError {
        message: String,
        source: Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;,
    },
}
</code></pre>
<h2>核心特性</h2>
<h3>1. 自动添加 Location 字段</h3>
<p>宏会为每个枚举变体自动添加 <code>location: snafu::Location</code> 字段，并配置必要的属性：</p>
<ul>
<li><code>#[snafu(implicit)]</code>：让 snafu 自动填充位置信息</li>
<li><code>#[serde(skip)]</code>：在序列化时跳过该字段（默认行为）</li>
</ul>
<h3>2. 智能 Source 字段处理</h3>
<p>宏能识别复杂的 source 字段类型，并自动添加 <code>#[snafu(source(false))]</code> 属性：</p>
<pre><code>// 自动识别并处理
source: Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;
</code></pre>
<h3>3. 自动生成工厂方法</h3>
<p>宏为每个变体生成相应的工厂方法：</p>
<h4>普通变体</h4>
<pre><code>// 生成：
pub fn validate_error(message: String) -&gt; Self { ... }
</code></pre>
<h4>复杂 Source 字段变体</h4>
<p>对于包含 <code>Option&lt;Box&lt;dyn Error + Send + Sync&gt;&gt;</code> 类型的 source 字段，宏会生成两个方法：</p>
<pre><code>// 基础方法（source = None）
pub fn internal_error(message: String) -&gt; Self { ... }

// 带 source 的方法
pub fn internal_error_with_source(message: String, source: Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;) -&gt; Self { ... }
</code></pre>
<h3>4. 灵活的配置选项</h3>
<h4>全局配置</h4>
<pre><code>#[with_err_location(serde = true)]  // 不添加 #[serde(skip)]
#[derive(Debug, Snafu)]
pub enum ApiError { ... }
</code></pre>
<h4>变体级别配置</h4>
<pre><code>#[with_err_location]
#[derive(Debug, Snafu)]
pub enum ApiError {
    #[location(serde = true)]  // 此变体不添加 #[serde(skip)]
    SpecialError {
        message: String,
    },
}
</code></pre>
<h2>实现细节</h2>
<h3>宏的工作流程</h3>
<ol>
<li><strong>解析输入</strong>：解析枚举定义和宏参数</li>
<li><strong>字段分析</strong>：检查每个变体的字段类型和现有属性</li>
<li><strong>添加 Location 字段</strong>：为没有 location 字段的变体添加</li>
<li><strong>属性处理</strong>：添加必要的 snafu 和 serde 属性</li>
<li><strong>工厂方法生成</strong>：基于字段类型生成相应的工厂方法</li>
</ol>
<h3>关键函数</h3>
<h4>字段类型检测</h4>
<pre><code>fn should_add_source_false(field: &amp;syn::Field) -&gt; bool {
    let type_str = field.ty.to_token_stream().to_string();
    let is_option_box_dyn_error = type_str.starts_with("Option &lt; Box &lt; dyn");
    let is_source_field = field.ident.as_ref().map(|name| name == "source").unwrap_or(false);
    is_source_field &amp;&amp; is_option_box_dyn_error
}
</code></pre>
<h4>工厂方法生成</h4>
<pre><code>fn generate_factory_methods(input_enum: &amp;ItemEnum) -&gt; darling::Result&lt;TokenStream&gt; {
    // 检测复杂 source 字段
    let has_complex_source = fields_named.named.iter().any(should_add_source_false);
    
    if has_complex_source {
        // 生成两个方法：基础方法和带 source 的方法
    } else {
        // 生成单个方法
    }
}
</code></pre>
<h2>使用示例</h2>
<h3>基本使用</h3>
<pre><code>#[with_err_location]
#[derive(Debug, Snafu)]
pub enum MyError {
    NetworkError { url: String },
    ValidationError { field: String, message: String },
}

// 使用生成的工厂方法
let error = MyError::network_error("https://api.example.com".to_string());
</code></pre>
<h3>复杂 Source 字段</h3>
<pre><code>#[with_err_location]
#[derive(Debug, Snafu)]
pub enum ComplexError {
    DatabaseError {
        query: String,
        source: Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;,
    },
}

// 两种使用方式
let error1 = ComplexError::database_error("SELECT * FROM users".to_string());
let error2 = ComplexError::database_error_with_source(
    "SELECT * FROM users".to_string(),
    Some(Box::new(io_error))
);
</code></pre>
<h3>配置选项</h3>
<pre><code>#[with_err_location(serde = true)]  // 全局配置
#[derive(Debug, Snafu)]
pub enum ApiError {
    #[location(serde = false)]  // 变体级别覆盖
    InternalError { message: String },
    
    PublicError { message: String },  // 使用全局配置
}
</code></pre>
<h2>完整代码</h2>
<pre><code>#[proc_macro_attribute]
pub fn with_err_location(
    args: proc_macro::TokenStream,
    input: proc_macro::TokenStream,
) -&gt; proc_macro::TokenStream {
    let args = args.into();
    with_err_location::with_err_location_impl(args, input.into())
        .unwrap_or_else(darling::Error::write_errors)
        .into()
} 
</code></pre>
<pre><code>use darling::{Error, FromMeta, ast::NestedMeta};
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::{Attribute, Field, Fields, ItemEnum, Meta, punctuated::Punctuated, token::Comma};

#[derive(Debug, FromMeta, Default)]
struct WithErrLocationArgs {
    pub serde: bool,
}

pub fn with_err_location_impl(
    args: TokenStream,
    input: TokenStream,
) -&gt; darling::Result&lt;TokenStream&gt; {
    let mut input_enum: ItemEnum = match syn::parse2(input) {
        Ok(v) =&gt; v,
        Err(e) =&gt; return Err(Error::from(e)),
    };

    // 解析全局参数
    let global_args = if args.is_empty() {
        WithErrLocationArgs::default()
    } else {
        let attr_args = match NestedMeta::parse_meta_list(args) {
            Ok(v) =&gt; v,
            Err(e) =&gt; return Err(Error::from(e)),
        };
        WithErrLocationArgs::from_list(&amp;attr_args).unwrap_or_default()
    };

    // 遍历枚举的所有变体
    for variant in &amp;mut input_enum.variants {
        // 查找并解析 #[location(...)] 属性
        let (location_config, remaining_attrs) =
            parse_and_remove_location_attrs(&amp;variant.attrs, &amp;global_args)?;

        // 移除 location 属性，保留其他属性
        variant.attrs = remaining_attrs;

        match &amp;mut variant.fields {
            Fields::Named(fields_named) =&gt; {
                // 检查是否已经有 location 字段
                let location_field_index = fields_named.named.iter().position(|field| {
                    field
                        .ident
                        .as_ref()
                        .map(|ident| ident == "location")
                        .unwrap_or(false)
                });
                match location_field_index {
                    Some(index) =&gt; {
                        // 如果已经有 location 字段，确保它至少有 #[snafu(implicit)]
                        let existing_field = &amp;mut fields_named.named[index];
                        ensure_location_field_has_snafu_implicit(existing_field, &amp;location_config);
                    }
                    None =&gt; {
                        // 如果没有 location 字段，则添加一个新的（总是带有 #[snafu(implicit)]）
                        let location_field = create_location_field(&amp;location_config);
                        fields_named.named.push(location_field);
                        fields_named.named.push_punct(Comma::default());
                    }
                }
                // 如果有source 且类型是Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt;
                // 需要为其加上#[snafu(source(false))]
                for field in &amp;mut fields_named.named {
                    if should_add_source_false(field) {
                        ensure_source_false_attribute(field);
                    }
                }
            }
            _ =&gt; {
                return Err(Error::unsupported_format(
                    "Only named fields variants are supported",
                ));
            }
        }
    }

    // 生成工厂方法
    let factory_methods = generate_factory_methods(&amp;input_enum)?;

    Ok(quote! {
        #input_enum
        #factory_methods
    })
}

/// 解析并移除 location 属性，返回配置和剩余属性
fn parse_and_remove_location_attrs(
    variant_attrs: &amp;[Attribute],
    global_args: &amp;WithErrLocationArgs,
) -&gt; darling::Result&lt;(LocationConfig, Vec&lt;Attribute&gt;)&gt; {
    let mut config = LocationConfig {
        serde: global_args.serde,
    };

    let mut remaining_attrs = Vec::new();

    for attr in variant_attrs {
        if attr.path().is_ident("location") {
            // 解析 location 属性的参数
            match &amp;attr.meta {
                Meta::List(meta_list) =&gt; {
                    let nested = meta_list.parse_args_with(
                        Punctuated::&lt;NestedMeta, syn::Token![,]&gt;::parse_terminated,
                    )?;
                    let location_args =
                        WithErrLocationArgs::from_list(&amp;nested.into_iter().collect::&lt;Vec&lt;_&gt;&gt;())?;

                    config.serde = location_args.serde;
                }
                _ =&gt; {
                    // 如果没有参数，使用默认配置
                }
            }
        } else {
            // 保留非 location 属性
            remaining_attrs.push(attr.clone());
        }
    }

    Ok((config, remaining_attrs))
}

#[derive(Debug)]
struct LocationConfig {
    serde: bool,
}

/// 确保现有的 location 字段至少有 #[snafu(implicit)] 属性
fn ensure_location_field_has_snafu_implicit(field: &amp;mut Field, config: &amp;LocationConfig) {
    // 根据配置添加或确保有 #[serde(skip)]
    if !config.serde {
        let has_serde_skip = field.attrs.iter().any(|attr| {
            if attr.path().is_ident("serde")
                &amp;&amp; let Meta::List(meta_list) = &amp;attr.meta
            {
                return meta_list.tokens.to_string().contains("skip");
            }
            false
        });

        if !has_serde_skip {
            let serde_skip_attr: Attribute = syn::parse_quote! {
                #[serde(skip)]
            };
            field.attrs.push(serde_skip_attr);
        }
    }
    let has_snafu_implicit = field.attrs.iter().any(|attr| {
        if attr.path().is_ident("snafu")
            &amp;&amp; let Meta::List(meta_list) = &amp;attr.meta
        {
            return meta_list.tokens.to_string().contains("implicit");
        }
        false
    });

    // 如果没有 #[snafu(implicit)]，则添加它
    if !has_snafu_implicit {
        let snafu_implicit_attr: Attribute = syn::parse_quote! {
            #[snafu(implicit)]
        };
        field.attrs.push(snafu_implicit_attr);
    }
}

/// 检查字段是否需要自动添加 #[snafu(source(false))]
fn should_add_source_false(field: &amp;syn::Field) -&gt; bool {
    let type_str = field.ty.to_token_stream().to_string();

    // 检查是否是 Option&lt;Box&lt;dyn std::error::Error + Send + Sync&gt;&gt; 类型
    let is_option_box_dyn_error = type_str.starts_with("Option &lt; Box &lt; dyn");

    // 检查字段名是否为 "source"
    let is_source_field = field
        .ident
        .as_ref()
        .map(|name| name == "source")
        .unwrap_or(false);

    is_source_field &amp;&amp; is_option_box_dyn_error
}

/// 确保复杂 source 字段有 #[snafu(source(false))] 属性
fn ensure_source_false_attribute(field: &amp;mut Field) {
    // 检查是否已经有 #[snafu(source(false))] 属性
    let has_source_false = field.attrs.iter().any(|attr| {
        if attr.path().is_ident("snafu")
            &amp;&amp; let Meta::List(meta_list) = &amp;attr.meta
        {
            let tokens_str = meta_list.tokens.to_string();
            return tokens_str.contains("source")
                &amp;&amp; (tokens_str.contains("false") || tokens_str.contains("( false )"));
        }
        false
    });

    // 如果没有，则添加 #[snafu(source(false))]
    if !has_source_false {
        let source_false_attr: Attribute = syn::parse_quote! {
            #[snafu(source(false))]
        };
        field.attrs.push(source_false_attr);
    }
}

/// 根据配置创建 location 字段
fn create_location_field(config: &amp;LocationConfig) -&gt; Field {
    if !config.serde {
        syn::parse_quote! {
            #[serde(skip)]
            #[snafu(implicit)]
            location: snafu::Location
        }
    } else {
        syn::parse_quote! {
            #[snafu(implicit)]
            location: snafu::Location
        }
    }
}

/// 为枚举生成工厂方法
fn generate_factory_methods(input_enum: &amp;ItemEnum) -&gt; darling::Result&lt;TokenStream&gt; {
    let enum_name = &amp;input_enum.ident;
    let mut methods = Vec::new();

    for variant in &amp;input_enum.variants {
        let variant_name = &amp;variant.ident;

        // 将变体名转换为 snake_case
        let method_name = convert_to_snake_case(&amp;variant_name.to_string());
        let method_ident = syn::Ident::new(&amp;method_name, variant_name.span());

        match &amp;variant.fields {
            Fields::Named(fields_named) =&gt; {
                // 检查是否有复杂的 source 字段
                let has_complex_source = fields_named.named.iter().any(should_add_source_false);

                if has_complex_source {
                    // 生成两个方法：基础方法（source = None）和带 source 的方法

                    // 1. 基础方法：source 为 None
                    let (base_params, base_assignments) =
                        analyze_fields_for_source_method(fields_named, true);
                    let base_method = quote! {
                        #[track_caller]
                        pub fn #method_ident(#(#base_params),*) -&gt; Self {
                            #enum_name::#variant_name {
                                #(#base_assignments,)*
                            }
                        }
                    };
                    methods.push(base_method);

                    // 2. 带 source 的方法
                    let source_method_name = format!("{}_with_source", method_name);
                    let source_method_ident =
                        syn::Ident::new(&amp;source_method_name, variant_name.span());
                    let (source_params, source_assignments) =
                        analyze_fields_for_source_method(fields_named, false);

                    let source_method = quote! {
                        #[track_caller]
                        pub fn #source_method_ident(#(#source_params),*) -&gt; Self
                        {
                            #enum_name::#variant_name {
                                #(#source_assignments,)*
                            }
                        }
                    };
                    methods.push(source_method);
                } else {
                    // 分析字段，确定需要的参数
                    let (params, field_assignments) = analyze_fields(fields_named);

                    // 生成基础方法
                    let method = quote! {
                        #[track_caller]
                        pub fn #method_ident(#(#params),*) -&gt; Self {
                            #enum_name::#variant_name {
                                #(#field_assignments,)*
                            }
                        }
                    };

                    methods.push(method);
                }
            }
            _ =&gt; continue,
        }
    }

    Ok(quote! {
        impl #enum_name {
            #(#methods)*
        }
    })
}

/// 将 PascalCase 转换为 snake_case
fn convert_to_snake_case(s: &amp;str) -&gt; String {
    let mut result = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() &amp;&amp; i &gt; 0 {
            result.push('_');
        }
        result.push(ch.to_lowercase().next().unwrap());
    }
    result
}

/// 分析字段，生成参数和字段赋值
fn analyze_fields(fields: &amp;syn::FieldsNamed) -&gt; (Vec&lt;TokenStream&gt;, Vec&lt;TokenStream&gt;) {
    let mut params = Vec::new();
    let mut assignments = Vec::new();

    for field in &amp;fields.named {
        let field_name = field.ident.as_ref().unwrap();
        let field_type = &amp;field.ty;

        if field_name == "location" {
            assignments.push(quote! { #field_name: snafu::GenerateImplicitData::generate() });
            continue;
        }

        // 普通字段作为参数
        params.push(quote! { #field_name: #field_type });
        assignments.push(quote! { #field_name });
    }

    (params, assignments)
}

/// 分析字段，为带 source 的方法生成参数和字段赋值
fn analyze_fields_for_source_method(
    fields: &amp;syn::FieldsNamed,
    is_base: bool,
) -&gt; (Vec&lt;TokenStream&gt;, Vec&lt;TokenStream&gt;) {
    let mut params = Vec::new();
    let mut assignments = Vec::new();

    for field in &amp;fields.named {
        let field_name = field.ident.as_ref().unwrap();
        let field_type = &amp;field.ty;

        if field_name == "location" {
            assignments.push(quote! { #field_name: snafu::GenerateImplicitData::generate() });
            continue;
        }

        if is_base &amp;&amp; should_add_source_false(field) {
            // 复杂 source 字段设为 None，不作为参数
            assignments.push(quote! { #field_name: None });
        } else {
            // 普通字段作为参数
            params.push(quote! { #field_name: #field_type });
            assignments.push(quote! { #field_name });
        }
    }

    (params, assignments)
}

</code></pre>
<h2>优势总结</h2>
<ol>
<li><strong>减少样板代码</strong>：自动生成重复的字段和方法定义</li>
<li><strong>类型安全</strong>：在编译时确保正确的类型处理</li>
<li><strong>灵活配置</strong>：支持全局和变体级别的配置选项</li>
<li><strong>智能处理</strong>：自动识别复杂类型并生成相应的方法</li>
<li><strong>向后兼容</strong>：可以与现有的 snafu 代码无缝集成</li>
</ol>
<h2>结论</h2>
<p><code>#[with_err_location]</code> 宏通过自动化错误处理中的重复工作，显著提升了开发效率和代码质量。它不仅减少了样板代码，还通过智能的类型检测和方法生成，提供了更加优雅和类型安全的错误处理解决方案。</p>
<p>无论是简单的错误类型还是复杂的带源错误的场景，这个宏都能提供恰到好处的自动化支持，让开发者能够专注于业务逻辑而不是重复的错误处理代码。</p>
]]></description><pubDate>2025-11-18 12:31:08</pubDate></item><item><title>Rust 中方法名到 SQL 语句的智能解析与构造</title><link>https://rustcc.cn/article?id=94e94dd2-2549-44b9-b884-da2655b1d5eb</link><description><![CDATA[<p>在构建任何复杂的应用程序时，数据持久化都是核心环节。通常会采用**仓储模式（Repository Pattern）**来解耦业务逻辑和数据访问逻辑。这带来了清晰的架构，但也引入了一个常见的问题：大量的样板代码（Boilerplate Code）。</p>
<p>每个实体都需要一个仓储接口，以及对应的实现。<code>find_by_id</code>, <code>find_by_email</code>, <code>exists_by_name</code>, <code>delete_by_id</code>... 这些简单却重复的方法，我们一遍又一遍地编写，不仅枯燥，还容易出错。</p>
<h3>痛点分析：传统仓储层的重复劳动</h3>
<p>下面是 <code>UserRepository</code> 在没有自动化工具时的完整面貌：</p>
<p><strong>1. Trait 定义 - 接口膨胀</strong></p>
<pre><code>// src/domain/repositories/user_repository.rs
pub trait UserRepository {
    // 基础CRUD
    async fn find_by_id(&amp;self, txn: &amp;mut Txn, id: &amp;UserId) -&gt; Result&lt;Option&lt;User&gt;&gt;;
    async fn save(&amp;self, txn: &amp;mut Txn, user: &amp;mut User) -&gt; Result&lt;()&gt;;
    async fn delete_by_id(&amp;self, txn: &amp;mut Txn, id: &amp;UserId) -&gt; Result&lt;()&gt;;
    
    // 各种查询方法
    async fn find_id_by_email(&amp;self, txn: &amp;mut Txn, email: &amp;Email) -&gt; Result&lt;Option&lt;UserId&gt;&gt;;
    async fn find_id_by_user_name(&amp;self, txn: &amp;mut Txn, user_name: &amp;str) -&gt; Result&lt;Option&lt;UserId&gt;&gt;;
    async fn exists_by_email(&amp;self, txn: &amp;mut Txn, email: &amp;Email) -&gt; Result&lt;bool&gt;;
    async fn find_by_status(&amp;self, txn: &amp;mut Txn, status: UserStatus) -&gt; Result&lt;Vec&lt;User&gt;&gt;;
    // ... 更多类似方法，接口越来越庞大
}
</code></pre>
<p><strong>2. 实现类 - 重复的SQL模板</strong></p>
<pre><code>// src/infrastructure/repositories_impl/user_repository_impl.rs
pub struct UserRepositoryImpl;

#[async_trait::async_trait]
impl UserRepository for UserRepositoryImpl {
    async fn find_by_id(&amp;self, txn: &amp;mut Txn, id: &amp;UserId) -&gt; Result&lt;Option&lt;User&gt;&gt; {
        // 每个方法都要写几乎相同的模板代码
        txn.query_sql_one("SELECT * FROM ua_user WHERE id = $1", [id.into()]).await
    }

    async fn find_id_by_email(&amp;self, txn: &amp;mut Txn, email: &amp;Email) -&gt; Result&lt;Option&lt;UserId&gt;&gt; {
        // 只是表名、字段名、参数位置变化，结构完全一样
        txn.query_sql_one("SELECT id FROM ua_user WHERE email = $1", [email.into()]).await
    }

    async fn find_id_by_user_name(&amp;self, txn: &amp;mut Txn, user_name: &amp;str) -&gt; Result&lt;Option&lt;UserId&gt;&gt; {
        // 重复第三次...
        txn.query_sql_one("SELECT id FROM ua_user WHERE user_name = $1", [user_name.into()]).await
    }

    async fn exists_by_email(&amp;self, txn: &amp;mut Txn, email: &amp;Email) -&gt; Result&lt;bool&gt; {
        // 稍微复杂一点，但模式仍然固定
        txn.query_sql_one("SELECT EXISTS(SELECT 1 FROM ua_user WHERE email = $1)", [email.into()]).await
    }
    
    // 保存逻辑更复杂，但也是固定模式
    async fn save(&amp;self, txn: &amp;mut Txn, user: &amp;mut User) -&gt; Result&lt;()&gt; {
        if user.is_new() {
            // INSERT 逻辑
            let sql = "INSERT INTO ua_user (id, email, user_name, ...) VALUES ($1, $2, $3, ...)";
            txn.execute_sql(sql, params![user.id(), user.email(), ...]).await?;
        } else {
            // UPDATE 逻辑  
            let sql = "UPDATE ua_user SET email = $1, user_name = $2, ... WHERE id = $3";
            txn.execute_sql(sql, params![user.email(), user.user_name(), user.id()]).await?;
        }
        Ok(())
    }
}
</code></pre>
<p><strong>3. 测试类 - 更多的重复</strong></p>
<pre><code>// tests/user_repository_test.rs
// 还需要为每个方法编写测试，Mock 各种依赖...
</code></pre>
<p>这种模式的问题很明显：</p>
<ul>
<li><strong>代码重复</strong>：每个查询方法都是相似的模板</li>
<li><strong>维护困难</strong>：表结构变更需要修改多个地方</li>
<li><strong>容易出错</strong>：手写SQL容易有拼写错误</li>
<li><strong>效率低下</strong>：花费大量时间在机械性编码上</li>
</ul>
<h3>✨ 解决方案：<code>#[repository]</code> 宏的威力</h3>
<p>现在让我们看看使用 <code>#[repository]</code> 宏之后的变化：</p>
<pre><code>// src/domain/repositories/user_repository.rs
use core_common::repository;

#[repository(aggregate = User, table_name = "ua_user")]
pub trait UserRepository: Send + Sync {
    // 复杂的、需要特殊逻辑的查询，保持手写实现
    async fn get_all_permissions(
        &amp;self,
        user_id: &amp;UserId,
        tenant_id: Option&lt;TenantId&gt;,
    ) -&gt; Result&lt;PermissionIdHashSet, RepositoryError&gt; {
        // 这里仍然可以手写复杂实现
        // 比如联表查询、特殊业务逻辑等
    }

    // 简单查询：只需定义方法签名，空函数体 {}
    // 宏会自动生成完整的SQL实现！
    
    // 根据ID查询
    async fn find_by_id(&amp;self, id: &amp;UserId) -&gt; Result&lt;Option&lt;User&gt;, RepositoryError&gt; {}
    
    // 根据各种字段查询ID
    async fn find_id_by_user_name(&amp;self, user_name: &amp;str) -&gt; Result&lt;Option&lt;UserId&gt;, RepositoryError&gt; {}
    async fn find_id_by_email(&amp;self, email: &amp;Email) -&gt; Result&lt;Option&lt;UserId&gt;, RepositoryError&gt; {}
    async fn find_id_by_phone(&amp;self, phone: &amp;Phone) -&gt; Result&lt;Option&lt;UserId&gt;, RepositoryError&gt; {}
    
    // 存在性检查
    async fn exists_by_email(&amp;self, email: &amp;Email) -&gt; Result&lt;bool, RepositoryError&gt; {}
    async fn exists_by_user_name(&amp;self, user_name: &amp;str) -&gt; Result&lt;bool, RepositoryError&gt; {}
    
    // 复杂条件查询
    async fn find_by_email_and_status(&amp;self, email: &amp;Email, status: UserStatus) -&gt; Result&lt;Vec&lt;User&gt;, RepositoryError&gt; {}
    async fn find_by_email_or_phone(&amp;self, email: &amp;Email, phone: &amp;Phone) -&gt; Result&lt;Vec&lt;User&gt;, RepositoryError&gt; {}
    
    // 统计查询
    async fn count_by_status(&amp;self, status: UserStatus) -&gt; Result&lt;i64, RepositoryError&gt; {}
    
    // 删除操作
    async fn delete_by_id(&amp;self, id: &amp;UserId) -&gt; Result&lt;(), RepositoryError&gt; {}
    
    // 保存操作 - 宏会自动处理INSERT/UPDATE逻辑
    async fn save(&amp;self, user: &amp;mut User) -&gt; Result&lt;(), RepositoryError&gt; {}
}
</code></pre>
<p><strong>宏的魔法效果详解：</strong></p>
<ol>
<li>
<p><strong>自动实现生成</strong></p>
<ul>
<li>编译时自动为每个空方法生成完整的SQL实现</li>
<li>无需手动编写 <code>UserRepositoryImpl</code></li>
<li>生成的代码与手写代码质量相当，但零错误</li>
</ul>
</li>
<li>
<p><strong>智能参数注入</strong></p>
<ul>
<li>自动添加事务参数 <code>txn: &amp;mut TC</code></li>
<li>自动处理参数类型转换（如 <code>Email</code> → 数据库类型）</li>
<li>最终方法签名实际上是：<code>find_id_by_email(&amp;self, txn: &amp;mut TC, email: &amp;Email)</code></li>
</ul>
</li>
<li>
<p><strong>CRUD 功能继承</strong></p>
<ul>
<li>通过 <code>aggregate = User</code> 自动继承 <code>CrudRepository&lt;User, TC&gt;</code></li>
<li>免费获得：<code>find_by_id</code>, <code>save</code>, <code>delete_by_id</code>, <code>exists_by_id</code> 等标准方法</li>
<li>无需重复定义基础CRUD操作</li>
</ul>
</li>
<li>
<p><strong>完整的测试支持</strong></p>
<ul>
<li>自动利用 <code>mockall</code> 生成Trait的Mock实现</li>
<li>在测试中可以直接：<code>let mut mock = MockUserRepository::new();</code></li>
<li>极大简化单元测试的编写</li>
</ul>
</li>
</ol>
<h3>🧙♂️ 魔法揭秘：命名约定解析引擎</h3>
<p>宏的核心是一个强大的方法名解析器，它将自然语言风格的方法名转换为精确的SQL查询。</p>
<h4>查询类型推断规则</h4>
<table>
<thead>
<tr>
<th>方法名前缀</th>
<th>生成的 SQL 类型</th>
<th>返回类型</th>
<th>示例</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>find_by_...</code></td>
<td><code>SELECT *</code></td>
<td><code>Option&lt;T&gt;</code> 或 <code>Vec&lt;T&gt;</code></td>
<td><code>find_by_email</code></td>
</tr>
<tr>
<td><code>find_{field}_by_...</code></td>
<td><code>SELECT {field}</code></td>
<td><code>Option&lt;FieldType&gt;</code></td>
<td><code>find_id_by_email</code></td>
</tr>
<tr>
<td><code>find_{field1}_and_{field2}_by_...</code></td>
<td><code>SELECT {field1}, {field2}</code></td>
<td>元组或自定义结构体</td>
<td><code>find_id_and_email_by_phone</code></td>
</tr>
<tr>
<td><code>exists_by_...</code></td>
<td><code>SELECT EXISTS(...)</code></td>
<td><code>bool</code></td>
<td><code>exists_by_email</code></td>
</tr>
<tr>
<td><code>count_by_...</code></td>
<td><code>SELECT COUNT(*)</code></td>
<td><code>i64</code></td>
<td><code>count_by_status</code></td>
</tr>
<tr>
<td><code>delete_by_...</code></td>
<td><code>DELETE</code></td>
<td><code>()</code></td>
<td><code>delete_by_id</code></td>
</tr>
</tbody>
</table>
<h4>条件运算符映射</h4>
<table>
<thead>
<tr>
<th>方法名后缀</th>
<th>SQL 运算符</th>
<th>示例</th>
<th>生成 WHERE 子句</th>
</tr>
</thead>
<tbody>
<tr>
<td>(无后缀)</td>
<td><code>=</code></td>
<td><code>find_by_email</code></td>
<td><code>email = $1</code></td>
</tr>
<tr>
<td><code>_not</code></td>
<td><code>!=</code></td>
<td><code>find_by_status_not</code></td>
<td><code>status != $1</code></td>
</tr>
<tr>
<td><code>_like</code></td>
<td><code>LIKE</code></td>
<td><code>find_by_name_like</code></td>
<td><code>name LIKE $1</code></td>
</tr>
<tr>
<td><code>_gte</code></td>
<td><code>&gt;=</code></td>
<td><code>find_by_age_gte</code></td>
<td><code>age &gt;= $1</code></td>
</tr>
<tr>
<td><code>_lte</code></td>
<td><code>&lt;=</code></td>
<td><code>find_by_age_lte</code></td>
<td><code>age &lt;= $1</code></td>
</tr>
<tr>
<td><code>_between</code></td>
<td><code>BETWEEN</code></td>
<td><code>find_by_age_between</code></td>
<td><code>age BETWEEN $1 AND $2</code></td>
</tr>
<tr>
<td><code>_in</code></td>
<td><code>IN</code></td>
<td><code>find_by_status_in</code></td>
<td><code>status IN ($1, $2, ...)</code></td>
</tr>
<tr>
<td><code>_is_null</code></td>
<td><code>IS NULL</code></td>
<td><code>find_by_deleted_at_is_null</code></td>
<td><code>deleted_at IS NULL</code></td>
</tr>
</tbody>
</table>
<h4>逻辑连接符处理</h4>
<table>
<thead>
<tr>
<th>连接词</th>
<th>SQL 逻辑</th>
<th>示例</th>
<th>生成条件</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>_and_</code></td>
<td><code>AND</code></td>
<td><code>find_by_email_and_status</code></td>
<td><code>email = $1 AND status = $2</code></td>
</tr>
<tr>
<td><code>_or_</code></td>
<td><code>OR</code></td>
<td><code>find_by_email_or_phone</code></td>
<td><code>email = $1 OR phone = $2</code></td>
</tr>
</tbody>
</table>
<h4>排序和分页支持</h4>
<table>
<thead>
<tr>
<th>后缀</th>
<th>SQL 子句</th>
<th>示例</th>
<th>效果</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>_order_by_{field}_asc</code></td>
<td><code>ORDER BY field ASC</code></td>
<td><code>find_by_status_order_by_created_at_asc</code></td>
<td>按创建时间升序</td>
</tr>
<tr>
<td><code>_order_by_{field}_desc</code></td>
<td><code>ORDER BY field DESC</code></td>
<td><code>find_by_status_order_by_created_at_desc</code></td>
<td>按创建时间降序</td>
</tr>
<tr>
<td><code>_first</code> / <code>_top</code></td>
<td><code>LIMIT 1</code></td>
<td><code>find_by_status_first</code></td>
<td>只返回第一条</td>
</tr>
<tr>
<td><code>_limit_{n}</code></td>
<td><code>LIMIT n</code></td>
<td><code>find_by_status_limit_10</code></td>
<td>返回前10条</td>
</tr>
</tbody>
</table>
<h4>实际解析示例</h4>
<p><strong>简单查询：</strong></p>
<pre><code>async fn find_id_by_email(&amp;self, email: &amp;Email) -&gt; Result&lt;Option&lt;UserId&gt;&gt; {}
</code></pre>
<p>↓ 生成 SQL：</p>
<pre><code>SELECT id FROM "ua_user" WHERE email = $1
</code></pre>
<p><strong>复杂查询：</strong></p>
<pre><code>async fn find_id_by_email_and_status_order_by_created_at_desc(
    &amp;self, 
    email: &amp;Email, 
    status: UserStatus
) -&gt; Result&lt;Option&lt;UserId&gt;&gt; {}
</code></pre>
<p>↓ 生成 SQL：</p>
<pre><code>SELECT id FROM "ua_user" 
WHERE email = $1 AND status = $2 
ORDER BY created_at DESC
</code></pre>
<p><strong>存在性检查：</strong></p>
<pre><code>async fn exists_by_email_and_tenant_id(
    &amp;self, 
    email: &amp;Email, 
    tenant_id: &amp;TenantId
) -&gt; Result&lt;bool&gt; {}
</code></pre>
<p>↓ 生成 SQL：</p>
<pre><code>SELECT EXISTS(
    SELECT 1 FROM "ua_user" 
    WHERE email = $1 AND tenant_id = $2
)
</code></pre>
<h3>⚙️ 灵活的配置选项</h3>
<p>宏支持丰富的配置参数来适应不同场景：</p>
<pre><code>// 基础配置
#[repository(aggregate = User, table_name = "ua_user")]

// 多租户支持
#[repository(aggregate = User, table_name = "ua_user", tenant = true)]

// 禁用Mock生成（用于性能敏感场景）
#[repository(aggregate = User, table_name = "ua_user", mock = false)]

// 自定义事务上下文
#[repository(
    aggregate = User, 
    table_name = "ua_user", 
    context = "db: &amp;Db"  // 使用自定义的db参数而非默认txn
)]

// 复杂配置组合
#[repository(
    aggregate = User,
    table_name = "ua_user",
    tenant = true,
    mock = true,
    context = "conn: &amp;mut PgConnection"
)]
</code></pre>
<h3>🎯 最佳实践和适用场景</h3>
<h4>推荐使用宏的场景：</h4>
<ul>
<li><strong>简单CRUD操作</strong>：95%的数据库查询都适合</li>
<li><strong>标准查询模式</strong>：等值查询、范围查询、存在性检查等</li>
<li><strong>快速原型开发</strong>：快速验证业务逻辑，后期可替换为手写优化SQL</li>
<li><strong>团队规范统一</strong>：确保所有开发者使用一致的查询模式</li>
</ul>
<h4>建议手写实现的场景：</h4>
<ul>
<li><strong>复杂联表查询</strong>：涉及多个表的复杂JOIN操作</li>
<li><strong>自定义聚合查询</strong>：GROUP BY、HAVING等复杂聚合</li>
<li><strong>数据库特定优化</strong>：需要数据库特定语法或优化提示</li>
<li><strong>存储过程调用</strong>：调用数据库存储过程或函数</li>
</ul>
<h3>📊 实际效果对比</h3>
<p><strong>代码量减少：</strong></p>
<ul>
<li>传统方式：每个查询方法需要 5-10 行实现代码</li>
<li>宏方式：每个查询方法只需 1 行声明</li>
<li>节省比例：约 80-90% 的代码量</li>
</ul>
<p><strong>开发效率提升：</strong></p>
<ul>
<li>新查询方法：从 5分钟/个 减少到 30秒/个</li>
<li>维护成本：表结构变更时，只需修改宏参数，无需改动多个方法</li>
<li>错误率：编译时检查替代运行时SQL错误</li>
</ul>
<h3>总结</h3>
<p><code>#[repository]</code> 宏不仅仅是一个代码生成工具，它代表了一种<strong>声明式数据访问</strong>的新范式。通过将开发者的重心从"如何实现"转移到"想要什么"，它真正实现了：</p>
<ul>
<li><strong>⚡ 极致效率</strong>：声明即实现，开发速度提升5-10倍</li>
<li><strong>🔒 绝对安全</strong>：编译时检查确保所有查询的类型安全</li>
<li><strong>📚 规范统一</strong>：强制执行一致的代码标准和命名约定</li>
<li><strong>🧪 测试友好</strong>：开箱即用的Mock支持，测试编写效率大幅提升</li>
<li><strong>🛠 灵活演进</strong>：复杂场景仍可手写实现，兼顾简单与复杂需求</li>
</ul>
<p>在Rust强大的元编程能力支持下，我们能够构建出这样既智能又实用的开发工具。这不仅是技术的进步，更是开发体验的革新——让我们能够更专注于业务逻辑本身，而不是重复的机械性工作。</p>
]]></description><pubDate>2025-11-18 12:17:16</pubDate></item></channel></rss>