Skip to main content

rca_sharing/
lib.rs

1#![deny(rustdoc::broken_intra_doc_links)]
2#![forbid(unsafe_code)]
3
4//! Shares values between owners without a Store or an async runtime.
5//!
6//! Use [`Shared`] when several owners need to update one value. Give a
7//! [`SharedReader`] to callers that only need to read it. For independent
8//! callers that open the same resource by key, use [`SharedKeyCache`].
9//! Applications that already use RCA can import these types from `rca`.
10//!
11//! # Examples
12//!
13//! ```
14//! use rca_sharing::{Shared, SharedAccessError};
15//!
16//! let count = Shared::new(0);
17//! let display = count.reader()?;
18//! count.update(|value| *value += 1, || {})?;
19//! assert_eq!(display.read(|value| *value)?, 1);
20//! # Ok::<(), SharedAccessError>(())
21//! ```
22//!
23//! # Access and publication
24//!
25//! [`Shared`] and its clones share one binding. Readers and projections keep
26//! the value that the binding selected at the time of capture.
27//! Independent bindings can refer to the same value after [`Shared::rebind`].
28//! Later changes to either binding do not affect the other. These handles own
29//! data, not Store membership or output authority. Retaining them cannot revive a retired scope.
30//!
31//! Access through a shared handle or projection is synchronous and non-blocking.
32//! No mutex guard or borrow of the value can escape an access callback. Overlapping access (including synchronous reentry)
33//! returns Busy; a panicking access callback poisons that value reference.
34//! Readers with interior-mutable values retain the capabilities inherent in `&T`;
35//! a reader grants no `&mut T` and cannot rebind a writer. A cache can replace an
36//! individual reader through [`SharedKeyCache::load_reader`].
37//!
38//! Mutation callbacks operate in place: returning `Err` retains earlier writes
39//! and the original typed cause. Every normally returning mutation invokes its
40//! explicit publication callback after unlocking, even on `Err` or an unchanged
41//! value. A panic does not publish. Publication may reenter and panic without
42//! poisoning the value. Publication means invoking the caller's callback;
43//! acceptance by an external destination remains the caller's responsibility.
44//! An in-memory handle does not register observers, compare values, spawn tasks, or persist changes.
45//! A [`SharedKeyCache`] uses its key's subscription to receive updates from a provider.
46//!
47//! Partial projections deliberately have **no last-value cache**. Reads and writes
48//! return Absent while the selected optional, case, or key is missing. They never
49//! recreate that payload. If it reappears in the same reference, the projection
50//! sees the current payload; this is data membership, not Store scope authority.
51//!
52//! # Ordering and lock boundaries
53//!
54//! A cohort access first captures its reference under the cohort mutex, releases
55//! that mutex, then tries the value mutex. A concurrent rebind after capture does
56//! not retarget the operation. Rebinding captures the target reference first and
57//! linearises at the receiving cohort's pointer swap; it never locks a value.
58//! A mutation's retained result becomes readable when its value lock is released.
59//! Serialised commits do not imply ordered publication callbacks across threads:
60//! another mutation may commit before an earlier callback reads the latest value.
61//! Capture an owned snapshot in the mutation result when exact snapshots matter.
62//!
63//! Error precedence is cohort capture, value lock, projection presence, then user
64//! mutation result. Rebinding checks target capture before receiver access. Busy
65//! and Poisoned reflect `Mutex::try_lock`; no waiting or poison recovery occurs.
66//! Failed access/absence skips both mutation and publication. Library-displaced
67//! references and returned results/errors are dropped outside library locks.
68//! Read/path/mutation callbacks and any destructors they themselves execute run
69//! under the value lock: keep them short and synchronous. Publication runs with
70//! no library lock held. Auto-traits follow stored ownership, without unsafe
71//! promotion or blanket value `Clone`, `Debug`, `Send`, or `Sync` requirements.
72
73mod cache;
74
75#[doc(inline)]
76pub use cache::{
77    SharedKey, SharedKeyCache, SharedKeyDefault, SharedKeyError, SharedKeyIdentity,
78    SharedLoadContext, SharedPublication, SharedReaderKey, SharedSubscribeContext,
79    SharedSubscriber,
80};
81
82use std::any::Any;
83use std::fmt;
84use std::marker::PhantomData;
85use std::sync::{Arc, Mutex, MutexGuard, OnceLock, TryLockError};
86
87/// Owns one value independently of any cohort that currently points to it.
88struct SharedReference<Value> {
89    /// Serialises synchronous value access without exposing its guard.
90    value: Mutex<Value>,
91    /// Keeps an optional cache subscription alive until the final owner drops this reference.
92    retained: OnceLock<Box<dyn Any + Send + Sync>>,
93}
94
95impl<Value> SharedReference<Value> {
96    /// Creates an uncached reference; cache construction may install one resource.
97    fn new(value: Value) -> Self {
98        Self {
99            value: Mutex::new(value),
100            retained: OnceLock::new(),
101        }
102    }
103}
104
105/// Distinguishes failed admission from a missing projected payload.
106#[derive(Clone, Copy, Debug, Eq, PartialEq)]
107enum AccessKind {
108    /// Another access currently owns the required mutex.
109    Busy,
110    /// A previous access unwound while holding the required mutex.
111    Poisoned,
112    /// A partial projection selected no current value.
113    Absent,
114}
115
116/// Reports unavailable synchronous access without exposing a lock guard.
117#[derive(Clone, Copy, Debug, Eq, PartialEq)]
118pub struct SharedAccessError {
119    /// The first failed step in capture, locking or projection.
120    kind: AccessKind,
121}
122
123impl SharedAccessError {
124    /// Returns whether another access currently holds the required lock.
125    #[must_use]
126    pub const fn is_busy(&self) -> bool {
127        matches!(self.kind, AccessKind::Busy)
128    }
129
130    /// Returns whether an operation found a poisoned lock for the binding, value, or reload coordinator.
131    #[must_use]
132    pub const fn is_poisoned(&self) -> bool {
133        matches!(self.kind, AccessKind::Poisoned)
134    }
135
136    /// Returns whether the selected partial projection is currently missing.
137    #[must_use]
138    pub const fn is_absent(&self) -> bool {
139        matches!(self.kind, AccessKind::Absent)
140    }
141
142    /// Shares a fixed, value-free description with cache error diagnostics.
143    const fn message(self) -> &'static str {
144        match self.kind {
145            AccessKind::Busy => "shared value access is busy",
146            AccessKind::Poisoned => "shared value access is poisoned",
147            AccessKind::Absent => "shared projection is absent",
148        }
149    }
150}
151
152impl fmt::Display for SharedAccessError {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.write_str(self.message())
155    }
156}
157
158impl std::error::Error for SharedAccessError {}
159
160/// Separates skipped mutation from a callback failure after retained writes.
161enum MutationFailure<Failure> {
162    /// Capture, locking or projection failed before mutation ran.
163    Access(SharedAccessError),
164    /// Mutation returned this cause and its publication callback returned normally.
165    Committed(Failure),
166}
167
168/// Preserves an access failure or a typed cause after retained mutation.
169pub struct SharedMutationError<Failure> {
170    /// Preserves either access classification or the caller's owned cause.
171    failure: MutationFailure<Failure>,
172}
173
174impl<Failure> SharedMutationError<Failure> {
175    /// Returns whether mutation retained its writes and the publication callback returned.
176    #[must_use]
177    pub const fn is_committed(&self) -> bool {
178        matches!(self.failure, MutationFailure::Committed(_))
179    }
180
181    /// Returns the access failure when the mutation never ran.
182    #[must_use]
183    pub const fn access_error(&self) -> Option<&SharedAccessError> {
184        match &self.failure {
185            MutationFailure::Access(error) => Some(error),
186            MutationFailure::Committed(_) => None,
187        }
188    }
189
190    /// Returns the original owned mutation cause, without requiring domain traits.
191    #[must_use]
192    pub fn into_failure(self) -> Option<Failure> {
193        match self.failure {
194            MutationFailure::Access(_) => None,
195            MutationFailure::Committed(failure) => Some(failure),
196        }
197    }
198}
199
200impl<Failure> From<SharedAccessError> for SharedMutationError<Failure> {
201    fn from(error: SharedAccessError) -> Self {
202        Self {
203            failure: MutationFailure::Access(error),
204        }
205    }
206}
207
208impl<Failure> fmt::Debug for SharedMutationError<Failure> {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.debug_struct("SharedMutationError")
211            .field("committed", &self.is_committed())
212            .field("access", &self.access_error())
213            .finish_non_exhaustive()
214    }
215}
216
217impl<Failure> fmt::Display for SharedMutationError<Failure> {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        match &self.failure {
220            MutationFailure::Access(error) => error.fmt(f),
221            MutationFailure::Committed(_) => {
222                f.write_str("shared mutation failed after retaining its writes")
223            }
224        }
225    }
226}
227
228impl<Failure: std::error::Error + 'static> std::error::Error for SharedMutationError<Failure> {
229    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
230        Some(match &self.failure {
231            MutationFailure::Access(error) => error,
232            MutationFailure::Committed(failure) => failure,
233        })
234    }
235}
236
237/// Gives multiple owners read and write access to the same value.
238///
239/// A clone shares this handle's binding: [`rebind`](Self::rebind) switches both handles to the new value.
240/// A [reader](Self::reader) or [projection](Self::project) keeps the original value alive.
241/// It sees later changes to that value, not the replacement.
242///
243/// Access never waits for another reader or writer. Overlapping access returns a
244/// [busy error](SharedAccessError::is_busy), even inside a callback on the same thread.
245/// [`update`](Self::update) changes the value in place, unlocks it, then calls the supplied publication callback.
246/// The handle itself does not notify a Store or save the value.
247///
248/// # Examples
249///
250/// ```
251/// # use rca_sharing as rca;
252/// use rca::Shared; // With rca-sharing alone, import rca_sharing::Shared.
253///
254/// let value = Shared::new(Some(1));
255/// let alias = value.clone();
256/// let reader = value.reader().unwrap();
257/// let child = value.project(Option::as_ref, Option::as_mut).unwrap();
258///
259/// value.rebind(&Shared::new(Some(10))).unwrap();
260/// child.update(|value| *value += 1, || {}).unwrap();
261/// assert_eq!(reader.read(|value| *value).unwrap(), Some(2));
262/// assert_eq!(alias.read(|value| *value).unwrap(), Some(10));
263/// ```
264pub struct Shared<Value> {
265    /// Shared rebinding slot; ordinary clones follow every successful pointer swap.
266    cohort: Arc<Mutex<SharedReader<Value>>>,
267}
268
269impl<Value> Shared<Value> {
270    /// Stores the value in a new handle with its own binding.
271    #[must_use]
272    pub fn new(value: Value) -> Self {
273        Self {
274            cohort: Arc::new(Mutex::new(SharedReader {
275                reference: Arc::new(SharedReference::new(value)),
276            })),
277        }
278    }
279
280    /// Captures the current reference as a reader, independent of later rebinding.
281    ///
282    /// # Errors
283    ///
284    /// Returns Busy or Poisoned if the binding is unavailable.
285    pub fn reader(&self) -> Result<SharedReader<Value>, SharedAccessError> {
286        Ok(try_lock(&self.cohort)?.clone())
287    }
288
289    /// Reads the currently captured value with a synchronous callback.
290    ///
291    /// # Errors
292    ///
293    /// Returns Busy or Poisoned. This method checks the binding before the value.
294    ///
295    /// # Panics
296    ///
297    /// If the read callback panics, the panic propagates and poisons the value.
298    /// If the callback rebinds this handle, the method releases its old reference before it returns.
299    /// A value or resource destructor can panic at that point.
300    pub fn read<ResultValue>(
301        &self,
302        read: impl FnOnce(&Value) -> ResultValue,
303    ) -> Result<ResultValue, SharedAccessError> {
304        let reference = self.reader()?;
305        let result = reference.read(read);
306        drop(reference);
307        result
308    }
309
310    /// Updates the value, releases its lock, then calls `publish`.
311    ///
312    /// If `update` returns normally, `publish` runs once, even for an unchanged value.
313    /// Another writer can change the value before `publish` reads it.
314    /// To keep the exact result of this update, return an owned value from `update`.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// # use rca_sharing as rca;
320    /// use rca::Shared; // With rca-sharing alone, import rca_sharing::Shared.
321    /// let value = Shared::new(1);
322    /// let previous = value.update(|value| std::mem::replace(value, 2), || {}).unwrap();
323    /// assert_eq!(previous, 1);
324    /// ```
325    ///
326    /// # Errors
327    ///
328    /// Returns Busy or Poisoned before invoking either callback.
329    ///
330    /// # Panics
331    ///
332    /// A mutation panic poisons the reference and skips publication. A publication
333    /// panic propagates after commit, without poisoning that reference. Releasing
334    /// a reference displaced by publication may also panic before returning.
335    pub fn update<ResultValue>(
336        &self,
337        update: impl FnOnce(&mut Value) -> ResultValue,
338        publish: impl FnOnce(),
339    ) -> Result<ResultValue, SharedAccessError> {
340        let reference = self.reader()?;
341        let result = update_reference(&reference, |value| Some(value), update, publish);
342        drop(reference);
343        result
344    }
345
346    /// Updates the value and calls `publish` even if `update` returns an error.
347    ///
348    /// If `update` returns `Err`, its writes remain.
349    /// As with [`Self::update`], this method releases the lock before it calls `publish`.
350    /// The returned result and typed cause are owned and cannot borrow the value.
351    ///
352    /// # Errors
353    ///
354    /// Returns an uncommitted access failure or the committed original user cause.
355    ///
356    /// # Panics
357    ///
358    /// A mutation panic poisons the reference and skips publication. A publication
359    /// panic propagates after commit, without poisoning that reference. Releasing
360    /// a reference displaced by publication may also panic before returning.
361    pub fn try_update<ResultValue, Failure>(
362        &self,
363        update: impl FnOnce(&mut Value) -> Result<ResultValue, Failure>,
364        publish: impl FnOnce(),
365    ) -> Result<ResultValue, SharedMutationError<Failure>> {
366        let reference = self.reader()?;
367        let result = match update_reference(&reference, |value| Some(value), update, publish) {
368            Ok(result) => result.map_err(|failure| SharedMutationError {
369                failure: MutationFailure::Committed(failure),
370            }),
371            Err(error) => Err(error.into()),
372        };
373        drop(reference);
374        result
375    }
376
377    /// Switches this handle and its clones to the target's current value.
378    ///
379    /// Existing readers and projections keep the original value. If the target has an independent
380    /// binding, later changes to its binding do not affect this handle.
381    /// The method releases the old reference outside the lock, so its destructor can access this handle.
382    ///
383    /// # Errors
384    ///
385    /// Checks the target binding first, then this binding. A Busy or Poisoned error leaves this binding unchanged.
386    ///
387    /// # Panics
388    ///
389    /// The old value's destructor can panic after the binding changes.
390    pub fn rebind(&self, target: &Self) -> Result<(), SharedAccessError> {
391        let replacement = target.reader()?;
392        let previous = {
393            let mut cohort = try_lock(&self.cohort)?;
394            std::mem::replace(&mut *cohort, replacement)
395        };
396        drop(previous);
397        Ok(())
398    }
399
400    /// Captures a writable partial projection without caching missing values.
401    ///
402    /// The getters must select the same logical field. Presence is evaluated on
403    /// each access, not when constructing the projection. Total fields use `Some`.
404    ///
405    /// # Errors
406    ///
407    /// Returns Busy or Poisoned if the binding is unavailable.
408    pub fn project<Child, Get, GetMut>(
409        &self,
410        get: Get,
411        get_mut: GetMut,
412    ) -> Result<SharedProjection<Value, Child, Get, GetMut>, SharedAccessError>
413    where
414        Get: for<'a> Fn(&'a Value) -> Option<&'a Child>,
415        GetMut: for<'a> Fn(&'a mut Value) -> Option<&'a mut Child>,
416    {
417        Ok(SharedProjection {
418            reader: self.reader()?.project(get),
419            get_mut,
420        })
421    }
422}
423
424impl<Value> Clone for Shared<Value> {
425    fn clone(&self) -> Self {
426        Self {
427            cohort: Arc::clone(&self.cohort),
428        }
429    }
430}
431
432impl<Value> fmt::Debug for Shared<Value> {
433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434        f.debug_struct("Shared").finish_non_exhaustive()
435    }
436}
437
438/// Gives read-only access to one shared value.
439///
440/// The reader sees writes to that value even after the original [`Shared`] handle switches to another value.
441/// Its callback receives `&Value`, never `&mut Value`. Interior mutability still works through that reference.
442pub struct SharedReader<Value> {
443    /// Keeps this exact value and any cache subscription alive across rebinding.
444    reference: Arc<SharedReference<Value>>,
445}
446
447impl<Value> SharedReader<Value> {
448    /// Reads the captured value through a non-escaping synchronous borrow.
449    ///
450    /// # Errors
451    ///
452    /// Returns Busy for overlapping access or Poisoned after a callback panic.
453    ///
454    /// # Panics
455    ///
456    /// Propagates a read callback panic and poisons the captured reference.
457    pub fn read<ResultValue>(
458        &self,
459        read: impl FnOnce(&Value) -> ResultValue,
460    ) -> Result<ResultValue, SharedAccessError> {
461        let value = try_lock(&self.reference.value)?;
462        let result = read(&value);
463        drop(value);
464        Ok(result)
465    }
466
467    /// Captures a partial read projection with no last-value cache.
468    #[must_use]
469    pub fn project<Child, Get>(&self, get: Get) -> SharedReadProjection<Value, Child, Get>
470    where
471        Get: for<'a> Fn(&'a Value) -> Option<&'a Child>,
472    {
473        SharedReadProjection {
474            root: self.clone(),
475            get,
476            marker: PhantomData,
477        }
478    }
479}
480
481impl<Value> Clone for SharedReader<Value> {
482    fn clone(&self) -> Self {
483        Self {
484            reference: Arc::clone(&self.reference),
485        }
486    }
487}
488
489impl<Value> fmt::Debug for SharedReader<Value> {
490    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491        f.debug_struct("SharedReader").finish_non_exhaustive()
492    }
493}
494
495/// Reads a partial field of a captured owned reference.
496pub struct SharedReadProjection<Root, Value, Get> {
497    /// Owns the original root, not the cohort's current replacement.
498    root: SharedReader<Root>,
499    /// Selects current membership on every read under the root's value lock.
500    get: Get,
501    /// Names the borrowed output without owning it or imposing its auto traits.
502    marker: PhantomData<fn() -> Value>,
503}
504
505impl<Root, Value, Get> SharedReadProjection<Root, Value, Get>
506where
507    Get: for<'a> Fn(&'a Root) -> Option<&'a Value>,
508{
509    /// Reads the currently present payload without retaining an absent value.
510    ///
511    /// # Errors
512    ///
513    /// Checks Busy/Poisoned before evaluating the path; missing paths return Absent.
514    ///
515    /// # Panics
516    ///
517    /// A path/read callback panic propagates and poisons the captured reference.
518    pub fn read<ResultValue>(
519        &self,
520        read: impl FnOnce(&Value) -> ResultValue,
521    ) -> Result<ResultValue, SharedAccessError> {
522        let root = try_lock(&self.root.reference.value)?;
523        let value = (self.get)(&root).ok_or(SharedAccessError {
524            kind: AccessKind::Absent,
525        })?;
526        let result = read(value);
527        drop(root);
528        Ok(result)
529    }
530}
531
532impl<Root, Value, Get: Clone> Clone for SharedReadProjection<Root, Value, Get> {
533    fn clone(&self) -> Self {
534        Self {
535            root: self.root.clone(),
536            get: self.get.clone(),
537            marker: PhantomData,
538        }
539    }
540}
541
542impl<Root, Value, Get> fmt::Debug for SharedReadProjection<Root, Value, Get> {
543    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
544        f.debug_struct("SharedReadProjection")
545            .finish_non_exhaustive()
546    }
547}
548
549/// Mutates a partial field while retaining its originally captured reference.
550pub struct SharedProjection<Root, Value, Get, GetMut> {
551    /// Provides the shared captured root and immutable selection path.
552    reader: SharedReadProjection<Root, Value, Get>,
553    /// Selects the same logical field for mutation under that root's value lock.
554    get_mut: GetMut,
555}
556
557impl<Root, Value, Get, GetMut> SharedProjection<Root, Value, Get, GetMut>
558where
559    Get: for<'a> Fn(&'a Root) -> Option<&'a Value>,
560    GetMut: for<'a> Fn(&'a mut Root) -> Option<&'a mut Value>,
561{
562    /// Reads the selected payload from the captured reference.
563    ///
564    /// # Errors
565    ///
566    /// Returns Busy, Poisoned, or Absent, in access-before-presence order.
567    ///
568    /// # Panics
569    ///
570    /// A path/read callback panic propagates and poisons the reference.
571    pub fn read<ResultValue>(
572        &self,
573        read: impl FnOnce(&Value) -> ResultValue,
574    ) -> Result<ResultValue, SharedAccessError> {
575        self.reader.read(read)
576    }
577
578    /// Returns a read-only projection onto the same value.
579    #[must_use]
580    pub fn reader(&self) -> SharedReadProjection<Root, Value, Get>
581    where
582        Get: Clone,
583    {
584        self.reader.clone()
585    }
586
587    /// Mutates a present payload and explicitly publishes after unlocking.
588    ///
589    /// This never inserts a missing payload or retargets the captured reference.
590    /// Publication runs exactly once after a normally returning mutation, even
591    /// when unchanged. The owned result cannot borrow the payload.
592    ///
593    /// # Errors
594    ///
595    /// Returns Busy, Poisoned, or Absent before invoking either callback.
596    ///
597    /// # Panics
598    ///
599    /// A path/mutation panic poisons the reference and skips publication.
600    /// A publication panic propagates after commit, without poisoning it.
601    pub fn update<ResultValue>(
602        &self,
603        update: impl FnOnce(&mut Value) -> ResultValue,
604        publish: impl FnOnce(),
605    ) -> Result<ResultValue, SharedAccessError> {
606        update_reference(&self.reader.root, &self.get_mut, update, publish)
607    }
608
609    /// Mutates a present payload and explicitly publishes after unlocking.
610    ///
611    /// This never inserts a missing payload. A user `Err` retains its partial
612    /// writes and publishes, just like [`Shared::try_update`].
613    ///
614    /// # Errors
615    ///
616    /// Returns uncommitted Busy/Poisoned/Absent or the committed original cause.
617    ///
618    /// # Panics
619    ///
620    /// A path/mutation panic poisons the reference and skips publication.
621    /// A publication panic propagates after commit, without poisoning it.
622    pub fn try_update<ResultValue, Failure>(
623        &self,
624        update: impl FnOnce(&mut Value) -> Result<ResultValue, Failure>,
625        publish: impl FnOnce(),
626    ) -> Result<ResultValue, SharedMutationError<Failure>> {
627        update_reference(&self.reader.root, &self.get_mut, update, publish)?.map_err(|failure| {
628            SharedMutationError {
629                failure: MutationFailure::Committed(failure),
630            }
631        })
632    }
633}
634
635impl<Root, Value, Get: Clone, GetMut: Clone> Clone for SharedProjection<Root, Value, Get, GetMut> {
636    fn clone(&self) -> Self {
637        Self {
638            reader: self.reader.clone(),
639            get_mut: self.get_mut.clone(),
640        }
641    }
642}
643
644impl<Root, Value, Get, GetMut> fmt::Debug for SharedProjection<Root, Value, Get, GetMut> {
645    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
646        f.debug_struct("SharedProjection").finish_non_exhaustive()
647    }
648}
649
650/// Classifies non-blocking access without waiting or recovering poisoned state.
651fn try_lock<Value>(mutex: &Mutex<Value>) -> Result<MutexGuard<'_, Value>, SharedAccessError> {
652    mutex.try_lock().map_err(|error| SharedAccessError {
653        kind: match error {
654            TryLockError::WouldBlock => AccessKind::Busy,
655            TryLockError::Poisoned(_) => AccessKind::Poisoned,
656        },
657    })
658}
659
660/// Retains the result locally through unlocked publication, including its panic path.
661///
662/// Failed access skips both callbacks. A normal mutation publishes even when its
663/// result is a user error; mutation panic unlocks without publishing.
664fn update_reference<Root, Value, ResultValue>(
665    reference: &SharedReader<Root>,
666    get_mut: impl for<'a> FnOnce(&'a mut Root) -> Option<&'a mut Value>,
667    update: impl FnOnce(&mut Value) -> ResultValue,
668    publish: impl FnOnce(),
669) -> Result<ResultValue, SharedAccessError> {
670    let result = {
671        let mut root = try_lock(&reference.reference.value)?;
672        let value = get_mut(&mut root).ok_or(SharedAccessError {
673            kind: AccessKind::Absent,
674        })?;
675        update(value)
676    };
677    publish();
678    Ok(result)
679}
680
681#[cfg(test)]
682mod update_tests {
683    use std::cell::Cell;
684
685    use super::Shared;
686
687    // Private lock fixtures make cohort contention and poison deterministic.
688    #[test]
689    fn cohort_capture_errors_preserve_rebind_ownership_and_precedence() {
690        let shared = Shared::new(String::from("original"));
691        let target = Shared::new(String::from("target"));
692        let original = shared.reader().unwrap();
693        let destination = target.reader().unwrap();
694        let cohort = shared.cohort.lock().unwrap();
695        assert!(shared.read(|_| panic!("busy read")).unwrap_err().is_busy());
696        assert!(
697            shared
698                .project(|value| Some(value), |value| Some(value))
699                .unwrap_err()
700                .is_busy()
701        );
702        assert!(shared.rebind(&target).unwrap_err().is_busy());
703        assert!(target.rebind(&shared).unwrap_err().is_busy());
704        drop(cohort);
705        assert!(shared.read(|value| value == "original").unwrap());
706        assert!(original.read(|value| value == "original").unwrap());
707        assert!(destination.read(|value| value == "target").unwrap());
708        shared.rebind(&target).unwrap();
709        assert!(shared.read(|value| value == "target").unwrap());
710
711        assert!(
712            std::panic::catch_unwind(|| {
713                let _cohort = target.cohort.lock().unwrap();
714                panic!("interrupted target capture");
715            })
716            .is_err()
717        );
718        let cohort = shared.cohort.lock().unwrap();
719        // Target poison wins over receiver contention; neither binding changes.
720        assert!(shared.rebind(&target).unwrap_err().is_poisoned());
721        drop(cohort);
722        assert!(target.rebind(&shared).unwrap_err().is_poisoned());
723        assert!(
724            target
725                .read(|_| panic!("poisoned read"))
726                .unwrap_err()
727                .is_poisoned()
728        );
729        assert!(
730            target
731                .project(|value| Some(value), |value| Some(value))
732                .unwrap_err()
733                .is_poisoned()
734        );
735        assert!(original.read(|value| value == "original").unwrap());
736        assert!(destination.read(|value| value == "target").unwrap());
737        assert!(shared.read(|value| value == "target").unwrap());
738        shared
739            .rebind(&Shared::new(String::from("replacement")))
740            .unwrap();
741        assert!(shared.read(|value| value == "replacement").unwrap());
742        assert!(destination.read(|value| value == "target").unwrap());
743    }
744
745    #[test]
746    fn cohort_busy_and_poisoned_skip_both_callbacks() {
747        let shared = Shared::new(0);
748        let reader = shared.reader().unwrap();
749        let mutations = Cell::new(0);
750        let publications = Cell::new(0);
751        let update = |value: &mut i32| {
752            mutations.set(mutations.get() + 1);
753            *value += 1;
754            Ok::<_, ()>(*value)
755        };
756        let publish = || publications.set(publications.get() + 1);
757        let cohort = shared.cohort.lock().unwrap();
758        assert!(
759            shared
760                .update(|_| panic!("busy mutation"), || panic!("busy publication"))
761                .unwrap_err()
762                .is_busy()
763        );
764        let error = shared.try_update(update, publish).unwrap_err();
765        assert!(!error.is_committed());
766        assert!(error.access_error().unwrap().is_busy());
767        assert_eq!(error.into_failure(), None);
768        assert_eq!((mutations.get(), publications.get()), (0, 0));
769        assert_eq!(reader.read(|value| *value).unwrap(), 0);
770        drop(cohort);
771        let panic = std::panic::catch_unwind(|| {
772            let _cohort = shared.cohort.lock().unwrap();
773            panic!("cohort");
774        });
775        panic.unwrap_err();
776        assert!(
777            shared
778                .update(
779                    |_| panic!("poisoned mutation"),
780                    || panic!("poisoned publication"),
781                )
782                .unwrap_err()
783                .is_poisoned()
784        );
785        let error = shared.try_update(update, publish).unwrap_err();
786        assert!(!error.is_committed());
787        assert!(error.access_error().unwrap().is_poisoned());
788        assert_eq!(error.into_failure(), None);
789        assert_eq!((mutations.get(), publications.get()), (0, 0));
790        assert_eq!(reader.read(|value| *value).unwrap(), 0);
791
792        let healthy = Shared::new(7);
793        assert_eq!(healthy.try_update(update, publish).unwrap(), 8);
794        assert_eq!((mutations.get(), publications.get()), (1, 1));
795        assert_eq!(healthy.read(|value| *value).unwrap(), 8);
796    }
797}