<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>搞笑，竟然溜到第一</title><link>https://rustcc.cn/article?id=e2ce1cab-67bb-4b4b-9dbb-d70ddc3dc141</link><description><![CDATA[<p>不得不感叹，有时候事情的发展确实挺滑稽的。</p>
<p>刚去看了一下 <a href="https://github.com/topics/rust" rel="noopener noreferrer">https://github.com/topics/rust</a>，发现 RustDesk 溜到榜首。</p>
<p>老实说有点懵，年前我印象里还是第三，当时就担心，万一冲到第一怎么办，维护上未必接得住。</p>
<p>结果怕什么来什么，各种 bot 攻击、CVE 报告接踵而至。</p>
<p>RustDesk 当年就是从 rustcc 开始的，最早在这里发帖、交流、被大家认识。
现在回头看这个变化，感觉挺不真实的，甚至有点不太想它变成这样。</p>
]]></description><pubDate>2026-05-09 03:33:28</pubDate></item><item><title>【Rust日报】2026-05-09 NVIDIA 发布 CUDA-Oxide 0.1：实验性 Rust 到 CUDA 编译器</title><link>https://rustcc.cn/article?id=180cce85-9c69-4722-82e6-260796b0b330</link><description><![CDATA[<h2>NVIDIA 发布 CUDA-Oxide 0.1：实验性 Rust 到 CUDA 编译器</h2>
<p>CUDA-Oxide 是 NVIDIA Labs 新放出的实验性项目，目标不是再包一层 DSL，而是把“用原生 Rust 写 CUDA 内核”这条链路直接打通。</p>
<ul>
<li><strong>Rust 直出 PTX</strong>：走自定义 <code>rustc</code> codegen 后端，把标准 Rust 代码编译到 NVIDIA PTX</li>
<li><strong>单源代码工作流</strong>：主机端与设备端代码可以放在同一份 Rust 源码中构建</li>
<li><strong>保留 Rust 语言表达力</strong>：支持更贴近 Rust 的类型系统、抽象方式与设备端编程体验</li>
<li><strong>仍处 Alpha 早期</strong>：目前还在积极开发期，API、稳定性和工具链都还有继续变化的空间</li>
</ul>
<p>如果这个方向后续跑顺，Rust 在 GPU 编程上的想象空间会比现在大很多。</p>
<p>原文链接：https://nvlabs.github.io/cuda-oxide/</p>
<h2>Burn 0.21.0 发布：框架开销最高降低 8 倍</h2>
<p>Burn 0.21.0 这次更新很扎实，覆盖分布式训练、内核调优、后端调度和嵌入式 / WebAssembly 场景，属于那种“工程能力和性能一起往前推”的版本。</p>
<ul>
<li><strong>分布式训练提速明显</strong>：围绕可微分集合操作重做分布式栈，设备传输速度提升 16-21 倍，<code>all_reduce</code> 提升约 6 倍</li>
<li><strong>框架开销继续下压</strong>：官方给出的数据里，部分场景框架开销最高下降到原来的八分之一左右</li>
<li><strong>内核可靠性增强</strong>：自动调优、微基准和验证层都做了加强，能更早发现越界访问等问题</li>
<li><strong>工程化更完整</strong>：新增 <code>burn.toml</code> 项目级配置、<code>burn-dispatch</code> crate，以及面向 WebAssembly / 嵌入式的轻量 CPU 后端 Burn Flex</li>
</ul>
<p>对关注 Rust AI / ML 框架的人来说，这次版本更新值得认真看一遍。</p>
<p>原文链接：https://burn.dev/blog/release-0.21.0/</p>
<h2>hpke-ng：更快、更小、更安全的 Rust HPKE 实现</h2>
<p>Symbolic Software 发布了新的 HPKE 实现 <code>hpke-ng</code>。它不只是做性能优化，也是在重新审视 Rust HPKE 库该怎么做 API 设计和安全边界。</p>
<ul>
<li><strong>性能很能打</strong>：在和 <code>hpke-rs</code> 的 62 项对比里，27 项领先、32 项持平、3 项落后</li>
<li><strong>后量子路径优势明显</strong>：ML-KEM / X-Wing 等测试里提速比较突出，而且没有出现落后的条目</li>
<li><strong>安全问题驱动重写</strong>：团队此前在 <code>hpke-rs</code> 中报告过零共享密钥检查缺失、消息计数器溢出等问题</li>
<li><strong>类型级密码套件设计</strong>：把运行时枚举切到类型状态表达，尽量把约束前移到编译期处理</li>
</ul>
<p>这类“性能 + 安全 + API 设计”三条线一起推进的密码学基础库，通常都值得多看两眼。</p>
<p>原文链接：https://symbolic.software/blog/2026-05-08-hpke-ng/</p>
<h2>Monocurl：用 Rust 做交互式数学动画</h2>
<p>Monocurl 是一个面向 STEM 动画的交互式桌面应用和编程语言，想做的是把“数学表达 + 动画渲染 + 演示输出”放进同一套工作流里。</p>
<ul>
<li><strong>一份源码多种产出</strong>：可以输出图像、视频和幻灯片演示</li>
<li><strong>强调交互式创作</strong>：参数调整、播放和渲染可以在同一工作区里完成</li>
<li><strong>语言和编辑器一起设计</strong>：不是在通用工具上拼出来，而是专门为程序化动画场景定制</li>
<li><strong>学习材料比较完整</strong>：官网已经提供从基础语法到高级主题的一整套学习路径</li>
</ul>
<p>如果你对 Rust 在创意工具、可视化表达这条线上的应用感兴趣，这个项目挺有意思。</p>
<p>原文链接：http://monocurl.github.io/</p>
]]></description><pubDate>2026-05-09 01:08:14</pubDate></item><item><title>把公网穿透做成我每天离不开的工具——pb-mapper</title><link>https://rustcc.cn/article?id=3eb436ef-20a7-488c-bca7-9d014a01a05c</link><description><![CDATA[<h1>把公网穿透做成我每天离不开的工具</h1>
<blockquote>
<p>用 Rust 从零写的公网穿透工具。一根公网端口承载所有本地服务，CLI 能跑、Flutter UI 也能跑，部署还能让 AI Agent 帮你搞定。</p>
</blockquote>
<h2>pb-mapper 是什么</h2>
<p><a href="https://github.com/acking-you/pb-mapper" rel="noopener noreferrer">pb-mapper</a> 是我自己写的一套 TCP/UDP 公网穿透系统。</p>
<p>跟 frp 那种"一个服务占一个端口"的思路不同，pb-mapper 所有本地服务共用同一个公网端口，靠一个 <strong>service key</strong> 做注册和订阅。公网侧跑一个 <code>pb-mapper-server</code> 当会合点，维护服务注册表，负责双向流转发。</p>
<p>说人话就是：家里的网盘、编译机、UDP 游戏房、博客后端……想暴露几个就暴露几个，VPS 上只开 <code>7666</code> 一个端口，不用每加一个服务就去防火墙多放一行规则。</p>
<pre><code>                 家里内网                         公网 VPS                      任意远端
┌──────────────────────────────┐    ┌─────────────────────────┐    ┌─────────────────────────────┐
│                              │    │                         │    │                             │
│  SSH :22 ──┐                 │    │                         │    │         用户 App            │
│            │                 │    │                         │    │            │                │
│  Web :8080 ┼─► server-cli ──┼───►│   pb-mapper-server      │◄───┼── client-cli / Flutter UI   │
│            │                 │    │        :7666            │    │            │                │
│  UDP :8211 ┘                 │    │                         │    │       本地监听端口          │
│                              │    │                         │    │                             │
└──────────────────────────────┘    └─────────────────────────┘    └─────────────────────────────┘
         注册 service key ──────────────────►  ◄──────────────────────── 订阅 service key
