View a markdown version of this page

Rust SQLx 用 Aurora DSQL コネクタ - Amazon Aurora DSQL

Rust SQLx 用 Aurora DSQL コネクタ

Rust 用 Aurora DSQL コネクタは、Rust アプリケーションを Amazon Aurora DSQL クラスターに接続するための IAM 認証を統合した SQLx 上に構築された Rust コネクタです。

コネクタはトークン生成、SSL 設定、および接続管理を処理するため、ユーザーはアプリケーションロジックに集中できます。

コネクタについて

Rust 用 Aurora DSQL コネクタは、IAM トークン生成を処理する SQLx 上に認証レイヤーを追加し、既存の SQLx ワークフローを変更せずに Aurora DSQL に接続できるようにします。

Aurora DSQL 認証とは

Aurora DSQL では、認証に以下が含まれます。

  • IAM 認証: すべての接続で、時間制限付きトークンによる IAM ベースの認証が使用されます

  • トークン生成: コネクタは AWS 認証情報を使用して認証トークンを生成します。これらのトークンの有効期間は設定可能です。

Rust 用 Aurora DSQL コネクタは、これらの要件を理解し、接続の確立時に IAM 認証トークンを自動的に生成します。

機能

  • 自動 IAM 認証 - Aurora DSQL トークンの生成と更新を処理

  • SQLx 上に構築 - Rust 用の一般的な PostgreSQL ドライバーをラップ

  • シームレスな統合 - 既存の SQLx ワークフローと連携

  • 接続プーリング - pool 機能を介したバックグラウンドでのトークン更新によるオプトインのプールサポート

  • リージョンの自動検出 - Aurora DSQL クラスターホスト名から AWS リージョンを抽出

  • AWS 認証情報のサポート - AWS プロファイルとデフォルトの認証情報チェーンをサポート

  • OCC 再試行 - エクスポネンシャルバックオフとジッターを使用したオプトインのオプティミスティック同時実行制御の再試行

サンプルアプリケーション

詳細な例については、GitHub のサンプルアプリケーションを参照してください。

クイックスタートガイド

要件

インストール

Cargo.toml に追加:

[dependencies] aurora-dsql-sqlx-connector = "0.1.2"

ほとんどのアプリケーションでは、pool 機能と occ 機能の両方を有効にします。

[dependencies] aurora-dsql-sqlx-connector = { version = "0.1.2", features = ["pool", "occ"] }

機能フラグ

機能 デフォルト 説明
pool いいえ バックグラウンドでのトークン更新機能付きの SQLx プールヘルパー
occ いいえ OCC 再試行ヘルパー (retry_on_occis_occ_error)

Usage

プール接続

use sqlx::Row; #[tokio::main] async fn main() -> anyhow::Result<()> { let pool = aurora_dsql_sqlx_connector::pool::connect( "postgres://admin@your-cluster.dsql.us-east-1.on.aws/postgres" ).await?; // Read let row = sqlx::query("SELECT 'Hello, DSQL!' as greeting") .fetch_one(&pool) .await?; let greeting: &str = row.get("greeting"); println!("{}", greeting); // Write — you must wrap writes in a transaction let mut tx = pool.begin().await?; sqlx::query("INSERT INTO users (id, name) VALUES (gen_random_uuid(), $1)") .bind("Alice") .execute(&mut *tx) .await?; tx.commit().await?; pool.close().await; Ok(()) }

シングル接続

シンプルなスクリプトの場合、または接続プーリングが必要ない場合:

use sqlx::Row; #[tokio::main] async fn main() -> anyhow::Result<()> { let mut conn = aurora_dsql_sqlx_connector::connection::connect( "postgres://admin@your-cluster.dsql.us-east-1.on.aws/postgres" ).await?; let row = sqlx::query("SELECT 1 as value") .fetch_one(&mut conn) .await?; let value: i32 = row.get("value"); println!("Result: {}", value); Ok(()) }

connection::connect() を呼び出すたびに、新しい IAM トークンが生成されます。トークン期間より長いオペレーションの場合は、新しい接続を作成します。

高度な使用法

ホスト設定

コネクタは、完全なクラスターエンドポイント (リージョンの自動検出) とクラスター ID (リージョンが必要) の両方をサポートしています。

// Full endpoint (region auto-detected) let opts = DsqlConnectOptions::from_connection_string( "postgres://admin@your-cluster.dsql.us-east-1.on.aws/postgres" )?; // Cluster ID (region required) let opts = DsqlConnectOptions::from_connection_string( "postgres://admin@your-cluster-id/postgres?region=us-east-1" )?;

