# @arrirpc/codegen-rust 中文文档

规范地址：https://npmcn.com/package/%40arrirpc/codegen-rust/

版本：0\.85\.0
npm 元数据更新时间：2026-10-03T04:03:59.248Z
中文译文更新时间：2026-11-06T20:22:19.102Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40arrirpc/codegen-rust
原文对照：https://npmcn.com/package/%40arrirpc/codegen-rust/?lang=original
项目主页：https://github.com/modiimedia/arri#readme
源码仓库：https://github.com/modiimedia/arri

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：156 kB，8 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2024-06-18T23:44:18.341Z
- 最新版本发布：2026-10-03T04:03:59.072Z
- 近 30 天下载量：4587（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：72（近 12 个月 11 个）

## 中文简介



## 安装

```sh
npm install @arrirpc/codegen-rust
```

也可以使用：`pnpm add @arrirpc/codegen-rust`、`yarn add @arrirpc/codegen-rust`、`bun add @arrirpc/codegen-rust`

## README

# 阿里·罗斯克根

## 设置

### 1) 将生成器添加到您的 arri 配置

```ts
// arri.config.ts
import { defineConfig, generators } from 'arri';

export default defineConfig({
    generators: [
        generators.rustClient({
            clientName: 'MyClient',
            outputFile: './some-project/my_client.g.rs',
        }),
    ],
});
```

**选项**

| 名称 | 说明 |
| --- | --- |
| 输出文件( 需要) | 由生成器创建的文件路径 |
| 客户端Name | 生成客户端结构的名称( 默认为“ 客户端 ” ) |
| 类型 前缀 | 在生成的 struct 名称中添加前缀 |
| 格式 | 是否运行 `rustfmt` 是否生成文件( 默认为“ true” ) |
| 根服务 | 生成客户端的根服务 |

### 2) 安装 Rust 客户端库

生成的代码依赖于 [客户端](https://npmcn.com/languages/rust/rust-client/README.md) 图书馆。 因此,确保它安装在任何正在使用生成代码的地方. 版本号应该符合您的 arri cli 版本 。 (运行 `arri version` 检查)

```bash
cargo add arri_client
```

## 使用生成的代码

此客户端中生成的所有程序都将是 Async 函数, 因此您需要像 Async 运行时间 [东木](https://tokio.rs/)

### 初始化客户端

```rust
let config = ArriClientConfig {
    http_client: reqwest::Client::new(),
    base_url: "https://example.com".to_string(),
    headers: Hashmap::new(),
}
let client = MyClient::create(config);

// start calling procedures
client.my_procedure().await;
```

根客户端将是一个包含所有服务和程序的结构。 如果你只需要特殊服务,你可以初始化服务.

```rust
let users_service = MyClientUsersService(config);
users_service.some_procedure().await;
```

### 更新信头

对于需要更新 http headers (类似于过期的认证符) 的情况, 您可以调用 `update_headers()` 函数。 当调用时,更改将推广到所有嵌入子服务.

```rust
client.update_headers(new_headers);
```

记住,如果 `update_headers()` 从子服务中调用它不会传播到母服务.

```rust
client.subservice.update_headers(new_headers);

// this will still use the original headers
client.do_something();
```

`update_headers()` 也称为横线.

```rust
let mut headers: HashMap<&'static str, String> = HashMap::new();
let config = ArriClientConfig {
    http_client: reqwest::Client::new(),
    base_url: "https://example.com".to_string(),
    headers: headers.clone(),
}
let client = Arc::new(MyClient::create(config));
tokio::spawn(async move {
    loop {
        client.do_something().await;
    }
});
tokio::spawn(async move {
    loop {
        client.do_another_thing().await;
    }
});

// wait two seconds then change the headers
tokio::time::sleep(Duration::from_millis(2000)).await;
headers.insert("hello", "world".to_string());
client.update_headers(headers.clone());
// now both threads will start using the updated headers on their next loop
```

### 调用SSE程序

```rust
let mut msg_count = 0;
let mut open_count = 0;
client
    .users
    .watch_user(
        &mut |event, controller| match event {
            SseEvent::Message(msg) => {
                msg_count += 1;
                printl("NEW_MESSAGE: {:?}", msg);
            }
            SSeEvent::Error(err) => {
                // call abort to close the event stream
                controller.abort()
            }
            SseEvent::Open => {
                open_count += 1;
            }
            SseEvent::Close => {}
        },
        None, // max_retry_count (u64)
        None, // max_retry_interval (u64)
    ).await;
```

### 使用生成的类型

所有生成类型都将采用以下方法

-   `from_json_string(String input) -> Self`
-   `from_json(serde_json::Value input) -> Self`
-   `to_json(&Self) -> serde_json::Value`
-   `to_json_string(&Self) -> String`
-   `to_query_params_string(&Self) -> String`

`serde_json` 用于解析 JSON。 但是,我们并不依赖 `serde` 本身是用来串联和破坏的.

生成类型还得出以下特征

-   克隆
-   调试
-   部分 Eq

# 发展

```bash
# run unit tests
nx test rust-codegen
```

## 常见问题

### 如何安装 @arrirpc/codegen-rust？

在项目目录运行 npm install @arrirpc/codegen-rust，或使用 pnpm add / yarn add / bun add。

### @arrirpc/codegen-rust 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @arrirpc/codegen-rust 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @arrirpc/codegen-rust 可以商用吗？

@arrirpc/codegen-rust 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @arrirpc/codegen-rust 的下载量有多少？

根据 npm 官方下载统计，@arrirpc/codegen-rust 在 2026/10/07 – 2026/11/05 这 30 天内被下载 4,587 次，日均约 153 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @arrirpc/codegen-rust 还在维护吗？

最新版本 0\.85\.0 发布于 2026/10/03（1 个月前）；至今共发布 72 个版本，其中过去 12 个月发布了 11 个；首次发布于 2024/06/19。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

