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
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53
#![warn(unnameable_types)]
54

            
55
pub mod events;
56

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

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

            
84
/// The size of the internal broadcast channel used to implement event subscription.
85
pub static BROADCAST_CAPACITY: usize = 512;
86

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

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

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

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

            
196
impl futures::stream::Stream for TorEventReceiver {
197
    type Item = TorEvent;
198

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

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

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

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

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

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

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

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

            
344
    #[test]
345
    fn subscriptions() {
346
        let rt = test_setup();
347

            
348
        rt.block_on(async move {
349
            // shouldn't have any subscribers at the start
350
            assert!(!event_has_subscribers(TorEventKind::Empty));
351

            
352
            let mut rx = EventReactor::receiver().unwrap();
353
            // creating a receiver shouldn't result in any subscriptions
354
            assert!(!event_has_subscribers(TorEventKind::Empty));
355

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

            
360
            rx.unsubscribe(TorEventKind::Empty);
361
            // unsubscribing should work
362
            assert!(!event_has_subscribers(TorEventKind::Empty));
363

            
364
            // subscription should be idempotent
365
            rx.subscribe(TorEventKind::Empty);
366
            rx.subscribe(TorEventKind::Empty);
367
            rx.subscribe(TorEventKind::Empty);
368
            assert!(event_has_subscribers(TorEventKind::Empty));
369

            
370
            rx.unsubscribe(TorEventKind::Empty);
371
            assert!(!event_has_subscribers(TorEventKind::Empty));
372

            
373
            rx.subscribe(TorEventKind::Empty);
374
            assert!(event_has_subscribers(TorEventKind::Empty));
375

            
376
            std::mem::drop(rx);
377
            // dropping the receiver should auto-unsubscribe
378
            assert!(!event_has_subscribers(TorEventKind::Empty));
379
        });
380
    }
381

            
382
    #[test]
383
    fn empty_recv() {
384
        let rt = test_setup();
385

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

            
394
    #[test]
395
    fn receives_events() {
396
        let rt = test_setup();
397

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

            
405
            let result = rx.next().await;
406
            assert_eq!(result, Some(TorEvent::Empty));
407
        });
408
    }
409

            
410
    #[test]
411
    fn does_not_send_to_no_subscribers() {
412
        let rt = test_setup();
413

            
414
        rt.block_on(async move {
415
            // this event should just get dropped on the floor, because no subscribers exist
416
            broadcast(TorEvent::Empty);
417

            
418
            let mut rx = EventReactor::receiver().unwrap();
419
            rx.subscribe(TorEventKind::Empty);
420

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