gRPC はサービス定義を使用して RPC メソッドとメッセージ型を記述し、tonic は Rust 用の非同期実装を提供します。一般的な組み合わせは Tokio、Tower、Prost です。生成コードにより手動でのシリアライズやインターフェースのボイラープレートコードが削減されますが、ネットワークの両端では、片方が .proto ファイルを変更しただけでは自動的に再コンパイルされません。
プロトコルのコンパイル時の型チェック、オンライン時のエンコーディング互換性、ビジネスセマンティクスは、3つの異なるレイヤーです。HTTP API でも OpenAPI などの記述とコード生成を使用できます。gRPC を選択する理由は、呼び出しモデル、ストリーミング機能、およびエコシステムの要件から来るべきものであり、別の種類のインターフェースを一律に「契約がない」と断じてはいけません。
greeter.proto メッセージフィールド番号と RPC リクエスト/レスポンス型 1 protoc + tonic-prost-build Prost メッセージ、サービストレイト、クライアント/サーバーラッパーの生成 2 Greeter トレイトの実装 ビジネス入力の検証、Response または Status の返却 3 tonic 転送層 HTTP/2、メッセージエンコーディング、メタデータ、フロー制御 4 プロトコルファイルから呼び出し可能なサービスへ:生成コードとランタイムがそ れぞれ一部を担う コード生成はローカルの型をチェックしますが、バージョン間の互換性とビジネス制約は別途設計する必要があります。
4つのRPC形式をまず理解する
形式 リクエストメッセージ数 レスポンスメッセージ数 典型的な用途
Unary 1 1 1回のクエリまたはコマンド
Server streaming 1 複数 クエリ結果を段階的に送信
Client streaming 複数 1 バッチアップロード後の集計
Bidirectional streaming 複数 複数 双方向で独立して進行
双方向ストリームは、リクエストを受信するたびにレスポンスを送信することを要求するものではなく、双方向に1対1の対応関係があることも保証しません。各方向内のメッセージには順序がありますが、アプリケーション側でメッセージID、完了条件、および失敗時のリカバリ方法を定義する必要があります。
最小限の完全なプロジェクト:生成ツールのバージョンを明確にする
以下では tonic 0.14 シリーズを使用します。このシリーズの Prost 統合は tonic-prost と tonic-prost-build にあります。古いチュートリアルの tonic_build::compile_protos を直接使用して混在させないでください。ローカル環境に protoc がインストールされている必要があり、実際の解析バージョンを記録するために Cargo.lock を保存してください。tonic 、tonic-prost-build
Cargo.toml:
[package]
name = "grpc-demo"
version = "0.1.0"
edition = "2024"
[dependencies]
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tonic = "0.14"
tonic-prost = "0.14"
prost = "0.14"
[build-dependencies]
tonic-prost-build = "0.14"
proto/greeter.proto:
syntax = "proto3";
package greeter;
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply);
}
message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }
build.rs:
fn main ( ) -> Result< ( ) , Box< dyn std:: error:: Error> > {
println! ( " cargo:rerun-if-changed=proto/greeter.proto" ) ;
tonic_prost_build:: configure( )
.compile_protos ( & [ " proto/greeter.proto" ] , & [ " proto" ] ) ? ;
Ok ( ( ) )
}
src/lib.rs:
pub mod greeter {
tonic:: include_proto! ( " greeter" ) ;
}
src/bin/server.rs:
use grpc_demo:: greeter:: { HelloReply, HelloRequest} ;
use grpc_demo:: greeter:: greeter_server:: { Greeter, GreeterServer} ;
use tonic:: { Request, Response, Status} ;
# [ derive ( Default ) ]
struct HelloService ;
# [ tonic ::async_trait ]
impl Greeter for HelloService {
async fn say_hello ( & self , request : Request< HelloRequest> )
-> Result< Response< HelloReply> , Status>
{
let name = request.into_inner ( ) .name;
if name.trim ( ) .is_empty ( ) {
return Err ( Status:: invalid_argument( " name is required" ) ) ;
}
Ok ( Response:: new( HelloReply { message: format! ( " Hello, {name} !" ) } ) )
}
}
# [ tokio ::main ]
async fn main ( ) -> Result< ( ) , Box< dyn std:: error:: Error> > {
tonic:: transport:: Server:: builder( )
.add_service ( GreeterServer:: new( HelloService) )
.serve ( " 127.0.0.1:50051" .parse ( ) ? )
.await? ;
Ok ( ( ) )
}
src/bin/client.rs:
use grpc_demo:: greeter:: { HelloRequest, greeter_client:: GreeterClient} ;
use std:: time:: Duration;
use tonic:: Request;
# [ tokio ::main ]
async fn main ( ) -> Result< ( ) , Box< dyn std:: error:: Error> > {
let mut client = GreeterClient:: connect( " http://127.0.0.1:50051" ) .await? ;
let mut request = Request:: new( HelloRequest { name: " Rust" .into ( ) } ) ;
request.set_timeout ( Duration:: from_secs( 2 ) ) ;
let reply = client.say_hello ( request) .await? .into_inner ( ) ;
println! ( " {} " , reply.message) ;
Ok ( ( ) )
}
2つのターミナルでそれぞれ cargo run --bin server と cargo run --bin client を実行すると、クライアントは Hello, Rust! を出力するはずです。ここではリクエストのチェーンを観察するためにローカルで平文リスニングを使用しています。実際のデプロイでは、環境に応じて TLS、認証、リソース制限を設定してください。
#[tonic::async_trait] は、このシリーズで生成されるトレイトの形式に合わせるために使用されます。Rust 1.75 以降ではトレイト内のネイティブな async fn がサポートされています。マクロを残しているからといって、言語が「まだサポートしていない」と解釈してはいけません。ネイティブな async trait、ダイナミックディスパッチ、および生成ライブラリが採用している規約は、それぞれ別々に考慮する必要があります。
.proto を修正しても旧クライアントが必ずしも壊れない理由
Protobuf のバイナリエンコーディングはフィールド番号に依存します。互換性のあるフィールドを追加する場合、旧クライアントは自分が認識しているフィールドを正常に読み続ける可能性があります。ローカルの Rust コードを修正する必要があるかどうかは、再生成を行うかどうか、および型をどのように構築するかによって異なります。オンラインでの互換性は、単一のリポジトリでのコンパイル成功によって証明されるものではありません。
フィールドを削除した後、その番号は保持し、通常は将来の誤用を防ぐために名前も保持してください。異なる意味を表現するために旧番号を再利用しないでください。フィールドタイプの変更は、ワイヤー互換性のルールに従って個別に判断する必要があります。エンコーディングがデコード可能であっても、単位が秒からミリ秒に変更されると、ビジネスセマンティクスが直接破壊される可能性があります。Proto3 更新ルール
「提供されていない」と「デフォルト値が提供されている」を区別する必要がある場合、フィールドの存在性設計を明確に使用すべきです。例えば、適切な optional フィールドを使用します。空文字列は、タイプが string だからといって自動的に検証エラーにはなりません。そのため、上記のハンドラーでは明示的に name をチェックしています。
2種類のメッセージ型を使用してフィールドの存在性と旧中継ノードを検証する
以下は独立した src/bin/compat.rs です。プロジェクトの既存の Prost 依存関係を使用し、新旧の構造を同じプログラム内で同時に観察するためにメッセージを直接宣言します。フィールド番号 1 は name を保持し、バージョン2では optional の locale フィールド番号 2 が追加されます。
use prost:: Message;
# [ derive ( Clone, PartialEq, Message ) ]
struct V1 {
#[prost(string, tag = "1")]
name : String,
}
# [ derive ( Clone, PartialEq, Message ) ]
struct V2 {
#[prost(string, tag = "1")]
name : String,
#[prost(string, optional, tag = "2")]
locale : Option< String> ,
}
fn main ( ) {
let absent = V2 { name: String :: new( ) , locale: None } ;
let empty = V2 { name: String :: new( ) , locale: Some ( String :: new( ) ) } ;
assert! ( absent.encode_to_vec ( ) .is_empty ( ) ) ;
assert_eq! ( empty.encode_to_vec ( ) , [ 0x12 , 0 ] ) ;
let new = V2 { name: " Rust" .into ( ) , locale: Some ( " zh-CN" .into ( ) ) } ;
let bytes = new.encode_to_vec ( ) ;
let old = V1 :: decode( bytes.as_slice ( ) ) .unwrap ( ) ;
assert_eq! ( old.name, " Rust" ) ;
let relayed = old.encode_to_vec ( ) ;
let decoded = V2 :: decode( relayed.as_slice ( ) ) .unwrap ( ) ;
assert_eq! ( decoded.name, " Rust" ) ;
assert_eq! ( decoded.locale, None ) ;
}
optional は、欠落と明示的な空値をそれぞれ None と Some("") にマッピングします。この例では、0x12 はフィールド番号 2、ワイヤータイプ 2 のキーであり、後の 0 はゼロバイトの長さを表します。したがって、ビジネス上の文字列がどちらも空であっても、オンラインでの表現は異なります。Prost フィールド表現
旧 V1 は、新しいデータから認識できる name を読み取ることができますが、この Prost メッセージ構造は再エンコーディング時に未知の locale を保持しません。したがって、「旧クライアントが新しいフィールドを含むメッセージを読み取れること」と「旧ノードを介してデコードおよび再エンコードされた後、新しいフィールドが終点に到達できること」は、2つの異なる互換性の要件です。旧ノードが元のメッセージバイトを透過的に転送するだけの場合は、ここで言及されている損失のある再構築は発生していません。具体的なチェーンは、実際のトランスフォーメーションプロセスに従って検証する必要があります。
リリース前に読み書きの方向でチェックする
シナリオ チェックすべき結果
新規書き込み → 旧読み取り 未知フィールドをスキップできるか、旧ビジネスロジックが正しく動作するか
旧書き込み → 新読み取り 欠落値に適切な意味があるか、すべてが合法であるとデフォルトで仮定しないこと
新規書き込み → 旧中継 → 新読み取り 再エンコーディングや JSON 変換によって新しい情報が失われないか
新列挙型値 → 旧ロジック 元の整数が保持されるか、デフォルトの意味が誤って適用されないか
データは互換性があるが単位が変更された ビジネス計算、範囲、表示が変更されていないか
段階的なリリースでは、通常、読み取り側が新しい形式を受け入れるようにしてから、新しい書き込みを有効にします。ロールバックする場合は、書き込まれた新しいデータを旧バージョンが適切に処理できるかも確認する必要があります。フィールド番号を保持することでエンコーディングの誤読を防げますが、単位、権限、またはステートマシンのセマンティクスの変更を自動的に解決するわけではありません。
旧ノードは新フィールドを保持できるか
None はフィールド 2 を送らず、Some("") はキーと長さゼロを送ります。生転送は違いを保持しますが、本文の旧 Prost V1 は name しか知らず、再構築で locale を失います。旧側が復号できるかだけでなく、読み書きの全経路で互換性を確認します。
図を準備しています 再読み込み
旧ノードは新フィールドを保持できるか Some("") はフィールド 2 の 12 00 を追加します。旧 Prost の再符号化は未定義フィールドを失い、生転送は保持します。
{"id":"rust-protobuf-presence","title":"旧ノードは新フィールドを保持できるか","summary":"Some(\"\") はフィールド 2 の 12 00 を追加します。旧 Prost の再符号化は未定義フィールドを失い、生転送は保持します。","height":1000,"html":"<h2 data-i18n=\"heading\"></h2><p class=\"intro\" data-i18n=\"intro\"></p><label class=\"check\"><input type=\"checkbox\" id=\"present\" checked><span data-i18n=\"present\"></span></label><div class=\"presets\" role=\"group\" data-i18n-label=\"mode\"><button data-mode=\"raw\" data-i18n=\"raw\"></button><button data-mode=\"decode\" data-i18n=\"decode\"></button></div><div class=\"track-row\"><span data-i18n=\"before\"></span><div id=\"before\" class=\"track\"></div></div><div class=\"track-row\"><span data-i18n=\"after\"></span><div id=\"after\" class=\"track\"></div></div><section class=\"panel\"><h3 data-i18n=\"receiver\"></h3><div id=\"receiver\"></div></section><div class=\"copy\"><p id=\"explanation\" role=\"status\"></p><p class=\"reserve\" aria-hidden=\"true\" data-i18n=\"explain\"></p></div><details class=\"scope\"><summary data-i18n=\"scopeLabel\"></summary><p data-i18n=\"scope\"></p></details>","css":".intro{margin:8px 0 18px;color:var(--muted);font-size:14px}.caption,.hint{font-size:12px;color:var(--muted);margin-top:12px}.control{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;align-items:center;margin:14px 0;font-size:13px}.control label{font-size:13px}.control output{color:var(--accent);min-width:5em;text-align:right;font-variant-numeric:tabular-nums}.control input{grid-column:1/-1;width:100%;margin:0}.presets{display:flex;gap:4px;align-items:stretch}.presets button{flex:1 1 0;min-width:0;overflow-wrap:anywhere;font-size:13px}.actions{display:flex;gap:8px;flex-wrap:wrap;margin:14px 0}.actions button{flex:1;min-width:0;font-size:13px;min-height:42px}.copy{display:grid;font-size:14px;margin:16px 0}.copy>*{grid-area:1/1;margin:0}.reserve{visibility:hidden}.scope{margin-top:14px;color:var(--muted);font-size:12px}.scope summary{padding:8px 0;cursor:pointer}.scope p{margin-top:10px}.two{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.card{border:1px solid var(--rule);border-radius:9px;padding:14px;min-width:0}.card header{font-size:14px;font-weight:600;margin-bottom:10px}.card button{font-size:12px;width:100%;min-width:0}.card small{display:block;font-size:12px;color:var(--muted)}.card code{font-size:12px;overflow-wrap:anywhere}.metrics{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin:16px 0}.metrics>div{border-left:2px solid var(--accent);padding-left:10px;min-width:0}.metrics span{display:block;min-height:3.2em;color:var(--muted);font-size:12px}.metrics strong{font-size:23px;display:block;font-weight:550;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.formula{border-top:1px solid var(--rule);padding-top:12px;margin-top:14px;font-size:13px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.value{font:550 20px ui-monospace,monospace}.legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:12px;color:var(--muted);margin:12px 0}.legend span:before{content:'';display:inline-block;width:8px;height:8px;border-radius:2px;background:var(--accent);margin-right:6px}.legend .second:before{background:var(--second)}.check{display:flex;align-items:center;gap:8px;font-size:13px;margin:12px 0}.check input{width:16px;height:16px;flex-shrink:0;accent-color:var(--accent)}select,input[type=text],input[type=number]{background:var(--paper);color:var(--ink);font:inherit;font-size:13px;padding:10px;border:1px solid var(--rule);border-radius:7px;max-width:100%;min-width:0}select{width:100%;min-height:42px}.band{height:20px;display:flex;background:var(--surface);border-radius:4px;overflow:hidden}.band i{height:100%;display:block;background:var(--accent);transition:width .25s}.band i.second{background:var(--second)}button:disabled{cursor:default}.status{font-size:13px;min-height:4.8em}.mono{font-family:ui-monospace,monospace;font-variant-numeric:tabular-nums}.muted{color:var(--muted)}\n@media(max-width:480px){.two{gap:8px}.card{padding:12px 9px}.actions button,.presets button{font-size:12px}.metrics strong{font-size:20px}.metrics{gap:8px}}\n@media(prefers-reduced-motion:reduce){*,*::before,*::after{transition:none!important;animation:none!important}}\n.track-row{margin:16px 0}.track-row>span{display:block;font-size:12px;color:var(--muted);margin-bottom:7px}.track{display:flex;gap:5px;min-width:0}.cell{flex:1;min-width:0;min-height:48px;border:1px solid var(--rule);border-radius:5px;background:var(--surface);display:flex;align-items:center;justify-content:center;text-align:center;padding:5px 3px;font-size:12px;overflow-wrap:anywhere;font-variant-numeric:tabular-nums}.cell.on{background:var(--accent-soft);border-color:var(--accent)}.cell.gold{background:var(--second-soft);border-color:var(--second)}.cell.empty{border-style:dashed;color:var(--muted)}.cell.error{border-color:var(--second);text-decoration:line-through}.choices{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:14px 0}.choices button{min-width:0;padding:10px 4px;font-size:12px;overflow-wrap:anywhere}.choices button[aria-current=true]{border-color:var(--accent);background:var(--accent-soft)}.relation{display:grid;grid-template-columns:minmax(0,1fr) 28px minmax(0,1fr);align-items:center;gap:6px;margin:12px 0}.relation .cell{min-height:72px}.relation>i{text-align:center;font-style:normal;color:var(--accent)}.readout{font-size:13px;white-space:pre-line;min-height:6.4em;overflow-wrap:anywhere}.plot{position:relative;border-left:1px solid var(--rule);border-bottom:1px solid var(--rule);padding:8px 0;margin:18px 0}.plot-row{height:28px;position:relative;margin:4px 0;background:var(--surface)}.plot-row i{position:absolute;inset-block:5px;background:var(--accent);min-width:2px;transition:width .2s,left .2s}.plot-row b{position:relative;padding:4px 6px;font:11px/28px ui-monospace,monospace;background:var(--paper);border-radius:3px}.axis{display:flex;justify-content:space-between;font-size:11px;color:var(--muted)}\n\n/* Action labels must remain readable across locales and narrow embeds. */\n.actions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}\n.actions button{overflow-wrap:anywhere;white-space:normal;min-height:58px;padding:8px}\nbutton{overflow-wrap:anywhere}\n@media(min-width:640px){.actions{grid-template-columns:repeat(3,minmax(0,1fr))}}\n\n.metrics span{overflow-wrap:anywhere}\n.panel{border:1px solid var(--rule);border-radius:9px;padding:12px;margin:14px 0;min-width:0}.panel h3{font-size:13px;margin:0 0 10px;color:var(--muted)}.source{font:13px/1.8 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:12px 0}.source mark{background:var(--accent-soft);color:var(--ink);border-bottom:2px solid var(--accent)}.source .fault{background:var(--second-soft);border-color:var(--second)}.diagram{display:block;width:100%;height:auto;max-height:320px;margin:14px 0;overflow:visible}.diagram text{fill:var(--ink);font:12px ui-monospace,monospace}.diagram .edge{stroke:var(--muted);stroke-width:1.5;fill:none}.diagram .edge.on{stroke:var(--accent);stroke-width:3}.diagram .node{fill:var(--surface);stroke:var(--rule);stroke-width:1.5}.diagram .node.on{fill:var(--accent-soft);stroke:var(--accent)}.diagram .node.gold{fill:var(--second-soft);stroke:var(--second)}.log{font:12px/1.8 ui-monospace,monospace;white-space:pre-line;overflow-wrap:anywhere;min-height:7.2em}.table{display:grid;gap:5px;margin:14px 0}.table .tr{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}.table .tr>*{padding:8px 5px;background:var(--surface);border-radius:4px;min-width:0;overflow-wrap:anywhere;font-size:12px}.table .tr .on{background:var(--accent-soft)}.table .tr .gold{background:var(--second-soft)}.choices button{min-height:44px}.metrics strong{min-height:1.6em}.code-line{display:block}.code-line.on{background:var(--accent-soft);border-left:2px solid var(--accent);padding-left:6px}.status-badge{font-size:12px;color:var(--accent)}.tile-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px}.tile-grid .cell{min-height:40px}.actions button{min-height:48px}.form-field{display:grid;gap:8px;margin:14px 0;font-size:13px}.form-field input{width:100%;font-family:ui-monospace,monospace}.metrics.three{grid-template-columns:repeat(3,minmax(0,1fr))}.formula{min-height:3.2em}.presets{flex-wrap:wrap}.presets button{flex-basis:25%;min-height:44px}\n\n.budget{display:flex;height:28px;margin:16px 0;background:var(--surface);border-radius:5px;overflow:hidden}.budget i{display:block;background:var(--accent);transition:width .2s}.budget i.gold{background:var(--second)}.intervals{margin:16px 0}.interval{position:relative;height:36px;background:var(--surface);margin:6px 0;border-radius:4px;overflow:hidden}.interval i{position:absolute;height:100%;background:var(--accent-soft);border-left:2px solid var(--accent)}.interval i.gold{background:var(--second-soft);border-color:var(--second)}.interval span{position:relative;z-index:1;font:12px/36px ui-monospace,monospace;padding-left:7px}.table .tr>*{min-height:4.8em}.formula{white-space:pre-line;min-height:7.2em}.actions:has(>button:only-child){grid-template-columns:1fr}.metrics strong{min-height:3.2em}.rangegrid{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:3px;margin:14px 0}.rangegrid .cell{min-height:30px;padding:3px 1px;font-size:10px}.message{min-height:7.2em;white-space:pre-line;font:13px/1.8 ui-monospace,monospace;overflow-wrap:anywhere}\n/* Allow CJK hanging punctuation without overflowing a metric's border box. */\n.metrics>div{padding-right:4px}.metrics span{line-break:anywhere}\n\n.chart-wrap{margin:18px 0}.chart-label{font-size:12px;color:var(--muted);min-height:3.2em}.curve{display:block;width:100%;height:auto;max-height:320px;overflow:visible}.curve text{font:11px ui-monospace,monospace;fill:var(--muted)}.gridline{stroke:var(--rule);stroke-width:1}.metrics strong{font-size:20px;min-height:3.2em}.formula{font:12px/1.8 ui-monospace,monospace;min-height:9em}.readout{min-height:8em}.presets button{flex-basis:30%}.scope p{overflow-wrap:anywhere} .unit-note{font-size:12px;color:var(--muted);margin:10px 0}\n\n.metrics span{word-break:break-all;line-break:strict}.metrics>div{padding-right:6px}\n\n.cell{min-height:72px}.metrics strong{min-height:3.6em}\n\n#receiver{min-height:3em;font:16px ui-monospace,monospace}","js":"const $=s=>document.querySelector(s);const set=(id,v)=>$('#'+id).textContent=v;const t=k=>viz.t(k);function cells(id,values){$('#'+id).replaceChildren(...values.map(v=>{const e=document.createElement('div');e.className='cell '+(v.cls||'');e.textContent=v.text;e.title=v.title||v.text;return e;}));}function pressed(mode){document.querySelectorAll('[data-mode]').forEach(e=>e.setAttribute('aria-pressed',String(e.dataset.mode===mode)));}const esc=s=>String(s).replace(/[&<>\"']/g,c=>({'&':'&','<':'<','>':'>','\"':'"',\"'\":'''}[c]));const fmt=s=>'{'+[...s].sort().join(', ')+'}';function graph(id,nodes,edges){const el=$('#'+id);el.setAttribute('viewBox','0 0 360 200');el.innerHTML='<defs><marker id=\"arrow-'+id+'\" viewBox=\"0 0 10 10\" refX=\"8\" refY=\"5\" markerWidth=\"5\" markerHeight=\"5\" orient=\"auto-start-reverse\"><path d=\"M 0 0 L 10 5 L 0 10 z\" fill=\"var(--muted)\"/></marker></defs>'+edges.map(e=>{const a=nodes[e[0]],b=nodes[e[1]],dx=b.x-a.x,dy=b.y-a.y,d=Math.hypot(dx,dy)||1;if(edges.some(r=>r[0]===e[1]&&r[1]===e[0])){const nx=-dy/d,ny=dx/d;return '<path class=\"edge '+(e[2]?'on':'')+'\" d=\"M '+(a.x+dx/d*22+nx*12)+' '+(a.y+dy/d*22+ny*12)+' Q '+((a.x+b.x)/2+nx*38)+' '+((a.y+b.y)/2+ny*38)+' '+(b.x-dx/d*25+nx*12)+' '+(b.y-dy/d*25+ny*12)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}return '<line class=\"edge '+(e[2]?'on':'')+'\" x1=\"'+(a.x+dx/d*25)+'\" y1=\"'+(a.y+dy/d*25)+'\" x2=\"'+(b.x-dx/d*28)+'\" y2=\"'+(b.y-dy/d*28)+'\" marker-end=\"url(#arrow-'+id+')\"/>';}).join('')+nodes.map(n=>'<g><circle class=\"node '+(n.cls||'')+'\" cx=\"'+n.x+'\" cy=\"'+n.y+'\" r=\"25\"/><text x=\"'+n.x+'\" y=\"'+(n.y+4)+'\" text-anchor=\"middle\">'+esc(n.name)+'</text>'+(n.sub?'<text x=\"'+n.x+'\" y=\"'+(n.y+43)+'\" text-anchor=\"middle\">'+esc(n.sub)+'</text>':'')+'</g>').join('');}function table(id,rows){$('#'+id).classList.add('table');$('#'+id).replaceChildren(...rows.map(r=>{const row=document.createElement('div');row.className='tr';row.style.gridTemplateColumns='repeat('+r.length+',minmax(0,1fr))';r.forEach(x=>{const c=document.createElement('div');if(typeof x==='object'){c.textContent=x.text;c.className=x.cls||'';}else c.textContent=x;row.append(c)});return row;}));}function band(id,parts,total){$('#'+id).replaceChildren(...parts.map((p,i)=>{const e=document.createElement('i');e.style.width=(100*p.value/total)+'%';e.className=i%2?'gold':'on';e.title=p.name+': '+p.value;return e}));}function intervals(id,items,total){$('#'+id).replaceChildren(...items.map(p=>{const row=document.createElement('div');row.className='interval';const bar=document.createElement('i');bar.style.left=(100*p.start/total)+'%';bar.style.width=(100*(p.end-p.start)/total)+'%';bar.className=p.cls||'';const label=document.createElement('span');label.textContent=p.label;row.append(bar,label);return row;}));}function plot(id,series,xr,yr,opts={}){const e=$('#'+id),X=x=>42+(x-xr[0])/(xr[1]-xr[0])*298,Y=y=>175-(y-yr[0])/(yr[1]-yr[0])*148;let out='<defs><clipPath id=\"clip-'+id+'\"><rect x=\"42\" y=\"27\" width=\"298\" height=\"148\"/></clipPath></defs>';for(let i=0;i<3;i++){let x=xr[0]+i*(xr[1]-xr[0])/2,y=yr[0]+i*(yr[1]-yr[0])/2;out+='<path class=\"gridline\" d=\"M '+X(x)+' 27V175M42 '+Y(y)+'H340\"/><text x=\"'+X(x)+'\" y=\"194\" text-anchor=\"middle\">'+esc(opts.xfmt?opts.xfmt(x):Number(x.toFixed(2)))+'</text><text x=\"36\" y=\"'+(Y(y)+4)+'\" text-anchor=\"end\">'+esc(opts.yfmt?opts.yfmt(y):Number(y.toFixed(2)))+'</text>';}out+='<g clip-path=\"url(#clip-'+id+')\">';for(const s of series){out+='<path fill=\"none\" stroke=\"'+(s.color||'var(--accent)')+'\" stroke-width=\"2.5\" '+(s.dash?'stroke-dasharray=\"5 4\"':'')+' d=\"'+s.pts.map((p,i)=>(i?'L':'M')+X(p[0]).toFixed(2)+','+Y(p[1]).toFixed(2)).join(' ')+'\"/>';}for(const p of opts.points||[])out+='<circle cx=\"'+X(p[0])+'\" cy=\"'+Y(p[1])+'\" r=\"4\" fill=\"var(--second)\" stroke=\"var(--paper)\" stroke-width=\"1.5\"/>';if(opts.cursor!==undefined)out+='<path d=\"M'+X(opts.cursor)+' 27V175\" stroke=\"var(--muted)\" stroke-dasharray=\"3 3\"/>';e.innerHTML=out+'</g>';e.dataset.curves=JSON.stringify(series.map(s=>s.pts));}const curve=(fn,lo,hi,n=120)=>Array.from({length:n+1},(_,i)=>{const x=lo+(hi-lo)*i/n;return[x,fn(x)]});function inputs(draw){document.querySelectorAll('input,select').forEach(e=>{e.addEventListener('input',draw);e.addEventListener('change',draw)});draw()}const n=id=>+$('#'+id).value;const show=(id,v,d=3)=>set(id,Number(v.toFixed(d)));let mode='raw';function draw(){pressed(mode);let p=$('#present').checked,a=['0A','01','41',...(p?['12','00']:[])],b=mode==='decode'?a.slice(0,3):a;for(let [id,vals]of [['before',a],['after',b]])cells(id,Array.from({length:5},(_,i)=>({text:vals[i]||'—',cls:i<vals.length?(i>=3?'gold':'on'):'empty'})));set('receiver',p&&mode==='raw'?'Some(\"\")':'None');set('explanation',t('explain'));}document.querySelectorAll('[data-mode]').forEach(b=>b.onclick=()=>{mode=b.dataset.mode;draw()});inputs(draw);","audio":false,"strings":{"after":"中継後のバイト","before":"V2 の送信バイト","decode":"V1 で再符号化","explain":"12 = (2 << 3) OR 2、00 は長さゼロです。符号化上の存在と文字列が空でないことは別です。","heading":"旧ノードは新フィールドを保持できるか","intro":"optional locale の未指定と明示的な空値を選び、生バイト転送と旧 Prost の再符号化を比べます。","mode":"旧中継の動作","present":"明示的な Some(\"\") を送る","raw":"生バイトを転送","receiver":"V2 受信側の locale","reset":"リセット","scope":"name=\"A\" がフィールド 1、optional locale が 2 です。本文の Prost V1/V2 のモデルで、全実装への一般化ではありません。","scopeLabel":"モデルの範囲と前提"}}
Status、デッドライン、およびリトライ
Status は RPC の結果を表し、HTTP のレスポンスステータスだけを見てはいけません。一般的な分類は以下の通りです。完全なコード定義は gRPC Status Codes を参照してください。
コード アプリケーションでの判断基準
InvalidArgument リクエスト自体が要件を満たしていない。そのまま再試行しても無益な場合が多い
Unauthenticated / PermissionDenied 有効なIDがない / 権限が許可されていない
NotFound / AlreadyExists ビジネスリソースの状態に関連する
ResourceExhausted クォータまたは容量制限。スロットリングまたは予算の調整が必要
Unavailable 一時的に利用できない可能性があるが、操作を安全に再試行できるかどうかを判断する必要がある
DeadlineExceeded / Cancelled 呼び出し元が待機を停止した。遠端で効果が生じていないことを証明するものではない
クライアントにはデッドライン(期限切れ時刻)を設定すべきです。総予算には、キュー待ち、接続、処理、および可能性のあるリトライのカバーが必要です。Request::set_timeout は grpc-timeout メタデータに書き込まれ、ローカルでの転送タイムアウトを設定するのとは異なる操作です。上記の設定は connect の後に発生するため、接続確立自体に2秒の上限を設定しているわけではありません。
サービスがキャンセルされた後、アプリケーションは作成したバックグラウンドワークを停止する必要があります。ダウンストリームに RPC を送信する際は、各レイヤーで完全なタイムアウトを再設定するのではなく、残りの予算を伝播してください。異なる言語やライブラリでの伝播のサポートは異なるため、明確に検証する必要があります。gRPC Deadlines
ストリーミング処理のライフサイクルはより長い
サーバーが Response<Stream> を返すのは、レスポンスストリームが確立されたことを示すだけで、すべてのビジネスメッセージが完了したことを意味しません。その後、ストリームの要素は通常 Result<Message, Status> となります。消費側は正常な終了とエラーを区別する必要があり、while let Some(Ok(...)) でエラーを静かに飲み込んではいけません。
有界の mpsc チャンネルへの send().await は、消費者の遅延を生産者にフィードバックできます。送信に失敗した場合は、受信側が消滅したことを意味するため、unwrap するのではなく対応する作業を終了すべきです。無界キューは、ネットワークのバックプレッシャーをメモリ増加に変換する可能性があります。バックグラウンドタスクは、適切なキャンセルシグナルを保持して応答する必要があります。
メッセージサイズの制限は、ストリームの総サイズ制限ではありません。長時間のストリームには、時間、総バイト数、同時実行数、またはビジネスウィンドウの制御が必要です。クライアントが一部のみを取得して破棄した場合、サーバーも関連するリソースを解放する必要があります。
メッセージ 1:Ok(reply) 部分的な結果を先に配信できる メッセージ 2:Err(Status) 例:Unavailable 呼び出し元は失敗を記録する 受信済みデータは元に戻らない 正常な EOF と終了エラーは別々に処理する必要がある 一部メッセージを受信した後、最終的なステータスが依然としてこのRPCの終了方 法を決定する ビジネスで完全なコレクションを要求する場合、正常な終了後にコミットする必要があります。増分配信の場合は、リカ バリポイントと重複排除を定義する必要があります。
プロセス内で生産者と消費者の終了プロトコルを検証する
前述の tokio 依存関係の features に "sync" を追加し、以下の src/bin/stream_state.rs を保存してください。これは、ストリーミングサービスで一般的な生産側と同じ有界チャネルを使用し、キュー内の Result を直接観察します。このステップでは、ポートのリスニングや遠端サービスの呼び出しは必要ありません。
use tokio:: sync:: mpsc;
use tonic:: { Code, Status} ;
use grpc_demo:: greeter:: HelloReply;
# [ tokio ::main ]
async fn main ( ) {
let ( sender, mut receiver) = mpsc:: channel:: < Result< HelloReply, Status> > ( 1 ) ;
let producer = tokio:: spawn( async move {
if sender.send ( Ok ( HelloReply { message: " part-1" .into ( ) } ) ) .await.is_err ( ) {
return ;
}
let _ = sender.send ( Err ( Status:: unavailable( " source interrupted" ) ) ) .await;
} ) ;
let mut received = Vec :: new( ) ;
let mut failure = None ;
while let Some ( item) = receiver.recv ( ) .await {
match item {
Ok ( reply) => received.push ( reply.message) ,
Err ( status) => {
failure = Some ( status.code ( ) ) ;
break ;
}
}
}
drop ( receiver) ;
producer.await.unwrap ( ) ;
assert_eq! ( received, [ " part-1" ] ) ;
assert_eq! ( failure, Some ( Code:: Unavailable) ) ;
let ( sender, receiver) = mpsc:: channel:: < Result< HelloReply, Status> > ( 1 ) ;
drop ( receiver) ;
assert! ( sender.send ( Ok ( HelloReply { message: " unused" .into ( ) } ) ) .await.is_err ( ) ) ;
}
有界容量 1 は、キューに積まれるメッセージ項目数だけを制約し、1つのメッセージ内の文字列バイト数や、生産者が send の前に構築済みのオブジェクトのサイズは制限しません。生産者は受信側が離脱すると送信を停止します。データベースカーソルを保持している場合や他のタスクを開始している場合は、それらのリソースも同時に解放またはキャンセルする必要があります。
実際の tonic クライアントは、stream.message().await の Result<Option<Message>, Status> を使用して、メッセージ、正常な終了、およびエラーを別々に処理できます。Err を None として扱うことはできません。ビジネスで1回の完全なスナップショットを要求する場合、上記の例の part-1 は一時保存データに過ぎず、最終的に失敗した場合は完全な結果としてコミットすべきではありません。ビジネスが増分消費を許可する場合、再接続を受け入れるためにメッセージシーケンス番号、リカバリカーソル、および冪等処理が必要です。
ローカル検証と転送検証は異なる問題をカバーする
生成された Greeter トレイトメソッドを直接呼び出して空の name と正常なレスポンスを検証し、Prost を使用してフィールドエンコーディングをテストできます。これらのチェックは、ビジネスおよびプロトコルモデルの問題を迅速に特定します。転送層では、メタデータ、TLS、メッセージ制限、デッドライン、およびストリームの終了状態を別途確認する必要があります。ハンドラーを直接呼び出す場合、tonic の HTTP/2 エンコーディング/デコーディングおよびミドルウェアを経由しないためです。
同様に、クライアントの set_timeout によって生成されたメタデータは、サーバーと中継チェーンが正しく理解する必要があります。これは、Channel 作成前の DNS/接続待機に予算を追加するものではなく、バックグラウンドタスクが自動的に停止することを意味するものでもありません。1つのユーザー操作围绕して総期限を設定し、接続確立、RPC 待機、およびアプリケーションリソースのクリーンアップをそれぞれ検証してください。
Interceptor はどのような場面に適しているか
Interceptor のインターフェースは Request<()> を処理し、リクエストまたは Status を同期的に返します。メタデータの読み取り、軽量コンテキストの注入、および即時拒絶に適しています。リモート認証を直接 await することはできず、任意のレスポンスボディの変換機能も提供しません。Interceptor
非同期の外部クエリ、リクエストとレスポンスの完全な観測、またはより細かいフロー制御が必要な場合は、挿入に適した Tower サービスを使用するか、ビジネスサービス内で明示的に完了してください。どこに配置するかにかかわらず、エラーがどのように Status に変換され、ストリーム終了時にリソースをどのようにクリーンアップするかを明確にする必要があります。Tower とミドルウェア を参照してください。