Skip to content

Commit

Permalink
Merge pull request #57 from liufuyang/increase-GCloudAuthorizedUser-p…
Browse files Browse the repository at this point in the history
…erformance

feat: cache token for GCloudAuthorizedUser
  • Loading branch information
hrvolapeter authored Oct 10, 2022
2 parents c7e04d5 + a00dcf3 commit c589190
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
2 changes: 1 addition & 1 deletion src/authentication_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl AuthenticationManager {
}

let client = types::client();
let gcloud_error = match GCloudAuthorizedUser::new() {
let gcloud_error = match GCloudAuthorizedUser::new().await {
Ok(service_account) => {
tracing::debug!("Using GCloudAuthorizedUser");
return Ok(Self::build(client, service_account));
Expand Down
29 changes: 19 additions & 10 deletions src/gcloud_authorized_user.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::RwLock;

use async_trait::async_trait;
use which::which;
Expand All @@ -14,18 +15,24 @@ use crate::Token;
pub(crate) struct GCloudAuthorizedUser {
gcloud: PathBuf,
project_id: Option<String>,
token: RwLock<Token>,
}

impl GCloudAuthorizedUser {
pub(crate) fn new() -> Result<Self, Error> {
pub(crate) async fn new() -> Result<Self, Error> {
let gcloud = which("gcloud").map_err(|_| GCloudNotFound)?;
let project_id = run(&gcloud, &["config", "get-value", "project"]).ok();
Ok(Self { gcloud, project_id })
let token = RwLock::new(Self::token(&gcloud)?);
Ok(Self {
gcloud,
project_id,
token,
})
}

fn token(&self) -> Result<Token, Error> {
fn token(gcloud: &Path) -> Result<Token, Error> {
Ok(Token::from_string(run(
&self.gcloud,
gcloud,
&["auth", "print-access-token", "--quiet"],
)?))
}
Expand All @@ -38,11 +45,13 @@ impl ServiceAccount for GCloudAuthorizedUser {
}

fn get_token(&self, _scopes: &[&str]) -> Option<Token> {
None
Some(self.token.read().unwrap().clone())
}

async fn refresh_token(&self, _client: &HyperClient, _scopes: &[&str]) -> Result<Token, Error> {
self.token()
let token = Self::token(&self.gcloud)?;
*self.token.write().unwrap() = token.clone();
Ok(token)
}
}

Expand All @@ -66,11 +75,11 @@ fn run(gcloud: &Path, cmd: &[&str]) -> Result<String, Error> {
mod tests {
use super::*;

#[test]
#[tokio::test]
#[ignore]
fn gcloud() {
let gcloud = GCloudAuthorizedUser::new().unwrap();
async fn gcloud() {
let gcloud = GCloudAuthorizedUser::new().await.unwrap();
println!("{:?}", gcloud.project_id);
println!("{:?}", gcloud.token());
println!("{:?}", gcloud.get_token(&[""]));
}
}

0 comments on commit c589190

Please sign in to comment.