1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
pub mod events;
52

            
53
use crate::events::{TorEvent, TorEventKind};
54
use async_broadcast::{InactiveReceiver, Receiver, Sender, TrySendError};
55
use futures::StreamExt;
56
use futures::channel::mpsc;
57
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
58
use futures::future::Either;
59
use std::pin::Pin;
60
use std::sync::OnceLock;
61
use std::sync::atomic::{AtomicUsize, Ordering};
62
use std::task::{Context, Poll};
63
use thiserror::Error;
64
use tracing::{error, warn};
65

            
66
/// Pointer to an `UnboundedSender`, used to send events into the `EventReactor`.
67
static EVENT_SENDER: OnceLock<UnboundedSender<TorEvent>> = OnceLock::new();
68
/// An inactive receiver for the currently active broadcast channel, if there is one.
69
static CURRENT_RECEIVER: OnceLock<InactiveReceiver<TorEvent>> = OnceLock::new();
70
/// The number of `TorEventKind`s there are.
71
const EVENT_KIND_COUNT: usize = 1;
72
/// An array containing one `AtomicUsize` for each `TorEventKind`, used to track subscriptions.
73
///
74
/// When a `TorEventReceiver` subscribes to a `TorEventKind`, it uses its `usize` value to index
75
/// into this array and increment the associated `AtomicUsize` (and decrements it to unsubscribe).
76
/// This lets event emitters check whether there are any subscribers, and avoid emitting events
77
/// if there aren't.
78
static EVENT_SUBSCRIBERS: [AtomicUsize; EVENT_KIND_COUNT] = [AtomicUsize::new(0); EVENT_KIND_COUNT];
79

            
80
/// The size of the internal broadcast channel used to implement event subscription.
81
pub static BROADCAST_CAPACITY: usize = 512;
82

            
83
/// A reactor used to forward events to make the event reporting system work.
84
///
85
/// # Note
86
///
87
/// Currently, this type is a singleton; there is one event reporting system used for the entire
88
/// program. This is not stable, and may change in future.
89
pub struct EventReactor {
90
    /// A receiver that the reactor uses to learn about incoming events.
91
    ///
92
    /// This is unbounded so that event publication doesn't have to be async.
93
    receiver: UnboundedReceiver<TorEvent>,
94
    /// A sender that the reactor uses to publish events.
95
    ///
96
    /// Events are only sent here if at least one subscriber currently wants them.
97
    broadcast: Sender<TorEvent>,
98
}
99

            
100
impl EventReactor {
101
    /// Initialize the event reporting system, returning a reactor that must be run for it to work,
102
    /// and a `TorEventReceiver` that can be used to extract events from the system. If the system
103
    /// has already been initialized, returns `None` instead of a reactor.
104
    ///
105
    /// # Warnings
106
    ///
107
    /// The returned reactor *must* be run with `EventReactor::run`, in a background async task.
108
    /// If it is not, the event system might consume unbounded amounts of memory.
109
8
    pub fn new() -> Option<Self> {
110
8
        let (tx, rx) = mpsc::unbounded();
111
8
        if EVENT_SENDER.set(tx).is_ok() {
112
2
            let (btx, brx) = async_broadcast::broadcast(BROADCAST_CAPACITY);
113
2
            CURRENT_RECEIVER
114
2
                .set(brx.deactivate())
115
2
                .expect("CURRENT_RECEIVER can't be set if EVENT_SENDER is unset!");
116
2
            Some(Self {
117
2
                receiver: rx,
118
2
                broadcast: btx,
119
2
            })
120
        } else {
121
6
            None
122
        }
123
8
    }
124
    /// Get a `TorEventReceiver` to receive events from, assuming an `EventReactor` is already
125
    /// running somewhere. (If it isn't, returns `None`.)
126
    ///
127
    /// As noted in the type-level documentation, this function might not always work this way.
128
8
    pub fn receiver() -> Option<TorEventReceiver> {
129
8
        CURRENT_RECEIVER
130
8
            .get()
131
12
            .map(|rx| TorEventReceiver::wrap(rx.clone()))
132
8
    }
133
    /// Run the event forwarding reactor.
134
    ///
135
    /// You *must* call this function once a reactor is created.
136
3
    pub async fn run(mut self) {
137
4
        while let Some(event) = self.receiver.next().await {
138
2
            match self.broadcast.try_broadcast(event) {
139
2
                Ok(_) => {}
140
                Err(TrySendError::Closed(_)) => break,
141
                Err(TrySendError::Full(event)) => {
142
                    // If the channel is full, do a blocking broadcast to wait for it to be
143
                    // not full, and log a warning about receivers lagging behind.
144
                    warn!("TorEventReceivers aren't receiving events fast enough!");
145
                    if self.broadcast.broadcast(event).await.is_err() {
146
                        break;
147
                    }
148
                }
149
                Err(TrySendError::Inactive(_)) => {
150
                    // no active receivers, so just drop the event on the floor.
151
                }
152
            }
153
        }
154
        // It shouldn't be possible to get here, since we have globals keeping the channels
155
        // open. Still, if we somehow do, log an error about it.
156
        error!("event reactor shutting down; this shouldn't ever happen");
157
    }
158
}
159

            
160
/// An error encountered when trying to receive a `TorEvent`.
161
#[derive(Clone, Debug, Error)]
162
#[non_exhaustive]
163
pub enum ReceiverError {
164
    /// The receiver isn't subscribed to anything, so wouldn't ever return any events.
165
    #[error("No event subscriptions")]
166
    NoSubscriptions,
167
    /// The internal broadcast channel was closed, which shouldn't ever happen.
168
    #[error("Internal event broadcast channel closed")]
169
    ChannelClosed,
170
}
171

            
172
/// A receiver for `TorEvent`s emitted by other users of this crate.
173
///
174
/// To use this type, first subscribe to some kinds of event by calling
175
/// `TorEventReceiver::subscribe`. Then, consume events using the implementation of
176
/// `futures::stream::Stream`.
177
///
178
/// # Warning
179
///
180
/// Once interest in events has been signalled with `subscribe`, events must be continuously
181
/// read from the receiver in order to avoid excessive memory consumption.
182
#[derive(Clone, Debug)]
183
pub struct TorEventReceiver {
184
    /// If no events have been subscribed to yet, this is an `InactiveReceiver`; otherwise,
185
    /// it's a `Receiver`.
186
    inner: Either<Receiver<TorEvent>, InactiveReceiver<TorEvent>>,
187
    /// Whether we're subscribed to each event kind (if `subscribed[kind]` is true, we're
188
    /// subscribed to `kind`).
189
    subscribed: [bool; EVENT_KIND_COUNT],
190
}
191

            
192
impl futures::stream::Stream for TorEventReceiver {
193
    type Item = TorEvent;
194

            
195
10
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
196
10
        let this = self.get_mut();
197
10
        match this.inner {
198
8
            Either::Left(ref mut active) => loop {
199
8
                match Pin::new(&mut *active).poll_next(cx) {
200
2
                    Poll::Ready(Some(e)) => {
201
2
                        if this.subscribed[e.kind() as usize] {
202
2
                            return Poll::Ready(Some(e));
203
                        }
204
                        // loop, since we weren't subscribed to that event
205
                    }
206
6
                    x => return x,
207
                }
208
            },
209
            Either::Right(_) => {
210
2
                warn!("TorEventReceiver::poll_next() called without subscriptions!");
211
2
                Poll::Ready(None)
212
            }
213
        }
214
10
    }
