rca-sharing 0.1.0

Share values and read-only projections between Rust components without a Store or runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
#![deny(rustdoc::broken_intra_doc_links)]
#![forbid(unsafe_code)]

//! Shares values between owners without a Store or an async runtime.
//!
//! Use [`Shared`] when several owners need to update one value. Give a
//! [`SharedReader`] to callers that only need to read it. For independent
//! callers that open the same resource by key, use [`SharedKeyCache`].
//! Applications that already use RCA can import these types from `rca`.
//!
//! # Examples
//!
//! ```
//! use rca_sharing::{Shared, SharedAccessError};
//!
//! let count = Shared::new(0);
//! let display = count.reader()?;
//! count.update(|value| *value += 1, || {})?;
//! assert_eq!(display.read(|value| *value)?, 1);
//! # Ok::<(), SharedAccessError>(())
//! ```
//!
//! # Access and publication
//!
//! [`Shared`] and its clones share one binding. Readers and projections keep
//! the value that the binding selected at the time of capture.
//! Independent bindings can refer to the same value after [`Shared::rebind`].
//! Later changes to either binding do not affect the other. These handles own
//! data, not Store membership or output authority. Retaining them cannot revive a retired scope.
//!
//! Access through a shared handle or projection is synchronous and non-blocking.
//! No mutex guard or borrow of the value can escape an access callback. Overlapping access (including synchronous reentry)
//! returns Busy; a panicking access callback poisons that value reference.
//! Readers with interior-mutable values retain the capabilities inherent in `&T`;
//! a reader grants no `&mut T` and cannot rebind a writer. A cache can replace an
//! individual reader through [`SharedKeyCache::load_reader`].
//!
//! Mutation callbacks operate in place: returning `Err` retains earlier writes
//! and the original typed cause. Every normally returning mutation invokes its
//! explicit publication callback after unlocking, even on `Err` or an unchanged
//! value. A panic does not publish. Publication may reenter and panic without
//! poisoning the value. Publication means invoking the caller's callback;
//! acceptance by an external destination remains the caller's responsibility.
//! An in-memory handle does not register observers, compare values, spawn tasks, or persist changes.
//! A [`SharedKeyCache`] uses its key's subscription to receive updates from a provider.
//!
//! Partial projections deliberately have **no last-value cache**. Reads and writes
//! return Absent while the selected optional, case, or key is missing. They never
//! recreate that payload. If it reappears in the same reference, the projection
//! sees the current payload; this is data membership, not Store scope authority.
//!
//! # Ordering and lock boundaries
//!
//! A cohort access first captures its reference under the cohort mutex, releases
//! that mutex, then tries the value mutex. A concurrent rebind after capture does
//! not retarget the operation. Rebinding captures the target reference first and
//! linearises at the receiving cohort's pointer swap; it never locks a value.
//! A mutation's retained result becomes readable when its value lock is released.
//! Serialised commits do not imply ordered publication callbacks across threads:
//! another mutation may commit before an earlier callback reads the latest value.
//! Capture an owned snapshot in the mutation result when exact snapshots matter.
//!
//! Error precedence is cohort capture, value lock, projection presence, then user
//! mutation result. Rebinding checks target capture before receiver access. Busy
//! and Poisoned reflect `Mutex::try_lock`; no waiting or poison recovery occurs.
//! Failed access/absence skips both mutation and publication. Library-displaced
//! references and returned results/errors are dropped outside library locks.
//! Read/path/mutation callbacks and any destructors they themselves execute run
//! under the value lock: keep them short and synchronous. Publication runs with
//! no library lock held. Auto-traits follow stored ownership, without unsafe
//! promotion or blanket value `Clone`, `Debug`, `Send`, or `Sync` requirements.

mod cache;

#[doc(inline)]
pub use cache::{
    SharedKey, SharedKeyCache, SharedKeyDefault, SharedKeyError, SharedKeyIdentity,
    SharedLoadContext, SharedPublication, SharedReaderKey, SharedSubscribeContext,
    SharedSubscriber,
};

