Skip to main content

operation_queue/
line_token.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//! Helpers for synchronizing operations (e.g. error handling) across futures.
6//!
7//! This module revolves around the [`Line`] struct, which is an asynchronous
8//! flow control structure that behaves a bit like a mutex, with the exception
9//! that consumers waiting for the [`Line`] to be released do not subsequently
10//! lock it.
11//!
12//! The design of a [`Line`] is inspired from the one of a [one-track railway
13//! line](https://en.wikipedia.org/wiki/Token_(railway_signalling)). To avoid
14//! collisions, conductors must acquire a token at the entrance to the line that
15//! ensures they're the only one on it. If the token is being held, traffic
16//! around this line stops until it's released again.
17//!
18//! Similarly, in a context with multiple parallel [`Future`]s, it might be
19//! necessary to ensure only one takes care of a given operation. For example,
20//! if multiple requests are being performed against the same service, and one
21//! of them hits an authentication error, it is likely the others will as well.
22//! In this case, it is preferrable to only let one future handle the error than
23//! let every request re-authenticate independently (in this example,
24//! credentials are the same across requests, and multiple simultaneous
25//! authentication attempts might cause issues with complex flows).
26//!
27//! Each future holds a shared on a [`Line`] (e.g. wrapped in an [`Rc`] or an
28//! [`Arc`]). Whenever a future needs to perform an operation that should only
29//! be performed once at a time, it attempts to acquire the line's token with
30//! [`Line::try_acquire_token`]. This function returns an enum
31//! ([`AcquireOutcome`]) describing one of two cases:
32//!
33//! * The line's token is available and has been acquired, and the future can
34//!   start performing the operation immediately. It is granted the line's
35//!   [`Token`], which it must hold in scope for the duration of the operation,
36//!   as dropping it releases the line.
37//! * The line's token has already been acquired by another future, in which
38//!   case the future must wait for the line to become available again. When the
39//!   line becomes available again, the future does not need to acquire another
40//!   token, as another future should have taken care of performing the
41//!   operation.
42//!
43//! [`OperationQueue`]: crate::operation_queue::OperationQueue
44//! [`Future`]: std::future::Future
45//! [`Rc`]: std::rc::Rc
46//! [`Arc`]: std::sync::Arc
47
48use async_lock::Mutex;
49use futures::{FutureExt, future::Shared};
50use oneshot::{Receiver, Sender};
51
52/// A oneshot channel used internally by a [`Line`] that's been acquired to
53/// communicate that the token has been dropped and the line was released.
54///
55/// The channel's [`Receiver`] is wrapped in a [`Shared`] that can be cloned
56/// when a new consumer tries and fails to acquire a token for the line.
57struct ReleaseChannel {
58    sender: Sender<()>,
59    receiver: Shared<Receiver<()>>,
60}
61
62/// A [`Line`] from which a [`Token`] can be acquired.
63///
64/// # Thread safety
65///
66/// `Line` is thread-safe and can be shared across threads via [`Arc`]:
67///
68/// ```rust
69/// use std::sync::Arc;
70/// use operation_queue::line_token::Line;
71///
72/// fn assert_send_sync<T: Send + Sync>() {}
73/// assert_send_sync::<Line>();
74/// ```
75///
76/// [`Arc`]: std::sync::Arc
77#[derive(Default)]
78pub struct Line {
79    channel: Mutex<Option<ReleaseChannel>>,
80}
81
82impl Line {
83    /// Instantiates a new [`Line`].
84    pub fn new() -> Line {
85        Line {
86            channel: Default::default(),
87        }
88    }
89
90    /// Attempts to acquire a [`Token`] for this line.
91    ///
92    /// The [`Token`] automatically releases the line upon leaving the current
93    /// scope and getting dropped.
94    ///
95    /// If a [`Token`] has already been acquired for this line, a future to
96    /// `await` is returned instead. It resolves when the current token holder
97    /// has finished handling the current error and releases the line.
98    pub async fn try_acquire_token<'l>(&'l self) -> AcquireOutcome<'l> {
99        let mut channel = self.channel.lock().await;
100
101        if let Some(channel) = channel.as_ref() {
102            // Since the oneshot `Receiver` is wrapped in a `Shared`, cloning it
103            // will return a new handle on the `Shared` which will resolve at
104            // the same time as the others.
105            return AcquireOutcome::Failure(channel.receiver.clone());
106        }
107
108        // The line is currently available, create a new channel and give the
109        // consumer their token.
110        let (sender, receiver) = oneshot::channel();
111        *channel = Some(ReleaseChannel {
112            sender,
113            receiver: receiver.shared(),
114        });
115
116        AcquireOutcome::Success(Token { line: self })
117    }
118
119    /// Releases the line, and resolves the [`Shared`] future other consumers
120    /// might be awaiting.
121    pub(self) fn release(&self) {
122        // "Take" the channel out of the `Mutex`; on top of letting us access
123        // its content, we're also making sure that even if something bad
124        // happens then the line can be acquired again.
125        match self.channel.lock_blocking().take() {
126            Some(channel) => match channel.sender.send(()) {
127                Ok(_) => (),
128                Err(_) => log::error!("trying to release using a closed channel"),
129            },
130            None => log::error!("trying to release before acquiring"),
131        };
132    }
133}
134
135/// The outcome from trying to acquire a [`Token`] for a [`Line`].
136#[must_use = "if the token is unused the line will immediately release again"]
137pub enum AcquireOutcome<'ao> {
138    /// The line could be acquired and returned a token to hold on to.
139    ///
140    /// The token must remain in scope, as it will release the line when
141    /// dropped.
142    Success(Token<'ao>),
143
144    /// The line could not be acquired as another consumer is holding a token
145    /// for it.
146    ///
147    /// This variant includes a [`Shared`] future that resolves when the current
148    /// token holder drops it and releases the line.
149    Failure(Shared<Receiver<()>>),
150}
151
152impl<'ao> AcquireOutcome<'ao> {
153    /// Returns the [`AcquireOutcome`] if it's a success, otherwise returns a
154    /// success with the provided token if it's not [`None`].
155    ///
156    /// If the current [`AcquireOutcome`] is a failure, and the provided token
157    /// is [`None`], the failure is returned.
158    ///
159    /// # Design considerations
160    ///
161    /// One way to make this method more straightforward could have been to make
162    /// `token` be a [`Token`], not an [`Option`], but the current signature was
163    /// picked to simplify the consumers (which store the token, if any, in an
164    /// [`Option`]).
165    pub fn or_token(self, token: Option<Token<'ao>>) -> Self {
166        match self {
167            AcquireOutcome::Success(_) => self,
168            AcquireOutcome::Failure(_) => match token {
169                Some(token) => AcquireOutcome::Success(token),
170                None => self,
171            },
172        }
173    }
174}
175
176/// A token that symbolizes the current consumer holds exclusive access to the
177/// corresponding [`Line`].
178///
179/// The [`Line`] is automatically released when this token goes out of scope and
180/// is dropped.
181#[must_use = "if unused the line will immediately release again"]
182pub struct Token<'t> {
183    line: &'t Line,
184}
185
186impl Drop for Token<'_> {
187    fn drop(&mut self) {
188        self.line.release();
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use tokio::time::Duration;
195
196    use super::*;
197
198    async fn get_token(line: &Line) -> Token<'_> {
199        match line.try_acquire_token().await {
200            AcquireOutcome::Success(token) => token,
201            AcquireOutcome::Failure(_) => panic!("expected a token from try_acquire_token()"),
202        }
203    }
204
205    #[tokio::test(flavor = "current_thread")]
206    async fn acquire_token() {
207        let line = Line::new();
208
209        let _token = get_token(&line).await;
210
211        match line.try_acquire_token().await {
212            AcquireOutcome::Success(_) => {
213                panic!("should not be able to acquire the line while the token is in scope")
214            }
215            AcquireOutcome::Failure(_) => (),
216        }
217    }
218
219    #[tokio::test(flavor = "current_thread")]
220    async fn token_out_of_scope() {
221        let line = Line::new();
222
223        {
224            let _token = get_token(&line).await;
225
226            match line.try_acquire_token().await {
227                AcquireOutcome::Success(_) => {
228                    panic!("should not be able to acquire the line while the token is in scope")
229                }
230                AcquireOutcome::Failure(_) => (),
231            }
232        }
233
234        match line.try_acquire_token().await {
235            AcquireOutcome::Success(_) => (),
236            AcquireOutcome::Failure(_) => {
237                panic!("expected a token now that the previous token has been dropped")
238            }
239        }
240    }
241
242    #[tokio::test(flavor = "current_thread")]
243    async fn or_token() {
244        let line = Line::new();
245
246        let token = get_token(&line).await;
247
248        match line.try_acquire_token().await.or_token(Some(token)) {
249            AcquireOutcome::Success(_) => (),
250            AcquireOutcome::Failure(_) => panic!("we should have kept our token"),
251        }
252    }
253
254    #[tokio::test(flavor = "current_thread")]
255    async fn line_release_on_drop() {
256        let line = Line::new();
257
258        // A mutable variable that will act as the test's success flag and will
259        // only be true if it succeeds.
260        let mut success = false;
261
262        // Acquire the line's token, sleep for a bit (10ms) and then drop it.
263        // The reason we sleep here is to give some time to `wait_for_line` to
264        // try (and fail) to acquire the line's token before we drop it.
265        async fn acquire_sleep_and_drop(line: &Line) {
266            let _token = get_token(&line).await;
267            tokio::time::sleep(Duration::from_millis(10)).await;
268        }
269
270        // Try (and fail) to acquire the token, then wait for the line to become
271        // available again. This function sets the success flag.
272        async fn wait_for_line(line: &Line, success: &mut bool) {
273            let shared = match line.try_acquire_token().await {
274                AcquireOutcome::Success(_) => {
275                    panic!("should not be able to acquire the line while the token is in scope")
276                }
277                AcquireOutcome::Failure(shared) => shared,
278            };
279
280            shared.await.unwrap();
281            *success = true;
282        }
283
284        // Run both futures in parallel. `biased;` ensures the futures are
285        // polled in order (meaning `acquire_sleep_and_drop` is run first).
286        tokio::join! {
287            biased;
288            acquire_sleep_and_drop(&line),
289            wait_for_line(&line, &mut success),
290        };
291
292        assert!(success)
293    }
294}