Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only perform fetches of credentials for a realm once #3237

Merged
merged 1 commit into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/uv-auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ base64 = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
once_cell = { workspace = true }
once-map = { workspace = true }
reqwest = { workspace = true }
reqwest-middleware = { workspace = true }
rust-netrc = { workspace = true }
tracing = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
urlencoding = { workspace = true }

Expand Down
4 changes: 4 additions & 0 deletions crates/uv-auth/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ use std::{collections::HashMap, sync::Mutex};
use crate::credentials::{Credentials, Username};
use crate::Realm;

use once_map::OnceMap;
use tracing::trace;
use url::Url;

pub struct CredentialsCache {
/// A cache per realm and username
realms: Mutex<HashMap<(Realm, Username), Arc<Credentials>>>,
/// A cache tracking the result of fetches from external services
pub(crate) fetches: OnceMap<(Realm, Username), Option<Arc<Credentials>>>,
Comment on lines 12 to +15
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This duplication hints that we should refactor the realm cache but I don't want to make further changes here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pub(crate) seems slightly off but perhaps not worth exposing these as methods.

/// A cache per URL, uses a trie for efficient prefix queries.
urls: Mutex<UrlTrie>,
}
Expand All @@ -25,6 +28,7 @@ impl CredentialsCache {
pub fn new() -> Self {
Self {
realms: Mutex::new(HashMap::new()),
fetches: OnceMap::default(),
urls: Mutex::new(UrlTrie::new()),
}
}
Expand Down
42 changes: 38 additions & 4 deletions crates/uv-auth/src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ impl Middleware for AuthMiddleware {
.await
{
request = credentials.authenticate(request);
Some(Arc::new(credentials))
Some(credentials)
} else {
// If we don't find a password, we'll still attempt the request with the existing credentials
Some(credentials)
Expand Down Expand Up @@ -244,7 +244,7 @@ impl Middleware for AuthMiddleware {
retry_request = credentials.authenticate(retry_request);
trace!("Retrying request for {url} with {credentials:?}");
return self
.complete_request(Some(Arc::new(credentials)), retry_request, extensions, next)
.complete_request(Some(credentials), retry_request, extensions, next)
.await;
}

Expand Down Expand Up @@ -300,9 +300,37 @@ impl AuthMiddleware {
&self,
credentials: Option<&Credentials>,
url: &Url,
) -> Option<Credentials> {
) -> Option<Arc<Credentials>> {
// Fetches can be expensive, so we will only run them _once_ per realm and username combination
// All other requests for the same realm will wait until the first one completes
let key = (
Realm::from(url),
Username::from(
credentials
.map(|credentials| credentials.username().unwrap_or_default().to_string()),
),
);

if !self.cache().fetches.register(key.clone()) {
let credentials = Arc::<_>::unwrap_or_clone(
self.cache()
.fetches
.wait(&key)
.await
.expect("The key must exist after register is called"),
);

if credentials.is_some() {
trace!("Using credentials from previous fetch for {url}");
} else {
trace!("Skipping fetch of credentails for {url}, previous attempt failed");
};

return credentials;
}

// Netrc support based on: <https://github.com/gribouille/netrc>.
if let Some(credentials) = self.netrc.as_ref().and_then(|netrc| {
let credentials = if let Some(credentials) = self.netrc.as_ref().and_then(|netrc| {
trace!("Checking netrc for credentials for {url}");
Credentials::from_netrc(
netrc,
Expand Down Expand Up @@ -336,6 +364,12 @@ impl AuthMiddleware {
} else {
None
}
.map(Arc::new);

// Register the fetch for this key
self.cache().fetches.done(key.clone(), credentials.clone());

credentials
}
}

Expand Down
Loading