</code></pre>
<h2>技术栈</h2>
<ul>
<li><strong>语言和运行时</strong>：Rust 2021 + Tokio 异步运行时</li>
<li><strong>内存分配器</strong>：自己 fork 的 <a href="https://github.com/acking-you/better_mimalloc_rs" rel="noopener noreferrer"><code>better_mimalloc_rs</code></a>，后面会细说为什么</li>
<li><strong>网络抽象</strong>：自研 <a href="https://github.com/acking-you/uni-stream" rel="noopener noreferrer"><code>uni-stream</code></a>，把 TCP 和 UDP 统一成一套流接口；底层用 <code>socket2</code> 控制 socket 选项，<code>trust-dns-resolver</code> 做 DNS</li>
<li><strong>协议</strong>：serde_json 序列化，自定义帧格式（checksum + 长度头），可选 <code>ring</code> 做 AES-256-GCM 端到端加密</li>
<li><strong>连接管理</strong>：V2 控制连接池 + 租约机制，不会因为一次 heartbeat 丢失就误判断开</li>
<li><strong>GUI</strong>：Flutter 前端，Rust 后端通过纯 C ABI FFI 暴露接口，<code>cdylib</code> + <code>staticlib</code> 双产物覆盖 Android/iOS/桌面</li>
</ul>
<h3>为什么 FFI 而不是跨语言框架</h3>
<p>最早 UI 用的是 Rinf（一个 signal-based 的 Rust↔Flutter 桥接框架），用起来确实方便，但产物体积大、冷启动慢。后来索性切到裸 FFI——<a href="https://github.com/acking-you/pb-mapper/blob/master/ui/native/pb_mapper_ffi/src/lib.rs#L14" rel="noopener noreferrer"><code>pb_mapper_ffi</code></a> 直接暴露一组 C 函数，Flutter 侧 <code>dart:ffi</code> 调过来。APK 瘦了、启动快了、调试也直观了，代价是得自己管 handle 生命周期和 JSON 的跨语言编解码——但对我来说这点工作量完全可接受（毕竟 cc 承担了一切）。</p>
<h3>为什么要自己 fork mimalloc</h3>
<p>这事儿是被线上问题逼出来的。</p>
<p>社区最活跃的那个 mimalloc Rust 封装（<code>mimalloc</code> crate），上游 mimalloc 的很多配置接口（<code>mi_option_set_*</code> 那一整套）压根没暴露到 Rust 层。更要命的是默认配置下 mimalloc 的内存回收策略非常懒——对短生命周期的程序无所谓，但对 pb-mapper 这种 7×24 挂机的服务进程就很不友好了。我在线上观察到的现象是：开了 mimalloc 之后进程 RSS 只涨不降，本来想省内存结果反而吃得更多。</p>
<p>所以我 fork 了一份，把需要的 option 全暴露出来，加了个 <code>config</code> feature，让你在声明 <code>#[global_allocator]</code> 的时候就能把 purge 策略、decommit 超时这些参数调成更积极的值。现在 pb-mapper 在我家服务器上长期挂机，RSS 一直稳定在一个很窄的区间，这个 allocator 层功不可没。</p>
<h2>怎么用</h2>
<p>公网服务端（<code>pb-mapper-server</code>）在 VPS 上部署一次，之后家里和外面随便哪台机器都能连。部署方式我留了三条路，挑适合你的就行。</p>
<h3>方式一：AI Agent 一键部署</h3>
<p>如果你在用 Claude Code、Cursor、Kiro 这类带 agent 能力的工具，仓库里自带两个部署 skill：</p>
<table>
<thead>
<tr>
<th>Skill</th>
<th>干什么</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>/pb-mapper-server-deploy</code></td>
<td>本地下载二进制 → SCP 传到 VPS → 写 systemd unit → 启动</td>
</tr>
<tr>
<td><code>/pb-mapper-client-cli-deploy</code></td>
<td>同样的流程，在任意 Linux 机器上起一条 client 隧道</td>
</tr>
</tbody>
</table>
<p>全程交互式，会问你 SSH 信息、端口、加密 key。GitHub 下载不通的话会自动走代理兜底，远程主机不需要能访问 GitHub。</p>
<h3>方式二：一条命令</h3>
<p>VPS 能直连 GitHub 的话：</p>
<pre><code>curl -fsSL https://raw.githubusercontent.com/acking-you/pb-mapper/master/scripts/install-server-github.sh | bash
</code></pre>
<p>装完默认监听 <code>7666</code>，开启 <code>--use-machine-msg-header-key</code>，密钥写到 <code>/var/lib/pb-mapper-server/msg_header_key</code>。client 侧 <code>export MSG_HEADER_KEY="$(cat /var/lib/pb-mapper-server/msg_header_key)"</code> 就能对上。</p>
<h3>方式三：手动跑 CLI 或者用 Flutter UI</h3>
<p>三个二进制，名字就是功能：</p>
<ul>
<li><code>pb-mapper-server</code>：公网中继</li>
<li><code>pb-mapper-server-cli</code>：跑在本地服务那一侧，把 <code>127.0.0.1:xxx</code> 注册成一个 service key</li>
<li><code>pb-mapper-client-cli</code>：跑在使用方那一侧，订阅 service key，在本地开一个监听端口</li>
</ul>
<p>举个例子——从咖啡店访问家里 <code>localhost:8080</code> 的 web 服务：</p>
<pre><code># VPS 上
pb-mapper-server --port 7666