use std::any::Any;
use std::fmt;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, TryLockError};

/// Owns one value independently of any cohort that currently points to it.
struct SharedReference<Value> {
    /// Serialises synchronous value access without exposing its guard.
    value: Mutex<Value>,
    /// Keeps an optional cache subscription alive until the final owner drops this reference.
    retained: OnceLock<Box<dyn Any + Send + Sync>>,
}

impl<Value> SharedReference<Value> {
    /// Creates an uncached reference; cache construction may install one resource.
    fn new(value: Value) -> Self {
        Self {
            value: Mutex::new(value),
            retained: OnceLock::new(),
        }
    }
}

/// Distinguishes failed admission from a missing projected payload.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AccessKind {
    /// Another access currently owns the required mutex.
    Busy,
    /// A previous access unwound while holding the required mutex.
    Poisoned,
    /// A partial projection selected no current value.
    Absent,
}

/// Reports unavailable synchronous access without exposing a lock guard.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SharedAccessError {
    /// The first failed step in capture, locking or projection.
    kind: AccessKind,
}

impl SharedAccessError {
    /// Returns whether another access currently holds the required lock.
    #[must_use]
    pub const fn is_busy(&self) -> bool {
        matches!(self.kind, AccessKind::Busy)
    }

    /// Returns whether an operation found a poisoned lock for the binding, value, or reload coordinator.
    #[must_use]
    pub const fn is_poisoned(&self) -> bool {
        matches!(self.kind, AccessKind::Poisoned)
    }

    /// Returns whether the selected partial projection is currently missing.
    #[must_use]
    pub const fn is_absent(&self) -> bool {
        matches!(self.kind, AccessKind::Absent)
    }

    /// Shares a fixed, value-free description with cache error diagnostics.
    const fn message(self) -> &'static str {
        match self.kind {
            AccessKind::Busy => "shared value access is busy",
            AccessKind::Poisoned => "shared value access is poisoned",
            AccessKind::Absent => "shared projection is absent",
        }
    }
}

impl fmt::Display for SharedAccessError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

impl std::error::Error for SharedAccessError {}

/// Separates skipped mutation from a callback failure after retained writes.
enum MutationFailure<Failure> {
    /// Capture, locking or projection failed before mutation ran.
    Access(SharedAccessError),
    /// Mutation returned this cause and its publication callback returned normally.
    Committed(Failure),
}

/// Preserves an access failure or a typed cause after retained mutation.
pub struct SharedMutationError<Failure> {
    /// Preserves either access classification or the caller's owned cause.
    failure: MutationFailure<Failure>,
}

impl<Failure> SharedMutationError<Failure> {
    /// Returns whether mutation retained its writes and the publication callback returned.
    #[must_use]
    pub const fn is_committed(&self) -> bool {
        matches!(self.failure, MutationFailure::Committed(_))
    }

    /// Returns the access failure when the mutation never ran.
    #[must_use]
    pub const fn access_error(&self) -> Option<&SharedAccessError> {
        match &self.failure {
            MutationFailure::Access(error) => Some(error),
            MutationFailure::Committed(_) => None,
        }
    }

    /// Returns the original owned mutation cause, without requiring domain traits.
    #[must_use]
    pub fn into_failure(self) -> Option<Failure> {
        match self.failure {
            MutationFailure::Access(_) => None,
            MutationFailure::Committed(failure) => Some(failure),
        }
    }
}

impl<Failure> From<SharedAccessError> for SharedMutationError<Failure> {
    fn from(error: SharedAccessError) -> Self {
        Self {
            failure: MutationFailure::Access(error),
        }
    }
}

impl<Failure> fmt::Debug for SharedMutationError<Failure> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedMutationError")
            .field("committed", &self.is_committed())
            .field("access", &self.access_error())
            .finish_non_exhaustive()
    }
}

