🖥️

TauriのIPCにProtobufを使う

に公開

はじめに

前回の記事では、TauriのIPCにGraphQLを使う方法を紹介しました。

https://zenn.dev/kaorun343/articles/ec7e1d7def2b94

今回はProtobufを使うバージョンです。Claude Codeに実装を大いに手伝ってもらいました。

実装方針

  • .proto ファイルをスキーマの唯一の情報源(Single Source of Truth)とし、Rust・TypeScript両方のコードを自動生成します。
  • Tauriのコマンドは proto_unary の1つだけを登録し、メソッドパス文字列(例: "hello.v1.HelloService/SayHello")で各RPCにディスパッチします。
  • IPC上のデータ形式はProtobufのバイナリエンコーディング(Vec<u8>)を使います。
  • Rust側: prost-build のカスタム ServiceGenerator を実装し、cargo build 時にサービストレイト・ディスパッチャを自動生成します。
  • TypeScript側: buf generate(protoc-gen-es)で型を生成し、@connectrpc/connect の Transport インターフェースを実装してTauri IPCをラップします。

Proto定義

gRPCと同じようにサービスとメッセージを .proto ファイルに定義します。ここでは HelloService を例に説明します。

syntax = "proto3";

package hello.v1;

// HelloRequest is a request to say hello.
message HelloRequest {
  // Name is the name of the person to greet.
  string name = 1;
}

// HelloResponse is a response to a hello request.
message HelloResponse {
  // Message is the greeting message.
  string message = 1;
}

// HelloService is a service that provides greetings.
service HelloService {
  // SayHello returns a greeting.
  rpc SayHello(HelloRequest) returns (HelloResponse) {}
}

この .proto ファイルから、Rust側とTypeScript側の両方にコードを生成していきます。

Rust側の実装

依存クレート

prostを用いてRust側のコード生成・アプリケーション実装をおこなっていきます。

https://github.com/tokio-rs/prost

Cargo.toml の関連部分は以下の通りです。

[build-dependencies]
prost-build = "0.14.3"
tauri-build = { version = "2", features = [] }

[dependencies]
anyhow = "1"
async-trait = "0.1"
prost = "0.14.3"
tauri = { version = "2", features = [] }

Protobufのスキーマファイルとバイナリ変換の仕組みに依存しており、gRPCには依存していません。したがって、tonic は使いません。

https://github.com/hyperium/tonic

build.rs - カスタムコード生成器

build.rs に prost_build::ServiceGenerator トレイトを実装した TauriServiceGenerator を定義します。

prost-build はProtoファイルからメッセージ型(構造体)のRustコードを自動生成しますが、service 定義に対しては何もしません。ServiceGenerator トレイトを実装することで、サービス定義からカスタムコードを生成できます。

TauriServiceGenerator は以下の3つを生成します。

  1. サービストレイト: 各RPCメソッドに対応する非同期メソッドを持つトレイト
  2. ServiceRegistry: 全サービスの実装を束ねる構造体
  3. proto_unary ディスパッチャ: メソッドパス文字列でmatchし、リクエストのデコード→サービス呼び出し→レスポンスのエンコードを行う #[tauri::command] 関数
// src-tauri/build.rs
use prost_build::{Method, Service, ServiceGenerator};
use std::io::Write;
use std::path::PathBuf;

/// Tauri IPC用のサービスコード生成器
struct TauriServiceGenerator {
    /// 生成されたUnary RPCのmatch arm
    unary_arms: Vec<String>,
    /// 生成されたServer Streaming RPCのmatch arm
    streaming_arms: Vec<String>,
    /// 生成されたサービストレイト定義
    trait_code: Vec<String>,
    /// ServiceRegistryのフィールド定義
    registry_fields: Vec<String>,
    /// 処理済みパッケージ名のリスト
    packages: Vec<String>,
    /// 出力ディレクトリ
    out_dir: PathBuf,
}

impl TauriServiceGenerator {
    fn new(out_dir: PathBuf) -> Self {
        Self {
            unary_arms: Vec::new(),
            streaming_arms: Vec::new(),
            trait_code: Vec::new(),
            registry_fields: Vec::new(),
            packages: Vec::new(),
            out_dir,
        }
    }

    /// スネークケースに変換
    fn to_snake_case(s: &str) -> String {
        let mut result = String::new();
        for (i, c) in s.chars().enumerate() {
            if c.is_uppercase() {
                if i > 0 {
                    result.push('_');
                }
                result.push(c.to_lowercase().next().unwrap());
            } else {
                result.push(c);
            }
        }
        result
    }