# 家里
pb-mapper-server-cli --server &lt;vps-ip&gt;:7666 --key web --local 127.0.0.1:8080

# 咖啡店
pb-mapper-client-cli --server &lt;vps-ip&gt;:7666 --key web --local 127.0.0.1:3000
# 浏览器打开 http://localhost:3000 就能访问家里的 web 服务了
</code></pre>
<p>不想敲命令的话，<code>ui/</code> 目录下有完整的 Flutter 界面，启停服务端、注册订阅、实时状态、配置管理、日志查看全都有，桌面和手机都能跑。</p>
<h2>这个项目怎么来的</h2>
<p>时间回到两年多前，我还在读本科、写毕设。</p>
<p>那会儿人在学校，但真正要跑编译、跑模型的时候得用家里的台式机。第一反应是自部署 RustDesk，结果体验很糟糕——带 UI 的远程桌面在校园网下卡得不行，而我 90% 的场景其实只需要一个 SSH 终端，根本用不着图形界面。</p>
<p>于是转向公网穿透方案。frp 是第一个试的，用了一段时间之后几个问题一直让我不舒服：</p>
<ol>
<li>每加一个服务就要改配置、多开一个端口，管理成本随服务数量线性增长</li>
<li>控制连接的断开判定太粗暴，heartbeat 丢一次就整条流断掉，家用网络稍微波动一下就得重连</li>
<li>资源占用对一台长期挂着的小机器来说不算轻</li>
</ol>
<p>想了想，干脆自己写一个。我脑子里的理想形态很清楚：<strong>一个公网端口、一个 service key 注册表、控制连接用租约而不是心跳超时、TCP 和 UDP 共用同一套流抽象</strong>。pb-mapper 的第一版就是这么来的。</p>
<p>之后两年多，它一直在被各种真实场景捶打。控制连接的租约逻辑改了好几轮（<a href="https://github.com/acking-you/pb-mapper/commit/81ebe63" rel="noopener noreferrer"><code>81ebe63</code></a>、<a href="https://github.com/acking-you/pb-mapper/commit/82659fc" rel="noopener noreferrer"><code>82659fc</code></a>、<a href="https://github.com/acking-you/pb-mapper/commit/367bddd" rel="noopener noreferrer"><code>367bddd</code></a> 这几个 commit 都是相关修复），UDP datagram 转发的边界情况也踩过不少坑（专门写了一篇 <a href="https://github.com/acking-you/pb-mapper/blob/master/docs/udp-datagram-forwarding.md" rel="noopener noreferrer">复盘</a>）。每修一次，它就更稳一层。</p>
<p>到今天，它已经是我日常开发离不开的基础设施了。</p>
<h2>实际跑了些什么</h2>
<p>几个真实场景：</p>
<ul>
<li><strong>幻兽帕鲁</strong>——火的那阵子，我把家里 Palworld 服务端的 UDP 8211 映射出去，和朋友们联机了好几周。延迟体感跟 frp 直映端口差不多。</li>
<li><strong><a href="https://acking-you.github.io" rel="noopener noreferrer">StaticFlow</a></strong>——我自己基于 LanceDB 写的个人内容平台（带一个"许愿入库"的 agent 工具），跑在家里的服务器上，通过 pb-mapper 把后端 API 映射到公网，已经稳定运行三四个月了。</li>
<li><strong>日常开发</strong>——SSH、远程 VSCode、临时给朋友开个 HTTP 文件服务……全走同一个公网 <code>:7666</code> 端口。</li>
</ul>
<p>性能方面，内存和 CPU 的资源消耗比 frp 更优——这点在长期挂机的场景下体感很明显。在保证单端口复用的服务注册订阅逻辑的前提下，转发延迟也没比 frp 那种一对一端口直映的方案差。如果你在意的是"一个进程能不能轻量地同时扛很多条隧道"，它应该能打。</p>
<h2>链接</h2>
<ul>
<li>仓库：https://github.com/acking-you/pb-mapper</li>
<li>用户手册：https://github.com/acking-you/pb-mapper/blob/master/docs/user-guide.zh-CN.md</li>
<li>Docker 部署：https://github.com/acking-you/pb-mapper/blob/master/DOCKER_README.md</li>
<li>UDP 转发原理：https://github.com/acking-you/pb-mapper/blob/master/docs/udp-datagram-forwarding.md</li>
</ul>
<p>有问题欢迎提 issue，两年多的打磨还在继续。</p>
]]></description><pubDate>2026-05-08 12:16:57</pubDate></item><item><title>Warp-parse 0.22 版本发布</title><link>https://rustcc.cn/article?id=5f215bb4-c76f-4fb6-aa8c-96eaae97de38</link><description><![CDATA[<h1>WarpParse 0.22</h1>
<p>亲爱的用户们，</p>
<p>我们很高兴地宣布 WarpParse 0.22 版本发布！本次更新主要聚焦于 <strong>运行时可运维性、远端工程同步、知识库能力补强，以及监控与规则体验增强</strong>。</p>
<h2>本次更新亮点</h2>
<ul>
<li>运行时管理面能力补齐，支持标准化状态查询与重载。</li>
<li>远端工程初始化、更新、热重载路径进一步统一。</li>
<li>知识库、WPL 与监控链路文档更加完整，正式使用路径更清晰。</li>
</ul>
<h2>Added</h2>
<h3>运行时管理面</h3>
<p>新增围绕在线实例的标准化运维入口：</p>
<ul>
<li><code>POST /admin/v1/reloads/model</code></li>
<li><code>wproj engine reload</code></li>
</ul>
<h3>远端同步与热更新</h3>
<p>围绕远端规则仓库，当前已经形成较完整的运维路径：</p>
<ol>
<li><code>wproj init --repo &lt;REPO&gt; [--version &lt;VERSION&gt;]</code></li>
<li><code>wproj conf update</code></li>
<li><code>wproj engine reload</code></li>
</ol>
<h3>自更新能力</h3>
<p>新增 CLI 自更新使用路径：</p>
<pre><code>wproj self check
wproj self update --yes
</code></pre>
<h3>支持远程数据库</h3>
<p>知识库当前已支持通过 <code>[provider]</code> 接入远程 PostgreSQL / MySQL：</p>
<ul>
<li>支持目录式 SQLite authority 与远程数据库二选一</li>
<li>支持通过 <code>connection_uri</code> 接入 PostgreSQL / MySQL</li>
<li><code>[cache]</code> 统一用于结果缓存配置</li>
</ul>
<h3>监控与链路观察</h3>
<p>配合 VictoriaMetrics、VictoriaLogs 与 Wp-Monitor，当前已经形成更完整的链路观察入口，可用于查看：</p>
<ul>
<li>链路是否正常处理数据</li>
<li>MISS 数据是否异常</li>
<li>下游输出是否波动</li>
</ul>
<p><a href="https://docs.warpparse.ai/zh/00-release/0.22.html" rel="noopener noreferrer">发布说明</a></p>
<p><a href="https://github.com/wp-labs" rel="noopener noreferrer">github</a></p>
]]></description><pubDate>2026-05-08 06:29:32</pubDate></item><item><title>【Rust日报】2026-05-08 Burn 0.21.0 发布：框架开销降低最高达8倍</title><link>https://rustcc.cn/article?id=38d8c972-78a1-4e80-8dab-d48d62ede8f7</link><description><![CDATA[<h2>Burn 0.21.0 发布：框架开销降低最高达8倍</h2>
<p>Burn 0.21.0 带来了一轮比较扎实的性能与可靠性更新，覆盖分布式训练、后端调度、CPU 后端和内核调优等多个方向。对关注 Rust AI / ML 框架的人来说，这次更新信息量不小。</p>
<ul>
<li><strong>分布式训练提速明显</strong>：基于可微分集合操作重做分布式计算架构，在 4 张 CUDA GPU 上，设备传输速度提升 16-21 倍，<code>all_reduce</code> 速度提升约 6 倍</li>
<li><strong>框架开销继续下压</strong>：重构设备句柄，官方给出的结论是部分场景下框架开销最高可下降 8 倍</li>
<li><strong>内核可靠性增强</strong>：改进自动调优和微基准测试策略，并加入 CubeCL 内核验证层，用于识别越界内存访问等问题</li>
<li><strong>工程化能力更完整</strong>：新增 <code>burn.toml</code> 项目级配置文件，引入 <code>burn-dispatch</code> crate，同时推出面向 WebAssembly / 嵌入式目标的轻量 CPU 后端 Burn Flex</li>
</ul>
<p>原文链接：https://burn.dev/blog/release-0.21.0/</p>
<h2>CUDA-Oxide：用纯 Rust 编写 GPU 内核的编译器后端</h2>
<p>CUDA-Oxide 是 NVlabs 放出的实验性项目，目标是把“用纯 Rust 写 CUDA 内核”这件事做成一条完整编译链，而不是再包一层 DSL 或外部语言绑定。</p>
<ul>
<li><strong>单源代码工作流</strong>：主机端与设备端代码可以放在同一份 Rust 源文件里，通过 <code>cargo oxide build</code> 一次构建</li>
<li><strong>直接走 Rust 编译后端路线</strong>：把带 <code>#[kernel]</code> 标注的函数编译为 PTX，编译流程为 Rust → MIR → Pliron IR → LLVM IR → PTX</li>
<li><strong>设备端抽象比较完整</strong>：覆盖共享内存、原子操作、屏障、warp / cluster 等 CUDA 常见能力</li>
<li><strong>异步模型也在考虑范围内</strong>：支持返回惰性 <code>DeviceOperation</code>，既能 <code>.sync()</code> 也能 <code>.await</code></li>
</ul>
<p>虽然项目目前还是 Alpha 阶段，但如果你关心 Rust 在 GPU 编程上的边界，这个方向很值得继续盯。</p>
<p>原文链接：https://github.com/NVlabs/cuda-oxide</p>
<h2>servo-fetch：将 Servo 浏览器引擎嵌入为库</h2>
<p>servo-fetch 想解决的是另一类很现实的问题：很多抓取、提取和网页理解任务，其实并不想背着一整个 Chrome 进程跑。这个项目把 Servo 浏览器引擎直接嵌进 Rust 库和 CLI 里，走的是更轻、更原生的路线。</p>
<ul>
<li><strong>进程内完成抓取与渲染</strong>：支持抓 URL、执行 JavaScript、计算 CSS 布局，并提取干净的 Markdown 内容</li>
<li><strong>资源占用更克制</strong>：相较常见的无头 Chrome / Playwright 方案，项目重点强调更低的运行时开销和更简单的部署结构</li>
<li><strong>适合代理和自动化场景</strong>：对 AI 代理、网页采集、内容提取工具链都很友好</li>
<li><strong>项目仍处早期</strong>：当前版本为 v0.8.1，1.0 之前 API 仍可能继续调整</li>
</ul>
<p>如果 Servo 生态后面能把这条链路继续磨顺，Rust 原生网页抓取这块会更有意思。</p>
<p>原文链接：https://github.com/konippi/servo-fetch</p>
<h2>Rust 最快的哈希表？ProbeMap</h2>
<p>ProbeMap 是一个基于 SwissTable 思路实现的哈希表项目，主打“稳定版 Rust + 直接 SIMD 指令 + 更激进的性能表现”。</p>
<ul>
<li><strong>直接使用 SSE2 SIMD 指令</strong>：在 x86_64 上走直接 intrinsics，其他架构则回退到标量实现</li>
<li><strong>针对查找与插删场景优化明显</strong>：项目给出的基准里，随机查找提升约 31%，顺序查找提升约 34%，插入删除提升约 35%</li>
<li><strong>接口设计也考虑工程实用性</strong>：支持自定义分配器、可插拔哈希器，以及“键嵌在值里”的 KeyExtract 模式</li>
<li><strong>目标不是花哨，而是更扁平的数据路径</strong>：作者把性能优势主要归因于单态化比较、更前向的槽位布局和更轻的结构抽象</li>
</ul>
<p>它现在还很新，但如果后续 benchmark 和真实 workload 都能站住脚，值得继续观察。</p>
<p>原文链接：https://github.com/NikoMalik/probemap</p>
]]></description><pubDate>2026-05-08 01:09:13</pubDate></item><item><title>Locus —— 开源Unity开发智能体</title><link>https://rustcc.cn/article?id=e3054d1f-2542-4a60-a78e-07ab3a8fdbb8</link><description><![CDATA[<p>我们开源了我们自己在使用的Unity开发Agent —— Locus for Unity。
介绍视频：https://www.bilibili.com/video/BV1H4ReBNELD
项目地址：https://github.com/r1n7aro/Locus</p>
<p>它能够：
· 编写C#代码，渐进式读入并修改Unity场景与资产，完成完整编辑器工具或者玩法功能开发流程
· 不需要自行插入Debug.Log打印数据调试，它可以编写脚本通过反射直接获取运行时状态，自行连接并分析Profiler数据
· 自主地把对话需求总结成设计文档，并且将完成任务时的项目理解保存在长期记忆中
· 进行可视化版本管理，支持Unity YAML资产的语义化差异分析与冲突处理
· 模型订阅帐号登录使用，并兼容多种LLM API格式</p>
<p>如果您有任何功能建议或 Bug 反馈，欢迎在仓库提交 Issue，或者发送邮件至open@farlocus.com
希望能够帮到在做游戏的大家！</p>
]]></description><pubDate>2026-05-07 14:49:52</pubDate></item><item><title>我写了个Rust网络管理daemon -- nipart</title><link>https://rustcc.cn/article?id=17da253f-bf86-40e5-b881-8bdfb87e4af1</link><description><![CDATA[<p><a href="https://github.com/nispor/nipart" rel="noopener noreferrer">https://github.com/nispor/nipart</a>
文档：<a href="https://nispor.github.io/nipart/" rel="noopener noreferrer">https://nispor.github.io/nipart/</a></p>
<p>NetworkManager太笨重了，用Rust写了个替代的。</p>
<p>内核通讯是rust-netlink，wifi基于wpa_supplicant DBUS API，
DHCP用mozim, YAML API改了一点点nmstate schema.</p>
<p>支持no-daemon模式，配置静态IP的WIFI 可以用:</p>
<pre><code>echo '
version: 1
routes:
  config:
  - destination: 0.0.0.0/0
    next-hop-interface: wlan0
    next-hop-address: 192.0.2.1
    metric: 100
