セクション 20 / 25

ケーススタディ:Quayside

目次

Quaysideは、この文書のために考案した架空のデスクトップアプリケーションです。私たちが作っている種類のソフトウェアをゆるやかに模していますが、以下の名前、数値、ファイルはすべて作りものです。Quaysideは通話を録音し、デバイス上で文字起こしをし、ローカルまたはクラウドのモデルで要約を書き、コーディングエージェントでフォローアップのタスクを実行し、アクションアイテムをチームの共有ボードに同期します。さらに、録音を見守ってメモを送り込めるスマートフォン用のコンパニオンアプリもあります。

Quaysideは小さなチームが急ぎながら2年かけて作ってきたもので、ちゃんと動いています。同時に、セクション1で述べたことすべての見本でもあります。

20.1. 移行前

src-tauri/src/
  main.rs                 40 lines
  lib.rs                  2,300 lines   setup, 148 commands, emit helpers, menu
  state.rs                AppState with 41 fields
  handlers.rs             31,000 lines  "all the commands"
  handlers/
    recording.rs          6,800 lines
    sync.rs               4,100 lines
    agents.rs             9,700 lines
  engine/
    recorder.rs           imports tauri::AppHandle to emit levels
    transcriber.rs        imports tauri::AppHandle to emit words
  db.rs                   opens SQLite connections in 9 places
  utils.rs                6,400 lines
  companion/              phone hub: crypto, pairing, and AppState everywhere
windowlib.rs · 2.3khandlers.rs · 31kAppState · 41engine/db.rs · 9 × openstatic × 12utils.rs · 6.4k

移行の手順1での測定結果です。

項目 値
Rustの行数(テストを除く) 約78,000
tauri::を使うファイル 112個中37個
#[tauri::command]関数 148個、4ファイルに分散
AppStateのフィールド 41個、うち14個がMutex<…>またはアトミック
状態を持つstatic 12個
書き込み用のSQLite接続を開く場所 9か所
#[cfg(target_os = …)]を含むファイル 23個
start_recording_*のバリエーション 7個
ドメインのテストの実行時間 ウィンドウが必要なので、誰も実行していない

20.2. コードに現れる症状

アプリケーションの状態です。41個のフィールドのうち11個を示します。

pub struct AppState {
    pub db_path: PathBuf,
    pub recording: Mutex<Option<RecordingSession>>,
    pub recording_cancel: AtomicBool,
    pub level_task: Mutex<Option<JoinHandle<()>>>,
    pub transcribing: Mutex<HashMap<String, CancellationToken>>,
    pub summarizing: Mutex<HashMap<String, CancellationToken>>,
    pub agent_runs: Mutex<HashMap<String, AgentRun>>,
    pub agent_slots: Mutex<usize>,
    pub sync_in_flight: AtomicBool,
    pub companion: Mutex<Option<CompanionHub>>,
    pub model_prices: Mutex<Option<(Instant, PriceList)>>,
}

録音をまたいで漏れる停止です。ユーザーが停止を押し、すぐに新しい録音を始めます。古い録音のループはまだフラグを読んでいません。新しい録音は何もリセットしません。次にrecording_cancelを確認したとき、止まるのは新しい録音です。

static RECORDING_CANCEL: AtomicBool = AtomicBool::new(false);

#[tauri::command]
fn stop_recording() {
    RECORDING_CANCEL.store(true, Ordering::SeqCst);
}

ドメインがウィンドウと直接やり取りしているので、ウィンドウなしではテストできません。

pub async fn transcribe(app: AppHandle, file: PathBuf) -> Result<(), String> {
    let mut words = whisper::stream(&file)?;
    while let Some(word) = words.next().await {
        app.emit("transcript-word", &word).map_err(|e| e.to_string())?;
    }
    Ok(())
}

バリエーションが増殖します。

pub async fn start_recording(…)
pub async fn start_recording_with_limit(…)
pub async fn start_recording_with_limit_and_device(…)
pub async fn start_recording_for_meeting(…)
pub async fn start_recording_for_meeting_with_limit(…)
pub async fn start_recording_from_companion(…)
pub async fn start_recording_with_test_hook(…)

そして、オペレーティングシステムがいたるところにあります。

#[cfg(target_os = "macos")]
fn reveal(path: &Path) {
    let _ = Command::new("sh").arg("-c").arg(format!("open -R '{}'", path.display())).spawn();
}

この最後の例は、引用符を含むファイル名を待っているシェルインジェクションでもあります。

20.3. 移行の手順

手順2:依存を逆転させる。 文字起こし処理はAppHandleを受け取らなくなります。単語はcoreが所有する容量制限付きのチャネルに書き込み、appがそのチャネルをウィンドウに流します。アップロードのコードはAppStateを読まなくなり、必要な2つの値を引数として受け取ります。

