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>) -> std::convert::Infallible {
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/// ) -> std::convert::Infallible {
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>) -> std::convert::Infallible {
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            let type_name = self.slot.inner_type_name();
133
134            self.slot.modify(
135                |value| {
136                    f(value);
137
138                    // TODO(DEV-532): add debug format
139                    veecle_telemetry::trace!("Slot modified", type_name);
140                },
141                span_context,
142            );
143            self.slot.increment_generation();
144        })
145        .with_span(span)
146        .await;
147    }
148
149    /// Reads the current value of a type.
150    ///
151    /// This method takes a closure to ensure the reference is not held across await points.
152    #[veecle_telemetry::instrument]
153    pub fn read<U>(&self, f: impl FnOnce(Option<&T::DataType>) -> U) -> U {
154        let type_name = self.slot.inner_type_name();
155        self.slot.read(|value| {
156            let value = value.as_ref();
157            // TODO(DEV-532): add debug format
158            veecle_telemetry::trace!("Slot read", type_name);
159            f(value)
160        })
161    }
162}
163
164impl<'a, T> Writer<'a, T>
165where
166    T: Storable + 'static,
167{
168    pub(crate) fn new(waiter: generational::Waiter<'a>, slot: Pin<&'a Slot<T>>) -> Self {
169        slot.take_writer();
170        Self {
171            slot,
172            waiter,
173            marker: PhantomData,
174        }
175    }
176}
177
178#[cfg(test)]
179#[cfg_attr(coverage_nightly, coverage(off))]
180mod tests {
181    use crate::datastore::{Slot, Storable, Writer, generational};
182    use core::pin::pin;
183
184    #[test]
185    fn ready_waits_for_increment() {
186        use futures::FutureExt;
187        #[derive(Debug)]
188        pub struct Data();
189        impl Storable for Data {
190            type DataType = Self;
191        }
192
193        let source = pin!(generational::Source::new());
194        let slot = pin!(Slot::<Data>::new());
195        let mut writer = Writer::new(source.as_ref().waiter(), slot.as_ref());
196
197        // Part 1. Initially, the writer is not ready. Calls to
198        // ready() will not resolve immediately in a single Future::poll() call,
199        // indicating that the writer needs more time. Additionally we check that
200        // calls to write() are also not resolving immediately, demonstrating that
201        // ready() actually was correct.
202        assert!(writer.ready().now_or_never().is_none());
203        assert!(writer.write(Data {}).now_or_never().is_none());
204
205        // Part 2. Increment the generation, which signals that the writer
206        // should be ready again. After the increment, ready() and write()
207        // are expected to resolve in a single Future::poll() call.
208        source.as_ref().increment_generation();
209        assert!(writer.ready().now_or_never().is_some());
210        assert!(writer.write(Data {}).now_or_never().is_some());
211
212        // Part 3. Trying to write again before the generation increments should be blocked.
213        assert!(writer.ready().now_or_never().is_none());
214        assert!(writer.write(Data {}).now_or_never().is_none());
215    }
216
217    #[test]
218    fn read_reads_latest_written_value() {
219        use futures::FutureExt;
220        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
221        pub struct Data(usize);
222        impl Storable for Data {
223            type DataType = Self;
224        }
225
226        let source = pin!(generational::Source::new());
227        let slot = pin!(Slot::<Data>::new());
228        let mut writer = Writer::new(source.as_ref().waiter(), slot.as_ref());
229
230        writer.read(|current_data| assert!(current_data.is_none()));
231
232        source.as_ref().increment_generation();
233
234        let want = Data(1);
235        writer.write(want).now_or_never().unwrap();
236        writer.read(|got| assert_eq!(got, Some(&want)));
237
238        source.as_ref().increment_generation();
239
240        let want = Data(2);
241        writer.write(want).now_or_never().unwrap();
242        writer.read(|got| assert_eq!(got, Some(&want)));
243    }
244}