Cosmos: Container Metadata Cache #3109
Draft
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.
This PR adds an initial version of the Container Metadata Cache, which caches metadata about a container that is frequently needed but infrequently changes. Right now, that's limited to the RID, but the patterns are here to allow us to add more cached metadata as needed.
To create an async single-flight (defined shortly) cache, I decided to use a third-party crate rather than building it myself. I did start along the path of building it myself and we can certainly do so, but as I got into testing I realized that I'd much rather use something well-tested that already exists for now. I chose the top result on crates.io when looking for an async cache: moka, which crates.io itself uses. It is frequently updated and highly used in the ecosystem. Plus, we don't expose anything from it on our public API, so we can replace it later without risk to users.
The main reason the cache is complicated is that I really wanted to make sure the cache was both async-friendly (i.e. works with async/await) and "single-flight", meaning there's only ever one outstanding request to update a given cache key. Those familiar with .NET might think about
Lazy<T>
's "LazyThreadSafeMode". A single-flight cache is similar toLazyThreadSafeMode.ExecutionAndPublication
, in that it ensures that only a single initialization function is running at a time. Moka does this, viaget_with
(we actually useget_with_by_ref
, but it's very similar), which guarantees:Not all of our SDKs do this kind of optimization, but I believe the .NET one does (from my reading) and if the Rust SDK is to serve as a core reference implementation, it seems important for it to do it as well.
Building an async single-flight cache in a runtime-agnostic way (i.e. not directly depending on tokio, smol, or some other async runtime) is possible, but complicated, so I wanted to let Moka do all that work for us for now ;).