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, a [`Mutex`](std::sync::Mutex), 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`, and never take a second borrow while one is live.**
24//!
25//! With a `RefCell` the second of those panics at the point of the mistake; with a `Mutex` it
26//! *deadlocks*, silently, somewhere else. That asymmetry is why this type exists rather than a
27//! bare `cfg` on each declaration: a crate that can be built both ways is one where the
28//! single-threaded build finds the bug and the multi-threaded build would only have hung.
29//!
30//! The crate's own device clusters deliberately keep their [`core::cell::RefCell`]s: a device is
31//! single-threaded by construction and converting them would trade a panic that points at the
32//! mistake for a deadlock that does not.
33
34#[cfg(not(feature = "sync-mutex"))]
35use core::cell::RefCell;
36
37/// State shared between the parts of a controller.
38///
39/// A [`core::cell::RefCell`] by default; a [`Mutex`](std::sync::Mutex) under `sync-mutex`.
40#[cfg(not(feature = "sync-mutex"))]
41#[derive(Debug, Default)]
42pub struct Shared<T>(RefCell<T>);
43
44/// State shared between the parts of a controller, across threads.
45#[cfg(feature = "sync-mutex")]
46#[derive(Debug, Default)]
47pub struct Shared<T>(std::sync::Mutex<T>);
48
49/// A shared borrow of the contents.
50#[cfg(not(feature = "sync-mutex"))]
51pub type Ref<'a, T> = core::cell::Ref<'a, T>;
52
53/// A shared borrow of the contents.
54///
55/// The same guard as [`RefMut`] under `sync-mutex`: a mutex has one kind of lock, so a reader
56/// and a writer exclude each other. Code that takes two `borrow()`s at once compiles and works
57/// without the feature, and deadlocks with it — which is the rule at the top of this module.
58#[cfg(feature = "sync-mutex")]
59pub type Ref<'a, T> = std::sync::MutexGuard<'a, T>;
60
61/// An exclusive borrow of the contents.
62#[cfg(not(feature = "sync-mutex"))]
63pub type RefMut<'a, T> = core::cell::RefMut<'a, T>;
64
65/// An exclusive borrow of the contents.
66#[cfg(feature = "sync-mutex")]
67pub type RefMut<'a, T> = std::sync::MutexGuard<'a, T>;
68
69impl<T> Shared<T> {
70 /// Wraps `value`.
71 #[must_use]
72 pub const fn new(value: T) -> Self {
73 #[cfg(not(feature = "sync-mutex"))]
74 {
75 Self(RefCell::new(value))
76 }
77 #[cfg(feature = "sync-mutex")]
78 {
79 Self(std::sync::Mutex::new(value))
80 }
81 }
82
83 /// Borrows the contents.
84 ///
85 /// # Panics
86 ///
87 /// Without `sync-mutex`, if a mutable borrow is live — [`core::cell::RefCell`]'s rule. With it, never:
88 /// a poisoned mutex is recovered from rather than propagated, because a controller that
89 /// stopped answering every node because one task panicked would turn one fault into an
90 /// outage.
91 pub fn borrow(&self) -> Ref<'_, T> {
92 #[cfg(not(feature = "sync-mutex"))]
93 {
94 self.0.borrow()
95 }
96 #[cfg(feature = "sync-mutex")]
97 {
98 self.0
99 .lock()
100 .unwrap_or_else(std::sync::PoisonError::into_inner)
101 }
102 }
103
104 /// Borrows the contents exclusively.
105 ///
106 /// # Panics
107 ///
108 /// The same rule as [`Shared::borrow`].
109 pub fn borrow_mut(&self) -> RefMut<'_, T> {
110 #[cfg(not(feature = "sync-mutex"))]
111 {
112 self.0.borrow_mut()
113 }
114 #[cfg(feature = "sync-mutex")]
115 {
116 self.0
117 .lock()
118 .unwrap_or_else(std::sync::PoisonError::into_inner)
119 }
120 }
121
122 /// Takes the contents out.
123 pub fn into_inner(self) -> T {
124 #[cfg(not(feature = "sync-mutex"))]
125 {
126 self.0.into_inner()
127 }
128 #[cfg(feature = "sync-mutex")]
129 {
130 self.0
131 .into_inner()
132 .unwrap_or_else(std::sync::PoisonError::into_inner)
133 }
134 }
135}
136
137/// Asserts at compile time that a controller's own state can cross threads under `sync-mutex`.
138///
139/// Not a test: a test would run once, and this fails the *build* the moment somebody adds a
140/// `Rc` or a `Cell` to one of these types. The claim is that the controller path is `Send`,
141/// and a claim about types is best checked by the type checker.
142#[cfg(all(feature = "sync-mutex", feature = "rustcrypto"))]
143const _: () = {
144 const fn assert_send<T: Send>() {}
145 const fn assert_sync<T: Sync>() {}
146
147 // The commissioning flow's state machine and the fabric's certificate authority: what a
148 // controller spawns one of per node it is bringing up.
149 assert_send::<crate::commissioning::commissioner::Commissioner>();
150 assert_send::<crate::ca::CertAuthority>();
151 assert_sync::<crate::ca::CertAuthority>();
152 // The client's half of a subscription — one per node a controller watches.
153 assert_send::<crate::im::client::Subscription>();
154 assert_sync::<crate::im::client::Subscription>();
155 assert_send::<crate::im::client::ReportAssembler<1024>>();
156 // And the seam itself, over anything that can cross a thread.
157 assert_send::<Shared<u32>>();
158 assert_sync::<Shared<u32>>();
159};