impl<Failure> fmt::Display for SharedMutationError<Failure> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.failure {
            MutationFailure::Access(error) => error.fmt(f),
            MutationFailure::Committed(_) => {
                f.write_str("shared mutation failed after retaining its writes")
            }
        }
    }
}

impl<Failure: std::error::Error + 'static> std::error::Error for SharedMutationError<Failure> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(match &self.failure {
            MutationFailure::Access(error) => error,
            MutationFailure::Committed(failure) => failure,
        })
    }
}

/// Gives multiple owners read and write access to the same value.
///
/// A clone shares this handle's binding: [`rebind`](Self::rebind) switches both handles to the new value.
/// A [reader](Self::reader) or [projection](Self::project) keeps the original value alive.
/// It sees later changes to that value, not the replacement.
///
/// Access never waits for another reader or writer. Overlapping access returns a
/// [busy error](SharedAccessError::is_busy), even inside a callback on the same thread.
/// [`update`](Self::update) changes the value in place, unlocks it, then calls the supplied publication callback.
/// The handle itself does not notify a Store or save the value.
///
/// # Examples
///
/// ```
/// # use rca_sharing as rca;
/// use rca::Shared; // With rca-sharing alone, import rca_sharing::Shared.
///
/// let value = Shared::new(Some(1));
/// let alias = value.clone();
/// let reader = value.reader().unwrap();
/// let child = value.project(Option::as_ref, Option::as_mut).unwrap();
///
/// value.rebind(&Shared::new(Some(10))).unwrap();
/// child.update(|value| *value += 1, || {}).unwrap();
/// assert_eq!(reader.read(|value| *value).unwrap(), Some(2));
/// assert_eq!(alias.read(|value| *value).unwrap(), Some(10));
/// ```
pub struct Shared<Value> {
    /// Shared rebinding slot; ordinary clones follow every successful pointer swap.
    cohort: Arc<Mutex<SharedReader<Value>>>,
}

impl<Value> Shared<Value> {
    /// Stores the value in a new handle with its own binding.
    #[must_use]
    pub fn new(value: Value) -> Self {
        Self {
            cohort: Arc::new(Mutex::new(SharedReader {
                reference: Arc::new(SharedReference::new(value)),
            })),
        }
    }

    /// Captures the current reference as a reader, independent of later rebinding.
    ///
    /// # Errors
    ///
    /// Returns Busy or Poisoned if the binding is unavailable.
    pub fn reader(&self) -> Result<SharedReader<Value>, SharedAccessError> {
        Ok(try_lock(&self.cohort)?.clone())
    }

    /// Reads the currently captured value with a synchronous callback.
    ///
    /// # Errors
    ///
    /// Returns Busy or Poisoned. This method checks the binding before the value.
    ///
    /// # Panics
    ///
    /// If the read callback panics, the panic propagates and poisons the value.
    /// If the callback rebinds this handle, the method releases its old reference before it returns.
    /// A value or resource destructor can panic at that point.
    pub fn read<ResultValue>(
        &self,
        read: impl FnOnce(&Value) -> ResultValue,
    ) -> Result<ResultValue, SharedAccessError> {
        let reference = self.reader()?;
        let result = reference.read(read);
        drop(reference);
        result
    }

    /// Updates the value, releases its lock, then calls `publish`.
    ///
    /// If `update` returns normally, `publish` runs once, even for an unchanged value.
    /// Another writer can change the value before `publish` reads it.
    /// To keep the exact result of this update, return an owned value from `update`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use rca_sharing as rca;
    /// use rca::Shared; // With rca-sharing alone, import rca_sharing::Shared.
    /// let value = Shared::new(1);
    /// let previous = value.update(|value| std::mem::replace(value, 2), || {}).unwrap();
    /// assert_eq!(previous, 1);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns Busy or Poisoned before invoking either callback.
    ///
    /// # Panics
    ///
    /// A mutation panic poisons the reference and skips publication. A publication
    /// panic propagates after commit, without poisoning that reference. Releasing
    /// a reference displaced by publication may also panic before returning.
    pub fn update<ResultValue>(
        &self,
        update: impl FnOnce(&mut Value) -> ResultValue,
        publish: impl FnOnce(),
    ) -> Result<ResultValue, SharedAccessError> {
        let reference = self.reader()?;
        let result = update_reference(&reference, |value| Some(value), update, publish);
        drop(reference);
        result
    }