215
}
216

            
217
impl TorEventReceiver {
218
    /// Create a `TorEventReceiver` from an `InactiveReceiver` handle.
219
8
    pub(crate) fn wrap(rx: InactiveReceiver<TorEvent>) -> Self {
220
8
        Self {
221
8
            inner: Either::Right(rx),
222
8
            subscribed: [false; EVENT_KIND_COUNT],
223
8
        }
224
8
    }
225
    /// Subscribe to a given kind of `TorEvent`.
226
    ///
227
    /// After calling this function, `TorEventReceiver::recv` will emit events of that kind.
228
    /// This function is idempotent (subscribing twice has the same effect as doing so once).
229
14
    pub fn subscribe(&mut self, kind: TorEventKind) {
230
14
        if !self.subscribed[kind as usize] {
231
10
            EVENT_SUBSCRIBERS[kind as usize].fetch_add(1, Ordering::SeqCst);
232
10
            self.subscribed[kind as usize] = true;
233
10
        }
234
        // FIXME(eta): cloning is ungood, but hard to avoid
235
14
        if let Either::Right(inactive) = self.inner.clone() {
236
10
            self.inner = Either::Left(inactive.activate());
237
10
        }
238
14
    }
239
    /// Unsubscribe from a given kind of `TorEvent`.
240
    ///
241
    /// After calling this function, `TorEventReceiver::recv` will no longer emit events of that
242
    /// kind.
243
    /// This function is idempotent (unsubscribing twice has the same effect as doing so once).
244
4
    pub fn unsubscribe(&mut self, kind: TorEventKind) {
245
4
        if self.subscribed[kind as usize] {
246
4
            EVENT_SUBSCRIBERS[kind as usize].fetch_sub(1, Ordering::SeqCst);
247
4
            self.subscribed[kind as usize] = false;
248
4
        }
249
        // If we're now not subscribed to anything, deactivate our channel.
250
6
        if self.subscribed.iter().all(|x| !*x) {
251
            // FIXME(eta): cloning is ungood, but hard to avoid
252
4
            if let Either::Left(active) = self.inner.clone() {
253
4
                self.inner = Either::Right(active.deactivate());
254
4
            }
255
        }
256
4
    }
257
}
258

            
259
impl Drop for TorEventReceiver {
260
8
    fn drop(&mut self) {
261
8
        for (i, subscribed) in self.subscribed.iter().enumerate() {
262
            // FIXME(eta): duplicates logic from Self::unsubscribe, because it's not possible
263
            //             to go from a `usize` to a `TorEventKind`
264
8
            if *subscribed {
265
6
                EVENT_SUBSCRIBERS[i].fetch_sub(1, Ordering::SeqCst);
266
6
            }
267
        }
268
8
    }
269
}
270

            
271
/// Returns a boolean indicating whether the event `kind` has any subscribers (as in,
272
/// whether `TorEventReceiver::subscribe` has been called with that event kind).
273
///
274
/// This is useful to avoid doing work to generate events that might be computationally expensive
275
/// to generate.
276
20
pub fn event_has_subscribers(kind: TorEventKind) -> bool {
277
20
    EVENT_SUBSCRIBERS[kind as usize].load(Ordering::SeqCst) > 0
278
20
}
279

            
280
/// Broadcast the given `TorEvent` to any interested subscribers.
281
///
282
/// As an optimization, does nothing if the event has no subscribers (`event_has_subscribers`
283
/// returns false). (also does nothing if the event subsystem hasn't been initialized yet)
284
///
285
/// This function isn't intended for use outside Arti crates (as in, library consumers of Arti
286
/// shouldn't broadcast events!).
287
4
pub fn broadcast(event: TorEvent) {
288
4
    if !event_has_subscribers(event.kind()) {
289
2
        return;
290
2
    }
291
2
    if let Some(sender) = EVENT_SENDER.get() {
292
2
        // If this fails, there isn't much we can really do about it!
293
2
        let _ = sender.unbounded_send(event);
294
2
    }
295
4
}
296

            
297
#[cfg(test)]
298
mod test {
299
    // @@ begin test lint list maintained by maint/add_warning @@
300
    #![allow(clippy::bool_assert_comparison)]
301
    #![allow(clippy::clone_on_copy)]
302
    #![allow(clippy::dbg_macro)]
303
    #![allow(clippy::mixed_attributes_style)]
304
    #![allow(clippy::print_stderr)]
305
    #![allow(clippy::print_stdout)]
306
    #![allow(clippy::single_char_pattern)]
307
    #![allow(clippy::unwrap_used)]
308
    #![allow(clippy::unchecked_time_subtraction)]
309
    #![allow(clippy::useless_vec)]
310
    #![allow(clippy::needless_pass_by_value)]
311
    #![allow(clippy::string_slice)] // See arti#2571
312
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
313
    use crate::{
314
        EventReactor, StreamExt, TorEvent, TorEventKind, broadcast, event_has_subscribers,
315
    };
316
    use std::sync::{Mutex, MutexGuard, OnceLock};
317
    use std::time::Duration;
318
    use tokio::runtime::Runtime;
319

            
320
    // HACK(eta): these tests need to run effectively singlethreaded, since they mutate global
321
    //            state. They *also* need to share the same tokio runtime, which the
322
    //            #[tokio::test] thing doesn't do (it makes a new runtime per test), because of
323
    //            the need to have a background singleton EventReactor.
324
    //
325
    //            To hack around this, we just have a global runtime protected by a mutex!
326
    static TEST_MUTEX: OnceLock<Mutex<Runtime>> = OnceLock::new();
327

            
328
    /// Locks the mutex, and makes sure the event reactor is initialized.
329
    fn test_setup() -> MutexGuard<'static, Runtime> {
330
        let mutex = TEST_MUTEX.get_or_init(|| Mutex::new(Runtime::new().unwrap()));
331
        let runtime = mutex
332
            .lock()
333
            .expect("mutex poisoned, probably by other failing tests");
334
        if let Some(reactor) = EventReactor::new() {
335
            runtime.handle().spawn(reactor.run());
336
        }
337
        runtime
338
    }
