-
Notifications
You must be signed in to change notification settings - Fork 313
Cosmos: Container Metadata Cache #3109
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
Draft
analogrelay
wants to merge
8
commits into
Azure:main
Choose a base branch
from
analogrelay:ashleyst/container-meta-cache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+504
−111
Draft
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
177b88a
add container routing map and tests
analogrelay 1165fc5
start on CMC
analogrelay 595692f
rename CosmosPipeline to CosmosConnection
analogrelay 30fea5b
container metadata cache, and caching for read_throughput
analogrelay 3e12377
update test recordings
analogrelay c8f88c9
final review tidy up
analogrelay d1a0cfd
removed unused metadata from cache for now
analogrelay 1eafb43
clippy lints
analogrelay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
{ | ||
"AssetsRepo": "Azure/azure-sdk-assets", | ||
"AssetsRepoPrefixPath": "rust", | ||
"Tag": "rust/azure_data_cosmos_a39b424a5b", | ||
"Tag": "rust/azure_data_cosmos_69ad1e4995", | ||
"TagPrefix": "rust/azure_data_cosmos" | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
use std::sync::Arc; | ||
|
||
use moka::future::Cache; | ||
|
||
use crate::{ | ||
models::{ContainerProperties, PartitionKeyDefinition}, | ||
resource_context::ResourceLink, | ||
ResourceId, | ||
}; | ||
|
||
#[derive(Debug)] | ||
pub enum CacheError { | ||
FetchError(Arc<azure_core::Error>), | ||
} | ||
|
||
impl From<Arc<azure_core::Error>> for CacheError { | ||
fn from(e: Arc<azure_core::Error>) -> Self { | ||
CacheError::FetchError(e) | ||
} | ||
} | ||
|
||
impl From<CacheError> for azure_core::Error { | ||
fn from(e: CacheError) -> Self { | ||
match e { | ||
CacheError::FetchError(e) => { | ||
let message = format!("error updating Container Metadata Cache: {}", e); | ||
azure_core::Error::with_error(azure_core::error::ErrorKind::Other, e, message) | ||
} | ||
} | ||
} | ||
} | ||
|
||
impl std::fmt::Display for CacheError { | ||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
match self { | ||
CacheError::FetchError(e) => write!(f, "error fetching latest value: {}", e), | ||
} | ||
} | ||
} | ||
|
||
impl std::error::Error for CacheError { | ||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | ||
match self { | ||
CacheError::FetchError(e) => Some(&**e), | ||
} | ||
} | ||
} | ||
|
||
/// A subset of container properties that are stable and suitable for caching. | ||
pub(crate) struct ContainerMetadata { | ||
pub self_link: String, | ||
pub resource_id: ResourceId, | ||
pub partition_key: PartitionKeyDefinition, | ||
pub container_link: ResourceLink, | ||
} | ||
|
||
impl ContainerMetadata { | ||
// We can't use From<ContainerProperties> because we also want the container link. | ||
pub fn from_properties( | ||
properties: &ContainerProperties, | ||
container_link: ResourceLink, | ||
) -> azure_core::Result<Self> { | ||
let self_link = properties | ||
.system_properties | ||
.self_link | ||
.as_ref() | ||
.ok_or_else(|| { | ||
azure_core::Error::new( | ||
azure_core::error::ErrorKind::Other, | ||
"container properties is missing expected value 'self_link'", | ||
) | ||
})? | ||
.clone(); | ||
let resource_id = properties | ||
.system_properties | ||
.resource_id | ||
.clone() | ||
.ok_or_else(|| { | ||
azure_core::Error::new( | ||
azure_core::error::ErrorKind::Other, | ||
"container properties is missing expected value 'resource_id'", | ||
) | ||
})?; | ||
Ok(Self { | ||
self_link, | ||
resource_id, | ||
partition_key: properties.partition_key.clone(), | ||
container_link, | ||
}) | ||
} | ||
} | ||
|
||
/// A cache for container metadata, including properties and routing information. | ||
/// | ||
/// The cache can be cloned cheaply, and all clones share the same underlying cache data. | ||
#[derive(Clone)] | ||
pub struct ContainerMetadataCache { | ||
/// Caches stable container metadata, mapping from container link to metadata. | ||
container_properties_cache: Cache<ResourceLink, Arc<ContainerMetadata>>, | ||
} | ||
|
||
// TODO: Review this value. | ||
// Cosmos has a backend limit of 500 databases and containers per account by default. | ||
// This value affects when Moka will start evicting entries from the cache. | ||
// It could probably be much lower without much impact, but we need to do the research to be sure. | ||
const MAX_CACHE_CAPACITY: u64 = 500; | ||
|
||
impl ContainerMetadataCache { | ||
/// Creates a new `ContainerMetadataCache` with default settings. | ||
/// | ||
/// Since the cache is designed to be shared, it is returned inside an `Arc`. | ||
pub fn new() -> Self { | ||
let container_properties_cache = Cache::new(MAX_CACHE_CAPACITY); | ||
Self { | ||
container_properties_cache, | ||
} | ||
} | ||
|
||
/// Unconditionally updates the cache with the provided container metadata. | ||
pub async fn set_container_metadata(&self, metadata: ContainerMetadata) { | ||
let metadata = Arc::new(metadata); | ||
|
||
self.container_properties_cache | ||
.insert(metadata.container_link.clone(), metadata) | ||
.await; | ||
} | ||
|
||
/// Gets the container metadata from the cache, or initializes it using the provided async function if not present. | ||
pub async fn get_container_metadata( | ||
&self, | ||
key: &ResourceLink, | ||
init: impl std::future::Future<Output = azure_core::Result<ContainerMetadata>>, | ||
) -> Result<Arc<ContainerMetadata>, CacheError> { | ||
// TODO: Background refresh. We can do background refresh by storing an expiry time in the cache entry. | ||
// Then, if the entry is stale, we can return the stale entry and spawn a background task to refresh it. | ||
// There's a little trickiness here in that we can't directly spawn a task because that depends on a specific Async Runtime (tokio, smol, etc). | ||
// The core SDK has an AsyncRuntime abstraction that we can use to spawn the task. | ||
Ok(self | ||
.container_properties_cache | ||
.try_get_with_by_ref(key, async { init.await.map(Arc::new) }) | ||
.await?) | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Azure/azure-sdk-assets@69ad1e4#diff-7879243660aeae990c47455256d1e25f7fe7ed0e8f9206a047e4eb054849ecd0