    /// メソッドのフルパスを生成 (例: "hello.v1.HelloService/SayHello")
    fn method_path(service: &Service, method: &Method) -> String {
        format!(
            "{}.{}/{}",
            service.package, service.proto_name, method.proto_name
        )
    }

    /// サービストレイトを生成
    fn generate_trait(&mut self, service: &Service) {
        let trait_name = &service.name;
        let field_name = Self::to_snake_case(trait_name);
        let mut buf = String::new();

        // トレイト定義開始
        buf.push_str(&format!(
            r#"/// {}
#[async_trait::async_trait]
pub trait {}: Send + Sync + 'static {{
"#,
            service
                .comments
                .leading
                .iter()
                .map(|s| s.trim())
                .collect::<Vec<_>>()
                .join("\n/// "),
            trait_name
        ));

        // 各メソッドを生成
        for method in &service.methods {
            let method_name = Self::to_snake_case(&method.proto_name);
            let input_type = &method.input_type;
            let output_type = &method.output_type;
            let comments = method
                .comments
                .leading
                .iter()
                .map(|s| s.trim())
                .collect::<Vec<_>>()
                .join("\n    /// ");

            // Unary RPC
            buf.push_str(&format!(
                r#"    /// {}
    async fn {}(&self, request: {}) -> anyhow::Result<{}>;
"#,
                comments, method_name, input_type, output_type
            ));
        }

        buf.push_str("}\n");

        self.trait_code.push(buf);

        // ServiceRegistryのフィールドを記録
        self.registry_fields.push(format!(
            "    pub {}: std::sync::Arc<dyn {} + Send + Sync>,",
            field_name, trait_name
        ));
    }

    /// ディスパッチャのmatch armを生成
    fn generate_match_arms(&mut self, service: &Service) {
        let trait_name = &service.name;
        let field_name = Self::to_snake_case(trait_name);

        for method in &service.methods {
            let method_path = Self::method_path(service, method);
            let method_name = Self::to_snake_case(&method.proto_name);
            let input_type = &method.input_type;

            // Unary RPC用のmatch arm
            let arm = format!(
                r#"        "{method_path}" => {{
            let request = {input_type}::decode(data)?;
            let response = registry.{field_name}.{method_name}(request).await?;
            let mut buf = Vec::with_capacity(response.encoded_len());
            response.encode(&mut buf)?;
            Ok(buf)
        }}"#,
                method_path = method_path,
                input_type = input_type,
                field_name = field_name,
                method_name = method_name,
            );
            self.unary_arms.push(arm);
        }
    }

    /// サービスコードをファイルに書き出す
    fn write_service_code(&self) -> std::io::Result<()> {
        let service_file = self.out_dir.join("services.rs");
        let mut file = std::fs::File::create(&service_file)?;

        // ヘッダー
        writeln!(file, "// This file is @generated by build.rs")?;
        writeln!(file, "// Do not edit manually.")?;
        writeln!(file)?;
        for pkg in &self.packages {
            writeln!(file, "use super::{}::*;", pkg)?;
        }
        writeln!(file)?;

        // トレイト定義
        for trait_code in &self.trait_code {
            writeln!(file, "{}", trait_code)?;
        }

        // ServiceRegistry定義
        writeln!(file, "/// サービスレジストリ")?;
        writeln!(file, "pub struct ServiceRegistry {{")?;
        for field in &self.registry_fields {
            writeln!(file, "{}", field)?;
        }
        writeln!(file, "}}")?;

        // Unary RPCディスパッチャ
        writeln!(
            file,
            r#"
/// Unary RPC用ディスパッチャ
#[tauri::command]
pub async fn proto_unary(
    method: String,
    data: Vec<u8>,
    registry: tauri::State<'_, ServiceRegistry>,
) -> Result<Vec<u8>, String> {{
    proto_unary_inner(&method, &data, &registry)
        .await
        .map_err(|e| e.to_string())
}}

async fn proto_unary_inner(
    method: &str,
    data: &[u8],
    registry: &ServiceRegistry,
) -> anyhow::Result<Vec<u8>> {{
    use prost::Message;
    match method {{"#
        )?;
        for arm in &self.unary_arms {
            writeln!(file, "{}", arm)?;
        }
        writeln!(
            file,
            r#"        _ => anyhow::bail!("unknown method: {{}}", method),
    }}
}}"#
        )?;

        Ok(())
    }
}

