1use std::any::{Any, TypeId};
41use std::collections::HashMap;
42use std::convert::Infallible;
43use std::fmt;
44use std::sync::{Arc, Mutex, Weak};
45
46use super::{Shared, SharedAccessError, SharedReader, SharedReference, try_lock};
47
48#[derive(Clone, Eq, PartialEq)]
50pub struct SharedKeyIdentity {
51 address: String,
53 codec: TypeId,
55 configuration: String,
57}
58
59impl SharedKeyIdentity {
60 #[must_use]
66 pub fn new<Codec: 'static>(
67 address: impl Into<String>,
68 configuration: impl Into<String>,
69 ) -> Self {
70 Self {
71 address: address.into(),
72 codec: TypeId::of::<Codec>(),
73 configuration: configuration.into(),
74 }
75 }
76}
77
78impl fmt::Debug for SharedKeyIdentity {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 f.debug_struct("SharedKeyIdentity").finish_non_exhaustive()
81 }
82}
83
84pub enum SharedLoadContext<'a, Value> {
86 Initial(&'a Value),
88 UserInitiated,
90}
91
92impl<Value> fmt::Debug for SharedLoadContext<'_, Value> {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.write_str(match self {
95 Self::Initial(_) => "SharedLoadContext::Initial(..)",
96 Self::UserInitiated => "SharedLoadContext::UserInitiated",
97 })
98 }
99}
100
101#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum SharedSubscribeContext {
104 Initial,
106 UserInitiated,
108}
109
110pub trait SharedReaderKey: Send + Sync + 'static {
120 type Value: Send + 'static;
122 type Error;
124 type Subscription: Send + Sync + 'static;
126
127 fn identity(&self) -> SharedKeyIdentity;
129
130 fn load(
135 &self,
136 context: SharedLoadContext<'_, Self::Value>,
137 ) -> impl Future<Output = Result<Option<Self::Value>, Self::Error>> + Send;
138
139 fn subscribe(
144 &self,
145 context: SharedSubscribeContext,
146 subscriber: SharedSubscriber<Self::Value>,
147 ) -> Result<Self::Subscription, Self::Error>;
148}
149
150pub trait SharedKey: SharedReaderKey {
156 fn save(&self, value: &Self::Value) -> impl Future<Output = Result<(), Self::Error>> + Send;
161}
162
163pub struct SharedSubscriber<Value> {
165 reference: Weak<SharedReference<Value>>,
167 loads: Weak<Mutex<Option<Weak<()>>>>,
169}
170
171impl<Value> SharedSubscriber<Value> {
172 pub fn yield_value(&self, mut value: Value) -> Result<bool, SharedAccessError> {
185 self.prepare_publication()
186 .map_or(Ok(false), |publication| publication.try_replace(&mut value))
187 }
188
189 #[must_use]
196 pub fn prepare_publication(&self) -> Option<SharedPublication<Value>> {
197 Some(SharedPublication {
198 reference: self.reference.upgrade()?,
199 loads: self.loads.upgrade()?,
200 })
201 }
202}
203
204#[must_use]
209pub struct SharedPublication<Value> {
210 reference: Arc<SharedReference<Value>>,
212 loads: Arc<Mutex<Option<Weak<()>>>>,
214}
215
216impl<Value> SharedPublication<Value> {
217 pub fn try_replace(&self, value: &mut Value) -> Result<bool, SharedAccessError> {
227 let retired = {
228 let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
229 let mut current = try_lock(&self.reference.value)?;
230 std::mem::swap(&mut *current, value);
231 latest.take()
232 };
233 drop(retired);
234 Ok(true)
235 }
236}
237
238impl<Value> fmt::Debug for SharedPublication<Value> {
239 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 f.debug_struct("SharedPublication").finish_non_exhaustive()
241 }
242}
243
244impl<Value> Clone for SharedSubscriber<Value> {
245 fn clone(&self) -> Self {
246 Self {
247 reference: Weak::clone(&self.reference),
248 loads: Weak::clone(&self.loads),
249 }
250 }
251}
252
253impl<Value> fmt::Debug for SharedSubscriber<Value> {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 f.debug_struct("SharedSubscriber").finish_non_exhaustive()
256 }
257}
258
259pub struct SharedKeyDefault<Key, Seed> {
261 key: Key,
263 seed: Seed,
265}
266
267impl<Key, Seed> SharedKeyDefault<Key, Seed> {
268 #[must_use]
270 pub const fn new(key: Key, seed: Seed) -> Self {
271 Self { key, seed }
272 }
273
274 #[must_use]
280 pub fn into_key(self) -> Key {
281 let Self { key, seed } = self;
282 drop(seed);
283 key
284 }
285}
286
287impl<Key: SharedReaderKey, Seed: Fn() -> Key::Value> SharedKeyDefault<Key, Seed> {
288 pub fn initial_value(&self) -> Key::Value {
290 (self.seed)()
291 }
292}
293
294impl<Key, Seed> fmt::Debug for SharedKeyDefault<Key, Seed> {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 f.debug_struct("SharedKeyDefault").finish_non_exhaustive()
297 }
298}
299
300enum Failure<Cause> {
302 Collision,
304 Absent,
306 Poisoned,
308 Access(SharedAccessError),
310 Provider(Cause),
312}
313
314pub struct SharedKeyError<Cause> {
316 failure: Failure<Cause>,
318}
319
320impl<Cause> SharedKeyError<Cause> {
321 #[must_use]
323 pub const fn is_collision(&self) -> bool {
324 matches!(self.failure, Failure::Collision)
325 }
326
327 #[must_use]
329 pub const fn is_absent(&self) -> bool {
330 matches!(self.failure, Failure::Absent)
331 }
332
333 #[must_use]
335 pub const fn is_poisoned(&self) -> bool {
336 matches!(self.failure, Failure::Poisoned)
337 }
338
339 #[must_use]
341 pub const fn access_error(&self) -> Option<&SharedAccessError> {
342 match &self.failure {
343 Failure::Access(error) => Some(error),
344 _ => None,
345 }
346 }
347
348 #[must_use]
350 pub fn into_failure(self) -> Option<Cause> {
351 match self.failure {
352 Failure::Provider(cause) => Some(cause),
353 _ => None,
354 }
355 }
356
357 const fn message(&self) -> &'static str {
359 match &self.failure {
360 Failure::Collision => "shared key has an incompatible live reference",
361 Failure::Absent => "required shared value is absent from storage",
362 Failure::Poisoned => "shared cache metadata is poisoned",
363 Failure::Access(error) => error.message(),
364 Failure::Provider(_) => "shared key provider failed",
365 }
366 }
367}
368
369impl<Cause> fmt::Debug for SharedKeyError<Cause> {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371 f.debug_struct("SharedKeyError")
372 .field("kind", &self.message())
373 .finish_non_exhaustive()
374 }
375}
376
377impl<Cause> fmt::Display for SharedKeyError<Cause> {
378 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
379 f.write_str(self.message())
380 }
381}
382
383impl<Cause: std::error::Error + 'static> std::error::Error for SharedKeyError<Cause> {
384 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
385 match &self.failure {
386 Failure::Access(error) => Some(error),
387 Failure::Provider(cause) => Some(cause),
388 _ => None,
389 }
390 }
391}
392
393impl<Cause> From<SharedAccessError> for SharedKeyError<Cause> {
394 fn from(error: SharedAccessError) -> Self {
395 Self {
396 failure: Failure::Access(error),
397 }
398 }
399}
400
401#[derive(Clone, Eq, PartialEq)]
403struct Compatibility {
404 identity: SharedKeyIdentity,
406}
407
408impl Compatibility {
409 fn for_key<Key: SharedReaderKey>(key: &Key) -> Self {
411 Self {
412 identity: key.identity(),
413 }
414 }
415}
416
417struct Entry {
419 codec: TypeId,
421 configuration: Box<str>,
423 reference: Weak<dyn Any + Send + Sync>,
425}
426
427impl Entry {
428 fn matches_at_same_address(&self, other: &Compatibility) -> bool {
430 self.codec == other.identity.codec
431 && self.configuration.as_ref() == other.identity.configuration.as_str()
432 }
433}
434
435struct KeyResource<Key: SharedReaderKey> {
437 key: Key,
439 compatibility: Compatibility,
441 namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
443 _subscription: Key::Subscription,
445 loads: Arc<Mutex<Option<Weak<()>>>>,
447}
448
449#[derive(Clone, Default)]
465pub struct SharedKeyCache {
466 entries: Arc<Mutex<HashMap<Box<str>, Entry>>>,
468}
469
470impl fmt::Debug for SharedKeyCache {
471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 f.debug_struct("SharedKeyCache").finish_non_exhaustive()
473 }
474}
475
476impl SharedKeyCache {
477 #[must_use]
479 pub fn new() -> Self {
480 Self::default()
481 }
482
483 pub async fn shared<Key: SharedKey>(
495 &self,
496 key: Key,
497 seed: impl FnOnce() -> Key::Value,
498 ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
499 Ok(cohort(self.reader(key, seed).await?))
500 }
501
502 pub async fn reader<Key: SharedReaderKey>(
516 &self,
517 key: Key,
518 seed: impl FnOnce() -> Key::Value,
519 ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
520 let compatibility = Compatibility::for_key(&key);
521 if let Some(reference) = self.lookup::<Key>(&compatibility)? {
522 let reader = SharedReader { reference };
523 resource::<Key>(&reader)?;
524 drop(compatibility);
525 drop(seed);
526 drop(key);
527 return Ok(reader);
528 }
529 let seed = seed();
530 let loaded = match key.load(SharedLoadContext::Initial(&seed)).await {
531 Ok(loaded) => loaded,
532 Err(cause) => {
533 let error = provider(cause);
534 drop(seed);
535 drop(compatibility);
536 drop(key);
537 return Err(error);
538 }
539 };
540 let value = match loaded {
541 Some(value) => {
542 drop(seed);
543 value
544 }
545 None => seed,
546 };
547 let reference = build_reference(
548 key,
549 compatibility.clone(),
550 Arc::downgrade(&self.entries),
551 value,
552 SharedSubscribeContext::Initial,
553 )?;
554 self.publish::<Key>(compatibility, reference)
555 }
556
557 pub async fn shared_default<Key: SharedKey, Seed: Fn() -> Key::Value>(
565 &self,
566 default: SharedKeyDefault<Key, Seed>,
567 ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
568 self.shared(default.key, default.seed).await
569 }
570
571 pub async fn reader_default<Key: SharedReaderKey, Seed: Fn() -> Key::Value>(
579 &self,
580 default: SharedKeyDefault<Key, Seed>,
581 ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
582 self.reader(default.key, default.seed).await
583 }
584
585 pub async fn require<Key: SharedKey>(
596 &self,
597 key: Key,
598 ) -> Result<Shared<Key::Value>, SharedKeyError<Key::Error>> {
599 Ok(cohort(self.require_reader(key).await?))
600 }
601
602 pub async fn require_reader<Key: SharedReaderKey>(
611 &self,
612 key: Key,
613 ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
614 let loaded = match key.load(SharedLoadContext::UserInitiated).await {
615 Ok(loaded) => loaded,
616 Err(cause) => {
617 let error = provider(cause);
618 drop(key);
619 return Err(error);
620 }
621 }
622 .ok_or(SharedKeyError {
623 failure: Failure::Absent,
624 })?;
625 let compatibility = Compatibility::for_key(&key);
626 if let Some(reference) = self.lookup::<Key>(&compatibility)? {
627 let reader = SharedReader { reference };
628 resource::<Key>(&reader)?;
629 drop(compatibility);
630 drop(loaded);
631 drop(key);
632 return Ok(reader);
633 }
634 let reference = build_reference(
635 key,
636 compatibility.clone(),
637 Arc::downgrade(&self.entries),
638 loaded,
639 SharedSubscribeContext::UserInitiated,
640 )?;
641 self.publish::<Key>(compatibility, reference)
642 }
643
644 pub async fn reload<Key: SharedReaderKey>(
657 &self,
658 shared: &Shared<Key::Value>,
659 key: &Key,
660 ) -> Result<(), SharedKeyError<Key::Error>> {
661 let reader = shared.reader()?;
662 let result = self.reload_reader(&reader, key).await;
663 drop(reader);
664 result
665 }
666
667 pub async fn reload_reader<Key: SharedReaderKey>(
675 &self,
676 reader: &SharedReader<Key::Value>,
677 key: &Key,
678 ) -> Result<(), SharedKeyError<Key::Error>> {
679 let resource = resource::<Key>(reader)?;
680 if !std::ptr::eq(resource.namespace.as_ptr(), Arc::as_ptr(&self.entries))
681 || resource.compatibility != Compatibility::for_key(key)
682 {
683 return Err(collision());
684 }
685 reload_reference(reader, key, &resource.loads).await
686 }
687
688 pub async fn load<Key: SharedKey>(
703 &self,
704 shared: &Shared<Key::Value>,
705 key: Key,
706 seed: impl FnOnce(&Key::Value) -> Key::Value,
707 ) -> Result<(), SharedKeyError<Key::Error>> {
708 let reader = self.replacement(&shared.reader()?, key, seed)?;
709 let resource = resource::<Key>(&reader)?;
710 shared.rebind(&cohort(reader.clone()))?;
711 let result = reload_reference(&reader, &resource.key, &resource.loads).await;
712 drop(reader);
713 result
714 }
715
716 pub async fn load_reader<Key: SharedReaderKey>(
728 &self,
729 reader: &mut SharedReader<Key::Value>,
730 key: Key,
731 seed: impl FnOnce(&Key::Value) -> Key::Value,
732 ) -> Result<(), SharedKeyError<Key::Error>> {
733 let replacement = self.replacement(reader, key, seed)?;
734 let previous = std::mem::replace(reader, replacement);
735 let resource = match resource::<Key>(reader) {
736 Ok(resource) => resource,
737 Err(error) => {
738 drop(std::mem::replace(reader, previous));
739 return Err(error);
740 }
741 };
742 drop(previous);
743 reload_reference(reader, &resource.key, &resource.loads).await
744 }
745
746 pub fn reset(&self) -> Result<(), SharedKeyError<Infallible>> {
753 let previous = {
754 let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
755 std::mem::take(&mut *entries)
756 };
757 drop(previous);
758 Ok(())
759 }
760
761 fn replacement<Key: SharedReaderKey>(
766 &self,
767 current: &SharedReader<Key::Value>,
768 key: Key,
769 seed: impl FnOnce(&Key::Value) -> Key::Value,
770 ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
771 let compatibility = Compatibility::for_key(&key);
772 if let Some(reference) = self.lookup::<Key>(&compatibility)? {
773 let reader = SharedReader { reference };
775 drop(compatibility);
776 drop(seed);
777 drop(key);
778 return Ok(reader);
779 }
780 let value = current.read(seed)?;
781 let reference = build_reference(
782 key,
783 compatibility.clone(),
784 Arc::downgrade(&self.entries),
785 value,
786 SharedSubscribeContext::UserInitiated,
787 )?;
788 self.publish::<Key>(compatibility, reference)
789 }
790
791 #[expect(
793 clippy::type_complexity,
794 reason = "keeps the value type and provider failure coupled at this private boundary"
795 )]
796 fn lookup<Key: SharedReaderKey>(
797 &self,
798 compatibility: &Compatibility,
799 ) -> Result<Option<Arc<SharedReference<Key::Value>>>, SharedKeyError<Key::Error>> {
800 let found = {
801 let entries = self.entries.lock().map_err(|_error| poisoned())?;
802 entries
803 .get(compatibility.identity.address.as_str())
804 .map(|entry| {
805 (
809 entry.matches_at_same_address(compatibility),
810 entry.reference.upgrade(),
811 )
812 })
813 };
814 match found {
815 Some((compatible, Some(reference))) => {
816 if !compatible {
817 return Err(collision());
818 }
819 reference
820 .downcast()
821 .map(Some)
822 .map_err(|_reference| collision())
823 }
824 _ => Ok(None),
825 }
826 }
827
828 fn publish<Key: SharedReaderKey>(
832 &self,
833 mut compatibility: Compatibility,
834 candidate: Arc<SharedReference<Key::Value>>,
835 ) -> Result<SharedReader<Key::Value>, SharedKeyError<Key::Error>> {
836 let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&candidate) as Arc<_>;
837 let (winner, previous) = {
838 let mut entries = self.entries.lock().map_err(|_error| poisoned())?;
839 let winner = entries
840 .get(compatibility.identity.address.as_str())
841 .and_then(|entry| {
842 entry
843 .reference
844 .upgrade()
845 .map(|reference| (entry.matches_at_same_address(&compatibility), reference))
846 });
847 let previous = if winner.is_none() {
848 entries.insert(
849 take_compact(&mut compatibility.identity.address),
850 Entry {
851 codec: compatibility.identity.codec,
852 configuration: take_compact(&mut compatibility.identity.configuration),
853 reference: Arc::downgrade(&erased),
854 },
855 )
856 } else {
857 None
858 };
859 (winner, previous)
860 };
861 drop(previous);
862 drop(erased);
863 if let Some((compatible, winner)) = winner {
864 if !compatible {
865 return Err(collision());
866 }
867 let reader = SharedReader {
868 reference: winner.downcast().map_err(|_reference| collision())?,
869 };
870 resource::<Key>(&reader)?;
871 drop(candidate);
872 return Ok(reader);
873 }
874 Ok(SharedReader {
875 reference: candidate,
876 })
877 }
878}
879
880fn take_compact(text: &mut String) -> Box<str> {
882 if text.len() == text.capacity() {
883 std::mem::take(text).into_boxed_str()
884 } else {
885 Box::from(text.as_str())
887 }
888}
889
890fn cohort<Value>(reader: SharedReader<Value>) -> Shared<Value> {
892 Shared {
893 cohort: Arc::new(Mutex::new(reader)),
894 }
895}
896
897fn build_reference<Key: SharedReaderKey>(
902 key: Key,
903 compatibility: Compatibility,
904 namespace: Weak<Mutex<HashMap<Box<str>, Entry>>>,
905 value: Key::Value,
906 context: SharedSubscribeContext,
907) -> Result<Arc<SharedReference<Key::Value>>, SharedKeyError<Key::Error>> {
908 let reference = Arc::new(SharedReference::new(value));
909 let loads = Arc::new(Mutex::new(None));
911 let subscription = match key.subscribe(
912 context,
913 SharedSubscriber {
914 reference: Arc::downgrade(&reference),
915 loads: Arc::downgrade(&loads),
916 },
917 ) {
918 Ok(subscription) => subscription,
919 Err(cause) => {
920 let error = provider(cause);
921 drop(loads);
922 drop(reference);
923 drop(namespace);
924 drop(compatibility);
925 drop(key);
926 return Err(error);
927 }
928 };
929 let installed = reference.retained.set(Box::new(KeyResource {
931 key,
932 compatibility,
933 namespace,
934 _subscription: subscription,
935 loads,
936 }));
937 assert!(
938 installed.is_ok(),
939 "a new shared reference has no retained resource"
940 );
941 Ok(reference)
942}
943
944fn resource<Key: SharedReaderKey>(
946 reader: &SharedReader<Key::Value>,
947) -> Result<&KeyResource<Key>, SharedKeyError<Key::Error>> {
948 reader
949 .reference
950 .retained
951 .get()
952 .and_then(|resource| resource.downcast_ref::<KeyResource<Key>>())
953 .ok_or_else(collision)
954}
955
956async fn reload_reference<Key: SharedReaderKey>(
958 reader: &SharedReader<Key::Value>,
959 key: &Key,
960 loads: &Mutex<Option<Weak<()>>>,
961) -> Result<(), SharedKeyError<Key::Error>> {
962 let attempt = ReferenceLoadAttempt::begin(&reader.reference, loads)?;
963 let loaded = key
964 .load(SharedLoadContext::UserInitiated)
965 .await
966 .map_err(provider)?;
967 attempt.commit(loaded)?;
968 Ok(())
969}
970
971struct ReferenceLoadAttempt<'a, Value> {
973 reference: &'a SharedReference<Value>,
975 loads: &'a Mutex<Option<Weak<()>>>,
977 identity: Arc<()>,
979 retired: bool,
981}
982
983impl<'a, Value> ReferenceLoadAttempt<'a, Value> {
984 fn begin(
986 reference: &'a SharedReference<Value>,
987 loads: &'a Mutex<Option<Weak<()>>>,
988 ) -> Result<Self, SharedAccessError> {
989 let identity = Arc::new(());
990 let previous = {
991 let mut latest = loads.lock().map_err(|_error| load_poisoned())?;
992 latest.replace(Arc::downgrade(&identity))
993 };
994 drop(previous);
995 Ok(Self {
996 reference,
997 loads,
998 identity,
999 retired: false,
1000 })
1001 }
1002
1003 fn is_latest(&self, latest: Option<&Weak<()>>) -> bool {
1005 latest.is_some_and(|latest| std::ptr::eq(latest.as_ptr(), Arc::as_ptr(&self.identity)))
1008 }
1009
1010 fn commit(mut self, value: Option<Value>) -> Result<bool, SharedAccessError> {
1014 let mut value = value;
1015 let (committed, displaced, previous) = {
1016 let mut latest = self.loads.lock().map_err(|_error| load_poisoned())?;
1017 if self.is_latest(latest.as_ref()) {
1018 let displaced = if value.is_some() {
1021 let mut current = try_lock(&self.reference.value)?;
1022 value
1023 .take()
1024 .map(|value| std::mem::replace(&mut *current, value))
1025 } else {
1026 None
1027 };
1028 (true, displaced, latest.take())
1029 } else {
1030 (false, None, None)
1031 }
1032 };
1033 self.retired = true;
1034 drop(previous);
1035 drop(displaced);
1036 drop(value);
1037 Ok(committed)
1038 }
1039}
1040
1041impl<Value> Drop for ReferenceLoadAttempt<'_, Value> {
1042 fn drop(&mut self) {
1043 if self.retired {
1044 return;
1045 }
1046 let previous = if let Ok(mut latest) = self.loads.lock() {
1049 if self.is_latest(latest.as_ref()) {
1050 latest.take()
1051 } else {
1052 None
1053 }
1054 } else {
1055 None
1056 };
1057 drop(previous);
1058 }
1059}
1060
1061fn load_poisoned() -> SharedAccessError {
1063 SharedAccessError {
1064 kind: super::AccessKind::Poisoned,
1065 }
1066}
1067
1068fn provider<Cause>(cause: Cause) -> SharedKeyError<Cause> {
1070 SharedKeyError {
1071 failure: Failure::Provider(cause),
1072 }
1073}
1074
1075fn collision<Cause>() -> SharedKeyError<Cause> {
1077 SharedKeyError {
1078 failure: Failure::Collision,
1079 }
1080}
1081
1082fn poisoned<Cause>() -> SharedKeyError<Cause> {
1084 SharedKeyError {
1085 failure: Failure::Poisoned,
1086 }
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091 use super::*;
1092
1093 #[test]
1095 fn take_compact_transfers_exact_capacity_buffers() {
1096 for expected in ["", "shared-profile"] {
1097 let mut text = Box::<str>::from(expected).into_string();
1098 let pointer = text.as_ptr();
1099 assert_eq!(text.capacity(), text.len());
1100
1101 let compact = take_compact(&mut text);
1102
1103 assert_eq!(compact.as_ref(), expected);
1104 if !expected.is_empty() {
1105 assert_eq!(compact.as_ptr(), pointer);
1106 }
1107 assert_eq!(text, "");
1108 assert_eq!(text.capacity(), 0);
1109 }
1110 }
1111
1112 #[test]
1114 fn take_compact_preserves_buffers_with_spare_capacity() {
1115 for expected in ["", "shared-profile"] {
1116 let mut text = String::with_capacity(expected.len() + 16);
1117 text.push_str(expected);
1118 let pointer = text.as_ptr();
1119 let capacity = text.capacity();
1120 assert!(capacity > text.len());
1121
1122 let compact = take_compact(&mut text);
1123
1124 assert_eq!(compact.as_ref(), expected);
1125 assert_eq!(text, expected);
1126 assert_eq!(text.as_ptr(), pointer);
1127 assert_eq!(text.capacity(), capacity);
1128 if !expected.is_empty() {
1129 assert_ne!(compact.as_ptr(), pointer);
1130 }
1131 }
1132 }
1133
1134 #[test]
1136 fn diagnostics_redact_resource_identity_and_non_debug_values() {
1137 struct Secret(&'static str);
1138
1139 let identity = SharedKeyIdentity::new::<()>("private-address", "private-configuration");
1140 let reference = Arc::new(SharedReference::new(Secret("private-value")));
1141 let loads = Arc::new(Mutex::new(None));
1142 let subscriber = SharedSubscriber {
1143 reference: Arc::downgrade(&reference),
1144 loads: Arc::downgrade(&loads),
1145 };
1146 let publication = subscriber.prepare_publication().unwrap();
1147 let value = reference.value.lock().unwrap();
1148 let initial = format!("{:?}", SharedLoadContext::Initial(&*value));
1149 let explicit = format!("{:?}", SharedLoadContext::<Secret>::UserInitiated);
1150 assert_ne!(initial, explicit);
1151 for diagnostic in [
1152 format!("{identity:?}"),
1153 format!("{subscriber:?}"),
1154 format!("{publication:?}"),
1155 format!("{:?}", SharedKeyCache::new()),
1156 initial,
1157 explicit,
1158 ] {
1159 for secret in ["private-address", "private-configuration", value.0] {
1160 assert!(!diagnostic.contains(secret));
1161 }
1162 }
1163 }
1164
1165 #[test]
1167 fn provider_error_source_preserves_the_cause_without_disclosing_it() {
1168 let error = provider(std::io::Error::new(
1169 std::io::ErrorKind::PermissionDenied,
1170 "private-provider-path",
1171 ));
1172 assert!(!error.is_absent());
1173 assert!(!error.is_collision());
1174 assert!(!error.is_poisoned());
1175 assert!(error.access_error().is_none());
1176 assert!(!format!("{error}: {error:?}").contains("private-provider-path"));
1177 let source = std::error::Error::source(&error)
1178 .unwrap()
1179 .downcast_ref::<std::io::Error>()
1180 .unwrap();
1181 assert_eq!(source.kind(), std::io::ErrorKind::PermissionDenied);
1182 assert_eq!(source.to_string(), "private-provider-path");
1183 let recovered = error.into_failure().unwrap();
1184 assert_eq!(recovered.kind(), std::io::ErrorKind::PermissionDenied);
1185 assert_eq!(recovered.to_string(), "private-provider-path");
1186 }
1187
1188 #[test]
1190 fn poisoned_metadata_rejects_lookup_publication_and_reset_without_revoking_owners() {
1191 let cache = SharedKeyCache::new();
1192 let seeds = std::cell::Cell::new(0);
1193 let seed = || {
1194 seeds.set(seeds.get() + 1);
1195 7
1196 };
1197 let owner = futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap();
1198 let compatibility = Compatibility::for_key(&LayoutKey);
1199 let candidate = build_reference(
1200 LayoutKey,
1201 compatibility.clone(),
1202 Arc::downgrade(&cache.entries),
1203 11,
1204 SharedSubscribeContext::UserInitiated,
1205 )
1206 .unwrap();
1207 let provisional = Arc::downgrade(&candidate);
1208 let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1209 let _guard = cache.entries.lock().unwrap();
1210 panic!("metadata interrupted");
1211 }));
1212 assert!(panic.is_err());
1213 let errors = [
1214 futures_executor::block_on(cache.reader(LayoutKey, seed)).unwrap_err(),
1215 cache
1216 .publish::<LayoutKey>(compatibility, candidate)
1217 .unwrap_err(),
1218 cache.reset().unwrap_err(),
1219 ];
1220 for error in errors {
1221 assert!(error.is_poisoned());
1222 assert!(!error.is_collision());
1223 assert!(!error.is_absent());
1224 assert!(error.access_error().is_none());
1225 assert!(std::error::Error::source(&error).is_none());
1226 assert!(error.to_string().contains("metadata is poisoned"));
1227 assert!(error.into_failure().is_none());
1228 }
1229 assert_eq!(seeds.get(), 1);
1230 assert!(provisional.upgrade().is_none());
1231 assert_eq!(owner.read(|value| *value).unwrap(), 7);
1232 }
1233
1234 #[test]
1236 fn mismatched_erased_entry_rejects_reader_without_seed_or_owner_leak() {
1237 let cache = SharedKeyCache::new();
1238 let compatibility = Compatibility::for_key(&LayoutKey);
1239 let owner = Arc::new(SharedReference::new("private-wrong-value"));
1240 let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
1241 cache.entries.lock().unwrap().insert(
1242 compatibility.identity.address.clone().into_boxed_str(),
1243 Entry {
1244 codec: compatibility.identity.codec,
1245 configuration: compatibility
1246 .identity
1247 .configuration
1248 .clone()
1249 .into_boxed_str(),
1250 reference: Arc::downgrade(&erased),
1251 },
1252 );
1253 drop(erased);
1254
1255 let error = futures_executor::block_on(cache.reader(LayoutKey, || {
1256 panic!("a mismatched live reference must not fall back to its seed")
1257 }))
1258 .unwrap_err();
1259 assert!(error.is_collision());
1260 assert_eq!(
1261 error.to_string(),
1262 "shared key has an incompatible live reference"
1263 );
1264 assert!(!format!("{error:?}").contains("private-wrong-value"));
1265 assert!(!error.is_poisoned());
1266 assert_eq!(Arc::strong_count(&owner), 1);
1267 assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
1268 drop(cache);
1269 assert_eq!(Arc::strong_count(&owner), 1);
1270 }
1271
1272 #[test]
1274 fn mismatched_erased_winner_rejects_publication_and_drops_candidate_outside_lock() {
1275 use std::sync::atomic::{AtomicUsize, Ordering};
1276
1277 struct CandidateDrop(SharedKeyCache, Arc<AtomicUsize>);
1278 impl Drop for CandidateDrop {
1279 fn drop(&mut self) {
1280 assert!(
1281 self.0.entries.try_lock().is_ok(),
1282 "candidate drop holds metadata lock"
1283 );
1284 self.1.fetch_add(1, Ordering::SeqCst);
1285 }
1286 }
1287
1288 let cache = SharedKeyCache::new();
1289 let compatibility = Compatibility::for_key(&LayoutKey);
1290 let owner = Arc::new(SharedReference::new("private-wrong-value"));
1291 let erased: Arc<dyn Any + Send + Sync> = Arc::clone(&owner) as Arc<_>;
1292 let retained = Arc::downgrade(&erased);
1293 cache.entries.lock().unwrap().insert(
1294 compatibility.identity.address.clone().into_boxed_str(),
1295 Entry {
1296 codec: compatibility.identity.codec,
1297 configuration: compatibility
1298 .identity
1299 .configuration
1300 .clone()
1301 .into_boxed_str(),
1302 reference: Weak::clone(&retained),
1303 },
1304 );
1305 drop(erased);
1306 let drops = Arc::new(AtomicUsize::new(0));
1307 let candidate = Arc::new(SharedReference::new(11_usize));
1308 candidate
1309 .retained
1310 .set(Box::new(CandidateDrop(cache.clone(), Arc::clone(&drops))))
1311 .unwrap_or_else(|_| panic!("fresh candidate has no retained resource"));
1312 let provisional = Arc::downgrade(&candidate);
1313
1314 let error = cache
1315 .publish::<LayoutKey>(compatibility.clone(), candidate)
1316 .unwrap_err();
1317 assert!(error.is_collision());
1318 assert_eq!(
1319 error.to_string(),
1320 "shared key has an incompatible live reference"
1321 );
1322 assert!(!format!("{error:?}").contains("private-wrong-value"));
1323 assert_eq!(drops.load(Ordering::SeqCst), 1);
1324 assert!(provisional.upgrade().is_none());
1325 assert_eq!(Arc::strong_count(&owner), 1);
1326 let entries = cache.entries.lock().unwrap();
1327 assert_eq!(entries.len(), 1);
1328 assert!(Weak::ptr_eq(
1329 &entries[compatibility.identity.address.as_str()].reference,
1330 &retained
1331 ));
1332 drop(entries);
1333 assert_eq!(*owner.value.lock().unwrap(), "private-wrong-value");
1334 drop(cache);
1335 assert_eq!(drops.load(Ordering::SeqCst), 1);
1336 assert_eq!(Arc::strong_count(&drops), 1);
1337 }
1338
1339 #[test]
1341 fn poisoned_reload_coordinator_preserves_values_and_does_not_panic_during_retirement() {
1342 let reference = Arc::new(SharedReference::new(7));
1343 let loads = Arc::new(Mutex::new(None));
1344 let subscriber = SharedSubscriber {
1345 reference: Arc::downgrade(&reference),
1346 loads: Arc::downgrade(&loads),
1347 };
1348 let publication = subscriber.prepare_publication().unwrap();
1349 let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1350 let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1351 let _guard = loads.lock().unwrap();
1352 panic!("reload coordination interrupted");
1353 }));
1354 assert!(panic.is_err());
1355 assert!(attempt.commit(Some(11)).unwrap_err().is_poisoned());
1356 let error = ReferenceLoadAttempt::begin(&reference, &loads)
1357 .err()
1358 .unwrap();
1359 assert!(error.is_poisoned());
1360 let mut next = 13;
1361 assert!(
1362 publication
1363 .try_replace(&mut next)
1364 .unwrap_err()
1365 .is_poisoned()
1366 );
1367 assert_eq!(next, 13);
1368 assert_eq!(*reference.value.lock().unwrap(), 7);
1369 assert!(loads.is_poisoned());
1370 }
1371
1372 #[test]
1374 fn reload_propagates_coordinator_poison_before_invoking_provider() {
1375 use std::sync::atomic::{AtomicUsize, Ordering};
1376
1377 #[derive(Clone)]
1378 struct Key {
1379 loads: Arc<AtomicUsize>,
1380 retirements: Arc<AtomicUsize>,
1381 }
1382 struct Subscription(Arc<AtomicUsize>);
1383
1384 impl Drop for Subscription {
1385 fn drop(&mut self) {
1386 self.0.fetch_add(1, Ordering::SeqCst);
1387 }
1388 }
1389
1390 impl SharedReaderKey for Key {
1391 type Value = usize;
1392 type Error = Infallible;
1393 type Subscription = Subscription;
1394
1395 fn identity(&self) -> SharedKeyIdentity {
1396 SharedKeyIdentity::new::<Self>("poisoned-reload", "")
1397 }
1398
1399 fn load(
1400 &self,
1401 _: SharedLoadContext<'_, usize>,
1402 ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
1403 self.loads.fetch_add(1, Ordering::SeqCst);
1404 std::future::ready(Ok(None))
1405 }
1406
1407 fn subscribe(
1408 &self,
1409 _: SharedSubscribeContext,
1410 _: SharedSubscriber<usize>,
1411 ) -> Result<Subscription, Infallible> {
1412 Ok(Subscription(Arc::clone(&self.retirements)))
1413 }
1414 }
1415
1416 let key = Key {
1417 loads: Arc::new(AtomicUsize::new(0)),
1418 retirements: Arc::new(AtomicUsize::new(0)),
1419 };
1420 let cache = SharedKeyCache::new();
1421 let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
1422 let owner = Arc::downgrade(&reader.reference);
1423 let loads = Arc::clone(&resource::<Key>(&reader).unwrap().loads);
1424 assert_eq!(key.loads.load(Ordering::SeqCst), 1);
1425 let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1426 let _guard = loads.lock().unwrap();
1427 panic!("reload coordination interrupted");
1428 }));
1429 assert!(panic.is_err());
1430
1431 let error = futures_executor::block_on(cache.reload_reader(&reader, &key)).unwrap_err();
1432 assert!(error.access_error().unwrap().is_poisoned());
1433 assert!(!error.is_poisoned(), "not a metadata-lock failure");
1434 assert!(!error.is_collision());
1435 assert!(
1436 std::error::Error::source(&error)
1437 .unwrap()
1438 .downcast_ref::<SharedAccessError>()
1439 .unwrap()
1440 .is_poisoned()
1441 );
1442 assert_eq!(key.loads.load(Ordering::SeqCst), 1);
1443 assert_eq!(reader.read(|value| *value).unwrap(), 7);
1444 assert!(loads.is_poisoned());
1445 assert_eq!(key.retirements.load(Ordering::SeqCst), 0);
1446 drop(reader);
1447 assert!(owner.upgrade().is_none());
1448 assert_eq!(key.retirements.load(Ordering::SeqCst), 1);
1449 }
1450
1451 #[test]
1453 fn reload_rejects_a_busy_cohort_without_changing_its_capture() {
1454 use std::sync::atomic::{AtomicUsize, Ordering};
1455
1456 #[derive(Clone)]
1457 struct CountingKey(Arc<AtomicUsize>);
1458
1459 impl SharedReaderKey for CountingKey {
1460 type Value = usize;
1461 type Error = Infallible;
1462 type Subscription = ();
1463
1464 fn identity(&self) -> SharedKeyIdentity {
1465 SharedKeyIdentity::new::<Self>("busy-cohort", "")
1466 }
1467
1468 fn load(
1469 &self,
1470 _: SharedLoadContext<'_, usize>,
1471 ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
1472 self.0.fetch_add(1, Ordering::SeqCst);
1473 std::future::ready(Ok(None))
1474 }
1475
1476 fn subscribe(
1477 &self,
1478 _: SharedSubscribeContext,
1479 _: SharedSubscriber<usize>,
1480 ) -> Result<(), Infallible> {
1481 Ok(())
1482 }
1483 }
1484
1485 let key = CountingKey(Arc::new(AtomicUsize::new(0)));
1486 let cache = SharedKeyCache::new();
1487 let reader = futures_executor::block_on(cache.reader(key.clone(), || 7)).unwrap();
1488 assert_eq!(key.0.load(Ordering::SeqCst), 1);
1489 let shared = cohort(reader.clone());
1490 let guard = shared.cohort.lock().unwrap();
1491 let error = futures_executor::block_on(cache.reload(&shared, &key)).unwrap_err();
1492 assert!(error.access_error().unwrap().is_busy());
1493 assert_eq!(key.0.load(Ordering::SeqCst), 1);
1494 assert_eq!(reader.read(|value| *value).unwrap(), 7);
1495 drop(guard);
1496 futures_executor::block_on(cache.reload(&shared, &key)).unwrap();
1497 assert_eq!(key.0.load(Ordering::SeqCst), 2);
1498 assert_eq!(shared.read(|value| *value).unwrap(), 7);
1499 }
1500
1501 #[test]
1503 fn load_contention_retires_provisional_subscription_before_retry() {
1504 #[derive(Clone)]
1505 struct Key(Arc<Mutex<Vec<&'static str>>>);
1506 struct Subscription(Arc<Mutex<Vec<&'static str>>>);
1507 impl Drop for Subscription {
1508 fn drop(&mut self) {
1509 self.0.lock().unwrap().push("retire");
1510 }
1511 }
1512 impl SharedReaderKey for Key {
1513 type Value = String;
1514 type Error = Infallible;
1515 type Subscription = Subscription;
1516
1517 fn identity(&self) -> SharedKeyIdentity {
1518 SharedKeyIdentity::new::<Self>("contended-load", "")
1519 }
1520 fn load(
1521 &self,
1522 context: SharedLoadContext<'_, String>,
1523 ) -> impl Future<Output = Result<Option<String>, Infallible>> + Send {
1524 assert!(matches!(context, SharedLoadContext::UserInitiated));
1525 self.0.lock().unwrap().push("reload");
1526 std::future::ready(Ok(None))
1527 }
1528 fn subscribe(
1529 &self,
1530 context: SharedSubscribeContext,
1531 _: SharedSubscriber<String>,
1532 ) -> Result<Subscription, Infallible> {
1533 assert_eq!(context, SharedSubscribeContext::UserInitiated);
1534 self.0.lock().unwrap().push("subscribe");
1535 Ok(Subscription(Arc::clone(&self.0)))
1536 }
1537 }
1538 impl SharedKey for Key {
1539 fn save(&self, _: &String) -> impl Future<Output = Result<(), Infallible>> + Send {
1540 self.0.lock().unwrap().push("save");
1541 std::future::ready(Ok(()))
1542 }
1543 }
1544
1545 let cache = SharedKeyCache::new();
1546 let key = Key(Arc::new(Mutex::new(Vec::new())));
1547 let shared = Shared::new(String::from("original"));
1548 let original = shared.reader().unwrap();
1549 let guard = shared.cohort.lock().unwrap();
1550 let error = futures_executor::block_on(cache.load(&shared, key.clone(), |_| {
1551 panic!("capture contention must not seed")
1552 }))
1553 .unwrap_err();
1554 assert!(error.access_error().unwrap().is_busy());
1555 assert!(error.into_failure().is_none());
1556 assert!(key.0.lock().unwrap().is_empty());
1557 drop(guard);
1558
1559 let mut retained_guard = None;
1560 let error = futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
1561 assert_eq!(value, "original");
1562 retained_guard = Some(shared.cohort.lock().unwrap());
1563 String::from("provisional")
1564 }))
1565 .unwrap_err();
1566 assert!(error.access_error().unwrap().is_busy());
1567 assert!(error.into_failure().is_none());
1568 assert_eq!(*key.0.lock().unwrap(), ["subscribe", "retire"]);
1569 drop(retained_guard);
1570 assert!(shared.read(|value| value == "original").unwrap());
1571 assert!(original.read(|value| value == "original").unwrap());
1572
1573 futures_executor::block_on(cache.load(&shared, key.clone(), |value| {
1574 assert_eq!(value, "original");
1575 String::from("replacement")
1576 }))
1577 .unwrap();
1578 assert_eq!(
1579 *key.0.lock().unwrap(),
1580 ["subscribe", "retire", "subscribe", "reload"]
1581 );
1582 assert!(shared.read(|value| value == "replacement").unwrap());
1583 assert!(original.read(|value| value == "original").unwrap());
1584 drop(shared);
1585 assert_eq!(
1586 *key.0.lock().unwrap(),
1587 ["subscribe", "retire", "subscribe", "reload", "retire"]
1588 );
1589 }
1590
1591 #[test]
1592 fn failed_subscription_orphan_cannot_prepare_without_its_coordinator() {
1593 struct Value(u8, Arc<Mutex<Vec<u8>>>);
1594 impl Drop for Value {
1595 fn drop(&mut self) {
1596 self.1.lock().unwrap().push(self.0);
1597 }
1598 }
1599 struct Captured {
1600 subscriber: SharedSubscriber<Value>,
1601 publication: SharedPublication<Value>,
1602 }
1603 struct FailingSubscription(Arc<Mutex<Option<Captured>>>);
1604 impl SharedReaderKey for FailingSubscription {
1605 type Value = Value;
1606 type Error = &'static str;
1607 type Subscription = ();
1608
1609 fn identity(&self) -> SharedKeyIdentity {
1610 SharedKeyIdentity::new::<Self>("orphan", "")
1611 }
1612
1613 fn load(
1614 &self,
1615 _: SharedLoadContext<'_, Value>,
1616 ) -> impl Future<Output = Result<Option<Value>, &'static str>> + Send {
1617 std::future::ready(Ok(None))
1618 }
1619
1620 fn subscribe(
1621 &self,
1622 context: SharedSubscribeContext,
1623 subscriber: SharedSubscriber<Value>,
1624 ) -> Result<(), &'static str> {
1625 assert!(matches!(context, SharedSubscribeContext::Initial));
1626 let publication = subscriber.prepare_publication().unwrap();
1627 assert!(
1628 self.0
1629 .lock()
1630 .unwrap()
1631 .replace(Captured {
1632 subscriber,
1633 publication,
1634 })
1635 .is_none()
1636 );
1637 Err("subscription failed")
1638 }
1639 }
1640
1641 let cache = SharedKeyCache::new();
1642 let captured = Arc::new(Mutex::new(None));
1643 let drops = Arc::new(Mutex::new(Vec::new()));
1644 let error = futures_executor::block_on(
1645 cache.reader(FailingSubscription(Arc::clone(&captured)), || {
1646 Value(1, Arc::clone(&drops))
1647 }),
1648 )
1649 .unwrap_err();
1650 assert_eq!(error.into_failure(), Some("subscription failed"));
1651 assert!(cache.entries.lock().unwrap().is_empty());
1652 assert!(drops.lock().unwrap().is_empty());
1653 let Captured {
1654 subscriber,
1655 publication,
1656 } = captured.lock().unwrap().take().unwrap();
1657
1658 let SharedPublication { reference, loads } = publication;
1661 assert!(reference.retained.get().is_none());
1662 assert_eq!(Arc::strong_count(&reference), 1);
1663 assert_eq!(Arc::strong_count(&loads), 1);
1664 drop(loads);
1665 assert!(subscriber.loads.upgrade().is_none());
1666 assert_eq!(subscriber.reference.strong_count(), 1);
1667
1668 assert!(subscriber.prepare_publication().is_none());
1669 assert_eq!(Arc::strong_count(&reference), 1);
1670 assert_eq!(reference.value.lock().unwrap().0, 1);
1671 assert!(drops.lock().unwrap().is_empty());
1672 assert!(
1673 !subscriber
1674 .yield_value(Value(2, Arc::clone(&drops)))
1675 .unwrap()
1676 );
1677 assert_eq!(*drops.lock().unwrap(), [2]);
1678 assert_eq!(reference.value.lock().unwrap().0, 1);
1679 assert_eq!(Arc::strong_count(&reference), 1);
1680 drop(reference);
1681 assert_eq!(*drops.lock().unwrap(), [2, 1]);
1682 assert!(subscriber.reference.upgrade().is_none());
1683 assert!(subscriber.prepare_publication().is_none());
1684 drop(subscriber);
1685 drop(cache);
1686 assert_eq!(*drops.lock().unwrap(), [2, 1]);
1687 assert_eq!(Arc::strong_count(&drops), 1);
1688 }
1689
1690 #[test]
1691 fn subscriber_swap_retains_displaced_value_until_external_fence_is_released() {
1692 struct Reentrant(Arc<Mutex<bool>>, Arc<std::sync::atomic::AtomicUsize>);
1693 impl Drop for Reentrant {
1694 fn drop(&mut self) {
1695 *self
1696 .0
1697 .try_lock()
1698 .expect("destructor can reenter cancellation") = false;
1699 self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1700 }
1701 }
1702 let control = Arc::new(Mutex::new(true));
1703 let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1704 let reference = Arc::new(SharedReference::new(Reentrant(
1705 Arc::clone(&control),
1706 Arc::clone(&drops),
1707 )));
1708 let loads = Arc::new(Mutex::new(None));
1709 let subscriber = SharedSubscriber {
1710 reference: Arc::downgrade(&reference),
1711 loads: Arc::downgrade(&loads),
1712 };
1713 let mut next = Reentrant(Arc::clone(&control), Arc::clone(&drops));
1714 let publication = subscriber.prepare_publication().unwrap();
1715 drop(reference);
1716 let guard = control.lock().unwrap();
1717 assert!(publication.try_replace(&mut next).unwrap());
1718 drop(guard);
1719 drop(next);
1720 assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 1);
1721 drop(publication);
1722 assert_eq!(drops.load(std::sync::atomic::Ordering::SeqCst), 2);
1723 assert!(!*control.lock().unwrap());
1724 assert!(subscriber.prepare_publication().is_none());
1725 }
1726
1727 #[test]
1728 fn prepared_publication_and_cancellation_have_one_final_commit_order() {
1729 let reference = Arc::new(SharedReference::new(7));
1730 let loads = Arc::new(Mutex::new(None));
1731 let subscriber = SharedSubscriber {
1732 reference: Arc::downgrade(&reference),
1733 loads: Arc::downgrade(&loads),
1734 };
1735 let publication = subscriber.prepare_publication().unwrap();
1736 let control = Arc::new(Mutex::new(true));
1737 let publishing = Arc::clone(&control);
1738 let cancelling = Arc::clone(&control);
1739 let (checked, checked_rx) = std::sync::mpsc::channel();
1740 let (resume, resume_rx) = std::sync::mpsc::channel();
1741 let (attempted, attempted_rx) = std::sync::mpsc::channel();
1742 let (cancelled, cancelled_rx) = std::sync::mpsc::channel();
1743 let worker = std::thread::spawn(move || {
1744 let mut next = 8;
1745 let fence = publishing.lock().unwrap();
1746 assert!(*fence);
1747 checked.send(()).unwrap();
1748 resume_rx.recv().unwrap(); assert!(publication.try_replace(&mut next).unwrap());
1750 drop(fence);
1751 assert_eq!(next, 7);
1752 });
1753 checked_rx.recv().unwrap();
1754 let cancellation_worker = std::thread::spawn(move || {
1755 attempted.send(()).unwrap();
1756 *cancelling.lock().unwrap() = false;
1757 cancelled.send(()).unwrap();
1758 });
1759 attempted_rx.recv().unwrap();
1760 assert_eq!(*reference.value.lock().unwrap(), 7);
1761 assert!(matches!(
1762 cancelled_rx.try_recv(),
1763 Err(std::sync::mpsc::TryRecvError::Empty)
1764 ));
1765 resume.send(()).unwrap();
1766 worker.join().unwrap();
1767 cancellation_worker.join().unwrap();
1768 cancelled_rx.recv().unwrap();
1769 assert_eq!(*reference.value.lock().unwrap(), 8);
1770 let publication = subscriber.prepare_publication().unwrap();
1771 let mut next = 99;
1772 {
1773 let fence = control.lock().unwrap();
1774 if *fence {
1775 publication.try_replace(&mut next).unwrap();
1776 }
1777 }
1778 assert_eq!(next, 99);
1779 assert_eq!(*reference.value.lock().unwrap(), 8);
1780 }
1781
1782 #[test]
1783 fn obsolete_attempts_cannot_clear_the_latest_loading_token() {
1784 let reference = SharedReference::new(1);
1785 let loads = Mutex::new(None);
1786 let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1787 let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1788 assert!(!old.commit(Some(10)).unwrap());
1789 assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
1790 assert!(latest.commit(Some(20)).unwrap());
1791 assert!(loads.lock().unwrap().is_none());
1792 assert_eq!(*reference.value.lock().unwrap(), 20);
1793
1794 let old = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1795 let latest = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1796 drop(old);
1797 assert!(latest.is_latest(loads.lock().unwrap().as_ref()));
1798 drop(latest);
1799 assert!(loads.lock().unwrap().is_none());
1800 }
1801
1802 #[test]
1803 fn latest_busy_commit_retires_without_replacing_or_poisoning() {
1804 let reference = SharedReference::new(1);
1805 let loads = Mutex::new(None);
1806 let attempt = ReferenceLoadAttempt::begin(&reference, &loads).unwrap();
1807 let current = reference.value.lock().unwrap();
1808 assert!(attempt.commit(Some(2)).unwrap_err().is_busy());
1809 assert!(loads.lock().unwrap().is_none());
1810 assert_eq!(*current, 1);
1811 drop(current);
1812 assert!(
1813 ReferenceLoadAttempt::begin(&reference, &loads)
1814 .unwrap()
1815 .commit(Some(3))
1816 .unwrap()
1817 );
1818 }
1819
1820 struct LayoutKey;
1821
1822 impl SharedReaderKey for LayoutKey {
1823 type Value = usize;
1824 type Error = Infallible;
1825 type Subscription = ();
1826
1827 fn identity(&self) -> SharedKeyIdentity {
1828 SharedKeyIdentity::new::<()>("layout", "")
1829 }
1830
1831 fn load(
1832 &self,
1833 _: SharedLoadContext<'_, usize>,
1834 ) -> impl Future<Output = Result<Option<usize>, Infallible>> + Send {
1835 std::future::ready(Ok(None))
1836 }
1837
1838 fn subscribe(
1839 &self,
1840 _: SharedSubscribeContext,
1841 _: SharedSubscriber<usize>,
1842 ) -> Result<(), Infallible> {
1843 Ok(())
1844 }
1845 }
1846
1847 #[test]
1848 fn reports_retained_reference_layout() {
1849 assert_eq!(size_of::<Shared<usize>>(), size_of::<Arc<()>>());
1851 assert_eq!(size_of::<SharedReader<usize>>(), size_of::<Arc<()>>());
1852 eprintln!(
1853 "Shared<usize>={} SharedReader<usize>={} old-value-mutex={} retained-reference={} keyed-resource={} coordinator={} attempt={} strong-token={} weak-token={} subscriber={}",
1854 size_of::<Shared<usize>>(),
1855 size_of::<SharedReader<usize>>(),
1856 size_of::<Mutex<usize>>(),
1857 size_of::<SharedReference<usize>>(),
1858 size_of::<KeyResource<LayoutKey>>(),
1859 size_of::<Mutex<Option<Weak<()>>>>(),
1860 size_of::<ReferenceLoadAttempt<'_, usize>>(),
1861 size_of::<Arc<()>>(),
1862 size_of::<Weak<()>>(),
1863 size_of::<SharedSubscriber<usize>>(),
1864 );
1865 }
1866}