interfaces:
- name: wlan0
  type: wifi-phy
  state: up
  mtu: 1492
  ipv4:
    enabled: true
    dhcp: false
    address:
    - ip: 192.0.2.99
      prefix-length: 24
  wifi:
    ssid: Test-WIFI
    password: your_password!
' | sudo npt apply - --no-daemon

</code></pre>
<p>用了一个多月了，还算稳定，但项目还比较早期，多包涵。</p>
]]></description><pubDate>2026-05-07 13:41:13</pubDate></item><item><title>【Rust日报】2026-05-07 404 Privacy - 浏览器指纹保护工具</title><link>https://rustcc.cn/article?id=309311be-6598-4a5d-9117-718791fe4f22</link><description><![CDATA[<h2>404 Privacy - 浏览器指纹保护工具</h2>
<p>404 Privacy 是一款面向高风险场景的浏览器隐私保护工具，目标是阻止网站通过浏览器指纹持续追踪用户。</p>
<ul>
<li><strong>覆盖面广</strong>：可拦截浏览器、设备、操作系统、语言、屏幕尺寸、时区、Canvas、WebGL 等多类指纹信号</li>
<li><strong>本地运行</strong>：以本地代理方式工作，不依赖云端服务</li>
<li><strong>开源可审计</strong>：采用 AGPL 许可证，代码可验证</li>
<li><strong>适用人群明确</strong>：记者、律师、研究机构与人权组织等更关注操作隐私的用户都能直接受益</li>
</ul>
<p>它的核心思路不是单点屏蔽，而是重写 TLS、HTTP、JavaScript 与 TCP/IP 等层面暴露出来的识别特征，并让同一会话中的配置保持一致，降低跨会话关联的可能性。</p>
<p>原文链接：https://404privacy.com/</p>
<h2>Aralez - 基于 Cloudflare Pingora 构建的反向代理</h2>
<p>Aralez 是一个基于 Cloudflare Pingora 引擎构建的 Rust 反向代理，主打高性能、零配置协议处理，以及适合现代基础设施场景的动态路由能力。</p>
<ul>
<li><strong>协议与 TLS 处理自动化</strong>：支持自动检测上游 TLS、WebSocket 与 gRPC 场景，减少手工配置</li>
<li><strong>动态更新能力强</strong>：可通过 API 实时更新上游配置，也支持配置热重载</li>
<li><strong>基础设施友好</strong>：集成 Consul 与 Kubernetes，适合作为轻量级 Ingress 或内部网关</li>
<li><strong>内置常用能力</strong>：提供认证、限流、负载均衡、健康检查、会话保持等能力</li>
</ul>
<p>如果你最近正好在看 Rust 网关、边缘代理或自建入口层，这个项目值得留意。</p>
<p>原文链接：https://github.com/sadoyan/aralez</p>
<h2>Redox OS 2026年4月月报</h2>
<p>Redox OS 公布了 2026 年 4 月月报，更新量相当扎实，重点仍然围绕系统可用性、硬件兼容性和基础组件完善展开。</p>
<ul>
<li><strong>实体硬件启动继续改善</strong>：修复长期回归问题，缩短多核机器启动时间</li>
<li><strong>RISC-V 兼容性提升</strong>：围绕 Sv39 MMU 与引导方案继续推进</li>
<li><strong>用户态体验更完整</strong>：tmux 已成功移植到 Redox</li>
<li><strong>图形性能优化</strong>：Orbital 开始支持部分窗口像素更新，减少整窗重绘开销</li>
<li><strong>生态建设推进</strong>：Cookbook Web 模式启用后，软件包搜索与分发体验更清晰</li>
</ul>
<p>对长期关注 Rust 操作系统生态的人来说，这类月报比单点发布更能反映项目真实推进速度。</p>
<p>原文链接：https://www.redox-os.org/news/this-month-260430/</p>
<h2>Splashboard - 基于 Rust 的终端启动界面工具</h2>
<p>Splashboard 是一个在 shell 启动或执行 <code>cd</code> 时渲染启动画面的 TUI 工具，主打“按目录自动切换”的终端首页体验。</p>
<ul>
<li><strong>按项目自动发现配置</strong>：向上查找 <code>.splashboard/dashboard.toml</code>，不同代码仓库可以拥有各自的启动面板</li>
<li><strong>组件体系完整</strong>：已经提供约 30 个数据获取器与 20 个渲染器</li>
<li><strong>设计思路清晰</strong>：采用 <code>Fetcher × Renderer × Shape</code> 三层模型组织能力</li>
<li><strong>安全边界明确</strong>：按组件粒度做信任控制，文件变更后会自动撤销对应信任</li>
</ul>
<p>它不是简单的“终端美化”，而是把项目上下文、状态信息和仪表板能力，做成了一个偏工程化的可配置入口页。</p>
<p>原文链接：https://www.reddit.com/r/rust/comments/1t5j9go/splashboard_a_perdirectory_terminal_splash_in_rust/</p>
]]></description><pubDate>2026-05-07 01:08:48</pubDate></item><item><title>求职 </title><link>https://rustcc.cn/article?id=4f5b5be7-3bc4-4b3a-b47d-64b6a84ec3ef</link><description><![CDATA[<p>求职信息｜后端工程师</p>
<p>大家好，很尴尬今年又在这个时候求职，我目前在深圳刚失业，接受上海深圳机会，月内到岗。
本科计算机科学与技术，约 3 年后端研发经验(两年左右的主要 rust 开发），去年开始结合 ai 开发的经历多，会使用 ai review code 提高代码质量。
主要使用 Go / Rust，有中台系统与业务服务端的落地经验，参与过物联网与设备管理等方向的后端建设，具备从需求分析到上线迭代的完整工程实践能力。</p>
<p>开源贡献：是 Zinx（7.2k stars）开发者之一
给Rust Axum（25.8k stars）框架贡献过模块的 pr 也已合并</p>
<p>如果有机会可联系，邮箱：y1185535289@outlook.com
个人 GitHub：https://github.com/YanHeDoki</p>
]]></description><pubDate>2026-05-06 05:31:55</pubDate></item><item><title>【Rust日报】2026-05-06 Sqlitex 0.3.0 - 具有编译时保证的 SQLite 库</title><link>https://rustcc.cn/article?id=463e7aee-84b0-40d8-bca8-b93eeacf90e3</link><description><![CDATA[<h2>Sqlitex 0.3.0 - 具有编译时保证的 SQLite 库</h2>
<ul>
<li><strong>项目更名</strong>：原名 Lazysql，现已更名为 Sqlitex</li>
<li><strong>定位</strong>：一个面向 Rust 的 SQLite 库，强调简单但足够强大</li>
<li><strong>核心特性</strong>：
<ul>
<li>编译阶段即可验证查询与类型，减少运行时踩坑</li>
<li>提供更友好的 IDE 支持，开发体验更顺手</li>
<li>自动缓存和复用预编译语句，并自动应用优化过的 PRAGMA 配置</li>
</ul>
</li>
<li><strong>补充信息</strong>：作者还专门整理了与 sqlx 的对比页面，方便开发者评估取舍</li>
</ul>
<p>原文链接：https://www.reddit.com/r/rust/comments/1t4a6n2/sqlitex_030_a_sqlite_library_with_compile_time/</p>
<h2>v0.7.5 版本发布 - 就地操作更新</h2>
<p>这是 hi_sparse_bitset 项目的 v0.7.5 版本更新，重点放在就地操作与物化性能改进。</p>
<ul>
<li><strong>物化性能改进</strong>：继续优化 BitSet 的 materialization 流程</li>
<li><strong>新增就地操作</strong>：
<ul>
<li><code>BitSet::unite</code></li>
<li><code>BitSet::into_union</code></li>
<li><code>BitSet::intersect</code></li>
<li><code>BitSet::into_intersection</code></li>
<li><code>BitSet::mem_info</code></li>
</ul>
</li>
<li><strong>补齐运算符实现</strong>：加入按位与 / 按位或相关实现，方便直接在集合运算场景里使用</li>
<li><strong>接口层补充</strong>：<code>BitSetInterface</code> 也增加了命名形式的并集、交集操作</li>
</ul>
<p>原文链接：https://github.com/tower120/hi_sparse_bitset/releases/tag/v0.7.5</p>
<h2>tracing-systemd 0.2.1 发布</h2>
<p><code>tracing-systemd</code> 是一个面向 Rust <code>tracing-subscriber</code> 生态的日志层库，主打更好读的 span chain 输出，以及更顺手的 systemd journal 集成。</p>
<ul>
<li><strong>为什么做</strong>：作者认为现有的 tracing-journald 缺少一些实际项目常用能力，比如格式化与更合适的日志级别过滤</li>
<li><strong>当前进展</strong>：项目已有约 2300 次下载，这次更新把它继续往可用性方向推进</li>
<li><strong>适用场景</strong>：
<ul>
<li>在 systemd 单元环境下输出更清晰的日志</li>
<li>需要 stdout / journald / JSON 等多种日志落点时更灵活</li>
</ul>
</li>
<li><strong>相关资源</strong>：项目同时提供 GitHub 仓库与 docs.rs 文档，方便直接上手</li>
</ul>
<p>原文链接：https://github.com/ziidonato/tracing-systemd</p>
<h2>Netbump - Linux 网络带宽限制工具</h2>
<p>Netbump 是一个面向 Linux 终端用户的带宽限制工具，目标是把“限速某个进程 / socket / cgroup”这类操作做得更直接。</p>
<ul>
<li><strong>可限制对象</strong>：
<ul>
<li>已存在的本地 socket（ip:port）</li>
<li>指定 PID 的进程，可选是否包含子进程</li>
<li>准备启动的命令</li>
<li>cgroup v2</li>
</ul>
</li>
<li><strong>规则管理能力</strong>：支持新增、查看、更新、删除规则，也能调整上传 / 下载限速与所用网卡</li>
<li><strong>实现方式</strong>：
<ul>
<li>采用客户端 / 服务器架构，通过 Unix socket 通信</li>
<li>借助 eBPF 标记目标流量，再由 Linux 内核侧完成实际限速</li>
<li>使用 SQLite 记录修改，方便异常退出后清理状态</li>
</ul>
</li>
<li><strong>系统要求</strong>：需要 Linux 具备 eBPF、流量整形、IFB、netlink 等相关能力</li>
</ul>
<p>原文链接：https://codeberg.org/gonbalf/netbump</p>
]]></description><pubDate>2026-05-06 01:07:29</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><item><title>RustDesk 招聘 Rust 开发 （SaaS)</title><link>https://rustcc.cn/article?id=665bacac-c297-4246-831b-9e598b53fe51</link><description><![CDATA[<p>谢谢社区的照顾，<a href="https://github.com/rustdesk/rustdesk" rel="noopener noreferrer">RustDesk</a> 一路成长，在发展开源的同时，我们也在努力推进商业化。</p>
<p>我们是一个纯远程团队，偏向能力全面的万精油选手。</p>
<p>现招聘一位主攻 SaaS 方向的 Rust 程序员。</p>
<p>你的主要工作：</p>
<ul>
<li>设计并实现 RustDesk SaaS 平台的核心服务（用户管理、计费、多租户等）</li>
<li>优化高并发场景下的系统性能</li>
<li>深度调优数据库（PostgreSQL）、缓存（Redis）、消息队列（Kafka/RabbitMQ）</li>
<li>在 AWS 上构建和维护基于 Kubernetes 的稳定部署架构（含 NLB、Auto Scaling 等）</li>
<li>用 Rust 编写高性能、低延迟的服务组件（已有大量 Rust 代码基础）</li>
</ul>
<p>我们希望你：</p>
<ul>
<li>有 3 年以上生产环境高并发系统开发经验（请附上你优化过的系统指标，如 QPS/延迟/错误率）</li>
<li>深度使用过至少两项：PostgreSQL 性能调优、Redis 高可用架构、Kafka 消息积压处理、K8s/K3s 在 AWS 上的生产部署</li>
<li>有 Rust 实战经验（非 toy project，需能直接参与核心模块开发）</li>
<li>能独立设计技术方案，并对线上系统稳定性负责</li>
<li>英语可读写（需查阅 AWS/K8s 官方文档）</li>
</ul>
<p>为什么加入我们？</p>
<ul>
<li>知名开源项目</li>
<li>真实盈利：无需担心现金流，专注技术本身</li>
<li>小团队高影响力：你的代码直接决定产品走向</li>
<li>远程友好</li>
<li>技术栈纯粹：Rust + PostgreSQL + Redis + K8s + AWS，无历史包袱</li>
</ul>
<p>请发送简历至：am9ic0BydXN0ZGVzay5jb20=</p>
]]></description><pubDate>2025-10-31 04:22:02</pubDate></item></channel></rss>