<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>【Rust日报】2026-04-18 Ironpress - 纯 Rust HTML/CSS/Markdown 转 PDF 工具</title><link>https://rustcc.cn/article?id=a5c6eaa9-3dd2-4b8b-a31d-0d7a49a123d6</link><description><![CDATA[<h2>Rust 1.95.0 发布公告</h2>
<p>Rust 团队于 2026 年 4 月 16 日宣布发布 Rust 1.95.0 版本。</p>
<h3>主要新特性</h3>
<ul>
<li>
<p><strong><code>cfg_select!</code> 宏</strong></p>
<ul>
<li>引入了新的 <code>cfg_select!</code> 宏，类似于编译时的 <code>match</code> 配置语句</li>
<li>功能与流行的 <code>cfg-if</code> crate 相似，但语法不同</li>
<li>会展开为第一个配置条件为真的分支内容</li>
<li>可用于根据不同平台或配置选择不同的代码实现</li>
</ul>
</li>
<li>
<p><strong><code>match</code> 表达式中的 <code>if-let</code> 守卫</strong></p>
<ul>
<li>Rust 1.88 稳定了 let 链式语法</li>
<li>Rust 1.95 将这个能力引入 <code>match</code> 表达式</li>
<li>允许基于模式匹配的条件判断</li>
<li>注意：编译器目前不会将 <code>if let</code> 守卫中的模式视为整体 <code>match</code> 穷尽性评估的一部分</li>
</ul>
</li>
</ul>
<h3>稳定化的 API</h3>
<ul>
<li><code>MaybeUninit</code> 相关的多个转换和引用方法</li>
<li><code>Cell</code> 类型的引用转换方法</li>
<li><code>bool</code> 类型可以从整数类型进行 <code>TryFrom</code> 转换</li>
<li>原子类型的 <code>update</code> 和 <code>try_update</code> 方法</li>
<li>指针类型的 <code>as_ref_unchecked</code> 和 <code>as_mut_unchecked</code> 方法</li>
<li>集合类型的 <code>push_mut</code> 和 <code>insert_mut</code> 方法</li>
<li><code>Layout</code> 类型的多个新方法</li>
<li>多个 API 现在支持在 const 上下文中使用</li>
</ul>
<h3>其他变更</h3>
<ul>
<li><strong>取消稳定的功能</strong>
<ul>
<li>移除了稳定版对向 rustc 传递自定义目标规范 JSON 的支持</li>
<li>不应影响使用完全稳定工具链的用户</li>
<li>团队正在收集自定义目标的使用案例</li>
</ul>
</li>
</ul>
<p><a href="https://blog.rust-lang.org/2026/04/16/Rust-1.95.0/" rel="noopener noreferrer">Rust 1.95.0 发布公告</a></p>
<h2>Ironpress - 纯 Rust HTML/CSS/Markdown 转 PDF 工具</h2>
<p>Ironpress 是一个纯 Rust 编写的 HTML/CSS/Markdown 到 PDF 转换器，无需浏览器和系统依赖。</p>
<h3>核心特点</h3>
<ul>
<li><strong>极致性能</strong>：比 Chrome headless 快 4,000 倍
<ul>
<li>简单 HTML：16 微秒/页（62,500 页/秒）</li>
<li>样式化 HTML：71 微秒/页（14,000 页/秒）</li>
<li>Markdown：141 微秒/页（7,000 页/秒）</li>
<li>表格：341 微秒/页（2,900 页/秒）</li>
<li>完整报告：587 微秒/页（1,700 页/秒）</li>
</ul>
</li>
</ul>
<h3>主要功能</h3>
<ul>
<li><strong>HTML 支持</strong>：50+ 元素（标题、表格、列表、表单、媒体、图片、内联 SVG）</li>
<li><strong>CSS 引擎</strong>：支持 Flexbox、Grid、多列布局、calc()、CSS 变量、@media、@page、@font-face</li>
<li><strong>字体系统</strong>：
<ul>
<li>基础 PDF 字体</li>
<li>自定义 TTF 字体嵌入和子集化</li>
<li>系统字体发现</li>
<li>Unicode/CJK 字体回退</li>
</ul>
</li>
<li><strong>数学公式</strong>：通过 <code>$...$</code> 和 <code>$$...$$</code> 支持 LaTeX 语法</li>
<li><strong>SVG 渲染</strong>：路径、形状、渐变、变换、裁剪路径</li>
<li><strong>图片支持</strong>：JPEG、PNG、数据 URI、本地文件、远程 URL</li>
<li><strong>PDF 输出</strong>：PDF 1.4、书签、链接注释、页眉页脚、渐变</li>
</ul>
<h3>使用方式</h3>
<ul>
<li><strong>Rust API</strong>：简单的函数调用和构建器模式</li>
<li><strong>命令行工具</strong>：通过 cargo 安装使用</li>
<li><strong>多语言绑定</strong>：Python、Ruby</li>
<li><strong>WebAssembly</strong>：100% 浏览器端运行</li>
<li><strong>安全性</strong>：默认对 HTML 进行清理</li>
</ul>
<h3>质量保证</h3>
<ul>
<li>2200+ 单元测试</li>
<li>基于属性的测试</li>
<li>6 个模糊测试目标</li>
<li>对比测试仪表板</li>
</ul>
<p><a href="https://old.reddit.com/r/rust/comments/1sp7q0m/ironpress_pure_rust_htmlcssmarkdown_to_pdf/" rel="noopener noreferrer">Ironpress - 纯 Rust HTML/CSS/Markdown 转 PDF 工具</a></p>
<h2>ndatafusion：为 DataFusion 提供线性代数和机器学习能力</h2>
<p>作者在 r/rust 社区发布了新项目 <strong>ndatafusion</strong> 🪐</p>
<h3>项目目标</h3>
<ul>
<li>让 Apache DataFusion 成为处理线性代数和机器学习工作负载的更自然平台</li>
<li>通过显式的 Arrow/DataFusion 契约为 DataFusion 引入数值计算能力</li>
</ul>
<h3>技术特点</h3>
<ul>
<li>底层由 <strong>nabled</strong> 驱动（作者开发的另一个用于线性代数/机器学习的 Rust crate）</li>
<li>解决核心问题：当使用 Arrow 和 DataFusion 时，不必在需要向量或矩阵运算时切换到其他生态系统</li>
</ul>
<h3>项目意义</h3>
<ul>
<li>填补了 Rust/DataFusion 生态系统在这一层面的空白</li>
<li>目前该领域缺少直接针对此类需求的解决方案</li>
</ul>
<h3>相关链接</h3>
<ul>
<li>Crates.io: https://crates.io/crates/ndatafusion</li>
<li>文档: https://docs.rs/ndatafusion</li>
<li>GitHub: https://github.com/georgeleepatterson/ndatafusion</li>
</ul>
<h3>反馈征集</h3>
<p>作者特别希望获得以下领域开发者的反馈：</p>
<ul>
<li>Rust 查询引擎</li>
<li>Arrow 原生系统</li>
<li>SQL 扩展</li>
<li>机器学习/数据基础设施</li>
</ul>
<p><a href="https://old.reddit.com/r/rust/comments/1sob6bg/ndatafusion_linear_algebra_and_ml_for_datafusion/" rel="noopener noreferrer">ndatafusion：为 DataFusion 提供线性代数和机器学习能力</a></p>
<h2>Zenoh 1.9.x: Longwang 版本发布</h2>
<p>Zenoh 1.9.x "Longwang"（龙王）版本于2026年4月17日在巴黎发布。该版本以中国神话中掌管海洋、水和天气的龙王命名，象征着其支持日益复杂网络拓扑的能力。</p>
<h3>核心亮点</h3>
<ul>
<li>
<p><strong>Regions（区域）架构</strong></p>
<ul>
<li>突破了传统的三层 router/peer/client 层级限制</li>
<li>支持任意深度的网络拓扑层级结构</li>
<li>可自定义网关关系配置</li>
<li>采用灵活的区域树模型替代固定的路由模型</li>
<li>允许边缘机器人部署将中心节点作为客户端而非路由器连接</li>
</ul>
</li>
<li>
<p><strong>QUIC 传输增强</strong></p>
<ul>
<li><strong>流多路复用</strong>：为每个优先级设置独立的 QUIC 流，消除混合优先级流量中的队头阻塞问题</li>
<li><strong>混合可靠性</strong>：在单个 QUIC 连接上结合可靠流和尽力而为的数据报，优化性能</li>
<li><strong>可靠 UDP</strong>：通过非安全 QUIC 模式提供可靠性和多路复用，无需 TLS 开销，适用于可信环境</li>
</ul>
</li>
<li>
<p><strong>Zenoh-Go 语言绑定</strong></p>
<ul>
<li>官方推出的 Go 语言绑定</li>
<li>符合 Go 语言习惯的 API 设计</li>
<li>首日即提供完整 API 覆盖</li>
</ul>
</li>
<li>
<p><strong>Zenoh-Pico 异步执行器</strong></p>
<ul>
<li>单线程任务执行，降低资源使用</li>
<li>将高级发布-订阅、连接事件、自动重连和点对点模式等功能扩展到单线程环境</li>
</ul>
</li>
<li>
<p><strong>Nuze 0.3.0</strong></p>
<ul>
<li>支持 Zenoh 消息解码</li>
<li>改进了基于 Nu 的 Zenoh CLI 中的匹配监听器命令</li>
</ul>
</li>
</ul>
<h3>重大变更</h3>
<p>版本引入了区域标识符的变更，并对节点绑定关系进行了限制：路由器只能位于其他路由器的南向（该限制在连接建立时强制执行）。除此约束外，用户可以完全自由地设计区域树架构。</p>
<p><a href="https://zenoh.io/blog/2026-04-16-zenoh-longwang/" rel="noopener noreferrer">Zenoh 1.9.x: Longwang 版本发布</a></p>
<p>--</p>
<p>From 日报小组 Mike</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-04-19 00:36:12</pubDate></item><item><title>【Rust日报】2026-04-17 Rust 1.95.0 发布</title><link>https://rustcc.cn/article?id=c68dc39a-5d54-4caf-a89a-0c760c245048</link><description><![CDATA[<h2>Rust 1.95.0 发布</h2>
<p>Rust 团队宣布推出全新版本 Rust 1.95.0。此次版本稳定了一批 API，以及新增 2 个非常使用的功能。</p>
<p><strong>稳定新特性</strong></p>
<p><strong><code>cfg_select!</code> 宏</strong></p>
<p>Rust 1.95 引入了 <code>cfg_select!</code> 宏，其作用近似于编译期针对 cfg 配置的 match 匹配，功能与广受欢迎的 <code>cfg-if</code> 库一致，但语法不同。<code>cfg_select!</code> 会展开执行第一个条件为真的分支右侧代码。</p>
<p>示例代码：</p>
<pre><code>cfg_select! {
    unix =&gt; {
        fn foo() { /* 类Unix系统专属功能 */ }
    }
    target_pointer_width = "32" =&gt; {
        fn foo() { /* 非类Unix、32位系统功能 */ }
    }
    _ =&gt; {
        fn foo() { /* 兜底实现 */ }
    }
}

