veecle_os_runtime/datastore/writer.rs
1use core::fmt::Debug;
2use core::marker::PhantomData;
3use core::pin::Pin;
4
5use super::slot::Slot;
6use super::{Storable, generational};
7
8/// Writer for a [`Storable`] type.
9///
10/// Allows [`Actor`]s to write a particular type read by another actor.
11/// The generic type `T` from the writer specifies the type of the value that is being written.
12///
13/// # Usage
14///
15/// All [`Reader`]s are guaranteed to be able to observe every write.
16/// For this reason, [`Writer::write`] is an async method.
17/// It will resolve once all [`Actor`]s awaiting a [`Reader`] for the same type had the chance to read the value.
18/// Typically, this only occurs when trying to write two values back to back.
19/// If all [`Reader`]s already had the chance to read the value, [`Writer::write`] will resolve immediately.
20/// The same is true for [`Writer::modify`].
21///
22/// # Examples
23///
24/// ```rust
25/// // Writing a value.
26/// # use std::fmt::Debug;
27/// #
28/// # use veecle_os_runtime::{Storable, Writer};
29/// #
30/// # #[derive(Debug, Default, Storable)]
31/// # pub struct Foo;
32/// #
33/// #[veecle_os_runtime::actor]
34/// async fn foo_writer(mut writer: Writer<'_, Foo>) -> veecle_os_runtime::Never {
35/// loop {
36/// // This call will yield to any readers needing to read the last value.
37/// writer.write(Foo::default()).await;
38/// }
39/// }
40/// ```
41///
42/// ```rust
43/// // Modifying a value.
44/// # use std::fmt::Debug;
45/// #
46/// # use veecle_os_runtime::{Storable, Writer};
47/// #
48/// # #[derive(Debug, Default, Storable)]
49/// # pub struct Foo;
50/// #
51/// #[veecle_os_runtime::actor]
52/// async fn foo_writer(
53/// mut writer: Writer<'_, Foo>,
54/// ) -> veecle_os_runtime::Never {
55/// loop {
56/// // This call will yield to any readers needing to read the last value.
57/// // The closure will run after yielding and right before continuing to the rest of the function.
58/// writer.modify(|previous_value: &mut Option<Foo>| {
59/// // mutate the previous value
60/// }).await;
61/// }
62/// }
63/// ```
64///
65/// [`Writer::ready`] allows separating the "waiting" from the "writing",
66/// After [`Writer::ready`] returns, the next write or modification will happen immediately.
67///
68/// ```rust
69/// # use std::fmt::Debug;
70/// #
71/// # use veecle_os_runtime::{Storable, Reader, Writer};
72/// #
73/// # #[derive(Debug, Default, Storable)]
74/// # pub struct Foo;
75/// #
76/// #[veecle_os_runtime::actor]
77/// async fn foo_writer(mut writer: Writer<'_, Foo>) -> veecle_os_runtime::Never {
78/// loop {
79/// // This call may yield to any readers needing to read the last value.
80/// writer.ready().await;
81///
82/// // This call will return immediately.
83/// writer.write(Foo::default()).await;
84/// // This call will yield to any readers needing to read the last value.
85/// writer.write(Foo::default()).await;
86/// }
87/// }
88/// ```
89///
90/// [`Actor`]: crate::Actor
91/// [`Reader`]: crate::Reader
92#[derive(Debug)]
93pub struct Writer<'a, T>
94where
95 T: Storable + 'static,
96{
97 slot: Pin<&'a Slot<T>>,
98 waiter: generational::Waiter<'a>,
99 marker: PhantomData<fn(T)>,
100}
101
102impl<T> Writer<'_, T>
103where
104 T: Storable + 'static,
105{
106 /// Writes a new value and notifies readers.
107 #[veecle_telemetry::instrument]
108 pub async fn write(&mut self, item: T::DataType) {
109 self.modify(|slot| {
110 let _ = slot.insert(item);
111 })
112 .await;
113 }
114
115 /// Waits for the writer to be ready to perform a write operation.
116 ///
117 /// After awaiting this method, the next call to [`Writer::write()`]
118 /// or [`Writer::modify()`] is guaranteed to resolve immediately.
119 pub async fn ready(&mut self) {
120 let _ = self.waiter.wait().await;
121 }
122
123 /// Updates the value in-place and notifies readers.
124 pub async fn modify(&mut self, f: impl FnOnce(&mut Option<T::DataType>)) {
125 use veecle_telemetry::future::FutureExt;
126 let span = veecle_telemetry::span!("modify");
127 let span_context = span.context();
128 (async move {
129 self.ready().await;
130 self.waiter.update_generation();
131
132 self.slot.modify(
133 |value| {
134 f(value);
135
136 veecle_telemetry::trace!("Slot modified", value = format_args!("{value:?}"));
137 },
138 span_context,
139 );
140 self.slot.increment_generation();
141 })
142 .with_span(span)
143 .await;
144 }
145
146 /// Reads the current value of a type.
147 ///
148 /// This method takes a closure to ensure the reference is not held across await points.
149 #[veecle_telemetry::instrument]
150 pub fn read<U>(&self, f: impl FnOnce(Option<&T::DataType>) -> U) -> U {
151 self.slot.read(|value| {
152 let value = value.as_ref();
153
154 veecle_telemetry::trace!("Slot read", value = format_args!("{value:?}"));
155
156 f(value)
157 })
158 }
159}
160
161impl<'a, T> Writer<'a, T>
162where
163 T: Storable + 'static,
164{
165 pub(crate) fn new(waiter: generational::Waiter<'a>, slot: Pin<&'a Slot<T>>) -> Self {
166 slot.take_writer();
167 Self {
168 slot,
169 waiter,
170 marker: PhantomData,
171 }
172 }
173}
174
175#[cfg(test)]
176#[cfg_attr(coverage_nightly, coverage(off))]
177mod tests {
178 use crate::datastore::{Slot, Storable, Writer, generational};
179 use core::pin::pin;
180
181 #[test]
182 fn ready_waits_for_increment() {
183 use futures::FutureExt;
184 #[derive(Debug)]
185 pub struct Data();
186 impl Storable for Data {
187 type DataType = Self;
188 }
189
190 let source = pin!(generational::Source::new());
191 let slot = pin!(Slot::<Data>::new());
192 let mut writer = Writer::new(source.as_ref().waiter(), slot.as_ref());
193
194 // Part 1. Initially, the writer is not ready. Calls to
195 // ready() will not resolve immediately in a single Future::poll() call,
196 // indicating that the writer needs more time. Additionally we check that
197 // calls to write() are also not resolving immediately, demonstrating that
198 // ready() actually was correct.
199 assert!(writer.ready().now_or_never().is_none());
200 assert!(writer.write(Data {}).now_or_never().is_none());
201
202 // Part 2. Increment the generation, which signals that the writer
203 // should be ready again. After the increment, ready() and write()
204 // are expected to resolve in a single Future::poll() call.
205 source.as_ref().increment_generation();
206 assert!(writer.ready().now_or_never().is_some());
207 assert!(writer.write(Data {}).now_or_never().is_some());
208
209 // Part 3. Trying to write again before the generation increments should be blocked.
210 assert!(writer.ready().now_or_never().is_none());
211 assert!(writer.write(Data {}).now_or_never().is_none());
212 }
213
214 #[test]
215 fn read_reads_latest_written_value() {
216 use futures::FutureExt;
217 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
218 pub struct Data(usize);
219 impl Storable for Data {
220 type DataType = Self;
221 }
222
223 let source = pin!(generational::Source::new());
224 let slot = pin!(Slot::<Data>::new());
225 let mut writer = Writer::new(source.as_ref().waiter(), slot.as_ref());
226
227 writer.read(|current_data| assert!(current_data.is_none()));
228
229 source.as_ref().increment_generation();
230
231 let want = Data(1);
232 writer.write(want).now_or_never().unwrap();
233 writer.read(|got| assert_eq!(got, Some(&want)));
234
235 source.as_ref().increment_generation();
236
237 let want = Data(2);
238 writer.write(want).now_or_never().unwrap();
239 writer.read(|got| assert_eq!(got, Some(&want)));
240 }
241}