Skip to content

Commit b543f41

Browse files
committed
Deploy: refresh token if close to expiry
Signed-off-by: itowlson <[email protected]>
1 parent c86d7c8 commit b543f41

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

src/commands/deploy.rs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ mod resource;
4040
const DEVELOPER_CLOUD_FAQ: &str = "https://developer.fermyon.com/cloud/faq";
4141
const SPIN_DEFAULT_KV_STORE: &str = "default";
4242

43+
/// The amount of time a token must have remaining before expiry for us to be
44+
/// confident it will last long enough to complete a deploy operation. That is,
45+
/// if a token is closer than this to expiration when we start a deploy
46+
/// operation, we should refresh it pre-emptively so that it's unlikely to expire
47+
/// while the operation is in progress.
48+
const TOKEN_MUST_HAVE_REMAINING: chrono::TimeDelta = chrono::TimeDelta::minutes(5);
49+
4350
// When we come to list features here, you can find consts for them in `spin_locked_app`
4451
// e.g. spin_locked_app::locked::SERVICE_CHAINING_KEY.
4552
const CLOUD_SUPPORTED_FEATURES: &[&str] = &[];
@@ -882,12 +889,17 @@ fn print_available_routes(
882889
println!("Manage application: {admin_url}");
883890
}
884891

885-
// Check if the token has expired.
886-
// If the expiration is None, assume the token has not expired
887-
fn has_expired(login_connection: &LoginConnection) -> Result<bool> {
892+
// Check if the token has expired - or is so close to expiring that we
893+
// aren't confident it will last long enough to complete a deploy!
894+
// If the expiration is None, assume the token is current and will last long enough.
895+
fn needs_renewal(login_connection: &LoginConnection) -> Result<bool> {
888896
match &login_connection.expiration {
889897
Some(expiration) => match DateTime::parse_from_rfc3339(expiration) {
890-
Ok(time) => Ok(Utc::now() > time),
898+
Ok(time) => {
899+
let time = time.to_utc();
900+
let token_time_remaining = time - Utc::now();
901+
Ok(token_time_remaining < TOKEN_MUST_HAVE_REMAINING)
902+
}
891903
Err(err) => Err(anyhow!(
892904
"Failed to parse token expiration time '{}'. Error: {}",
893905
expiration,
@@ -926,7 +938,7 @@ pub async fn login_connection(deployment_env_id: Option<&str>) -> Result<LoginCo
926938
};
927939

928940
let mut login_connection: LoginConnection = serde_json::from_str(&data)?;
929-
let expired = match has_expired(&login_connection) {
941+
let expired = match needs_renewal(&login_connection) {
930942
Ok(val) => val,
931943
Err(err) => {
932944
eprintln!("{}\n", err);

0 commit comments

Comments
 (0)