let is_windows_str = cfg_select! {
    windows =&gt; "windows",
    _ =&gt; "not windows",
};
</code></pre>
<p><strong><code>match</code> 模式中的 <code>if-let</code> 守卫</strong></p>
<p>Rust 1.88 稳定了 <code>let</code> 链式语法，Rust 1.95 将该能力扩展到 <code>match</code> 表达式，支持基于模式匹配的条件判断。</p>
<p>示例代码：</p>
<pre><code>match value {
    Some(x) if let Ok(y) = compute(x) =&gt; {
        // 此处可同时使用 x 和 y
        println!("{}, {}", x, y);
    }
    _ =&gt; {}
}
</code></pre>
<p>原文：https://blog.rust-lang.org/2026/04/16/Rust-1.95.0/</p>
<h2>markdown-reader：一款终端端 Markdown 浏览器，支持内嵌 Mermaid</h2>
<p><img src="https://preview.redd.it/markdown-reader-a-terminal-markdown-browser-with-inline-v0-ylacyzf34nvg1.png?width=1080&amp;crop=smart&amp;auto=webp&amp;s=98682df893f5c7dc8ed3286d6e7c46dc541353f7" alt=""></p>
<p>markdown-reader：一款终端 Markdown 浏览器，支持内嵌 Mermaid、Vim 风格编辑与全项目搜索（Rust/ratatui）。</p>
<p>过去几周，我一直在用 Rust 迭代开发一款终端端 Markdown 阅读器，现在它已经初具雏形，希望能得到大家的体验与反馈。项目核心目标：无需离开终端，即可浏览文件夹内的 Markdown 笔记（调研文档、规格说明、项目文档等），并能直接查看内嵌的 Mermaid 图表与表格。</p>
<pre><code>cargo install markdown-tui-explorer
</code></pre>
<p>安装后二进制文件名为 <code>markdown-reader</code>。</p>
<p><strong>功能特性</strong></p>
<ul>
<li>
<p>遵循 <code>.gitignore</code> 规则浏览 Markdown 文件目录树，文件修改后功能特性</p>
</li>
<li>
<p>遵循 <code>.gitignore</code> 规则浏览 Markdown 文件目录树，文件修改后实时重载，可恢复各目录的标签页与滚动位置</p>
</li>
<li>
<p>对围栏代码块提供完善的语法高亮（基于 syntect + 纯 Rust 正则实现）</p>
</li>
<li>
<p>通过 Kitty 图片协议 / Sixel /iTerm2 协议内嵌渲染 Mermaid 图表；在 tmux 或不支持图片的终端中，会降级展示带样式的源码文本</p>
</li>
<li>
<p>全屏全局搜索：显示单文件匹配次数 + 预览内容、智能大小写匹配、结果数量超限后自动截断并提示</p>
</li>
<li>
<p>Vim 风格导航，配有可见光标；支持行级可视化选择，以及通过 <code>V/y/yy</code> 结合 OSC 52 协议复制到剪贴板</p>
</li>
<li>
<p>按下 <code>i</code> 可在光标所在源码行直接进入内嵌 Vim 风格编辑器（edtui），支持 <code>:w/:q/:wq/:q!</code> 操作</p>
</li>
<li>
<p>内置 8 款主题，其中包含面向浅色主题用户的 GitHub Light 和 Gruvbox Light</p>
</li>
</ul>
<p><strong>技术栈</strong></p>
<ul>
<li>ratatui + crossterm 构建终端界面（TUI）</li>
<li>pulldown-cmark 解析 Markdown，syntect（fancy-regex 后端）实现语法高亮</li>
<li>mermaid-rs-renderer + resvg 将 Mermaid 转为 PNG，ratatui-image 实现内嵌展示</li>
<li>edtui 提供内嵌编辑能力</li>
<li>tokio 处理异步文件 I/O 与后台搜索</li>
</ul>
<p>Repo: https://github.com/leboiko/markdown-reader</p>
<h2>Unreal Majid：一个粒子系统</h2>
<p><img src="https://preview.redd.it/my-second-gpgpu-particle-system-v0-ivm1jh9m0nug1.png?width=1080&amp;crop=smart&amp;auto=webp&amp;s=75115c9178f2fba6a973e6625a0aa662715089b8" alt=""></p>
<p>Unreal Majid 是一款基于 Rust 与 wgpu 构建的高性能 GPU 粒子模拟系统。本项目展示了计算着色器（Compute Shader）的强大能力：可实时处理数百万级粒子的物理运算，并在桌面原生平台与 WebAssembly 网页端高效完成渲染。</p>
<p>** 功能特性**</p>
<ul>
<li>GPU 计算着色器：将粒子物理运算（位置、速度、加速度）交由 GPU 处理，实现大规模并行计算。</li>
<li>跨平台：可在 Windows/Linux/macOS 原生运行，也支持在兼容 WebGPU 的现代浏览器中运行。</li>
<li>可交互相机：飞行视角控制模式，支持鼠标视角操控。</li>
<li>动态模拟效果：
<ul>
<li>重力控制：可自由开启/关闭重力效果。</li>
<li>鼠标引力：粒子会受鼠标光标位置吸引。</li>
<li>形态重置：可一键将粒子重新排列为球体或立方体形态。</li>
</ul>
</li>
</ul>
<p>在线演示：https://majidabdelilah.github.io/Unreal_Majid/</p>
<p>Repo：https://github.com/MajidAbdelilah/Unreal_Majid</p>
<p>--</p>
<p>From 日报小组 Yuan YQ</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-04-17 02:38:09</pubDate></item><item><title>【Rust日报】2026-04-16 GitComet v0.1.11 更快、更清爽</title><link>https://rustcc.cn/article?id=f223fa6a-6faa-4a2b-82a0-38f4072ee71d</link><description><![CDATA[<h2>GitComet v0.1.11 更快、更清爽</h2>
<p><img src="https://github.com/Auto-Explore/GitComet/raw/main/assets/gitcomet.gif" alt=""></p>
<p>GitComet 是我们致力于打造的一款快速、本地优先、开源的 Git 图形化客户端，即便在大型代码仓库中使用也能保持流畅体验。本次版本更新大量内容均直接源自用户反馈，因此可以说，这个版本是由实际使用者共同打磨而成的。</p>
<p><strong>技术栈</strong></p>
<p>Rust 工作区；使用 <code>gix</code> 处理 Git 底层逻辑（部分操作仍依赖 Git 命令行）；桌面 UI 基于 gpui 社区版分支 开发；异步任务采用 <code>smol</code> 运行时。我们始终执着于性能优化，本次更新进一步提升了侧边栏加载速度，并完善了快捷键支持。</p>
<p>Repo: https://github.com/Auto-Explore/GitComet</p>
<h2>ChronoGrapher:</h2>
<p><img src="https://github.com/GitBrincie212/ChronoGrapher/raw/master/assets/ChronoGrapher%20Logo.png" alt=""></p>
<p>ChronoGrapher 是一个多语言统一任务调度与工作流编排平台，主打跨语言、高性能、可扩展，目标是解决现代多语言架构下调度工具割裂、难协同、难扩展的问题。</p>
<p><strong>核心定位与解决的问题</strong></p>
<p>现代技术栈普遍多语言，但调度工具大多语言绑定，导致：</p>
<ul>
<li>跨语言流程需要大量胶水代码</li>
<li>学习与维护成本高</li>
<li>扩展性、一致性差</li>
</ul>
<p>ChronoGrapher 提供一套 API 统一调度 Python/TS/JS/Rust/Java，无侵入、高性能、易扩展。</p>
<p><strong>核心特性</strong></p>
<ol>
<li>统一多语言 API：一套接口打通多语言，无需胶水代码，跨语言流程无缝协作。</li>
<li>设计无偏向、高度可扩展：核心调度极简，能力以可选扩展提供，架构预留大量集成与扩展点。</li>
<li>Rust 引擎，极致性能与伸缩：单机到分布式集群无缝扩展，崩溃可恢复、状态持久化不丢进度。</li>
<li>毫秒级日历调度：支持按毫秒 / 秒 / 分 / 时 / 日 / 周 / 月精细控制，支持区间、间隔、指定点等多种规则。</li>
<li>可组合任务架构 + 钩子系统：任务可组合：重试、超时、降级、依赖、并行 / 串行、条件执行等；钩子监听：任务启停、重试、超时、依赖决议等事件，可对接监控（如 Prometheus）</li>
</ol>
<p>Repo: https://github.com/GitBrincie212/ChronoGrapher</p>
<p>--</p>
<p>From 日报小组 Yuan YQ</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-04-16 02:46:14</pubDate></item><item><title>【Rust日报】2026-04-15 plotlars v0.12.0: 已实现后端无关性</title><link>https://rustcc.cn/article?id=cd965cd3-7719-444a-baab-1c671b636f9b</link><description><![CDATA[<h2>Sniffnet v1.5：网络流量监控工具</h2>
<p><img src="https://raw.githubusercontent.com/GyulyVGC/sniffnet/main/resources/repository/pages/overview.png" alt=""></p>
<p>Sniffnet v1.5正式上线，核心更新与改进如下：</p>
<ol>
<li>新增应用识别功能：可查看占用网络带宽的程序及对应网络连接，支持添加收藏并接收流量通知，覆盖 Windows、Linux、macOS、BSD 系统。</li>
<li>支持自定义 IP 黑名单：可导入公共威胁情报或个人黑名单，实时提醒恶意连接。</li>
<li>优化界面预览：启动页可展示所有网卡流量预览，快速查看活跃接口与流量概况。</li>
</ol>
<p>Repo: https://github.com/GyulyVGC/sniffnet</p>
<h2>plotlars v0.12.0: 已实现后端无关性</h2>
<p><img src="https://camo.githubusercontent.com/573969cdaca1e61d1f177fb99c73ccdf54a1dd02fc9bd62219eb11ca49116f9e/68747470733a2f2f696d6775722e636f6d2f71304b376379502e706e67" alt=""></p>
<p>Plotlars 是一款功能全面的 Rust 库，它在功能强大的 Polars 数据分析库与各类可视化渲染后端之间搭建起桥梁。该库支持两种渲染后端：一是用于生成交互式 HTML 图表的 Plotly，二是用于输出 PNG、SVG 等静态图片的 Plotters。</p>
<p>Plotlars 简化了基于数据帧创建可视化图表的流程，让开发者能够专注于挖掘数据价值，而非纠结于绘图实现的复杂细节。</p>
<p>0.12.0 是一个里程碑版本：该库现已实现<strong>后端无关性</strong>。图表定义基于一套中间表示层构建，而实际渲染器则通过 Cargo 特性进行选择。</p>
<p>除了现有的 Plotly 后端外，现在新增了 <strong>Plotters 后端</strong>，可生成静态 PNG/SVG 图片，供不想依赖 JavaScript 库的用户使用。</p>
<p>本版本其他更新：</p>
<ul>
<li>内置文件加载器（CsvReader、ParquetReader、JsonReader、ExcelReader），无需在自己的 Cargo.toml 中单独引入 Polars 仅用于读取数据，即可实现从文件到图表的一站式绘制。</li>
<li>Polars 已在 <code>plotlars::polars</code> 模块下重新导出。当你需要使用 Polars 完整 API 时，该重导出机制能确保使用的版本与 Plotlars 编译时所用版本完全一致，避免出现版本不匹配的意外问题。</li>
</ul>
<p>Repo: https://github.com/alceal/plotlars</p>
<h2>flate2 计划默认切换至 zlib-rs</h2>
<p>flate2 是一个基于 DEFLATE 算法、支持流式处理的 Rust 压缩 / 解压缩库。项目团队计划不久后将 flate2 的默认实现切换为使用 zlib-rs 后端。zlib-rs 是 zlib 的纯 Rust 实现，在基准测试中，其性能优于 C 语言实现。它将替代当前默认的 miniz_oxide。将 zlib-rs 设为默认选项，能让 Rust 生态中大量项目免费获得性能提升。现在已经可以通过特性开关显式启用 zlib-rs 来获取这一性能优化。</p>
<p>Repo: https://github.com/rust-lang/flate2-rs</p>
<p>--</p>
<p>From 日报小组 Yuan YQ</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-04-15 02:13:07</pubDate></item><item><title>Vectorless: 一个用 Rust 编写的、推理原生的文档智能引擎</title><link>https://rustcc.cn/article?id=04f049a4-bf6a-4eeb-a710-9c6e7b36d74e</link><description><![CDATA[<p><strong>Vectorless</strong> 是一个用 Rust 开发的文档智能引擎，核心是“推理优先”。它完全抛弃了向量数据库、嵌入和相似度搜索，而是把文档转成层级化的语义树，然后让大模型在这棵树里“导航”——通过深度理解上下文来找到最相关的内容，而不是靠向量计算。</p>
<h2>思路</h2>
<p>结构化文档（技术报告、法律合同、研究论文）本身就自带语义层级 —— 标题、章节、段落之间的关系天然构成了一棵树。保留这棵树，让 LLM 沿着树结构做推理导航，而不是把文档拍平后算向量距离。</p>
<h2>工作流程</h2>
<pre><code>文档 → 解析为层级语义树 → 存储 → LLM 推理导航树结构 → 返回最相关内容
</code></pre>
<ul>
<li><strong>Parse</strong>：将 Markdown / PDF 解析为层级语义树，保留章节结构和语义关系</li>
<li><strong>Index</strong>：存储树结构及元数据、关键词、摘要；支持增量索引</li>
<li><strong>Query</strong>：LLM 在树上做推理导航，定位最相关节点，无需 Embedding 和向量搜索</li>
</ul>
<h2>代码示例</h2>
<h3>Python</h3>
<pre><code>import asyncio
from vectorless import Engine, IndexContext

