AWS SDK for Rust でのインターセプターの設定 - AWS SDK for Rust

AWS SDK for Rust でのインターセプターの設定

インターセプターを使用して、API リクエストおよびレスポンスの実行フローにフックを挿入できます。インターセプターは、SDK がユーザー定義のコードを呼び出して、リクエスト/レスポンスのライフサイクルに処理を挿入できるようにする、柔軟な仕組みです。これにより、進行中のリクエストの変更、リクエスト処理のデバッグ、エラーの確認などを行うことができます。

次の例は、再試行ループに入る前にすべての送信リクエストにヘッダーを追加するシンプルなインターセプターを示しています。

use std::borrow::Cow; use aws_smithy_runtime_api::client::interceptors::{ Intercept, context::BeforeTransmitInterceptorContextMut, }; use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents; use aws_smithy_types::config_bag::ConfigBag; use aws_smithy_runtime_api::box_error::BoxError; #[derive(Debug)] struct AddHeaderInterceptor { key: Cow<'static, str>, value: Cow<'static, str>, } impl AddHeaderInterceptor { fn new(key: &'static str, value: &'static str) -> Self { Self { key: Cow::Borrowed(key), value: Cow::Borrowed(value), } } } impl Intercept for AddHeaderInterceptor { fn name(&self) -> &'static str { "AddHeader" } fn modify_before_retry_loop( &self, context: &mut BeforeTransmitInterceptorContextMut<'_>, _runtime_components: &RuntimeComponents, _cfg: &mut ConfigBag, ) -> Result<(), BoxError> { let headers = context.request_mut().headers_mut(); headers.insert(self.key.clone(), self.value.clone()); Ok(()) } }

詳細と使用可能なインターセプターフックについては、「インターセプト」トレイトを参照してください。

インターセプターの登録

インターセプターは、サービスクライアントをコンストラクトするときや、特定のオペレーションの設定をオーバーライドするときに登録します。登録方法は、インターセプターをクライアントのすべてのオペレーションに適用するか、特定のオペレーションのみに適用するかによって異なります。

サービスクライアントに対するすべてのオペレーションのインターセプター

クライアント全体のインターセプターを登録するには、Builder パターンを使用してインターセプターを追加します。

let config = aws_config::defaults(BehaviorVersion::latest()) .load() .await; // All service operations invoked using 's3' will have the header added. let s3_conf = aws_sdk_s3::config::Builder::from(&config) .interceptor(AddHeaderInterceptor::new("x-foo-version", "2.7")) .build(); let s3 = aws_sdk_s3::Client::from_conf(s3_conf);

特定のオペレーションのみのインターセプター

1 回のオペレーションのみにインターセプターを登録するには、customize 拡張機能を使用します。このメソッドを使用すると、サービスクライアントの設定をオペレーション単位でオーバーライドできます。これらのカスタマイズ可能なオペレーションの詳細については、「AWS SDK for Rust で、クライアントの 1 回でのオペレーション設定をオーバーライドする」を参照してください。

// Only the list_buckets operation will have the header added. s3.list_buckets() .customize() .interceptor(AddHeaderInterceptor::new("x-bar-version", "3.7")) .send() .await?;