pub struct StaticPartitionMap<K, V> { /* private fields */ }
Expand description
A data structure for persisting and sharing state between multiple clients.
Some state should be shared between multiple clients. For example, when creating multiple clients for the same service, it’s desirable to share a client rate limiter. This way, when one client receives a throttling response, the other clients will be aware of it as well.
Whether clients share state is dependent on their partition key K
. Going back to the client
rate limiter example, K
would be a struct containing the name of the service as well as the
client’s configured region, since receiving throttling responses in us-east-1
shouldn’t
throttle requests to the same service made in other regions.
Values stored in a StaticPartitionMap
will be cloned whenever they are requested. Values must
be initialized before they can be retrieved, and the StaticPartitionMap::get_or_init
method is
how you can ensure this.
§Example
use std::sync::{Arc, Mutex};
use aws_smithy_runtime::static_partition_map::StaticPartitionMap;
// The shared state must be `Clone` and will be internally mutable. Deriving `Default` isn't
// necessary, but allows us to use the `StaticPartitionMap::get_or_init_default` method.
#[derive(Clone, Default)]
pub struct SomeSharedState {
inner: Arc<Mutex<Inner>>
}
#[derive(Default)]
struct Inner {
// Some shared state...
}
// `Clone`, `Hash`, and `Eq` are all required trait impls for partition keys
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct SharedStatePartition {
region: String,
service_name: String,
}
impl SharedStatePartition {
pub fn new(region: impl Into<String>, service_name: impl Into<String>) -> Self {
Self { region: region.into(), service_name: service_name.into() }
}
}
static SOME_SHARED_STATE: StaticPartitionMap<SharedStatePartition, SomeSharedState> = StaticPartitionMap::new();
struct Client {
shared_state: SomeSharedState,
}
impl Client {
pub fn new() -> Self {
let key = SharedStatePartition::new("us-east-1", "example_service_20230628");
Self {
// If the stored value implements `Default`, you can call the
// `StaticPartitionMap::get_or_init_default` convenience method.
shared_state: SOME_SHARED_STATE.get_or_init_default(key),
}
}
}
Implementations§
source§impl<K, V> StaticPartitionMap<K, V>
impl<K, V> StaticPartitionMap<K, V>
source§impl<K, V> StaticPartitionMap<K, V>
impl<K, V> StaticPartitionMap<K, V>
source§impl<K, V> StaticPartitionMap<K, V>
impl<K, V> StaticPartitionMap<K, V>
sourcepub fn get_or_init_default(&self, partition_key: K) -> V
pub fn get_or_init_default(&self, partition_key: K) -> V
Gets the value for the given partition key, initializing it if it doesn’t exist.