Skip to content

Commit f4e9f8c

Browse files
marcbowesdanielfrankcom
authored andcommitted
rust/sqlx: Refresh the token every 10 minutes
Launch a tokio task that updates the password every 10 minutes. The tokens expire every 15 minutes. This is a stopgap until sqlx can be made to support this natively. See also: launchbadge/sqlx#445
1 parent ed00833 commit f4e9f8c

1 file changed

Lines changed: 25 additions & 2 deletions

File tree

rust/sqlx/src/main.rs

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1+
use std::time::Duration;
2+
13
use aws_config::{BehaviorVersion, Region};
24
use aws_sdk_dsql::auth_token::{AuthTokenGenerator, Config};
35
use rand::Rng;
4-
use sqlx::Row;
56
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
7+
use sqlx::Row;
8+
use tokio::time;
69
use uuid::Uuid;
710

811
async fn example(cluster_endpoint: String, region: String) -> anyhow::Result<()> {
@@ -12,10 +15,14 @@ async fn example(cluster_endpoint: String, region: String) -> anyhow::Result<()>
1215
Config::builder()
1316
.hostname(&cluster_endpoint)
1417
.region(Region::new(region))
18+
.expires_in(900)
1519
.build()
1620
.unwrap(),
1721
);
18-
let password_token = signer.db_connect_admin_auth_token(&sdk_config).await.unwrap();
22+
let password_token = signer
23+
.db_connect_admin_auth_token(&sdk_config)
24+
.await
25+
.unwrap();
1926

2027
// Setup connections
2128
let connection_options = PgConnectOptions::new()
@@ -31,6 +38,22 @@ async fn example(cluster_endpoint: String, region: String) -> anyhow::Result<()>
3138
.connect_with(connection_options.clone())
3239
.await?;
3340

41+
// XXX: Periodically refresh the password by regenerating the token. This
42+
// runs every 10 minutes and provides a token valid for 15 minutes.
43+
let _pool = pool.clone(); // Pool uses an Arc internally
44+
tokio::spawn(async move {
45+
loop {
46+
time::sleep(Duration::from_secs(600)).await;
47+
let password_token = signer
48+
.db_connect_admin_auth_token(&sdk_config)
49+
.await
50+
.unwrap();
51+
let connect_options_with_new_token =
52+
connection_options.clone().password(password_token.as_str());
53+
_pool.set_connect_options(connect_options_with_new_token);
54+
}
55+
});
56+
3457
// Create owners table
3558
// To avoid Optimistic concurrency control (OCC) conflicts
3659
// Have this table created already.

0 commit comments

Comments
 (0)