pub async fn transcribe(file: &Path, words: WordSink) -> Result<Outcome<Transcript>, TranscribeError> {
    let mut stream = drivers::whisper::stream(file).await?;
    let mut transcript = Transcript::default();
    while let Some(word) = stream.next().await {
        transcript.push(word.clone());
        if words.send(word) == Sent::Closed {
            return Ok(Outcome::Cancelled);
        }
    }
    Ok(Outcome::Done(transcript))
}

手順3:appとcoreを分ける。 quayside-core(tauriなし)と、appとしての既存のsrc-tauriからなるワークスペースを作ります。アプリのlib.rsにはpub use quayside_core::{…};を残すので、古いパスはすべて引き続きコンパイルされます。証明として、coreにuse tauri::Manager;を仕込むとコンパイルに失敗します。

手順4:kit、store、drivers。 9か所あったSQLiteの接続は、quayside-storeの1つのライターにまとまります。録音処理、文字起こし処理、モデルのクライアント、gitはquayside-driversに移ります。#[cfg]を含む23個のファイルは、unix.rs、macos.rs、unsupported.rsを持つ1つのplatform/フォルダーになり、revealは契約になります。

pub fn reveal_path(path: &Path) -> Result<(), PlatformError> {
    let status = Command::new("/usr/bin/open").arg("-R").arg(path).status()?;
    status.success().then_some(()).ok_or(PlatformError::Refused("open -R"))
}

シェルも、引用符の処理も、インジェクションもありません。

手順5:スライス。 handlers.rsとutils.rsを、小さいものから順にスライスへと分解します。

settings → device → llm → summary → transcript → board → companion → agent → recording

手順6:kit::Jobs。 transcribingとsummarizing(キャンセルトークンを持つ2つのマップ)は、文字起こしサービスの中の1つのJobs<TranscriptId>と、要約サービスの中の1つのJobs<SummaryId>になります。

手順7:アクター。 9.1のテストに通る状態は3つです。録音、エージェントの実行、ボードの同期です。最初は録音で、今日の振る舞いに対するupdateのテストを先に書きます。AtomicBoolはなくなります。停止は対象とする録音の世代を運ぶようになり、20.2の漏れは、ずっとグリーンのままの1行のテストになります。7つのstart_recording_*関数は1つになります。

pub struct StartRecording {
    pub title: String,
    pub device: Option<DeviceId>,
    pub meeting: Option<MeetingId>,
    pub limit: Option<Duration>,
    pub origin: Origin,
}

手順8:チェック。 セクション16の各チェックを、そのベースライン付きで有効にします。ほとんどのベースラインはすでに空です。上の手順で違反が取り除かれたからです。

20.4. 移行後

Cargo.toml                       [workspace]
crates/
  quayside-kit/                  paths, ids, durable_file, jobs, logging
  quayside-store/                writer, schema, migrations
  quayside-drivers/
    src/
      whisper.rs  recorder.rs  models.rs  git.rs
      platform/   mod.rs  unix.rs  macos.rs  unsupported.rs
  quayside-core/
    src/
      recording/  mod.rs model.rs logic.rs service.rs actor/
      transcript/ mod.rs model.rs logic.rs store.rs service.rs
      summary/    mod.rs model.rs service.rs
      agent/      mod.rs model.rs logic.rs store.rs service.rs actor/
      board/      mod.rs model.rs logic.rs store.rs service.rs actor/
      companion/  mod.rs model.rs logic.rs store.rs service.rs
      device/  llm/  settings/  guard/
src-tauri/
  src/
    main.rs lib.rs state.rs error.rs platform.rs
    recording/  mod.rs commands.rs dto.rs events.rs
    transcript/ mod.rs commands.rs dto.rs events.rs
    …
    doors/companion/

移行後のコマンドです。

#[tauri::command]
pub async fn recording_stop(
    state: State<'_, AppState>,
    generation: u64,
) -> Result<(), IpcError> {
    state.recordings.send(recording::Msg::Stop { generation }).await?;
    Ok(())
}

同じ測定をもう一度行った結果です。

項目 移行前 移行後
tauri::を使うファイル 37 12、すべてsrc-tauri内
最長のコマンド 140行 9行
AppStateのフィールド 41 9
状態を持つstatic 12 0
書き込み用のSQLite接続 9か所 1
オペレーティングシステムの#[cfg]を含むファイル 23 3、すべてplatform/内
start_recording_*のバリエーション 7 1
ドメインのテスト ウィンドウが必要だった ウィンドウなしで数秒で実行
LinuxとWindows向けのコンパイル(appを除く) できない できる、CIで確認

これらの数値は説明のためのものです。大切なのは変化の形です。どの行も、所有者は1人、場所は1つ、ルールは1つ、という方向に動きました。