use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::convert::Infallible;
use std::fmt;
use std::sync::{Arc, Mutex, Weak};
use super::{Shared, SharedAccessError, SharedReader, SharedReference, try_lock};
#[derive(Clone, Eq, PartialEq)]
pub struct SharedKeyIdentity {
address: String,
codec: TypeId,
configuration: String,
}
impl SharedKeyIdentity {
#[must_use]
pub fn new<Codec: 'static>(
address: impl Into<String>,
configuration: impl Into<String>,
) -> Self {
Self {
address: address.into(),
codec: TypeId::of::<Codec>(),
configuration: configuration.into(),
}
}
}
impl fmt::Debug for SharedKeyIdentity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SharedKeyIdentity").finish_non_exhaustive()
}
}
pub enum SharedLoadContext<'a, Value> {
Initial(&'a Value),
UserInitiated,
}
impl<Value> fmt::Debug for SharedLoadContext<'_, Value> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Initial(_) => "SharedLoadContext::Initial(..)",
Self::UserInitiated => "SharedLoadContext::UserInitiated",
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SharedSubscribeContext {
Initial,
UserInitiated,
}
pub trait SharedReaderKey: Send + Sync + 'static {
type Value: Send + 'static;
type Error;
type Subscription: Send + Sync + 'static;
fn identity(&self) -> SharedKeyIdentity;
fn load(
&self,
context: SharedLoadContext<'_, Self::Value>,
) -> impl Future<Output = Result<Option<Self::Value>, Self::Error>> + Send;
fn subscribe(
&self,
context: SharedSubscribeContext,
subscriber: SharedSubscriber<Self::Value>,
) -> Result<Self::Subscription, Self::Error>;
}
pub trait SharedKey: SharedReaderKey {
fn save(&self, value: &Self::Value) -> impl Future<Output = Result<(), Self::Error>> + Send;
}
pub struct SharedSubscriber<Value> {
reference: Weak<SharedReference<Value>>,
loads: Weak<Mutex<Option<Weak<()>>>>,
}
impl<Value> SharedSubscriber<Value> {
pub fn yield_value(&self, mut value: Value) -> Result<bool, SharedAccessError> {
self.prepare_publication()
.map_or(Ok(false), |publication| publication.try_replace(&mut value))
}
#[must_use]
pub fn prepare_publication(&self) -> Option<SharedPublication<Value>> {
Some(SharedPublication {
reference: self.reference.upgrade()?,
loads: self.loads.upgrade()?,
})
}
}
#[must_use]
pub struct SharedPublication<Value> {
reference: Arc<SharedReference<Value>>,
loads: Arc<Mutex<Option<Weak<()>>>>,
}
impl<Value> SharedPublication<Value> {
pub fn try_replace(&self, value: &mut Value) -> Result<bool, SharedAccessError> {
let retired = {
let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
let mut current = try_lock(&self.reference.value)?;
std::mem::swap(&mut *current, value);
latest.take()
};
drop(retired);
Ok(true)
}
}
impl<Value> fmt::Debug for SharedPublication<Value> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SharedPublication").finish_non_exhaustive()
}
}
impl<Value> Clone for SharedSubscriber<Value> {
fn clone(&self) -> Self {
Self {
reference: Weak::clone(&self.reference),
loads: Weak::clone(&self.loads),
}
}
}
impl<Value> fmt::Debug for SharedSubscriber<Value> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SharedSubscriber").finish_non_exhaustive()
}
}
pub struct SharedKeyDefault<Key, Seed> {
key: Key,
seed: Seed,
}
impl<Key, Seed> SharedKeyDefault<Key, Seed> {
#[must_use]
pub const fn new(key: Key, seed: Seed) -> Self {
Self { key, seed }
}
#[must_use]
pub fn into_key(self) -> Key {
let Self { key, seed } = self;
drop(seed);
key
}
}
impl<Key: SharedReaderKey, Seed: Fn() -> Key::Value> SharedKeyDefault<Key, Seed> {
pub fn initial_value(&self) -> Key::Value {
(self.seed)()
}
}
impl<Key, Seed> fmt::Debug for SharedKeyDefault<Key, Seed> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SharedKeyDefault").finish_non_exhaustive()
}
}
enum Failure<Cause> {
Collision,
Absent,
Poisoned,
Access(SharedAccessError),
Provider(Cause),
}
pub struct SharedKeyError<Cause> {
failure: Failure<Cause>,
}
impl<Cause> SharedKeyError<Cause> {
#[must_use]
pub const fn is_collision(&self) -> bool {
matches!(self.failure, Failure::Collision)
}
#[must_use]
pub const fn is_absent(&self) -> bool {
matches!(self.failure, Failure::Absent)
}
#[must_use]
pub const fn is_poisoned(&self) -> bool {
matches!(self.failure, Failure::Poisoned)
}
#[must_use]
pub const fn access_error(&self) -> Option<&SharedAccessError> {
match &self.failure {
Failure::Access(error) => Some(error),
_ => None,
}
}
#[must_use]
pub fn into_failure(self) -> Option<Cause> {
match self.failure {
Failure::Provider(cause) => Some(cause),
_ => None,
}
}
const fn message(&self) -> &'static str {
match &self.failure {
Failure::Collision => "shared key has an incompatible live reference",
Failure::Absent => "required shared value is absent from storage",
Failure::Poisoned => "shared cache metadata is poisoned",
Failure::Access(error) => error.message(),
Failure::Provider(_) => "shared key provider failed",
}
}
}
impl<Cause> fmt::Debug for SharedKeyError<Cause> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SharedKeyError")
.field("kind", &self.message())
.finish_non_exhaustive()
}
}
impl<Cause> fmt::Display for SharedKeyError<Cause> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl<Cause: std::error::Error + 'static> std::error::Error for SharedKeyError<Cause> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.failure {
Failure::Access(error) => Some(error),
Failure::Provider(cause) => Some(cause),
_ => None,
}
}
}
impl<Cause> From<SharedAccessError> for SharedKeyError<Cause> {
fn from(error: SharedAccessError) -> Self {
Self {
failure: Failure::Access(error),
}
}
}
#[derive(Clone, Eq, PartialEq)]
struct Compatibility {
identity: SharedKeyIdentity,
}
impl Compatibility {
fn for_key<Key: SharedReaderKey>(key: &Key) -> Self {
Self {
identity: key.identity(),
}
}
}
struct Entry {
codec: TypeId,
configuration: Box<str>,
reference: Weak<dyn Any + Send + Sync>,
}
impl Entry {
fn matches_at_same_address(&self, other: &Compatibility) -> bool {
self.codec == other.identity.codec
&& self.configuration.as_ref() == other.identity.configuration.as_str()
}
}
struct KeyResource<Key: SharedReaderKey> {
key: Key,
compatibility: Compatibility,
namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
_subscription: Key::Subscription,
loads: Arc<Mutex<Option<Weak<()>>>>,
}
#[derive(Clone, Default)]
pub struct SharedKeyCache {
entries: Arc<Mutex<HashMap<Box<str>, Entry>>>,
}
impl fmt::Debug for SharedKeyCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SharedKeyCache").finish_non_exhaustive()
}
}
impl SharedKeyCache {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub async fn shared<Key: SharedKey>(
&self,
key: Key,
seed: impl FnOnce() -> Key::Value,
) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
Ok(cohort(self.reader(key, seed).await?))
}
pub async fn reader<Key: SharedReaderKey>(
&self,
key: Key,
seed: impl FnOnce() -> Key::Value,
) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
let compatibility = Compatibility::for_key(&key);
if let Some(reference) = self.lookup::<Key>(&compatibility)? {
let reader = SharedReader { reference };
resource::<Key>(&reader)?;
drop(compatibility);
drop(seed);
drop(key);
return Ok(reader);
}
let seed = seed();
let loaded = match key.load(SharedLoadContext::Initial(&seed)).await {
Ok(loaded) => loaded,
Err(cause) => {
let error = provider(cause);
drop(seed);
drop(compatibility);
drop(key);
return Err(error);
}
};
let value = match loaded {
Some(value) => {
drop(seed);
value
}
None => seed,
};
let reference = build_reference(
key,
compatibility.clone(),
Arc::downgrade(&self.entries),
value,
SharedSubscribeContext::Initial,
)?;
self.publish::<Key>(compatibility, reference)
}
pub async fn shared_default<Key: SharedKey, Seed: Fn() -> Key::Value>(
&self,
default: SharedKeyDefault<Key, Seed>,
) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
self.shared(default.key, default.seed).await
}
pub async fn reader_default<Key: SharedReaderKey, Seed: Fn() -> Key::Value>(
&self,
default: SharedKeyDefault<Key, Seed>,
) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
self.reader(default.key, default.seed).await
}
pub async fn require<Key: SharedKey>(
&self,
key: Key,
) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
Ok(cohort(self.require_reader(key).await?))
}
pub async fn require_reader<Key: SharedReaderKey>(
&self,
key: Key,
) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
let loaded = match key.load(SharedLoadContext::UserInitiated).await {
Ok(loaded) => loaded,
Err(cause) => {
let error = provider(cause);
drop(key);
return Err(error);
}
}
.ok_or(SharedKeyError {
failure: Failure::Absent,
})?;
let compatibility = Compatibility::for_key(&key);
if let Some(reference) = self.lookup::<Key>(&compatibility)? {
let reader = SharedReader { reference };
resource::<Key>(&reader)?;
drop(compatibility);
drop(loaded);
drop(key);
return Ok(reader);
}
let reference = build_reference(
key,
compatibility.clone(),
Arc::downgrade(&self.entries),
loaded,
SharedSubscribeContext::UserInitiated,
)?;
self.publish::<Key>(compatibility, reference)
}
pub async fn reload<Key: SharedReaderKey>(
&self,
shared: &Shared<Key::Value>,
key: &Key,
) -> Result<(), SharedKeyError<Key::Error>> {
let reader = shared.reader()?;
let result = self.reload_reader(&reader, key).await;
drop(reader);
result
}
pub async fn reload_reader<Key: SharedReaderKey>(
&self,
reader: &SharedReader<Key::Value>,
key: &Key,
) -> Result<(), SharedKeyError<Key::Error>> {
let resource = resource::<Key>(reader)?;
if !std::ptr::eq(resource.namespace.as_ptr(), Arc::as_ptr(&self.entries))
|| resource.compatibility != Compatibility::for_key(key)
{
return Err(collision());
}
reload_reference(reader, key, &resource.loads).await
}
pub async fn load<Key: SharedKey>(
&self,
shared: &Shared<Key::Value>,
key: Key,
seed: impl FnOnce(&Key::Value) -> Key::Value,
) -> Result<(), SharedKeyError<Key::Error>> {
let reader = self.replacement(&shared.reader()?, key, seed)?;
let resource = resource::<Key>(&reader)?;
shared.rebind(&cohort(reader.clone()))?;
let result = reload_reference(&reader, &resource.key, &resource.loads).await;
drop(reader);
result
}
pub async fn load_reader<Key: SharedReaderKey>(
&self,
reader: &mut SharedReader<Key::Value>,
key: Key,
seed: impl FnOnce(&Key::Value) -> Key::Value,
) -> Result<(), SharedKeyError<Key::Error>> {
let replacement = self.replacement(reader, key, seed)?;
let previous = std::mem::replace(reader, replacement);
let resource = match resource::<Key>(reader) {
Ok(resource) => resource,
Err(error) => {
drop(std::mem::replace(reader, previous));
return Err(error);
}
};
drop(previous);
reload_reference(reader, &resource.key, &resource.loads).await
}
pub fn reset(&self) -> Result<(), SharedKeyError<Infallible>> {
let previous = {
let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
std::mem::take(&mut *entries)
};
drop(previous);
Ok(())
}
fn replacement<Key: SharedReaderKey>(
&self,
current: &SharedReader<Key::Value>,
key: Key,
seed: impl FnOnce(&Key::Value) -> Key::Value,
) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
let compatibility = Compatibility::for_key(&key);
if let Some(reference) = self.lookup::<Key>(&compatibility)? {
let reader = SharedReader { reference };
drop(compatibility);
drop(seed);
drop(key);
return Ok(reader);
}
let value = current.read(seed)?;
let reference = build_reference(
key,
compatibility.clone(),
Arc::downgrade(&self.entries),
value,
SharedSubscribeContext::UserInitiated,
)?;
self.publish::<Key>(compatibility, reference)
}
#[expect(
clippy::type_complexity,
reason = "keeps the value type and provider failure coupled at this private boundary"
)]
fn lookup<Key: SharedReaderKey>(
&self,
compatibility: &Compatibility,
) -> Result<Option<Arc<SharedReference<Key::Value>>>, SharedKeyError<Key::Error>> {
let found = {
let entries = self.entries.lock().map_err(|_error| poisoned())?;
entries
.get(compatibility.identity.address.as_str())
.map(|entry| {
(
entry.matches_at_same_address(compatibility),
entry.reference.upgrade(),
)
})
};
match found {
Some((compatible, Some(reference))) => {
if !compatible {
return Err(collision());
}
reference
.downcast()
.map(Some)
.map_err(|_reference| collision())
}
_ => Ok(None),
}
}
fn publish<Key: SharedReaderKey>(
&self,
mut compatibility: Compatibility,
candidate: Arc<SharedReference<Key::Value>>,
) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&candidate) as Arc<_>;
let (winner, previous) = {
let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
let winner = entries
.get(compatibility.identity.address.as_str())
.and_then(|entry| {
entry
.reference
.upgrade()
.map(|reference| (entry.matches_at_same_address(&compatibility), reference))
});
let previous = if winner.is_none() {
entries.insert(
take_compact(&mut compatibility.identity.address),
Entry {
codec: compatibility.identity.codec,
configuration: take_compact(&mut compatibility.identity.configuration),
reference: Arc::downgrade(&erased),
},
)
} else {
None
};
(winner, previous)
};
drop(previous);
drop(erased);
if let Some((compatible, winner)) = winner {
if !compatible {
return Err(collision());
}
let reader = SharedReader {
reference: winner.downcast().map_err(|_reference| collision())?,
};
resource::<Key>(&reader)?;
drop(candidate);
return Ok(reader);
}
Ok(SharedReader {
reference: candidate,
})
}
}
fn take_compact(text: &mut String) -> Box<str> {
if text.len() == text.capacity() {
std::mem::take(text).into_boxed_str()
} else {
Box::from(text.as_str())
}
}
fn cohort<Value>(reader: SharedReader<Value>) -> Shared<Value> {
Shared {
cohort: Arc::new(Mutex::new(reader)),
}
}
fn build_reference<Key: SharedReaderKey>(
key: Key,
compatibility: Compatibility,
namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
value: Key::Value,
context: SharedSubscribeContext,
) -> Result<Arc<SharedReference<Key::Value>>, SharedKeyError<Key::Error>> {
let reference = Arc::new(SharedReference::new(value));
let loads = Arc::new(Mutex::new(None));
let subscription = match key.subscribe(
context,
SharedSubscriber {
reference: Arc::downgrade(&reference),
loads: Arc::downgrade(&loads),
},
) {
Ok(subscription) => subscription,
Err(cause) => {
let error = provider(cause);
drop(loads);
drop(reference);
drop(namespace);
drop(compatibility);
drop(key);
return Err(error);
}
};
let installed = reference.retained.set(Box::new(KeyResource {
key,
compatibility,
namespace,
_subscription: subscription,
loads,
}));
assert!(
installed.is_ok(),
"a new shared reference has no retained resource"
);
Ok(reference)
}
fn resource<Key: SharedReaderKey>(
reader: &SharedReader<Key::Value>,
) -> Result<&KeyResource<Key>, SharedKeyError<Key::Error>> {
reader
.reference
.retained
.get()
.and_then(|resource| resource.downcast_ref::<KeyResource<Key>>())
.ok_or_else(collision)
}
async fn reload_reference<Key: SharedReaderKey>(
reader: &SharedReader<Key::Value>,
key: &Key,
loads: &Mutex<Option<Weak<()>>>,
) -> Result<(), SharedKeyError<Key::Error>> {
let attempt = ReferenceLoadAttempt::begin(&reader.reference, loads)?;
let loaded = key
.load(SharedLoadContext::UserInitiated)
.await
.map_err(provider)?;
attempt.commit(loaded)?;
Ok(())
}
struct ReferenceLoadAttempt<'a, Value> {
reference: &'a SharedReference<Value>,
loads: &'a Mutex<Option<Weak<()>>>,
identity: Arc<()>,
retired: bool,
}
impl<'a, Value> ReferenceLoadAttempt<'a, Value> {
fn begin(
reference: &'a SharedReference<Value>,
loads: &'a Mutex<Option<Weak<()>>>,
) -> Result<Self, SharedAccessError> {
let identity = Arc::new(());
let previous = {
let mut latest = loads.lock().map_err(|_error| load_poisoned())?;
latest.replace(Arc::downgrade(&identity))
};
drop(previous);
Ok(Self {
reference,
loads,
identity,
retired: false,
})
}
fn is_latest(&self, latest: Option<&Weak<()>>) -> bool {
latest.is_some_and(|latest| std::ptr::eq(latest.as_ptr(), Arc::as_ptr(&self.identity)))
}
fn commit(mut self, value: Option<Value>) -> Result<bool, SharedAccessError> {
let mut value = value;
let (committed, displaced, previous) = {
let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
if self.is_latest(latest.as_ref()) {
let displaced = if value.is_some() {
let mut current = try_lock(&self.reference.value)?;
value
.take()
.map(|value| std::mem::replace(&mut *current, value))
} else {
None
};
(true, displaced, latest.take())
} else {
(false, None, None)
}
};
self.retired = true;
drop(previous);
drop(displaced);
drop(value);
Ok(committed)
}
}
impl<Value> Drop for ReferenceLoadAttempt<'_, Value> {
fn drop(&mut self) {
if self.retired {
return;
}
let previous = if let Ok(mut latest) = self.loads.lock() {
if self.is_latest(latest.as_ref()) {
latest.take()
} else {
None
}
} else {
None
};
drop(previous);
}
}
fn load_poisoned() -> SharedAccessError {
SharedAccessError {
kind: super::AccessKind::Poisoned,
}
}
fn provider<Cause>(cause: Cause) -> SharedKeyError<Cause> {
SharedKeyError {
failure: Failure::Provider(cause),
}
}
fn collision<Cause>() -> SharedKeyError<Cause> {
SharedKeyError {
failure: Failure::Collision,
}
}
fn poisoned<Cause>() -> SharedKeyError<Cause> {
SharedKeyError {
failure: Failure::Poisoned,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn take_compact_transfers_exact_capacity_buffers() {
for expected in ["", "shared-profile"] {
let mut text = Box::<str>::from(expected).into_string();
let pointer = text.as_ptr();
assert_eq!(text.capacity(), text.len());
let compact = take_compact(&mut text);
assert_eq!(compact.as_ref(), expected);
if !expected.is_empty() {
assert_eq!(compact.as_ptr(), pointer);
}
assert_eq!(text, "");
assert_eq!(text.capacity(), 0);
}
}
#[test]
fn take_compact_preserves_buffers_with_spare_capacity() {
for expected in ["", "shared-profile"] {
let mut text = String::with_capacity(expected.len() + 16);
text.push_str(expected);
let pointer = text.as_ptr();
let capacity = text.capacity();
assert!(capacity > text.len());
let compact = take_compact(&mut text);
assert_eq!(compact.as_ref(), expected);
assert_eq!(text, expected);
assert_eq!(text.as_ptr(), pointer);
assert_eq!(text.capacity(), capacity);
if !expected.is_empty() {
assert_ne!(compact.as_ptr(), pointer);
}
}
}
#[test]
fn diagnostics_redact_resource_identity_and_non_debug_values() {
struct Secret(&'static str);
let identity = SharedKeyIdentity::new::<()>("private-address", "private-configuration");
let reference = Arc::new(SharedReference::new(Secret("private-value")));
let loads = Arc::new(Mutex::new(None));
let subscriber = SharedSubscriber {
reference: Arc::downgrade(&reference),
loads: Arc::downgrade(&loads),
};
let publication = subscriber.prepare_publication().unwrap();
let value = reference.value.lock().unwrap();
let initial = format!("{:?}", SharedLoadContext::Initial(&*value));
let explicit = format!("{:?}", SharedLoadContext::<Secret>::UserInitiated);
assert_ne!(initial, explicit);
for diagnostic in [
format!("{identity:?}"),
format!("{subscriber:?}"),
format!("{publication:?}"),
format!("{:?}", SharedKeyCache::new()),
initial,
explicit,
] {
for secret in ["private-address", "private-configuration", value.0] {
assert!(!diagnostic.contains(secret));
}
}
}
#[test]
fn provider_error_source_preserves_the_cause_without_disclosing_it() {
let error = provider(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"private-provider-path",
));
assert!(!error.is_absent());
assert!(!error.is_collision());
assert!(!error.is_poisoned());
assert!(error.access_error().is_none());
assert!(!format!("{error}: {error:?}").contains("private-provider-path"));
let source = std::error::Error::source(&error)
.unwrap()
.downcast_ref::<std::io::Error>()
.unwrap();
assert_eq!(source.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(source.to_string(), "private-provider-path");
let recovered = error.into_failure().unwrap();
assert_eq!(recovered.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(recovered.to_string(), "private-provider-path");
}
#[test]
fn poisoned_metadata_rejects_lookup_publication_and_reset_without_revoking_owners() {
let cache = SharedKeyCache::new();
let seeds = std::cell::Cell::new(0);
let seed = || {
seeds.set(seeds.get() + 1);
7
};
let owner = futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap();
let compatibility = Compatibility::for_key(&LayoutKey);
let candidate = build_reference(
LayoutKey,
compatibility.clone(),
Arc::downgrade(&cache.entries),
11,
SharedSubscribeContext::UserInitiated,
)
.unwrap();
let provisional = Arc::downgrade(&candidate);
let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = cache.entries.lock().unwrap();
panic!("metadata interrupted");
}));
assert!(panic.is_err());
let errors = [
futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap_err(),
cache
.publish::<LayoutKey>(compatibility, candidate)
.unwrap_err(),
cache.reset().unwrap_err(),
];
for error in errors {
assert!(error.is_poisoned());
assert!(!error.is_collision());
assert!(!error.is_absent());
assert!(error.access_error().is_none());
assert!(std::error::Error::source(&error).is_none());
assert!(error.to_string().contains("metadata is poisoned"));
assert!(error.into_failure().is_none());
}
assert_eq!(seeds.get(), 1);
assert!(provisional.upgrade().is_none());
assert_eq!(owner.read(|value| *value).unwrap(), 7);
}
#[test]
fn mismatched_erased_entry_rejects_reader_without_seed_or_owner_leak() {
let cache = SharedKeyCache::new();
let compatibility = Compatibility::for_key(&LayoutKey);
let owner = Arc::new(SharedReference::new("private-wrong-value"));
let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
cache.entries.lock().unwrap().insert(
compatibility.identity.address.clone().into_boxed_str(),
Entry {
codec: compatibility.identity.codec,
configuration: compatibility
.identity
.configuration
.clone()
.into_boxed_str(),
reference: Arc::downgrade(&erased),
},
);
drop(erased);
let error = futures_executor::block_on(cache.reader(LayoutKey, || {
panic!("a mismatched live reference must not fall back to its seed")
}))
.unwrap_err();
assert!(error.is_collision());
assert_eq!(
error.to_string(),
"shared key has an incompatible live reference"
);
assert!(!format!("{error:?}").contains("private-wrong-value"));
assert!(!error.is_poisoned());
assert_eq!(Arc::strong_count(&owner), 1);
assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
drop(cache);
assert_eq!(Arc::strong_count(&owner), 1);
}
#[test]
fn mismatched_erased_winner_rejects_publication_and_drops_candidate_outside_lock() {
use std::sync::atomic::{AtomicUsize, Ordering};
struct CandidateDrop(SharedKeyCache, Arc<AtomicUsize>);
impl Drop for CandidateDrop {
fn drop(&mut self) {
assert!(
self.0.entries.try_lock().is_ok(),
"candidate drop holds metadata lock"
);
self.1.fetch_add(1, Ordering::SeqCst);
}
}
let cache = SharedKeyCache::new();
let compatibility = Compatibility::for_key(&LayoutKey);
let owner = Arc::new(SharedReference::new("private-wrong-value"));
let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
let retained = Arc::downgrade(&erased);
cache.entries.lock().unwrap().insert(
compatibility.identity.address.clone().into_boxed_str(),
Entry {
codec: compatibility.identity.codec,
configuration: compatibility
.identity
.configuration
.clone()
.into_boxed_str(),
reference: Weak::clone(&retained),
},
);
drop(erased);
let drops = Arc::new(AtomicUsize::new(0));
let candidate = Arc::new(SharedReference::new(11_usize));
candidate
.retained
.set(Box::new(CandidateDrop(cache.clone(), Arc::clone(&drops))))
.unwrap_or_else(|_| panic!("fresh candidate has no retained resource"));
let provisional = Arc::downgrade(&candidate);
let error = cache
.publish::<LayoutKey>(compatibility.clone(), candidate)
.unwrap_err();
assert!(error.is_collision());
assert_eq!(
error.to_string(),
"shared key has an incompatible live reference"
);
assert!(!format!("{error:?}").contains("private-wrong-value"));
assert_eq!(drops.load(Ordering::SeqCst), 1);
assert!(provisional.upgrade().is_none());
assert_eq!(Arc::strong_count(&owner), 1);
let entries = cache.entries.lock().unwrap();
assert_eq!(entries.len(), 1);
assert!(Weak::ptr_eq(
&entries[compatibility.identity.address.as_str()].reference,
&retained
));
drop(entries);
assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
drop(cache);
assert_eq!(drops.load(Ordering::SeqCst), 1);
assert_eq!(Arc::strong_count(&drops), 1);
}
#[test]
fn poisoned_reload_coordinator_preserves_values_and_does_not_panic_during_retirement() {
let reference = Arc::new(SharedReference::new(7));
let loads = Arc::new(Mutex::new(None));
let subscriber = SharedSubscriber {
reference: Arc::downgrade(&reference),
loads: Arc::downgrade(&loads),
};
let publication = subscriber.prepare_publication().unwrap();
let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = loads.lock().unwrap();
panic!("reload coordination interrupted");
}));
assert!(panic.is_err());
assert!(attempt.commit(Some(11)).unwrap_err().is_poisoned());
let error = ReferenceLoadAttempt::begin(&reference, &loads)
.err()
.unwrap();
assert!(error.is_poisoned());
let mut next = 13;
assert!(
publication
.try_replace(&mut next)
.unwrap_err()
.is_poisoned()
);
assert_eq!(next, 13);
assert_eq!(*reference.value.lock().unwrap(), 7);
assert!(loads.is_poisoned());
}
#[test]
fn reload_propagates_coordinator_poison_before_invoking_provider() {
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone)]
struct Key {
loads: Arc<AtomicUsize>,
retirements: Arc<AtomicUsize>,
}
struct Subscription(Arc<AtomicUsize>);
impl Drop for Subscription {
fn drop(&mut self) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
impl SharedReaderKey for Key {
type Value = usize;
type Error = Infallible;
type Subscription = Subscription;
fn identity(&self) -> SharedKeyIdentity {
SharedKeyIdentity::new::<Self>("poisoned-reload", "")
}
fn load(
&self,
_: SharedLoadContext<'_, usize>,
) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
self.loads.fetch_add(1, Ordering::SeqCst);
std::future::ready(Ok(None))
}
fn subscribe(
&self,
_: SharedSubscribeContext,
_: SharedSubscriber<usize>,
) -> Result<Subscription, Infallible> {
Ok(Subscription(Arc::clone(&self.retirements)))
}
}
let key = Key {
loads: Arc::new(AtomicUsize::new(0)),
retirements: Arc::new(AtomicUsize::new(0)),
};
let cache = SharedKeyCache::new();
let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
let owner = Arc::downgrade(&reader.reference);
let loads = Arc::clone(&resource::<Key>(&reader).unwrap().loads);
assert_eq!(key.loads.load(Ordering::SeqCst), 1);
let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = loads.lock().unwrap();
panic!("reload coordination interrupted");
}));
assert!(panic.is_err());
let error = futures_executor::block_on(cache.reload_reader(&reader, &key)).unwrap_err();
assert!(error.access_error().unwrap().is_poisoned());
assert!(!error.is_poisoned(), "not a metadata-lock failure");
assert!(!error.is_collision());
assert!(
std::error::Error::source(&error)
.unwrap()
.downcast_ref::<SharedAccessError>()
.unwrap()
.is_poisoned()
);
assert_eq!(key.loads.load(Ordering::SeqCst), 1);
assert_eq!(reader.read(|value| *value).unwrap(), 7);
assert!(loads.is_poisoned());
assert_eq!(key.retirements.load(Ordering::SeqCst), 0);
drop(reader);
assert!(owner.upgrade().is_none());
assert_eq!(key.retirements.load(Ordering::SeqCst), 1);
}
#[test]
fn reload_rejects_a_busy_cohort_without_changing_its_capture() {
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone)]
struct CountingKey(Arc<AtomicUsize>);
impl SharedReaderKey for CountingKey {
type Value = usize;
type Error = Infallible;
type Subscription = ();
fn identity(&self) -> SharedKeyIdentity {
SharedKeyIdentity::new::<Self>("busy-cohort", "")
}
fn load(
&self,
_: SharedLoadContext<'_, usize>,
) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
self.0.fetch_add(1, Ordering::SeqCst);
std::future::ready(Ok(None))
}
fn subscribe(
&self,
_: SharedSubscribeContext,
_: SharedSubscriber<usize>,
) -> Result<(), Infallible> {
Ok(())
}
}
let key = CountingKey(Arc::new(AtomicUsize::new(0)));
let cache = SharedKeyCache::new();
let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
assert_eq!(key.0.load(Ordering::SeqCst), 1);
let shared = cohort(reader.clone());
let guard = shared.cohort.lock().unwrap();
let error = futures_executor::block_on(cache.reload(&shared, &key)).unwrap_err();
assert!(error.access_error().unwrap().is_busy());
assert_eq!(key.0.load(Ordering::SeqCst), 1);
assert_eq!(reader.read(|value| *value).unwrap(), 7);
drop(guard);
futures_executor::block_on(cache.reload(&shared, &key)).unwrap();
assert_eq!(key.0.load(Ordering::SeqCst), 2);
assert_eq!(shared.read(|value| *value).unwrap(), 7);
}
#[test]
fn load_contention_retires_provisional_subscription_before_retry() {
#[derive(Clone)]
struct Key(Arc<Mutex<Vec<&'static str>>>);
struct Subscription(Arc<Mutex<Vec<&'static str>>>);
impl Drop for Subscription {
fn drop(&mut self) {
self.0.lock().unwrap().push("retire");
}
}
impl SharedReaderKey for Key {
type Value = String;
type Error = Infallible;
type Subscription = Subscription;
fn identity(&self) -> SharedKeyIdentity {
SharedKeyIdentity::new::<Self>("contended-load", "")
}
fn load(
&self,
context: SharedLoadContext<'_, String>,
) -> impl Future<Output = Result<Option<String>, Infallible>> + Send {
assert!(matches!(context, SharedLoadContext::UserInitiated));
self.0.lock().unwrap().push("reload");
std::future::ready(Ok(None))
}
fn subscribe(
&self,
context: SharedSubscribeContext,
_: SharedSubscriber<String>,
) -> Result<Subscription, Infallible> {
assert_eq!(context, SharedSubscribeContext::UserInitiated);
self.0.lock().unwrap().push("subscribe");
Ok(Subscription(Arc::clone(&self.0)))
}
}
impl SharedKey for Key {
fn save(&self, _: &String) -> impl Future<Output = Result<(), Infallible>> + Send {
self.0.lock().unwrap().push("save");
std::future::ready(Ok(()))
}
}
let cache = SharedKeyCache::new();
let key = Key(Arc::new(Mutex::new(Vec::new())));
let shared = Shared::new(String::from("original"));
let original = shared.reader().unwrap();
let guard = shared.cohort.lock().unwrap();
let error = futures_executor::block_on(cache.load(&shared, key.clone(), |_| {
panic!("capture contention must not seed")
}))
.unwrap_err();
assert!(error.access_error().unwrap().is_busy());
assert!(error.into_failure().is_none());
assert!(key.0.lock().unwrap().is_empty());
drop(guard);
let mut retained_guard = None;
let error = futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
assert_eq!(value, "original");
retained_guard = Some(shared.cohort.lock().unwrap());
String::from("provisional")
}))
.unwrap_err();
assert!(error.access_error().unwrap().is_busy());
assert!(error.into_failure().is_none());
assert_eq!(*key.0.lock().unwrap(), ["subscribe", "retire"]);
drop(retained_guard);
assert!(shared.read(|value| value == "original").unwrap());
assert!(original.read(|value| value == "original").unwrap());
futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
assert_eq!(value, "original");
String::from("replacement")
}))
.unwrap();
assert_eq!(
*key.0.lock().unwrap(),
["subscribe", "retire", "subscribe", "reload"]
);
assert!(shared.read(|value| value == "replacement").unwrap());
assert!(original.read(|value| value == "original").unwrap());
drop(shared);
assert_eq!(
*key.0.lock().unwrap(),
["subscribe", "retire", "subscribe", "reload", "retire"]
);
}
#[test]
fn failed_subscription_orphan_cannot_prepare_without_its_coordinator() {
struct Value(u8, Arc<Mutex<Vec<u8>>>);
impl Drop for Value {
fn drop(&mut self) {
self.1.lock().unwrap().push(self.0);
}
}
struct Captured {
subscriber: SharedSubscriber<Value>,
publication: SharedPublication<Value>,
}
struct FailingSubscription(Arc<Mutex<Option<Captured>>>);
impl SharedReaderKey for FailingSubscription {
type Value = Value;
type Error = &'static str;
type Subscription = ();
fn identity(&self) -> SharedKeyIdentity {
SharedKeyIdentity::new::<Self>("orphan", "")
}
fn load(
&self,
_: SharedLoadContext<'_, Value>,
) -> impl Future<Output = Result<Option<Value>, &'static str>> + Send {
std::future::ready(Ok(None))
}
fn subscribe(
&self,
context: SharedSubscribeContext,
subscriber: SharedSubscriber<Value>,
) -> Result<(), &'static str> {
assert!(matches!(context, SharedSubscribeContext::Initial));
let publication = subscriber.prepare_publication().unwrap();
assert!(
self.0
.lock()
.unwrap()
.replace(Captured {
subscriber,
publication,
})
.is_none()
);
Err("subscription failed")
}
}
let cache = SharedKeyCache::new();
let captured = Arc::new(Mutex::new(None));
let drops = Arc::new(Mutex::new(Vec::new()));
let error = futures_executor::block_on(
cache.reader(FailingSubscription(Arc::clone(&captured)), || {
Value(1, Arc::clone(&drops))
}),
)
.unwrap_err();
assert_eq!(error.into_failure(), Some("subscription failed"));
assert!(cache.entries.lock().unwrap().is_empty());
assert!(drops.lock().unwrap().is_empty());
let Captured {
subscriber,
publication,
} = captured.lock().unwrap().take().unwrap();
let SharedPublication { reference, loads } = publication;
assert!(reference.retained.get().is_none());
assert_eq!(Arc::strong_count(&reference), 1);
assert_eq!(Arc::strong_count(&loads), 1);
drop(loads);
assert!(subscriber.loads.upgrade().is_none());
assert_eq!(subscriber.reference.strong_count(), 1);
assert!(subscriber.prepare_publication().is_none());
assert_eq!(Arc::strong_count(&reference), 1);
assert_eq!(reference.value.lock().unwrap().0, 1);
assert!(drops.lock().unwrap().is_empty());
assert!(
!subscriber
.yield_value(Value(2, Arc::clone(&drops)))
.unwrap()
);
assert_eq!(*drops.lock().unwrap(), [2]);
assert_eq!(reference.value.lock().unwrap().0, 1);
assert_eq!(Arc::strong_count(&reference), 1);
drop(reference);
assert_eq!(*drops.lock().unwrap(), [2, 1]);
assert!(subscriber.reference.upgrade().is_none());
assert!(subscriber.prepare_publication().is_none());
drop(subscriber);
drop(cache);
assert_eq!(*drops.lock().unwrap(), [2, 1]);
assert_eq!(Arc::strong_count(&drops), 1);
}
#[test]
fn subscriber_swap_retains_displaced_value_until_external_fence_is_released() {
struct Reentrant(Arc<Mutex<bool>>, Arc<std::sync::atomic::AtomicUsize>);
impl Drop for Reentrant {
fn drop(&mut self) {
*self
.0
.try_lock()
.expect("destructor can reenter cancellation") = false;
self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
}
let control = Arc::new(Mutex::new(true));
let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let reference = Arc::new(SharedReference::new(Reentrant(
Arc::clone(&control),
Arc::clone(&drops),
)));
let loads = Arc::new(Mutex::new(None));
let subscriber = SharedSubscriber {
reference: Arc::downgrade(&reference),
loads: Arc::downgrade(&loads),
};
let mut next = Reentrant(Arc::clone(&control), Arc::clone(&drops));
let publication = subscriber.prepare_publication().unwrap();
drop(reference);
let guard = control.lock().unwrap();
assert!(publication.try_replace(&mut next).unwrap());
drop(guard);
drop(next);
assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 1);
drop(publication);
assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 2);
assert!(!*control.lock().unwrap());
assert!(subscriber.prepare_publication().is_none());
}
#[test]
fn prepared_publication_and_cancellation_have_one_final_commit_order() {
let reference = Arc::new(SharedReference::new(7));
let loads = Arc::new(Mutex::new(None));
let subscriber = SharedSubscriber {
reference: Arc::downgrade(&reference),
loads: Arc::downgrade(&loads),
};
let publication = subscriber.prepare_publication().unwrap();
let control = Arc::new(Mutex::new(true));
let publishing = Arc::clone(&control);
let cancelling = Arc::clone(&control);
let (checked, checked_rx) = std::sync::mpsc::channel();
let (resume, resume_rx) = std::sync::mpsc::channel();
let (attempted, attempted_rx) = std::sync::mpsc::channel();
let (cancelled, cancelled_rx) = std::sync::mpsc::channel();
let worker = std::thread::spawn(move || {
let mut next = 8;
let fence = publishing.lock().unwrap();
assert!(*fence);
checked.send(()).unwrap();
resume_rx.recv().unwrap(); assert!(publication.try_replace(&mut next).unwrap());
drop(fence);
assert_eq!(next, 7);
});
checked_rx.recv().unwrap();
let cancellation_worker = std::thread::spawn(move || {
attempted.send(()).unwrap();
*cancelling.lock().unwrap() = false;
cancelled.send(()).unwrap();
});
attempted_rx.recv().unwrap();
assert_eq!(*reference.value.lock().unwrap(), 7);
assert!(matches!(
cancelled_rx.try_recv(),
Err(std::sync::mpsc::TryRecvError::Empty)
));
resume.send(()).unwrap();
worker.join().unwrap();
cancellation_worker.join().unwrap();
cancelled_rx.recv().unwrap();
assert_eq!(*reference.value.lock().unwrap(), 8);
let publication = subscriber.prepare_publication().unwrap();
let mut next = 99;
{
let fence = control.lock().unwrap();
if *fence {
publication.try_replace(&mut next).unwrap();
}
}
assert_eq!(next, 99);
assert_eq!(*reference.value.lock().unwrap(), 8);
}
#[test]
fn obsolete_attempts_cannot_clear_the_latest_loading_token() {
let reference = SharedReference::new(1);
let loads = Mutex::new(None);
let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
assert!(!old.commit(Some(10)).unwrap());
assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
assert!(latest.commit(Some(20)).unwrap());
assert!(loads.lock().unwrap().is_none());
assert_eq!(*reference.value.lock().unwrap(), 20);
let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
drop(old);
assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
drop(latest);
assert!(loads.lock().unwrap().is_none());
}
#[test]
fn latest_busy_commit_retires_without_replacing_or_poisoning() {
let reference = SharedReference::new(1);
let loads = Mutex::new(None);
let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
let current = reference.value.lock().unwrap();
assert!(attempt.commit(Some(2)).unwrap_err().is_busy());
assert!(loads.lock().unwrap().is_none());
assert_eq!(*current, 1);
drop(current);
assert!(
ReferenceLoadAttempt::begin(&reference, &loads)
.unwrap()
.commit(Some(3))
.unwrap()
);
}
struct LayoutKey;
impl SharedReaderKey for LayoutKey {
type Value = usize;
type Error = Infallible;
type Subscription = ();
fn identity(&self) -> SharedKeyIdentity {
SharedKeyIdentity::new::<()>("layout", "")
}
fn load(
&self,
_: SharedLoadContext<'_, usize>,
) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
std::future::ready(Ok(None))
}
fn subscribe(
&self,
_: SharedSubscribeContext,
_: SharedSubscriber<usize>,
) -> Result<(), Infallible> {
Ok(())
}
}
#[test]
fn reports_retained_reference_layout() {
assert_eq!(size_of::<Shared<usize>>(), size_of::<Arc<()>>());
assert_eq!(size_of::<SharedReader<usize>>(), size_of::<Arc<()>>());
eprintln!(
"Shared<usize>={} SharedReader<usize>={} old-value-mutex={} retained-reference={} keyed-resource={} coordinator={} attempt={} strong-token={} weak-token={} subscriber={}",
size_of::<Shared<usize>>(),
size_of::<SharedReader<usize>>(),
size_of::<Mutex<usize>>(),
size_of::<SharedReference<usize>>(),
size_of::<KeyResource<LayoutKey>>(),
size_of::<Mutex<Option<Weak<()>>>>(),
size_of::<ReferenceLoadAttempt<'_, usize>>(),
size_of::<Arc<()>>(),
size_of::<Weak<()>>(),
size_of::<SharedSubscriber<usize>>(),
);
}
}