    /// Updates the value and calls `publish` even if `update` returns an error.
    ///
    /// If `update` returns `Err`, its writes remain.
    /// As with [`Self::update`], this method releases the lock before it calls `publish`.
    /// The returned result and typed cause are owned and cannot borrow the value.
    ///
    /// # Errors
    ///
    /// Returns an uncommitted access failure or the committed original user cause.
    ///
    /// # Panics
    ///
    /// A mutation panic poisons the reference and skips publication. A publication
    /// panic propagates after commit, without poisoning that reference. Releasing
    /// a reference displaced by publication may also panic before returning.
    pub fn try_update<ResultValue, Failure>(
        &self,
        update: impl FnOnce(&mut Value) -> Result<ResultValue, Failure>,
        publish: impl FnOnce(),
    ) -> Result<ResultValue, SharedMutationError<Failure>> {
        let reference = self.reader()?;
        let result = match update_reference(&reference, |value| Some(value), update, publish) {
            Ok(result) => result.map_err(|failure| SharedMutationError {
                failure: MutationFailure::Committed(failure),
            }),
            Err(error) => Err(error.into()),
        };
        drop(reference);
        result
    }

    /// Switches this handle and its clones to the target's current value.
    ///
    /// Existing readers and projections keep the original value. If the target has an independent
    /// binding, later changes to its binding do not affect this handle.
    /// The method releases the old reference outside the lock, so its destructor can access this handle.
    ///
    /// # Errors
    ///
    /// Checks the target binding first, then this binding. A Busy or Poisoned error leaves this binding unchanged.
    ///
    /// # Panics
    ///
    /// The old value's destructor can panic after the binding changes.
    pub fn rebind(&self, target: &Self) -> Result<(), SharedAccessError> {
        let replacement = target.reader()?;
        let previous = {
            let mut cohort = try_lock(&self.cohort)?;
            std::mem::replace(&mut *cohort, replacement)
        };
        drop(previous);
        Ok(())
    }

    /// Captures a writable partial projection without caching missing values.
    ///
    /// The getters must select the same logical field. Presence is evaluated on
    /// each access, not when constructing the projection. Total fields use `Some`.
    ///
    /// # Errors
    ///
    /// Returns Busy or Poisoned if the binding is unavailable.
    pub fn project<Child, Get, GetMut>(
        &self,
        get: Get,
        get_mut: GetMut,
    ) -> Result<SharedProjection<Value, Child, Get, GetMut>, SharedAccessError>
    where
        Get: for<'a> Fn(&'a Value) -> Option<&'a Child>,
        GetMut: for<'a> Fn(&'a mut Value) -> Option<&'a mut Child>,
    {
        Ok(SharedProjection {
            reader: self.reader()?.project(get),
            get_mut,
        })
    }
}

impl<Value> Clone for Shared<Value> {
    fn clone(&self) -> Self {
        Self {
            cohort: Arc::clone(&self.cohort),
        }
    }
}

impl<Value> fmt::Debug for Shared<Value> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Shared").finish_non_exhaustive()
    }
}

/// Gives read-only access to one shared value.
///
/// The reader sees writes to that value even after the original [`Shared`] handle switches to another value.
/// Its callback receives `&Value`, never `&mut Value`. Interior mutability still works through that reference.
pub struct SharedReader<Value> {
    /// Keeps this exact value and any cache subscription alive across rebinding.
    reference: Arc<SharedReference<Value>>,
}

