Skip to main content

matter_kit/
sync.rs

1//! Shared state for a controller that runs on more than one thread.
2//!
3//! The crate is single-threaded by construction, and that splits it in two. A *device* is one
4//! event loop, one `RefCell` per piece of state, and no atomics an MCU would have to pay for.
5//! A *controller* on a multi-threaded runtime is none of those things: it drives many nodes
6//! from a work-stealing pool, and a future that is `!Send` cannot be spawned there at all.
7//!
8//! [`Shared`] is the seam. Without the `sync-mutex` feature it is a [`core::cell::RefCell`] and the
9//! controller stays single-threaded and cheap; with it, an [`RwLock`](std::sync::RwLock), and the
10//! state becomes `Send + Sync` so a run future holding it can be spawned across threads.
11//!
12//! ```rust,ignore
13//! use matter_kit::sync::Shared;
14//!
15//! let fabrics = Shared::new(FabricTable::new());
16//! // The same two lines compile either way.
17//! let count = fabrics.borrow().len();
18//! fabrics.borrow_mut().remove(index);
19//! ```
20//!
21//! # One rule, and it is not optional
22//!
23//! **Never hold a borrow across an `await`.**
24//!
25//! That is the whole of it, in both builds, because [`RwLock`](std::sync::RwLock) is the shape
26//! [`core::cell::RefCell`] already has: many shared borrows, or one exclusive borrow. A
27//! [`Mutex`](std::sync::Mutex) would have one kind of lock, so two `borrow()`s would compile and
28//! work without the feature and deadlock with it — and a seam whose two builds disagree about
29//! what is legal is a seam that tests one of them.
30//!
31//! What differs between the builds is only what happens when the rule is broken: a `RefCell`
32//! panics at the mistake, a lock waits somewhere else. Which is why the single-threaded build is
33//! the one to develop against.
34//!
35//! The crate's own device clusters deliberately keep their [`core::cell::RefCell`]s: a device is
36//! single-threaded by construction and converting them would trade a panic that points at the
37//! mistake for a deadlock that does not.
38
39#[cfg(not(feature = "sync-mutex"))]
40use core::cell::RefCell;
41
42/// State shared between the parts of a controller.
43///
44/// A [`core::cell::RefCell`] by default; an [`RwLock`](std::sync::RwLock) under `sync-mutex`.
45/// Both admit many readers or one writer, so code written against one is correct on the other.
46#[cfg(not(feature = "sync-mutex"))]
47#[derive(Debug, Default)]
48pub struct Shared<T>(RefCell<T>);
49
50/// State shared between the parts of a controller, across threads.
51#[cfg(feature = "sync-mutex")]
52#[derive(Debug, Default)]
53pub struct Shared<T>(std::sync::RwLock<T>);
54
55/// A shared borrow of the contents.
56#[cfg(not(feature = "sync-mutex"))]
57pub type Ref<'a, T> = core::cell::Ref<'a, T>;
58
59/// A shared borrow of the contents.
60///
61/// A read guard under `sync-mutex`, so several may be live at once — the same rule
62/// [`core::cell::Ref`] follows.
63#[cfg(feature = "sync-mutex")]
64pub type Ref<'a, T> = std::sync::RwLockReadGuard<'a, T>;
65
66/// An exclusive borrow of the contents.
67#[cfg(not(feature = "sync-mutex"))]
68pub type RefMut<'a, T> = core::cell::RefMut<'a, T>;
69
70/// An exclusive borrow of the contents.
71#[cfg(feature = "sync-mutex")]
72pub type RefMut<'a, T> = std::sync::RwLockWriteGuard<'a, T>;
73
74impl<T> Shared<T> {
75    /// Wraps `value`.
76    #[must_use]
77    pub const fn new(value: T) -> Self {
78        #[cfg(not(feature = "sync-mutex"))]
79        {
80            Self(RefCell::new(value))
81        }
82        #[cfg(feature = "sync-mutex")]
83        {
84            Self(std::sync::RwLock::new(value))
85        }
86    }
87
88    /// Borrows the contents.
89    ///
90    /// # Panics
91    ///
92    /// Without `sync-mutex`, if a mutable borrow is live — [`core::cell::RefCell`]'s rule. With
93    /// it, never: a poisoned lock is recovered from rather than propagated, because a controller
94    /// that stopped answering every node because one task panicked would turn one fault into an
95    /// outage.
96    pub fn borrow(&self) -> Ref<'_, T> {
97        #[cfg(not(feature = "sync-mutex"))]
98        {
99            self.0.borrow()
100        }
101        #[cfg(feature = "sync-mutex")]
102        {
103            self.0
104                .read()
105                .unwrap_or_else(std::sync::PoisonError::into_inner)
106        }
107    }
108
109    /// Borrows the contents exclusively.
110    ///
111    /// # Panics
112    ///
113    /// The same rule as [`Shared::borrow`].
114    pub fn borrow_mut(&self) -> RefMut<'_, T> {
115        #[cfg(not(feature = "sync-mutex"))]
116        {
117            self.0.borrow_mut()
118        }
119        #[cfg(feature = "sync-mutex")]
120        {
121            self.0
122                .write()
123                .unwrap_or_else(std::sync::PoisonError::into_inner)
124        }
125    }
126
127    /// Takes the contents out.
128    pub fn into_inner(self) -> T {
129        #[cfg(not(feature = "sync-mutex"))]
130        {
131            self.0.into_inner()
132        }
133        #[cfg(feature = "sync-mutex")]
134        {
135            self.0
136                .into_inner()
137                .unwrap_or_else(std::sync::PoisonError::into_inner)
138        }
139    }
140}
141
142/// Asserts at compile time that a controller's own state can cross threads under `sync-mutex`.
143///
144/// Not a test: a test would run once, and this fails the *build* the moment somebody adds a
145/// `Rc` or a `Cell` to one of these types. The claim is that the controller path is `Send`,
146/// and a claim about types is best checked by the type checker.
147#[cfg(all(feature = "sync-mutex", feature = "rustcrypto"))]
148const _: () = {
149    const fn assert_send<T: Send>() {}
150    const fn assert_sync<T: Sync>() {}
151
152    // The commissioning flow's state machine and the fabric's certificate authority: what a
153    // controller spawns one of per node it is bringing up.
154    assert_send::<crate::commissioning::commissioner::Commissioner>();
155    assert_send::<crate::ca::CertAuthority>();
156    assert_sync::<crate::ca::CertAuthority>();
157    // The client's half of a subscription — one per node a controller watches.
158    assert_send::<crate::im::client::Subscription>();
159    assert_sync::<crate::im::client::Subscription>();
160    assert_send::<crate::im::client::ReportAssembler<1024>>();
161    // And the seam itself, over anything that can cross a thread.
162    assert_send::<Shared<u32>>();
163    assert_sync::<Shared<u32>>();
164};
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    /// The property the backing type is chosen for: what compiles and works in the
171    /// single-threaded build does the same thing in the multi-threaded one. A `Mutex` behind
172    /// `Shared` would deadlock here under `sync-mutex` and pass without it.
173    #[test]
174    fn two_shared_borrows_are_live_at_once() {
175        let shared = Shared::new(41u32);
176        let first = shared.borrow();
177        let second = shared.borrow();
178        assert_eq!(*first + *second, 82);
179    }
180
181    #[test]
182    fn an_exclusive_borrow_writes_through() {
183        let shared = Shared::new(1u32);
184        *shared.borrow_mut() = 7;
185        assert_eq!(*shared.borrow(), 7);
186        assert_eq!(shared.into_inner(), 7);
187    }
188}