impl ServiceGenerator for TauriServiceGenerator {
    fn generate(&mut self, service: Service, _buf: &mut String) {
        // トレイトとmatch armを生成(bufには書かない)
        self.generate_trait(&service);
        self.generate_match_arms(&service);
    }

    fn finalize(&mut self, _buf: &mut String) {
        // 何もしない(bufには書かない)
    }

    fn finalize_package(&mut self, package: &str, _buf: &mut String) {
        // パッケージ名を記録("hello.v1" → "hello::v1")
        let module_name = package.replace('.', "::");
        if !self.packages.contains(&module_name) {
            self.packages.push(module_name);
        }
        // パッケージ処理完了時にファイルを書き出す
        if let Err(e) = self.write_service_code() {
            panic!("Failed to write service code: {}", e);
        }
    }
}

fn main() -> std::io::Result<()> {
    let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());

    let mut config = prost_build::Config::new();
    config.out_dir(&out_dir);
    config.service_generator(Box::new(TauriServiceGenerator::new(out_dir)));

    config.compile_protos(
        &["../proto/hello/v1/hello_service.proto"],
        &["../proto"],
    )?;

    tauri_build::build();

    Ok(())
}

このコードが cargo build 時に実行されると、OUT_DIR に以下のようなコードが生成されます。

生成される services.rs のイメージ:

use super::hello::v1::*;

#[async_trait::async_trait]
pub trait HelloService: Send + Sync + 'static {
    async fn say_hello(&self, request: HelloRequest) -> anyhow::Result<HelloResponse>;
}

/// サービスレジストリ
pub struct ServiceRegistry {
    pub hello_service: std::sync::Arc<dyn HelloService + Send + Sync>,
}

/// Unary RPC用ディスパッチャ
#[tauri::command]
pub async fn proto_unary(
    method: String,
    data: Vec<u8>,
    registry: tauri::State<'_, ServiceRegistry>,
) -> Result<Vec<u8>, String> {
    proto_unary_inner(&method, &data, &registry)
        .await
        .map_err(|e| e.to_string())
}

async fn proto_unary_inner(
    method: &str,
    data: &[u8],
    registry: &ServiceRegistry,
) -> anyhow::Result<Vec<u8>> {
    use prost::Message;
    match method {
        "hello.v1.HelloService/SayHello" => {
            let request = HelloRequest::decode(data)?;
            let response = registry.hello_service.say_hello(request).await?;
            let mut buf = Vec::with_capacity(response.encoded_len());
            response.encode(&mut buf)?;
            Ok(buf)
        }
        _ => anyhow::bail!("unknown method: {}", method),
    }
}

生成コードの取り込み (src/proto/mod.rs)

prost-build は生成コードを OUT_DIR に出力します。これをRustモジュールとして取り込むには include! マクロを使います。

// src-tauri/src/proto/mod.rs

pub mod hello {
    pub mod v1 {
        include!(concat!(env!("OUT_DIR"), "/hello.v1.rs"));
    }
}

mod services {
    include!(concat!(env!("OUT_DIR"), "/services.rs"));
}

pub use hello::v1::*;
pub use services::*;

ここでのポイントは2つあります。

  1. hello::v1 のようにネストされたモジュール構造にする必要があります。prost-build はパッケージ間の型参照を hello::v1::HelloRequest のようなパスで生成するためです。
  2. services モジュールは mod services { ... } で囲む必要があります。生成された services.rs 内の use super::hello::v1::*; が、super 経由で親モジュール(proto)の hello::v1 を参照するためです。

サービス実装

生成されたトレイトを実装します。

// src-tauri/src/services/hello_service_impl.rs
use crate::proto::{HelloRequest, HelloResponse, HelloService};

pub struct HelloServiceImpl;

impl HelloServiceImpl {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait::async_trait]
impl HelloService for HelloServiceImpl {
    async fn say_hello(&self, request: HelloRequest) -> anyhow::Result<HelloResponse> {
        let message = format!("Hello, {}! You've been greeted from Rust!", request.name);
        Ok(HelloResponse { message })
    }
}

アプリケーション起動 (lib.rs)

最後に ServiceRegistry を組み立て、Tauriの manage で登録します。invoke_handler に登録するコマンドは proto_unary の1つだけです。

// src-tauri/src/lib.rs
mod proto;
mod services;

use std::sync::Arc;

use proto::{HelloService, ServiceRegistry, proto_unary};
use services::HelloServiceImpl;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    let hello_service: Arc<dyn HelloService + Send + Sync> = Arc::new(HelloServiceImpl::new());

    let registry = ServiceRegistry {
        hello_service,
    };

    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .manage(registry)
        .invoke_handler(tauri::generate_handler![proto_unary])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