impl<Value> SharedReader<Value> {
    /// Reads the captured value through a non-escaping synchronous borrow.
    ///
    /// # Errors
    ///
    /// Returns Busy for overlapping access or Poisoned after a callback panic.
    ///
    /// # Panics
    ///
    /// Propagates a read callback panic and poisons the captured reference.
    pub fn read<ResultValue>(
        &self,
        read: impl FnOnce(&Value) -> ResultValue,
    ) -> Result<ResultValue, SharedAccessError> {
        let value = try_lock(&self.reference.value)?;
        let result = read(&value);
        drop(value);
        Ok(result)
    }

    /// Captures a partial read projection with no last-value cache.
    #[must_use]
    pub fn project<Child, Get>(&self, get: Get) -> SharedReadProjection<Value, Child, Get>
    where
        Get: for<'a> Fn(&'a Value) -> Option<&'a Child>,
    {
        SharedReadProjection {
            root: self.clone(),
            get,
            marker: PhantomData,
        }
    }
}

impl<Value> Clone for SharedReader<Value> {
    fn clone(&self) -> Self {
        Self {
            reference: Arc::clone(&self.reference),
        }
    }
}

impl<Value> fmt::Debug for SharedReader<Value> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedReader").finish_non_exhaustive()
    }
}

/// Reads a partial field of a captured owned reference.
pub struct SharedReadProjection<Root, Value, Get> {
    /// Owns the original root, not the cohort's current replacement.
    root: SharedReader<Root>,
    /// Selects current membership on every read under the root's value lock.
    get: Get,
    /// Names the borrowed output without owning it or imposing its auto traits.
    marker: PhantomData<fn() -> Value>,
}

impl<Root, Value, Get> SharedReadProjection<Root, Value, Get>
where
    Get: for<'a> Fn(&'a Root) -> Option<&'a Value>,
{
    /// Reads the currently present payload without retaining an absent value.
    ///
    /// # Errors
    ///
    /// Checks Busy/Poisoned before evaluating the path; missing paths return Absent.
    ///
    /// # Panics
    ///
    /// A path/read callback panic propagates and poisons the captured reference.
    pub fn read<ResultValue>(
        &self,
        read: impl FnOnce(&Value) -> ResultValue,
    ) -> Result<ResultValue, SharedAccessError> {
        let root = try_lock(&self.root.reference.value)?;
        let value = (self.get)(&root).ok_or(SharedAccessError {
            kind: AccessKind::Absent,
        })?;
        let result = read(value);
        drop(root);
        Ok(result)
    }
}

impl<Root, Value, Get: Clone> Clone for SharedReadProjection<Root, Value, Get> {
    fn clone(&self) -> Self {
        Self {
            root: self.root.clone(),
            get: self.get.clone(),
            marker: PhantomData,
        }
    }
}

impl<Root, Value, Get> fmt::Debug for SharedReadProjection<Root, Value, Get> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedReadProjection")
            .finish_non_exhaustive()
    }
}

/// Mutates a partial field while retaining its originally captured reference.
pub struct SharedProjection<Root, Value, Get, GetMut> {
    /// Provides the shared captured root and immutable selection path.
    reader: SharedReadProjection<Root, Value, Get>,
    /// Selects the same logical field for mutation under that root's value lock.
    get_mut: GetMut,
}

