Skip to main content

moq_ext_access/policy/
queue.rs

1//! A policy that hands each decision to the application.
2
3use std::fmt;
4
5use super::{Authorization, Decision, PeerRequest, Policy, Rejection};
6use crate::PeerId;
7
8/// A policy that hands each decision to the application, through a bounded queue.
9///
10/// The application takes the requests with [`next`](Self::next) and answers
11/// each [`Pending`] with [`admit`](Pending::admit) or
12/// [`reject`](Pending::reject). Clones share one queue, so the node can hold
13/// the policy while the application holds a clone to answer from.
14///
15/// A request that finds the queue full is rejected at once with
16/// [`moq_net::Error::TooManyRequests`], so a slow application does not pile up
17/// sessions whose peers wait. A node also gives up on a decision after its
18/// decide timeout, such as `NodeConfig::decide_timeout` in iroh-live-node,
19/// which is 10 seconds there by default. Raise it when a person answers.
20///
21/// # Examples
22///
23/// Admit the peers that present a known token:
24///
25/// ```
26/// use moq_ext_access::{
27///     Grant,
28///     policy::{Queue, Rejection},
29/// };
30///
31/// # async fn run() {
32/// let queue = Queue::<String>::new(16);
33/// // Give `queue.clone()` to the node as its policy, then answer:
34/// while let Some(pending) = queue.next().await {
35///     if pending.request().token() == Some("secret") {
36///         pending.admit(Grant::subscribe_only());
37///     } else {
38///         pending.reject(Rejection::new("unknown token"));
39///     }
40/// }
41/// # }
42/// ```
43#[derive(Clone)]
44pub struct Queue<P: PeerId> {
45    sender: async_channel::Sender<Pending<P>>,
46    receiver: async_channel::Receiver<Pending<P>>,
47}
48
49impl<P: PeerId> fmt::Debug for Queue<P> {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        f.debug_struct("Queue")
52            .field("waiting", &self.receiver.len())
53            .field("closed", &self.receiver.is_closed())
54            .finish()
55    }
56}
57
58impl<P: PeerId> Queue<P> {
59    /// Creates a queue that holds up to `capacity` requests.
60    ///
61    /// A request that finds the queue full is rejected with
62    /// [`moq_net::Error::TooManyRequests`]. A node treats that as no answer
63    /// when it asks again about a live peer: the peer keeps its
64    /// authorization, and the node asks again later.
65    ///
66    /// # Panics
67    ///
68    /// Panics if `capacity` is zero.
69    #[must_use]
70    pub fn new(capacity: usize) -> Self {
71        let (sender, receiver) = async_channel::bounded(capacity);
72        Self { sender, receiver }
73    }
74
75    /// Waits for the next request to answer.
76    ///
77    /// Returns `None` once the queue is closed and empty. Cancellation safe:
78    /// dropping the future loses no request.
79    pub async fn next(&self) -> Option<Pending<P>> {
80        self.receiver.recv().await.ok()
81    }
82
83    /// Closes the queue for every clone.
84    ///
85    /// Requests that arrive later are rejected. The ones already queued stay
86    /// for [`next`](Self::next), which returns `None` after them.
87    pub fn close(&self) {
88        self.sender.close();
89    }
90}
91
92impl<P: PeerId> Policy<P> for Queue<P> {
93    async fn decide(&self, request: &PeerRequest<P>) -> Decision {
94        let (reply, answer) = async_channel::bounded(1);
95        let pending = Pending {
96            request: request.clone(),
97            reply,
98        };
99        if let Err(err) = self.sender.try_send(pending) {
100            return Err(match err {
101                async_channel::TrySendError::Full(_) => {
102                    Rejection::new("the admission queue is full")
103                        .with_code(moq_net::Error::TooManyRequests)
104                }
105                // A closed queue admits nobody any more.
106                async_channel::TrySendError::Closed(_) => {
107                    Rejection::new("the admission queue is closed")
108                }
109            });
110        }
111        // A dropped `Pending` drops its sender, which ends the receive.
112        answer
113            .recv()
114            .await
115            .unwrap_or_else(|_| Err(Rejection::new("not answered")))
116    }
117}
118
119/// A request waiting in a [`Queue`] for the application's answer.
120///
121/// Dropping it without an answer rejects the request.
122pub struct Pending<P: PeerId> {
123    request: PeerRequest<P>,
124    reply: async_channel::Sender<Decision>,
125}
126
127impl<P: PeerId> fmt::Debug for Pending<P> {
128    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129        f.debug_struct("Pending")
130            .field("request", &self.request)
131            .finish_non_exhaustive()
132    }
133}
134
135impl<P: PeerId> Pending<P> {
136    /// Returns the request to answer.
137    #[must_use]
138    pub fn request(&self) -> &PeerRequest<P> {
139        &self.request
140    }
141
142    /// Admits the peer with `authorization`, such as a [`Grant`](crate::Grant).
143    ///
144    /// Does nothing if the node no longer waits, for example after its
145    /// decide timeout.
146    pub fn admit(self, authorization: impl Into<Authorization>) {
147        self.answer(Ok(authorization.into()));
148    }
149
150    /// Rejects the peer, which closes its session with the rejection's code.
151    pub fn reject(self, rejection: Rejection) {
152        self.answer(Err(rejection));
153    }
154
155    /// Sends `decision` to the node, if it still waits.
156    fn answer(self, decision: Decision) {
157        // The channel holds one answer, so it is never full. A closed one
158        // means nobody waits anymore.
159        self.reply.try_send(decision).ok();
160    }
161}