Skip to main content

rtci_host/
ask_gate.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! [`AskGate`]: an asynchronous [`NetGate`] whose questions a front end
4//! reads as [`GateRequest`]s (the `gaterequest` event) and answers by
5//! ticket with [`AskGate::answer`]. `rtci-ffi`'s gate is one: JavaScript
6//! answers each request from `Deno.permissions`.
7
8use std::cell::RefCell;
9use std::collections::HashMap;
10use std::collections::VecDeque;
11use std::rc::Rc;
12use std::rc::Weak;
13use std::time::Duration;
14
15use serde::Serialize;
16use tokio::sync::oneshot;
17
18use crate::gate::DEFAULT_ASK_TIMEOUT;
19use crate::gate::Host;
20use crate::gate::LocalBoxFuture;
21use crate::gate::NetGate;
22use crate::gate::Reach;
23use crate::gate::ReachKey;
24use crate::gate::Verdict;
25
26/// The refusal for every question asked before [`AskGate::attach`].
27pub const NO_GATE_REGISTERED: &str = "no permission gate registered";
28
29/// One question for the front end: the `gaterequest` event.
30///
31/// Serializes as
32/// `{"type":"gaterequest","ticket":1,"kind":"remoteCandidate","dir":"connect","proto":"udp","host":"192.0.2.1","port":5000,"resolvedFrom":null}`.
33/// `kind` is a [`ReachKind`](crate::ReachKind) name, or `"interfaces"` for
34/// the interface-list question (whose `dir`, `proto`, `host`, `port` and
35/// `resolvedFrom` are `null`). `host` is a name or an IP address (an IPv6
36/// one without brackets); `port` is `null` for a bind (any port).
37#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
38#[serde(tag = "type", rename = "gaterequest", rename_all = "camelCase")]
39pub struct GateRequest {
40  /// What [`AskGate::answer`] takes.
41  pub ticket: u32,
42  pub kind: &'static str,
43  pub dir: Option<&'static str>,
44  pub proto: Option<&'static str>,
45  pub host: Option<String>,
46  pub port: Option<u16>,
47  pub resolved_from: Option<String>,
48  /// The question itself (`None` for the interface list).
49  #[serde(skip)]
50  pub reach: Option<Reach>,
51}
52
53impl GateRequest {
54  fn new(ticket: u32, reach: Option<Reach>) -> Self {
55    match reach {
56      Some(r) => Self {
57        ticket,
58        kind: r.kind.as_str(),
59        dir: Some(r.dir.as_str()),
60        proto: Some(r.proto.as_str()),
61        host: Some(match &r.host {
62          Host::Name(name) => name.clone(),
63          Host::Ip(ip) => ip.to_string(),
64        }),
65        port: r.port,
66        resolved_from: r.resolved_from.clone(),
67        reach: Some(r),
68      },
69      None => Self {
70        ticket,
71        kind: "interfaces",
72        dir: None,
73        proto: None,
74        host: None,
75        port: None,
76        resolved_from: None,
77        reach: None,
78      },
79    }
80  }
81}
82
83/// What an answer is remembered by.
84#[derive(Clone, PartialEq, Eq, Hash)]
85enum Key {
86  Reach(ReachKey),
87  Interfaces,
88}
89
90#[derive(Default)]
91struct State {
92  attached: bool,
93  last_ticket: u32,
94  /// Unanswered tickets: what they ask and where the answer goes.
95  pending: HashMap<u32, (Key, oneshot::Sender<Verdict>)>,
96  /// Requests the front end hasn't taken yet.
97  queue: VecDeque<GateRequest>,
98  /// Answers given, reused by `decide` (for every connection on this gate).
99  answers: HashMap<Key, Verdict>,
100  timeout: Option<Duration>,
101}
102
103#[derive(Default)]
104struct Inner {
105  state: RefCell<State>,
106  notify: RefCell<Option<Rc<dyn Fn()>>>,
107}
108
109/// An asynchronous gate answered by ticket. Deny by default: until
110/// [`AskGate::attach`] every question is refused at once
111/// ([`NO_GATE_REGISTERED`]). Once attached, each question the engine asks
112/// queues a [`GateRequest`] ([`AskGate::take_requests`]) and runs the
113/// notifier ([`AskGate::set_notify`]); [`AskGate::answer`] delivers the
114/// verdict. An answer is remembered and reused for the same question from
115/// any connection on this gate ([`NetGate::decide`]).
116///
117/// A request the engine stops waiting for (its connection closed, or
118/// [`NetGate::ask_timeout`] passed, which is a refusal) leaves the queue
119/// and its ticket: a later `answer` for it returns `false`. Dropping the
120/// last clone, or [`AskGate::detach`], refuses everything pending.
121///
122/// Single-threaded, like the engine: answer on the engine's thread.
123#[derive(Clone, Default)]
124pub struct AskGate {
125  inner: Rc<Inner>,
126}
127
128impl AskGate {
129  /// A detached gate (every question refused).
130  pub fn new() -> Self {
131    Self::default()
132  }
133
134  /// Starts asking (a front end registered its handler).
135  pub fn attach(&self) {
136    self.inner.state.borrow_mut().attached = true;
137  }
138
139  /// Stops asking: everything pending is refused, and so is every later
140  /// question that wasn't answered before.
141  pub fn detach(&self) {
142    let pending: Vec<_> = {
143      let mut state = self.inner.state.borrow_mut();
144      state.attached = false;
145      state.queue.clear();
146      state.pending.drain().map(|(_, (_, tx))| tx).collect()
147    };
148    for tx in pending {
149      let _ = tx.send(Verdict::Deny(NO_GATE_REGISTERED.to_string()));
150    }
151  }
152
153  pub fn is_attached(&self) -> bool {
154    self.inner.state.borrow().attached
155  }
156
157  /// Runs after each request is queued (a front end wakes its event loop
158  /// here). It must not call back into the engine.
159  pub fn set_notify(&self, f: impl Fn() + 'static) {
160    *self.inner.notify.borrow_mut() = Some(Rc::new(f));
161  }
162
163  /// How long the engine waits for an answer (default
164  /// [`DEFAULT_ASK_TIMEOUT`]).
165  pub fn set_timeout(&self, timeout: Duration) {
166    self.inner.state.borrow_mut().timeout = Some(timeout);
167  }
168
169  /// The requests queued since the last call, oldest first.
170  pub fn take_requests(&self) -> Vec<GateRequest> {
171    self.inner.state.borrow_mut().queue.drain(..).collect()
172  }
173
174  /// Tickets waiting for an answer.
175  pub fn pending(&self) -> usize {
176    self.inner.state.borrow().pending.len()
177  }
178
179  /// Answers `ticket`. `false` when no one waits for it any more (an
180  /// unknown ticket, answered already, timed out, or its connection
181  /// closed). The verdict is remembered either way for a known question.
182  pub fn answer(&self, ticket: u32, verdict: Verdict) -> bool {
183    let entry = {
184      let mut state = self.inner.state.borrow_mut();
185      let entry = state.pending.remove(&ticket);
186      if let Some((key, _)) = &entry {
187        state.answers.insert(key.clone(), verdict.clone());
188      }
189      state.queue.retain(|r| r.ticket != ticket);
190      entry
191    };
192    match entry {
193      Some((_, tx)) => tx.send(verdict).is_ok(),
194      None => false,
195    }
196  }
197
198  fn ask_key(
199    &self,
200    key: Key,
201    reach: Option<Reach>,
202  ) -> LocalBoxFuture<'static, Verdict> {
203    let (ticket, rx) = {
204      let mut state = self.inner.state.borrow_mut();
205      if !state.attached {
206        return Box::pin(std::future::ready(Verdict::Deny(
207          NO_GATE_REGISTERED.to_string(),
208        )));
209      }
210      if let Some(verdict) = state.answers.get(&key) {
211        return Box::pin(std::future::ready(verdict.clone()));
212      }
213      let mut ticket = state.last_ticket.wrapping_add(1).max(1);
214      while state.pending.contains_key(&ticket) {
215        ticket = ticket.wrapping_add(1).max(1);
216      }
217      state.last_ticket = ticket;
218      let (tx, rx) = oneshot::channel();
219      state.pending.insert(ticket, (key, tx));
220      state.queue.push_back(GateRequest::new(ticket, reach));
221      (ticket, rx)
222    };
223    let notify = self.inner.notify.borrow().clone();
224    if let Some(f) = notify {
225      f();
226    }
227    let guard = TicketGuard {
228      inner: Rc::downgrade(&self.inner),
229      ticket,
230    };
231    Box::pin(async move {
232      let _guard = guard;
233      rx.await.unwrap_or_else(|_| {
234        Verdict::Deny("The permission request was dropped".to_string())
235      })
236    })
237  }
238}
239
240/// Withdraws a ticket whose future was dropped unanswered.
241struct TicketGuard {
242  inner: Weak<Inner>,
243  ticket: u32,
244}
245
246impl Drop for TicketGuard {
247  fn drop(&mut self) {
248    if let Some(inner) = self.inner.upgrade()
249      && let Ok(mut state) = inner.state.try_borrow_mut()
250    {
251      state.pending.remove(&self.ticket);
252      state.queue.retain(|r| r.ticket != self.ticket);
253    }
254  }
255}
256
257impl NetGate for AskGate {
258  fn decide(&self, reach: &Reach) -> Option<Verdict> {
259    let state = self.inner.state.borrow();
260    if !state.attached {
261      return Some(Verdict::Deny(NO_GATE_REGISTERED.to_string()));
262    }
263    state
264      .answers
265      .get(&Key::Reach(ReachKey::from(reach)))
266      .cloned()
267  }
268
269  fn ask(&self, reach: Reach) -> LocalBoxFuture<'static, Verdict> {
270    self.ask_key(Key::Reach(ReachKey::from(&reach)), Some(reach))
271  }
272
273  fn interfaces(&self) -> Option<Verdict> {
274    let state = self.inner.state.borrow();
275    if !state.attached {
276      return Some(Verdict::Deny(NO_GATE_REGISTERED.to_string()));
277    }
278    state.answers.get(&Key::Interfaces).cloned()
279  }
280
281  fn ask_interfaces(&self) -> LocalBoxFuture<'static, Verdict> {
282    self.ask_key(Key::Interfaces, None)
283  }
284
285  fn ask_timeout(&self) -> Duration {
286    self
287      .inner
288      .state
289      .borrow()
290      .timeout
291      .unwrap_or(DEFAULT_ASK_TIMEOUT)
292  }
293}