impl<Root, Value, Get, GetMut> SharedProjection<Root, Value, Get, GetMut>
where
    Get: for<'a> Fn(&'a Root) -> Option<&'a Value>,
    GetMut: for<'a> Fn(&'a mut Root) -> Option<&'a mut Value>,
{
    /// Reads the selected payload from the captured reference.
    ///
    /// # Errors
    ///
    /// Returns Busy, Poisoned, or Absent, in access-before-presence order.
    ///
    /// # Panics
    ///
    /// A path/read callback panic propagates and poisons the reference.
    pub fn read<ResultValue>(
        &self,
        read: impl FnOnce(&Value) -> ResultValue,
    ) -> Result<ResultValue, SharedAccessError> {
        self.reader.read(read)
    }

    /// Returns a read-only projection onto the same value.
    #[must_use]
    pub fn reader(&self) -> SharedReadProjection<Root, Value, Get>
    where
        Get: Clone,
    {
        self.reader.clone()
    }

    /// Mutates a present payload and explicitly publishes after unlocking.
    ///
    /// This never inserts a missing payload or retargets the captured reference.
    /// Publication runs exactly once after a normally returning mutation, even
    /// when unchanged. The owned result cannot borrow the payload.
    ///
    /// # Errors
    ///
    /// Returns Busy, Poisoned, or Absent before invoking either callback.
    ///
    /// # Panics
    ///
    /// A path/mutation panic poisons the reference and skips publication.
    /// A publication panic propagates after commit, without poisoning it.
    pub fn update<ResultValue>(
        &self,
        update: impl FnOnce(&mut Value) -> ResultValue,
        publish: impl FnOnce(),
    ) -> Result<ResultValue, SharedAccessError> {
        update_reference(&self.reader.root, &self.get_mut, update, publish)
    }

    /// Mutates a present payload and explicitly publishes after unlocking.
    ///
    /// This never inserts a missing payload. A user `Err` retains its partial
    /// writes and publishes, just like [`Shared::try_update`].
    ///
    /// # Errors
    ///
    /// Returns uncommitted Busy/Poisoned/Absent or the committed original cause.
    ///
    /// # Panics
    ///
    /// A path/mutation panic poisons the reference and skips publication.
    /// A publication panic propagates after commit, without poisoning it.
    pub fn try_update<ResultValue, Failure>(
        &self,
        update: impl FnOnce(&mut Value) -> Result<ResultValue, Failure>,
        publish: impl FnOnce(),
    ) -> Result<ResultValue, SharedMutationError<Failure>> {
        update_reference(&self.reader.root, &self.get_mut, update, publish)?.map_err(|failure| {
            SharedMutationError {
                failure: MutationFailure::Committed(failure),
            }
        })
    }
}

impl<Root, Value, Get: Clone, GetMut: Clone> Clone for SharedProjection<Root, Value, Get, GetMut> {
    fn clone(&self) -> Self {
        Self {
            reader: self.reader.clone(),
            get_mut: self.get_mut.clone(),
        }
    }
}

impl<Root, Value, Get, GetMut> fmt::Debug for SharedProjection<Root, Value, Get, GetMut> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedProjection").finish_non_exhaustive()
    }
}

/// Classifies non-blocking access without waiting or recovering poisoned state.
fn try_lock<Value>(mutex: &Mutex<Value>) -> Result<MutexGuard<'_, Value>, SharedAccessError> {
    mutex.try_lock().map_err(|error| SharedAccessError {
        kind: match error {
            TryLockError::WouldBlock => AccessKind::Busy,
            TryLockError::Poisoned(_) => AccessKind::Poisoned,
        },
    })
}

/// Retains the result locally through unlocked publication, including its panic path.
///
/// Failed access skips both callbacks. A normal mutation publishes even when its
/// result is a user error; mutation panic unlocks without publishing.
fn update_reference<Root, Value, ResultValue>(
    reference: &SharedReader<Root>,
    get_mut: impl for<'a> FnOnce(&'a mut Root) -> Option<&'a mut Value>,
    update: impl FnOnce(&mut Value) -> ResultValue,
    publish: impl FnOnce(),
) -> Result<ResultValue, SharedAccessError> {
    let result = {
        let mut root = try_lock(&reference.reference.value)?;
        let value = get_mut(&mut root).ok_or(SharedAccessError {
            kind: AccessKind::Absent,
        })?;
        update(value)
    };
    publish();
    Ok(result)
}

#[cfg(test)]
mod update_tests {
    use std::cell::Cell;

    use super::Shared;