339

            
340
    #[test]
341
    fn subscriptions() {
342
        let rt = test_setup();
343

            
344
        rt.block_on(async move {
345
            // shouldn't have any subscribers at the start
346
            assert!(!event_has_subscribers(TorEventKind::Empty));
347

            
348
            let mut rx = EventReactor::receiver().unwrap();
349
            // creating a receiver shouldn't result in any subscriptions
350
            assert!(!event_has_subscribers(TorEventKind::Empty));
351

            
352
            rx.subscribe(TorEventKind::Empty);
353
            // subscription should work
354
            assert!(event_has_subscribers(TorEventKind::Empty));
355

            
356
            rx.unsubscribe(TorEventKind::Empty);
357
            // unsubscribing should work
358
            assert!(!event_has_subscribers(TorEventKind::Empty));
359

            
360
            // subscription should be idempotent
361
            rx.subscribe(TorEventKind::Empty);
362
            rx.subscribe(TorEventKind::Empty);
363
            rx.subscribe(TorEventKind::Empty);
364
            assert!(event_has_subscribers(TorEventKind::Empty));
365

            
366
            rx.unsubscribe(TorEventKind::Empty);
367
            assert!(!event_has_subscribers(TorEventKind::Empty));
368

            
369
            rx.subscribe(TorEventKind::Empty);
370
            assert!(event_has_subscribers(TorEventKind::Empty));
371

            
372
            std::mem::drop(rx);
373
            // dropping the receiver should auto-unsubscribe
374
            assert!(!event_has_subscribers(TorEventKind::Empty));
375
        });
376
    }