async def main():
    engine = Engine(workspace="./data", api_key="sk-...", model="gpt-4o")

    result = await engine.index(IndexContext.from_file("./report.pdf"))
    doc_id = result.doc_id

    answer = await engine.query(doc_id, "What is the total revenue?")
    print(answer.single().content)

asyncio.run(main())
</code></pre>
<h3>Rust</h3>
<pre><code>use vectorless::{EngineBuilder, IndexContext, QueryContext};

let engine = EngineBuilder::new()
    .with_workspace("./data")
    .with_key("sk-...")
    .with_model("gpt-4o")
    .build()
    .await?;

let result = engine.index(IndexContext::from_path("./report.pdf")).await?;
let doc_id = result.doc_id().unwrap();

let result = engine.query(
    QueryContext::new("总营收是多少?").with_doc_id(doc_id)
).await?;
println!("{}", result.content);
</code></pre>
<h2>技术特点</h2>
<ul>
<li><strong>纯 Rust 实现</strong>：内存安全，高性能，低资源占用</li>
<li><strong>零向量依赖</strong>：无需向量数据库、无需 Embedding 模型、无需相似度计算</li>
<li><strong>LLM 推理导航</strong>：在文档语义树上做逐层推理决策，而非黑盒数值匹配</li>
<li><strong>混合检索</strong>：BM25 预过滤 + LLM 精排，兼顾效率与准确性</li>
<li><strong>全程可解释</strong>：完整检索链路可追溯，每次决策都可审计</li>
<li><strong>Python + Rust 双语言支持</strong>：Rust 核心引擎，PyO3 提供原生 Python 绑定</li>
</ul>
<h2>适用场景</h2>
<ul>
<li>技术文档 / API 文档的智能问答</li>
<li>法律合同、合规报告的精准检索</li>
<li>研究论文的多跳推理查询</li>
<li>需要检索过程可解释、可审计的场景</li>
</ul>
<h2>开源</h2>
<p>GitHub: https://github.com/vectorlessflow/vectorless,
如果感兴趣欢迎⭐repo。</p>
]]></description><pubDate>2026-04-14 06:11:08</pubDate></item><item><title>【Rust日报】2026-04-14 Servo v0.1.0：首个 crates.io 版本与长期支持版发布</title><link>https://rustcc.cn/article?id=a2f4ac1f-3c2c-4893-9778-7c4ba615679e</link><description><![CDATA[<h2>Servo v0.1.0：首个 crates.io 版本与长期支持版发布</h2>
<p>今天，Servo 团队发布了 <code>servo</code> crate 的 v0.1.0 版本。这是首次将 <code>servo</code> crate 发布到 crates.io，它支持将 Servo 作为库使用。与此同时，团队决定推出 Servo 长期支持（LTS）版本。常规月度发布预计会包含破坏性变更，部分集成方更希望按半年周期进行重大升级，同时仍能获取安全更新，并（有望）获得迁移指南。</p>
<p>Servo 是由 Mozilla 发起、Linux 欧洲实验室及社区主导维护，是目前最知名的用 Rust 从头重写的现代化浏览器引擎。</p>
<p><strong>核心定位</strong></p>
<ul>
<li>目标：打造安全、并行、高性能的 Web 引擎</li>
<li>语言：几乎完全使用 Rust 编写，天生内存安全、线程安全</li>
<li>地位：Rust 生态最具代表性的大型项目之一，也是下一代嵌入式 / 轻量化浏览器的核心引擎</li>
</ul>
<p><strong>主要特点</strong></p>
<ul>
<li>并行渲染架构页面布局、绘制、脚本执行高度并行，充分利用多核，理论上比传统引擎更快。</li>
<li>极致安全无 C/C++ 常见的内存越界、空指针、use-after-free 等高危漏洞，非常适合安全敏感场景。</li>
<li>模块化 &amp; 可嵌入最新版本已发布到 crates.io，可以作为独立库嵌入到其他应用中，不再只是一个演示浏览器。
标准兼容持续实现现代 Web 标准：HTML、CSS、DOM、WebGPU、WebAssembly 等。</li>
<li>跨平台支持 Linux、macOS、Windows、Android 等，可用于桌面、嵌入式、车载、IoT 等场景。</li>
</ul>
<p>Github: https://github.com/servo/servo</p>
<h2>colr：通用的、可扩展的颜色库</h2>
<p>colr 是Rust 语言编写的、类型安全的通用色彩处理库**，核心设计是在**类型层面统一色彩空间、通道布局、存储格式，从编译期杜绝色彩混用错误，主打零成本安全、高性能、可扩展。</p>
<p><strong>核心功能</strong></p>
<ol>
<li>支持的色彩空间（完整覆盖专业场景）</li>
</ol>
<ul>
<li>RGB 类：sRGB、Display P3、Adobe RGB、Linear RGB</li>
<li>感知均匀空间：OKLab、OKLch（现代色彩处理首选）</li>
<li>标准空间：XYZ (D65)、Lab (D65)、Lch (D65)</li>
<li>支持 HDR、线性 / 非线性传递函数、白点转换（D65/D50）</li>
</ul>
<ol start="2">
<li>核心能力</li>
</ol>
<ul>
<li>色彩空间<strong>显式转换</strong>（编译期安全）</li>
<li>通道布局转换（RGBA ↔ ARGB ↔ RGB 等）</li>
<li>位深度转换：f32 ↔ u8，支持抖动（dither）减少量化误差</li>
<li>色适应（白点变换，如 D65 ↔ D50）</li>
<li>基础色彩运算：混合、插值、亮度 / 饱和度调整</li>
</ul>
<p>Repo：https://codeberg.org/chaynabors/colr</p>
<h2>文章：仅仅使用标量类型是不够的，一切皆需指定类型</h2>
<p>这篇文章核心观点：仅用基础标量类型（string/int 等）的类型安全是浅层的，会隐藏大量业务语义错误，应通过为领域概念创建专属类型（Newtype/branded type）让无效状态无法表示。</p>
<p><strong>核心问题</strong></p>
<ol>
<li>
<p>位置参数风险</p>
<p>多个同类型参数（如 ShopID、CustomerID 均为 string）易被传参颠倒，编译器不报错，引发生产故障。</p>
</li>
<li>
<p>结构体仅缓解不根治</p>
<p>用结构体做命名参数，仍可把错误语义值赋给同类型字段，类型系统不校验业务含义。</p>
</li>
<li>
<p>标量抹去语义</p>
<p>基础类型只描述数据形状，不表达业务意义，无法区分 ID、金额、单位、安全状态等，导致混淆 ID、单位错乱、注入风险、经纬度互换等 bug。</p>
</li>
</ol>
<p><strong>解决方案：为领域概念封装专属类型</strong></p>
<ul>
<li>Rust：用 Newtype（如 ShopId (String)）+ Deref/From/Display/ 构造函数校验。</li>
<li>Go：定义独立类型（type ShopID string），类型不兼容、自带方法。</li>
<li>TypeScript：用 Branded type（带唯一标识的交叉类型）实现编译期隔离。</li>
<li>关键效果：<strong>不同业务类型不可互换，传参 / 赋值错误直接编译报错</strong>。</li>
</ul>
<p><strong>收益与成本</strong></p>
<ul>
<li><strong>收益</strong>：代码自文档、重构安全、边界一次性校验、可检索性强、编译器强制安全规则。</li>
<li><strong>成本</strong>：少量类型封装代码，远低于故障与人工校验成本。</li>
</ul>
<p>原文：https://sot.dev/everything-should-be-typed.html</p>
<p>--</p>
<p>From 日报小组 Yuan YQ</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc 论坛: 支持 RSS</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-04-14 02:05:44</pubDate></item><item><title>一款使用 GPUI 构建，基于 Alacritty / Wezterm 内核的开源跨平台终端应用</title><link>https://rustcc.cn/article?id=c30ffa2c-eed8-4487-91a4-099fcdddbcdf</link><description><![CDATA[<h3>特性 ❇️</h3>
<ul>
<li> 跨平台：Linux / macOS / Windows</li>
<li> 终端内核：支持 Alacritty / WezTerm 后端</li>
<li> SSH：基于 <code>wezterm-ssh</code>，支持 Password / SSH Config / ProxyCommand / ProxyJump</li>
<li> 串口：支持串口会话、波特率 / 校验位 / 流控配置</li>
<li> SFTP 文件操作：支持文件（拖拽）上传、并发控制等</li>
<li> 终端共享：通过 relay 分享终端会话</li>
<li> Cast 录制回放：录制与回放终端操作</li>
<li> 批量支持：多终端批量执行</li>
<li> AI 助手：内置 ZeroClaw Assistant</li>
<li> 多主题：支持主题切换、通过主题编辑器新增或编辑主题</li>
<li> 锁屏：应用锁屏与超时自动锁定</li>
<li> 静态提示：基于预配置的静态命令提示，支持占位符</li>
</ul>
<h3>路线 🏁</h3>
<ul>
<li> 支持 Lua 脚本，支持更多场景的可定制化</li>
<li> 支持工作流</li>
<li> ...</li>
</ul>
<h3>快速上手</h3>
<h4>回放 cast</h4>
<p>除了图形界面里的录制 / 回放能力，Termua 也支持命令行直接播放 cast：</p>
<pre><code>termua --play-cast demo.cast
termua --play-cast demo.cast --speed 2
</code></pre>
<h4>终端会话共享</h4>
<p>除了可以使用 <code>termua-relay</code> 启动 relay 进程，也可以在 Termua 配置页中启动本地 relay 进程用于测试</p>
<pre><code>termua-relay --listen 127.0.0.1:7231
</code></pre>
<p>观看侧在会话共享期间可以申请操作终端，共享侧也支持回收操作权限。</p>
<h3>配置</h3>
<h4><code>settings.json</code> 示例</h4>
<pre><code>{
  "appearance": {
    "theme": "system",
    "language": "zh-CN"
  },
  "terminal": {
    "default_backend": "alacritty",
    "ssh_backend": "ssh2",
    "font_family": ".ZedMono",
    "font_size": 15,
    "ligatures": true,
    "cursor_shape": "block",
    "blinking": "on",
    "option_as_meta": false,
    "show_scrollbar": true,
    "show_line_numbers": true,
    "copy_on_select": true,
    "suggestions_enabled": false,
    "suggestions_max_items": 8,
    "sftp_upload_max_concurrency": 5
  },
  "sharing": {
    "enabled": false,
    "relay_url": "ws://127.0.0.1:7231/ws"
  },
  "recording": {
    "include_input_by_default": false,
    "playback_speed": 1.0
  },
  "logging": {
    "level": "default",
    "path": "termua.log"
  }
}
</code></pre>
<p>不建议直接修改 <code>settings.json</code> 文件，建议通过 <code>Termua</code> 的配置页进行修改。</p>
]]></description><pubDate>2026-04-13 06:52:30</pubDate></item><item><title>【Rust日报】2026-04-13 farben: 用标记式语法设置终端色彩和样式</title><link>https://rustcc.cn/article?id=41dc1fc3-e6de-4dff-9166-75935cc38627</link><description><![CDATA[<h2>xuniq: 超快的行去重命令行工具</h2>
<p>xuniq 是一个超快的针对行内容去重的工具，并且，和 uniq 相比，它不需要先排序，可以直接对未排序的内容去重。以下是性能对比测试结果：</p>
<p><img src="https://github.com/lalitshankarch/xuniq/raw/master/benchmark.png" alt=""></p>
<p>Github: https://github.com/lalitshankarch/xuniq</p>
<h2>farben: 用标记式语法设置终端色彩和样式</h2>
<p><img src="https://github.com/razkar-studio/farben/raw/main/farben/images/farben.png" alt=""></p>
<p>farben 是一个用 Rust 开发的、零依赖、高性能、安全的终端彩色 / 样式标记库，替代手写 <code>\x1b{insert\_element\_0\_}[31m</code> 这类转义码。</p>
<p><strong>核心特性</strong></p>
<ol>
<li>类标记语法：易读、易写，使用时功能强大。</li>
<li>零运行时依赖：仅将 farben-core 作为路径依赖，Farben 不会引入复杂的依赖树。</li>
<li>可选编译时处理：通过 <code>compile</code> 特性标志，在编译期验证并处理标记语法，无任何运行时开销。</li>
<li>完整工具集：支持命名颜色、ANSI256 色、RGB 色、强调样式、样式链式调用，同时支持前景色与背景色设置。</li>
<li>即用型打印宏：<code>cprint!</code>、<code>cprintln!</code>、<code>cprintb!</code>、<code>cprintbln!</code> 的用法与 <code>print!</code> 和 <code>println!</code> 完全一致，仅额外支持标记语法。对应的写入宏 <code>cwrite!</code>、<code>cwriteln!</code>、<code>cwriteb!</code>、<code>cwritebln!</code> 可适配所有实现了 <code>Write</code>  trait 的类型。</li>
<li>标准错误输出变体：所有打印宏均提供以 <code>e</code> 开头的变体（如 <code>ceprint!</code>、<code>ceprintln!</code> 等），用于输出至标准错误流（stderr）。</li>
<li>样式延续变体：<code>cprintb!</code>、<code>cprintbln!</code>、<code>colorb()</code> 及 <code>colorb!()</code> 不会在末尾自动重置样式，可让样式效果在多次调用中持续生效。</li>
<li>用户自定义样式：通过 <code>style!()</code> 定义专属标签，可展开为任意支持标签的组合。</li>
<li>自定义样式文件：只需添加 <code>名称.frb.toml</code> 文件，在 <code>build.rs</code> 中写 1 行代码、在 <code>main.rs</code> 中写 2 行代码，即可加载该文件中的所有样式配置。</li>
<li>与 anstyle 兼容互通：借助标记语法的便捷写法，接入整个 anstyle 生态体系。</li>
</ol>
<p>Github: https://github.com/razkar-studio/farben</p>
<p>--</p>
<p>From 日报小组 Yuan YQ</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-04-13 03:38:12</pubDate></item><item><title>【Rust日报】2026-04-10 miro v0.8.0: 增加演示和全屏模式</title><link>https://rustcc.cn/article?id=ae8d8bb0-5d58-4b2b-aadf-fff41c72fcee</link><description><![CDATA[<h2>miro v0.8.0: 增加演示和全屏模式</h2>
<p><img src="https://github.com/vincent-uden/miro/raw/master/assets/screenshot.png" alt=""></p>
<p>miro 是一个使用 Rust 开发的 PDF 阅读器，它基于 iced 和 mupdf-rs 构建。此次 v0.8.0 增加了演示模式和全屏模式。</p>
<p><strong>功能特性</strong></p>
<ul>
<li>深色模式（界面与 PDF 同步生效）</li>
<li>类 Vim 快捷键绑定（默认启用）</li>
<li>独立配置文件，可自定义快捷键（不喜欢 Vim 风格时使用）</li>
<li>鼠标操作支持</li>
<li>多标签页打开多个 PDF</li>
<li>支持命令行参数，可从终端直接打开 PDF</li>
<li>已打开 PDF 自动热重载（尤其适合编写 LaTeX、Typst 等可编译为 PDF 的文档时使用）</li>
<li>文档文本复制功能</li>
<li>内部链接跳转（如目录跳转）</li>
<li>外部链接支持（点击即可复制邮箱、网址等）</li>
<li>书签功能</li>
<li>跳转历史记录</li>
<li>可选 RPC 服务端，支持通过其他程序控制阅读器</li>
<li>调用系统默认浏览器打印</li>
<li>键盘快捷键打开链接</li>
<li>全屏模式</li>
<li>演示模式：隐藏全部界面元素</li>
</ul>
<p>Github: https://github.com/vincent-uden/miro</p>
<h2>minikv v1.0.0 发布</h2>
<p><img src="https://preview.redd.it/minikv-v1-0-0-distributed-key-value-object-store-v0-ic1hjmb1z5ug1.jpeg?width=1080&amp;crop=smart&amp;auto=webp&amp;s=969987d95be6f938e21bc73b93761d843e8cbeab" alt=""></p>
<p>minikv 是一个基于 Rust 开发的分布式、多租户键值与对象存储系统，内置 Raft 一致性协议、预写日志（WAL）持久化保障，并面向生产环境设计运维特性。</p>
<p>v1.0.0 为正式发布版本，主打面向数据/机器学习工作流与运维可靠性。</p>
<ul>
<li>时序 API 处理器已具备生产级支持（<code>/ts/write</code>、<code>/ts/query</code>）</li>
<li>向量搜索接口已可用，数据持久化存储在协调节点磁盘</li>
<li>Python SDK 预览版支持笔记本工作流（内置 pandas/polars/pyarrow 辅助工具）</li>
<li>可观测性套件现已包含 Grafana 仪表板预置与 Prometheus 告警规则</li>
<li>提供 Helm Chart，并附带开发 / 预发 / 生产三套环境配置文件</li>
<li>发布工程体系包含前置检查项与运维运行手册</li>
</ul>
<p>Github: https://github.com/whispem/minikv</p>
<p>--</p>
<p>From 日报小组 Yuan YQ</p>
<p>社区学习交流平台订阅：</p>
<ul>
<li><a href="https://rustcc.cn/" rel="noopener noreferrer">Rustcc论坛: 支持rss</a></li>
<li><a href="https://rustcc.cn/article?id=ed7c9379-d681-47cb-9532-0db97d883f62" rel="noopener noreferrer">微信公众号：Rust语言中文社区</a></li>
</ul>
]]></description><pubDate>2026-04-10 02:32:29</pubDate></item><item><title>[开源]墨睿思 MORES：一个用Rust实现的可控、可解释的决策引擎</title><link>https://rustcc.cn/article?id=725c285a-ee07-41f0-bb4f-2b650bca254c</link><description><![CDATA[<p>断断续续写了一年多，终于敢拿出来了。
<strong>为什么做这个？</strong>
家里有一本老《辞海》，是爷爷留下的。做这个项目的起点，就是想试试——能不能让AI也像辞海一样：准确、可信、经得起查。</p>
<p><strong>MORES 是什么？</strong>
一个 <strong>可控、可解释</strong> 的决策引擎。</p>
<ul>
<li>不是大模型，是大模型“之后的那一步”</li>
<li>规则可定义，决策可追溯，置信度可量化</li>
</ul>
<p><strong>它能做什么？</strong></p>
<ul>
<li><strong>古文字识别</strong>：甲骨文、金文的检测与识别（少样本方向）</li>
<li><strong>昇腾NPU适配</strong>：已完成华为昇腾开发板的适配（设备初始化、模型加载、推理接口）</li>
<li><strong>Docker一键部署</strong>：<code>docker run -p 8000:8000 mores-core:api</code></li>
<li><strong>Python SDK</strong>：<code>pip install mores-community</code></li>
</ul>
<p><strong>技术栈</strong></p>
<ul>
<li>核心：<strong>Rust</strong> (性能 + 内存安全)</li>
<li>绑定：PyO3 (Rust → Python)</li>
<li>容器：Docker</li>
</ul>
<p><strong>开源策略</strong></p>
<ul>
<li><strong>通用代码</strong>：Apache 2.0，完全开源</li>
<li><strong>核心算法</strong>：私有，仅授权使用（不是不想开，是专利和商业化考虑）</li>
</ul>
<p><strong>快速体验</strong></p>
<pre><code># 1. 拉取并运行 API 服务
docker run -p 8000:8000 mores-core:api

# 2. 新开一个终端，发送测试请求
curl -X POST http://localhost:8000/decide \
  -H "Content-Type: application/json" \
  -d '{"input":"这是一个测试"}'
</code></pre>
<p>返回结果会包含 decision、confidence、reasoning，整个过程是可解释的。</p>
<p>项目地址
https://gitee.com/moshi-lab/mores-community</p>
<p>写在最后
这个项目还远不完美，昇腾适配也只是“开发板级”，不敢说企业可用。
但我们在认真做：</p>
<p>· 从《辞海》出发，尊重文字
· 用Rust写，尊重性能与安全
· 适配国产硬件，尊重这个时代</p>
<p>欢迎任何形式的Issue、PR或只是聊聊。
不强求，但准备着。</p>
]]></description><pubDate>2026-04-10 02:27:05</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>
]]></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>