AWS プロファイル

認証情報の AWS プロファイルを指定します。

let pool = aurora_dsql_sqlx_connector::pool::connect( "postgres://admin@your-cluster.dsql.us-east-1.on.aws/postgres?profile=production" ).await?;

接続文字列形式

コネクタは、PostgreSQL 接続文字列形式をサポートしています。

postgres://[user@]host[:port]/[database][?param=value&...] postgresql://[user@]host[:port]/[database][?param=value&...]

サポートされているクエリパラメータ: regionprofiletokenDurationSecsormPrefix

プール設定

カスタムプール設定の場合は、PgPoolOptionsconnect_with() に渡します。

use aurora_dsql_sqlx_connector::DsqlConnectOptions; use sqlx::postgres::PgPoolOptions; let config = DsqlConnectOptions::from_connection_string( "postgres://admin@your-cluster.dsql.us-east-1.on.aws/postgres" )?; let pool = aurora_dsql_sqlx_connector::pool::connect_with( &config, PgPoolOptions::new().max_connections(20), ).await?;

プログラムによる設定

プログラムで設定する場合は DsqlConnectOptionsBuilder を使用します。

use aurora_dsql_sqlx_connector::{DsqlConnectOptionsBuilder, Region}; use sqlx::postgres::PgConnectOptions; let pg = PgConnectOptions::new() .host("your-cluster.dsql.us-east-1.on.aws") .username("admin") .database("postgres"); let opts = DsqlConnectOptionsBuilder::default() .pg_connect_options(pg) .region(Some(Region::new("us-east-1"))) .build()?; let mut conn = aurora_dsql_sqlx_connector::connection::connect_with(&opts).await?;

OCC 再試行

Aurora DSQL は、オプティミスティック同時実行制御 (OCC) を使用します。2 つのトランザクションが同じデータを変更する場合、最初のトランザクションはコミットに成功し、2 番目のトランザクションは OCC エラーを受け取ります。

OCC 再試行はオプトインです。occ 機能を有効にし、retry_on_occ を使用してエクスポネンシャルバックオフとジッターによる自動再試行を有効にします。

use aurora_dsql_sqlx_connector::{retry_on_occ, OCCRetryConfig}; let config = OCCRetryConfig::default(); // max_attempts: 3, exponential backoff retry_on_occ(&config, || async { let mut tx = pool.begin().await?; sqlx::query("UPDATE accounts SET balance = balance - 100 WHERE id = $1") .bind(account_id) .execute(&mut *tx) .await?; tx.commit().await?; Ok(()) }).await?;
警告

OCC の競合が発生した場合、retry_on_occ はクロージャ全体を再実行するため、クロージャ内にはデータベースオペレーションのみを含め、安全に再試行できるようにする必要があります。

設定オプション

フィールド タイプ デフォルト 説明
host String (必須) クラスターエンドポイントまたはクラスター ID
region Option<Region> (自動検出) AWS リージョン (host がクラスター ID の場合は必須)
user String "admin" データベースユーザー
database String "postgres" データベース名
port u16 5432 データベースポート
profile Option<String> None 認証情報の AWS プロファイル名
tokenDurationSecs u64 900 (15 分) トークンの有効期間 (秒)
ormPrefix Option<String> None application_name の ORM プレフィックス (例えば、"diesel""diesel:aurora-dsql-rust-sqlx/{version}" を生成します)

認証

コネクタは、AWS 認証情報を使用してトークンを生成することで、Aurora DSQL 認証を自動的に処理します。AWS リージョンを指定しない場合、コネクタはホスト名からリージョンを解析します。

Aurora DSQL の認証の詳細については、「Aurora DSQL の認証および認可」を参照してください。

トークン生成

  • 接続プール: バックグラウンドタスクは、トークン期間の 80% でトークンを更新します。更新タスクを停止してプールリソースを解放するには、pool.close().await を呼び出します。

  • 単一接続: コネクタは接続時に新しいトークンを生成します。

  • トークン生成は、ローカル SigV4 署名付きオペレーションであり、コストはごくわずかです。

管理者ユーザーと通常のユーザー

  • 「admin」という名前のユーザーは、管理者認証トークンを自動的に使用します。

  • 他のすべてのユーザーは通常の認証トークンを使用します。

  • コネクタは、接続ごとにトークンを動的に生成します。