377

            
378
    #[test]
379
    fn empty_recv() {
380
        let rt = test_setup();
381

            
382
        rt.block_on(async move {
383
            let mut rx = EventReactor::receiver().unwrap();
384
            // attempting to read from a receiver with no subscriptions should return None
385
            let result = rx.next().await;
386
            assert!(result.is_none());
387
        });
388
    }
389

            
390
    #[test]
391
    fn receives_events() {
392
        let rt = test_setup();
393

            
394
        rt.block_on(async move {
395
            let mut rx = EventReactor::receiver().unwrap();
396
            rx.subscribe(TorEventKind::Empty);
397
            // HACK(eta): give the event reactor time to run
398
            tokio::time::sleep(Duration::from_millis(100)).await;
399
            broadcast(TorEvent::Empty);
400

            
401
            let result = rx.next().await;
402
            assert_eq!(result, Some(TorEvent::Empty));
403
        });
404
    }
405

            
406
    #[test]
407
    fn does_not_send_to_no_subscribers() {
408
        let rt = test_setup();
409

            
410
        rt.block_on(async move {
411
            // this event should just get dropped on the floor, because no subscribers exist
412
            broadcast(TorEvent::Empty);
413

            
414
            let mut rx = EventReactor::receiver().unwrap();
415
            rx.subscribe(TorEventKind::Empty);
416

            
417
            // this shouldn't have an event to receive now
418
            let result = tokio::time::timeout(Duration::from_millis(100), rx.next()).await;
419
            assert!(result.is_err());
420
        });
421
    }
422
}