Skip to content

Commit

Permalink
Make client Sync
Browse files Browse the repository at this point in the history
  • Loading branch information
mzohreva committed Nov 18, 2021
1 parent 2ebb724 commit 77743b7
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ use rustc_serialize::base64::{ToBase64, STANDARD};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use std::cell::RefCell;
use std::fmt;
use std::io::Read;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

Expand Down Expand Up @@ -104,7 +104,7 @@ impl SdkmsClientBuilder {
client,
api_endpoint: self.api_endpoint.unwrap_or_else(|| DEFAULT_API_ENDPOINT.to_owned()),
auth: self.auth,
last_used: RefCell::new(0),
last_used: AtomicU64::new(0),
auth_response: None,
})
}
Expand Down Expand Up @@ -151,7 +151,7 @@ pub struct SdkmsClient {
auth: Option<Auth>,
api_endpoint: String,
client: Arc<HyperClient>,
last_used: RefCell<u64>, // Time.0
last_used: AtomicU64, // Time.0
auth_response: Option<AuthResponse>,
}

Expand All @@ -177,7 +177,7 @@ impl SdkmsClient {
client: self.client.clone(),
api_endpoint: self.api_endpoint.clone(),
auth: Some(Auth::Bearer(auth_response.access_token.clone())),
last_used: RefCell::new(now().0),
last_used: AtomicU64::new(now().0),
auth_response: Some(auth_response),
})
}
Expand Down Expand Up @@ -224,7 +224,7 @@ impl SdkmsClient {
{
let Self { ref client, ref api_endpoint, ref auth, .. } = *self;
let result = json_request_with_auth(client, api_endpoint, method, uri, auth.as_ref(), req)?;
self.last_used.replace(now().0);
self.last_used.store(now().0, Ordering::Relaxed);
Ok(result)
}
}
Expand Down Expand Up @@ -280,8 +280,7 @@ impl SdkmsClient {
}

pub fn expires_in(&self) -> Option<u64> {
let expires_at =
*self.last_used.borrow() + self.auth_response().map_or(0, |ar| ar.expires_in as u64);
let expires_at = self.last_used.load(Ordering::Relaxed) + self.auth_response().map_or(0, |ar| ar.expires_in as u64);
expires_at.checked_sub(now().0)
}
}
Expand Down Expand Up @@ -387,3 +386,20 @@ where
}
}
}

#[cfg(test)]
mod tests {
use super::*;

fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}

#[test]
fn client_is_send_and_sync() {
assert_send::<SdkmsClient>();
assert_sync::<SdkmsClient>();

assert_send::<SdkmsClientBuilder>();
assert_sync::<SdkmsClientBuilder>();
}
}

0 comments on commit 77743b7

Please sign in to comment.