第 6 节,共 25 节

切片

目录

切片是产品的一个功能。它的名字是 snake_case 的单数名词:recording、transcript、board、trigger。不是 recordings_manager,也不是 utils。如果产品有前端,切片名与前端的功能文件夹保持一致,这样同一个词就能在两侧找到代码。

一个切片存在于两个层级中:它的领域在 core,它的入口(命令、DTO、事件)在 app。

app/recording/mod.rscommands.rsdto.rsevents.rscore/recording/mod.rsservice.rsmodel.rsactor/logic.rsstore.rs

6.1. core 中的切片

core/src/<slice>/
  mod.rs        public API of the slice: only `mod …;` and `pub use …;`
  model.rs      domain types, state enums, identifiers; no I/O, no async
  logic.rs      pure functions: validation, decisions, mappings, calculations
  store.rs      this slice's reads from SQL and files, and its write commands through the writer
  service.rs    use cases: async, composes logic + store + drivers; no state of its own
  error.rs      optional: the slice's error enum
  actor/        only for a slice with background state, section 9
  tests.rs      optional: unit tests of the slice

规则:

  • 切片不需要的文件就不存在。 小切片在超过大约 400 行之前,可以只是一个包含模型和服务的 mod.rs。
  • 变大的文件变成同名文件夹:logic.rs 变为 logic/mod.rs 加 logic/<topic>.rs。职责不变,只是文件数量变了。
  • 过大的切片拆分为子切片:run/ 变为 run/start/、run/step/、run/finish/,每个都采用相同的文件布局。父级只保留一个用于重新导出的 mod.rs。
  • mod.rs 是切片的正门,就像 Nx 库的 index.ts。其他切片只通过它导入。

一个典型的 mod.rs:

mod logic;
mod model;
mod service;
mod store;

pub use model::{Transcript, TranscriptId, Word};
pub use service::TranscriptService;

6.2. app 中的切片

app/src/<slice>/
  mod.rs        `mod …;` and `pub mod commands;` (the command list itself is in lib.rs, 6.4)
  commands.rs   #[tauri::command] functions; at most 10 lines each
  dto.rs        wire types: serde camelCase, #[serde(other)] on enums, From<model>, From<error> for IpcError
  events.rs     event names and payloads sent to the window; snapshot subscription loops

app crate 的其余部分:

app/src/
  main.rs       calls lib::run(); nothing else
  lib.rs        run(): Builder, plugins, setup, generate_handler! with every command, grouped by slice
  state.rs      AppState: the composition root, section 11
  error.rs      entry error → code and text for the window
  platform.rs   optional: window and menu settings that depend on the operating system, section 12.3
  doors/        entries other than the window: MCP server, bridge for agents, remote hub

6.3. 命令的参考形态

#[tauri::command]
pub async fn transcript_search(
    state: State<'_, AppState>,
    input: SearchInput,
) -> Result<Vec<TranscriptHitDto>, IpcError> {
    let hits = state.transcripts.search(input.into()).await?;
    Ok(hits.into_iter().map(Into::into).collect())
}

如果一个命令需要 if、循环或两次调用切片,那段逻辑就属于 service.rs 或 logic.rs。10 行的限制与风格无关。只做转换的命令不需要单独的单元测试,因为它的逻辑已在切片中测试过。剩下需要证明的是人看到的那句话,这要通过入口进行端到端测试(第 14 节)。

6.4. 注册命令

tauri::generate_handler! 需要每个命令的完整路径,所以 lib.rs 维护一份列表。按切片分组,每个切片一个块,这样新增命令只需在相邻命令旁加一行:

pub fn run() {
    tauri::Builder::default()
        .setup(setup)
        .invoke_handler(tauri::generate_handler![
            recording::commands::recording_start,
            recording::commands::recording_stop,
            recording::commands::recording_list,
            transcript::commands::transcript_read,
            transcript::commands::transcript_search,
            board::commands::board_list,
            board::commands::board_sync,
        ])
        .run(tauri::generate_context!())
        .expect("the window could not start");
}

一个存在于切片中却不在这份列表里的命令能够编译,却悄无声息地什么也不做。第 16 节提供了一个小检查,用于比对两者,在它们不一致时失败。

6.5. 切片命名

  • 每个功能一个名词,用单数:trigger,不是 triggers。
  • 用用户认得的事物名称,而不是技术名称:transcript,不是 whisper_pipeline。
  • 两个功能总是一起变化时,它们是一个切片。一个功能中有各自独立变化的部分时,它们是子切片。
  • 横切策略也是切片:访问门控、限额、预算和密钥保护都位于 core/<policy>/(例如 core/guard/),其他所有切片调用它们。