前回のGraphQL版では graphql コマンドを1つ登録していましたが、今回も同様に proto_unary コマンド1つだけです。サービスが増えても、ServiceRegistry にフィールドを追加するだけで、invoke_handler の変更は不要です。

TypeScript側の実装

TypeScript側のコード生成には buf と、 protobuf-es の protoc-gen-es を使います。 protobuf-es は @connectrpc/connect を使うために選択しました。

@connectrpc/connect を使って invoke 関数の呼び出しをラップすることにしました。
これにより、protoファイルから自動生成したコードからで各種サービスのrpc メソッドを自動生成できるようになりました。

https://buf.build/

https://github.com/bufbuild/protobuf-es

https://connectrpc.com

コード生成 (buf.gen.yaml)

# buf.gen.yaml
version: v2
plugins:
  - local: protoc-gen-es
    out: packages/app/src/proto/generated
    opt:
      - target=ts

buf generate を実行すると、.proto ファイルからTypeScriptの型定義とサービスディスクリプタが生成されます。

createTauriTransport の実装

@connectrpc/connect の Transport インターフェースを実装し、内部でTauriの invoke を呼び出します。

// packages/app/src/libraries/tauri-transport.ts
import type {
  DescMessage,
  DescMethodUnary,
  MessageInitShape,
} from "@bufbuild/protobuf";
import { create, fromBinary, toBinary } from "@bufbuild/protobuf";
import type { Transport, UnaryResponse } from "@connectrpc/connect";
import { createContextValues } from "@connectrpc/connect";
import { runUnaryCall } from "@connectrpc/connect/protocol";
import { invoke } from "@tauri-apps/api/core";

export interface TauriTransportOptions {
  invoke?: typeof invoke;
  defaultTimeoutMs?: number;
}

export const createTauriTransport = (
  options: TauriTransportOptions = {},
): Transport => {
  const { invoke: tauriInvoke = invoke, defaultTimeoutMs = 30000 } = options;

  return {
    async unary<I extends DescMessage, O extends DescMessage>(
      method: DescMethodUnary<I, O>,
      signal: AbortSignal | undefined,
      timeoutMs: number | undefined,
      header: HeadersInit | undefined,
      input: MessageInitShape<I>,
    ): Promise<UnaryResponse<I, O>> {
      const resolvedTimeoutMs =
        timeoutMs === undefined
          ? defaultTimeoutMs
          : timeoutMs <= 0
            ? undefined
            : timeoutMs;

      return await runUnaryCall<I, O>({
        signal,
        timeoutMs: resolvedTimeoutMs,
        req: {
          stream: false,
          service: method.parent,
          method,
          url: `${method.parent.typeName}/${method.name}`,
          requestMethod: "POST",
          header: new Headers(header),
          contextValues: createContextValues(),
          message: input,
        },
        next: async (req) => {
          // 入力メッセージをProtobufバイナリにシリアライズ
          const message = create(method.input, req.message);
          const binaryRequest = toBinary(method.input, message);

          // Tauri IPCコール
          const response = await tauriInvoke<number[]>("proto_unary", {
            method: req.url, // "hello.v1.HelloService/SayHello"
            data: Array.from(binaryRequest),
          });

          // レスポンスをデシリアライズ
          const responseMessage = fromBinary(
            method.output,
            new Uint8Array(response),
          );

          return {
            stream: false,
            service: method.parent,
            method,
            header: req.header,
            message: responseMessage,
            trailer: new Headers(),
          };
        },
      });
    },

    // stream メソッドも同様に実装(省略)
  };
};

ポイントは req.url の組み立てです。method.parent.typeName(= "hello.v1.HelloService")と method.name(= "SayHello")を / で結合すると、Rust側のディスパッチャが期待するメソッドパス "hello.v1.HelloService/SayHello" と一致します。

使い方

フロントエンドからは createClient を使って、完全に型付けされたRPCクライアントとして利用できます。

import { createClient } from "@connectrpc/connect";
import { createTauriTransport } from "../../libraries/tauri-transport.js";
import { HelloService } from "../../proto/generated/hello/v1/hello_service_pb.js";

const transport = createTauriTransport({
  defaultTimeoutMs: 5000,
});

const client = createClient(HelloService, transport);

const response = await client.sayHello({ name: "John Doe" });

おわりに

このようにして、IPCにProtobufを使うことができました。ぜひ参考にしてみてください。

Discussion