    // Private lock fixtures make cohort contention and poison deterministic.
    #[test]
    fn cohort_capture_errors_preserve_rebind_ownership_and_precedence() {
        let shared = Shared::new(String::from("original"));
        let target = Shared::new(String::from("target"));
        let original = shared.reader().unwrap();
        let destination = target.reader().unwrap();
        let cohort = shared.cohort.lock().unwrap();
        assert!(shared.read(|_| panic!("busy read")).unwrap_err().is_busy());
        assert!(
            shared
                .project(|value| Some(value), |value| Some(value))
                .unwrap_err()
                .is_busy()
        );
        assert!(shared.rebind(&target).unwrap_err().is_busy());
        assert!(target.rebind(&shared).unwrap_err().is_busy());
        drop(cohort);
        assert!(shared.read(|value| value == "original").unwrap());
        assert!(original.read(|value| value == "original").unwrap());
        assert!(destination.read(|value| value == "target").unwrap());
        shared.rebind(&target).unwrap();
        assert!(shared.read(|value| value == "target").unwrap());

        assert!(
            std::panic::catch_unwind(|| {
                let _cohort = target.cohort.lock().unwrap();
                panic!("interrupted target capture");
            })
            .is_err()
        );
        let cohort = shared.cohort.lock().unwrap();
        // Target poison wins over receiver contention; neither binding changes.
        assert!(shared.rebind(&target).unwrap_err().is_poisoned());
        drop(cohort);
        assert!(target.rebind(&shared).unwrap_err().is_poisoned());
        assert!(
            target
                .read(|_| panic!("poisoned read"))
                .unwrap_err()
                .is_poisoned()
        );
        assert!(
            target
                .project(|value| Some(value), |value| Some(value))
                .unwrap_err()
                .is_poisoned()
        );
        assert!(original.read(|value| value == "original").unwrap());
        assert!(destination.read(|value| value == "target").unwrap());
        assert!(shared.read(|value| value == "target").unwrap());
        shared
            .rebind(&Shared::new(String::from("replacement")))
            .unwrap();
        assert!(shared.read(|value| value == "replacement").unwrap());
        assert!(destination.read(|value| value == "target").unwrap());
    }

    #[test]
    fn cohort_busy_and_poisoned_skip_both_callbacks() {
        let shared = Shared::new(0);
        let reader = shared.reader().unwrap();
        let mutations = Cell::new(0);
        let publications = Cell::new(0);
        let update = |value: &mut i32| {
            mutations.set(mutations.get() + 1);
            *value += 1;
            Ok::<_, ()>(*value)
        };
        let publish = || publications.set(publications.get() + 1);
        let cohort = shared.cohort.lock().unwrap();
        assert!(
            shared
                .update(|_| panic!("busy mutation"), || panic!("busy publication"))
                .unwrap_err()
                .is_busy()
        );
        let error = shared.try_update(update, publish).unwrap_err();
        assert!(!error.is_committed());
        assert!(error.access_error().unwrap().is_busy());
        assert_eq!(error.into_failure(), None);
        assert_eq!((mutations.get(), publications.get()), (0, 0));
        assert_eq!(reader.read(|value| *value).unwrap(), 0);
        drop(cohort);
        let panic = std::panic::catch_unwind(|| {
            let _cohort = shared.cohort.lock().unwrap();
            panic!("cohort");
        });
        panic.unwrap_err();
        assert!(
            shared
                .update(
                    |_| panic!("poisoned mutation"),
                    || panic!("poisoned publication"),
                )
                .unwrap_err()
                .is_poisoned()
        );
        let error = shared.try_update(update, publish).unwrap_err();
        assert!(!error.is_committed());
        assert!(error.access_error().unwrap().is_poisoned());
        assert_eq!(error.into_failure(), None);
        assert_eq!((mutations.get(), publications.get()), (0, 0));
        assert_eq!(reader.read(|value| *value).unwrap(), 0);

        let healthy = Shared::new(7);
        assert_eq!(healthy.try_update(update, publish).unwrap(), 8);
        assert_eq!((mutations.get(), publications.get()), (1, 1));
        assert_eq!(healthy.read(|value| *value).unwrap(), 8);
    }
}