Skip to main content

plexus_core/plexus/
duplex_gate.rs

1//! BIDIR-8 (BIDIR-5's rule, made a library) — the gate over a duplex call.
2//!
3//! A duplex call is params, then an input half and an output half
4//! (BIDIR-1). [`DuplexGate::open`] decides it as the grant gate decides any
5//! call — once, the method's grant on its target, within the ceiling — and
6//! takes the call's place on its connection ([`CallCounter`]: in a server,
7//! plexus-transport's `ConnectionCalls`, one per connection, a duplex call
8//! counted as one call). The [`DuplexCall`] it answers holds the caller and
9//! admits each input frame **without asking the gate**:
10//!
11//! | when | the gate does | refusal (`error_kind`) | ends the call? |
12//! |---|---|---|---|
13//! | open | [`Gate::check`] once | `forbidden {grant, scope, roles, held_on}` / `unauthenticated` | never opens |
14//! | open, past the connection's calls | count it as any call | `too_many_calls {max}` | never opens |
15//! | an input frame from another connection | compare connection ids | `not_this_call` (to the sender) | no |
16//! | an input frame past credit | compare `seq` with the credit granted | `past_credit {seq, credit}` | yes |
17//! | an input frame past a ceiling its method opted into, or past what one call may hold | count items and bytes | `too_much_input {limit, max}` | yes |
18//! | an input frame out of sequence | the transport compares `seq` with the next expected | `out_of_sequence {seq, expected}` | yes |
19//! | the gate's grants generation moves (grant, revoke, role edit, team, sign-out) | [`Gate::check`] once per call | `forbidden` / `unauthenticated` | yes, items after it dropped |
20//! | the sign-in's expiry | the call's own timer: the caller proves no one | `unauthenticated` | yes |
21//! | a question answered | [`Answerer`]: own connection; a person; or a grant on the target ([`Gate::check`] once per answer) | `not_this_call` / `person_required` / `forbidden` | no |
22//!
23//! A frame's admission is: the half is open, the frame is the call's own
24//! connection's, the gate's generation is the one last verified (one atomic
25//! load), the frame is within credit and the ceiling. So a revoke reaches
26//! every open call at the generation's move — [`DuplexCall::input`] selects
27//! on it, so a quiet call ends then too — and no item ever costs a gate
28//! check. The generation is the gate's own ([`Gate::generation`],
29//! plexus-auth-core): every service that keeps a gate keeps one, and moves
30//! it with [`Gate::moved`] wherever it writes a grant.
31//!
32//! Every typed refusal is one audit record
33//! ([`AuditRecordKind::DuplexRefused`](plexus_auth_core::audit::AuditRecordKind::DuplexRefused)),
34//! built only when it happens and offered to a bounded [`AuditQueue`] that
35//! never waits ([`DuplexGate::with_audit`]): an admitted frame allocates
36//! nothing.
37//!
38//! BIDIR-6's call slot ([`super::input`]), keyed by `(connection,
39//! subscription)`, feeds [`DuplexCall::input`] one [`InputFrame`] for each
40//! `{ns}.input {subscription, seq, items}`. `seq` counts frames; credit counts
41//! items, so a frame carries how many it holds.
42
43use std::sync::atomic::{AtomicU64, Ordering};
44use std::sync::Arc;
45
46use futures::stream::{Stream, StreamExt};
47use plexus_auth_core::audit::{AuditQueue, AuditRecord};
48use plexus_auth_core::duplex::is_person;
49/// The gate's terms for a duplex call (plexus-auth-core), re-exported so a
50/// caller of this module needs no second import.
51pub use plexus_auth_core::duplex::{Answerer, CallCeiling, CallRef, DuplexRefusalCode};
52pub use plexus_auth_core::grants::{GrantsGeneration, GrantsMove};
53use plexus_auth_core::grants::{Gate, Grant, Membership, Memberships, Resolve, RoleTable, ScopeRef};
54use serde_json::{json, Value};
55use tokio::sync::{mpsc, watch};
56
57use super::auth::AuthContext;
58use super::context::PlexusContext;
59use super::plexus::{error_item, PlexusError};
60use super::types::{spec_code, spec_fields, PlexusStreamItem, StreamMetadata};
61use super::RemoteError;
62
63/// A connection, as the transport numbers it.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
65pub struct ConnId(pub u64);
66
67impl From<ConnId> for CallRef {
68    /// A call on `conn` with no subscription named (0) — a test's, or a
69    /// caller that keys calls by connection alone.
70    fn from(conn: ConnId) -> Self {
71        CallRef { conn: conn.0, subscription: 0 }
72    }
73}
74
75/// A call's place on its connection, held for as long as the call is open
76/// and given back when dropped — whatever the counter keeps behind it.
77pub struct CallPlace(#[allow(dead_code)] Box<dyn Send + Sync>);
78
79impl CallPlace {
80    /// A place that gives itself back when `held` is dropped.
81    pub fn new(held: impl Send + Sync + 'static) -> Self {
82        Self(Box::new(held))
83    }
84}
85
86/// The calls open on one connection, as whoever counts them keeps them —
87/// plexus-transport's `ConnectionCalls` in a server (BIDIR-8: the count is
88/// the transport's, so no service writes it). A duplex call is one call.
89pub trait CallCounter: Send + Sync {
90    /// A place for one more call, or the most there may be (`too_many_calls
91    /// {max}`).
92    fn take_place(&self) -> Result<CallPlace, usize>;
93}
94
95/// The wall clock, in unix seconds: when a sign-in expires.
96pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;
97
98fn wall_clock() -> i64 {
99    chrono::Utc::now().timestamp()
100}
101
102/// Why the gate refused a duplex call, a frame or an answer — each typed on
103/// the wire as an error item with its `error_kind`.
104#[derive(Debug, Clone)]
105pub enum DuplexRefusal {
106    /// The grant gate's own refusal (`forbidden`, `unauthenticated`).
107    Gate(PlexusError),
108    TooManyCalls { max: usize },
109    NotThisCall,
110    PastCredit { seq: u64, credit: u64 },
111    TooMuchInput { limit: &'static str, max: u64 },
112    PersonRequired,
113    /// The input half is already closed (a frame after the end).
114    InputClosed,
115    /// A frame out of sequence, on a socket that delivers in order.
116    OutOfSequence { seq: u64, expected: u64 },
117    /// An item of frame `seq` that does not decode as the method's type.
118    InvalidInput { seq: u64, message: String },
119}
120
121impl DuplexRefusal {
122    /// The `error_kind` it goes on the wire as.
123    pub fn kind(&self) -> &'static str {
124        match self {
125            Self::Gate(PlexusError::Forbidden { .. }) => "forbidden",
126            Self::Gate(PlexusError::Unauthenticated(_)) => "unauthenticated",
127            Self::Gate(PlexusError::InvalidParams { .. }) => "invalid_params",
128            Self::Gate(_) => "error",
129            other => other.code().as_str(),
130        }
131    }
132
133    /// The refusal's code: its audit `reason` (a gate refusal other than
134    /// `unauthenticated` is `forbidden`).
135    pub fn code(&self) -> DuplexRefusalCode {
136        match self {
137            Self::Gate(PlexusError::Unauthenticated(_)) => DuplexRefusalCode::Unauthenticated,
138            Self::Gate(_) => DuplexRefusalCode::Forbidden,
139            Self::TooManyCalls { .. } => DuplexRefusalCode::TooManyCalls,
140            Self::NotThisCall => DuplexRefusalCode::NotThisCall,
141            Self::PastCredit { .. } => DuplexRefusalCode::PastCredit,
142            Self::TooMuchInput { .. } => DuplexRefusalCode::TooMuchInput,
143            Self::PersonRequired => DuplexRefusalCode::PersonRequired,
144            Self::InputClosed => DuplexRefusalCode::InputClosed,
145            Self::OutOfSequence { .. } => DuplexRefusalCode::OutOfSequence,
146            Self::InvalidInput { .. } => DuplexRefusalCode::InvalidInput,
147        }
148    }
149
150    /// Whether it ends the call's input half (else it refuses one frame or
151    /// one answer to its sender, and the call runs on).
152    pub fn ends_input(&self) -> bool {
153        !matches!(self, Self::NotThisCall | Self::PersonRequired)
154    }
155
156    /// The gate's own refusal, when it is one.
157    pub fn into_plexus(self) -> Option<PlexusError> {
158        match self {
159            Self::Gate(e) => Some(e),
160            _ => None,
161        }
162    }
163
164    /// The error item: a gate refusal exactly as `{ns}.call` sends one; the
165    /// rest a typed error item (spec/05), `error_kind` and its facts beside
166    /// `message`.
167    pub fn to_item(&self, ns: &str) -> Value {
168        let (message, facts) = match self {
169            Self::Gate(e) => return error_item(ns, e),
170            Self::TooManyCalls { max } => (format!("too many calls open on this connection (at most {max})"), json!({ "max": max })),
171            Self::NotThisCall => ("this call is not yours: input and answers come from the connection that opened it".into(), json!({})),
172            Self::PastCredit { seq, credit } => (format!("item {seq} is past the credit granted ({credit})"), json!({ "seq": seq, "credit": credit })),
173            Self::TooMuchInput { limit, max } => (format!("this call takes at most {max} {limit} of input"), json!({ "limit": limit, "max": max })),
174            Self::PersonRequired => ("this question needs a person's answer".into(), json!({})),
175            Self::InputClosed => ("the input half is closed".into(), json!({})),
176            Self::OutOfSequence { seq, expected } => (format!("input frame {seq} is out of sequence: {expected} comes next"), json!({ "seq": seq, "expected": expected })),
177            Self::InvalidInput { seq, message } => (format!("an item of input frame {seq} is not this method's input: {message}"), json!({ "seq": seq })),
178        };
179        let Value::Object(facts) = facts else { unreachable!("facts are an object") };
180        let metadata = StreamMetadata::new(vec![ns.into()], PlexusContext::hash());
181        // RETURNS-36: an error item carries its typed `RemoteError`; a kind
182        // the vocabulary does not know is `Other`, its facts its fields.
183        let error = match self {
184            Self::TooManyCalls { max } => RemoteError::TooManyCalls { max: *max as u64, child: None },
185            _ => RemoteError::Other(plexus_client::OtherError { kind: self.kind().to_string(), fields: facts }),
186        };
187        let item = PlexusStreamItem::Error {
188            metadata,
189            message,
190            code: Some(spec_code(&error)),
191            recoverable: false,
192            fields: spec_fields(&error),
193            error,
194        };
195        serde_json::to_value(&item).unwrap_or(Value::Null)
196    }
197}
198
199/// What the transport found wrong with a frame when it arrived. It holds
200/// nothing past the first one, so the frame says so and goes through the
201/// same admission as any other, whenever that comes: [`DuplexCall::admit`]
202/// refuses it, whatever the credit has become since.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub enum Overrun {
205    /// More items than the window holds were outstanding: past credit.
206    Credit,
207    /// Out of sequence.
208    Sequence { expected: u64 },
209    /// A frame of no items: a broken client (`invalid_input`).
210    Empty,
211}
212
213/// One input frame as the transport hands it over: which connection sent
214/// it, its `seq`, what it holds, how many items that is, and their size on
215/// the wire.
216#[derive(Debug, Clone)]
217pub struct InputFrame<I = Value> {
218    pub from: ConnId,
219    pub seq: u64,
220    pub item: I,
221    /// Items in the frame: what credit counts.
222    pub items: u64,
223    pub bytes: u64,
224    /// `Some`: the transport refused it on arrival.
225    pub overrun: Option<Overrun>,
226}
227
228impl InputFrame {
229    /// A frame of one item, its size its JSON (a transport has the raw
230    /// length already).
231    pub fn new(from: ConnId, seq: u64, item: Value) -> Self {
232        let bytes = serde_json::to_vec(&item).map(|v| v.len() as u64).unwrap_or(0);
233        Self { from, seq, item, items: 1, bytes, overrun: None }
234    }
235}
236
237/// The credit a call has granted, shared with whoever grants it: the
238/// transport's pipe grants as the handler consumes, on a call that
239/// [`DuplexCall::input`] has taken.
240#[derive(Debug, Clone)]
241pub struct CreditLine(Arc<AtomicU64>);
242
243impl CreditLine {
244    /// `n` more items.
245    pub fn grant(&self, n: u64) {
246        let _ = self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |c| Some(c.saturating_add(n)));
247    }
248
249    /// Every item granted so far.
250    pub fn granted(&self) -> u64 {
251        self.0.load(Ordering::Acquire)
252    }
253}
254
255/// The gate of a service that has none: nobody holds anything, and its
256/// generation is nobody's to move, so a call is never asked again.
257struct Nobody;
258
259impl Memberships for Nobody {
260    fn held(&self, _who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
261        Vec::new()
262    }
263}
264
265impl Resolve for Nobody {
266    fn chain(&self, _target: &str) -> Option<Vec<ScopeRef>> {
267        None
268    }
269}
270
271/// The gate over duplex calls: a [`Gate`] (and its grants generation, which
272/// says when to ask it again), the audit, and the clock expiry is read by.
273#[derive(Clone)]
274pub struct DuplexGate {
275    gate: Gate,
276    checks: Arc<AtomicU64>,
277    audit: Option<AuditQueue>,
278    clock: Clock,
279}
280
281impl DuplexGate {
282    /// The gate over duplex calls in front of `gate`; re-verifies when
283    /// `gate`'s generation ([`Gate::generation`]) moves.
284    pub fn new(gate: Gate) -> Self {
285        Self { gate, checks: Arc::new(AtomicU64::new(0)), audit: None, clock: Arc::new(wall_clock) }
286    }
287
288    /// The duplex gate of a service with no [`Gate`]: as a call on it
289    /// dispatches ungated, a duplex call opens with [`admitted`](Self::admitted)
290    /// and is never asked again; credit, the ceilings and the sign-in's expiry
291    /// hold as on any other.
292    pub fn ungated() -> Self {
293        Self::new(Gate::new(Arc::new(Nobody), Arc::new(RoleTable::new()), Arc::new(Nobody)))
294    }
295
296    /// Every typed refusal to `audit` (one record each, never waiting).
297    pub fn with_audit(mut self, audit: AuditQueue) -> Self {
298        self.audit = Some(audit);
299        self
300    }
301
302    /// When a sign-in expires is read by `clock` (unix seconds; a test's).
303    pub fn with_clock(mut self, clock: Clock) -> Self {
304        self.clock = clock;
305        self
306    }
307
308    /// The grant gate it asks (its [`Gate::generation`], [`Gate::moved`]).
309    pub fn gate(&self) -> &Gate {
310        &self.gate
311    }
312
313    /// How many times the gate has been asked through this one.
314    pub fn gate_checks(&self) -> u64 {
315        self.checks.load(Ordering::Relaxed)
316    }
317
318    fn check(&self, caller: Option<&AuthContext>, grant: &Grant, target: Option<&str>) -> Result<(), DuplexRefusal> {
319        self.checks.fetch_add(1, Ordering::Relaxed);
320        self.gate.check(caller, grant, target).map(drop).map_err(|r| DuplexRefusal::Gate(r.into()))
321    }
322
323    /// The refusal, audited: one record, built here and only here.
324    fn audited(&self, call: CallRef, who: Option<&AuthContext>, grant: &Grant, why: DuplexRefusal) -> DuplexRefusal {
325        if let Some(q) = &self.audit {
326            q.offer(AuditRecord::duplex_refused(call, why.code(), who, grant.as_str()));
327        }
328        why
329    }
330
331    /// Open a duplex call: the gate first (a refusal takes no place), then
332    /// the call's place on its connection. `at` is the call — its
333    /// connection and subscription (a [`ConnId`] alone is subscription 0).
334    #[allow(clippy::too_many_arguments)]
335    pub fn open(
336        &self,
337        at: impl Into<CallRef>,
338        calls: &dyn CallCounter,
339        caller: Option<Arc<AuthContext>>,
340        grant: &str,
341        target: Option<&str>,
342        ceiling: CallCeiling,
343        answer_by: Answerer,
344    ) -> Result<DuplexCall, DuplexRefusal> {
345        let at = at.into();
346        // Subscribe before deciding: a move after the check is a wake.
347        let mut moves = self.gate.generation().subscribe();
348        let seen = *moves.borrow_and_update();
349        let grant = Grant::new(grant);
350        if let Err(e) = self.check(caller.as_deref(), &grant, target) {
351            return Err(self.audited(at, caller.as_deref(), &grant, e));
352        }
353        let targets = target.map(str::to_string).into_iter().collect();
354        self.opened(at, calls, caller, grant, targets, seen, moves, true, ceiling, answer_by)
355    }
356
357    /// BIDIR-6: open a call the service's dispatch has already decided, so
358    /// the decision is still made once. `seen` is the generation read before
359    /// that decision: a move since is found at the first frame (or at once,
360    /// by [`DuplexCall::input`]). `recheck` false: the method is one the gate
361    /// admits whoever calls (`public`, a signed-in grant), so a move asks
362    /// nothing; the sign-in's expiry still holds. `targets`: every value the
363    /// dispatch checked, asked again together.
364    #[allow(clippy::too_many_arguments)]
365    pub fn admitted(
366        &self,
367        at: impl Into<CallRef>,
368        calls: &dyn CallCounter,
369        caller: Option<Arc<AuthContext>>,
370        grant: &str,
371        targets: Vec<String>,
372        seen: u64,
373        recheck: bool,
374        ceiling: CallCeiling,
375        answer_by: Answerer,
376    ) -> Result<DuplexCall, DuplexRefusal> {
377        let mut moves = self.gate.generation().subscribe();
378        moves.mark_changed();
379        self.opened(at.into(), calls, caller, Grant::new(grant), targets, seen, moves, recheck, ceiling, answer_by)
380    }
381
382    #[allow(clippy::too_many_arguments)]
383    fn opened(
384        &self,
385        at: CallRef,
386        calls: &dyn CallCounter,
387        caller: Option<Arc<AuthContext>>,
388        grant: Grant,
389        targets: Vec<String>,
390        seen: u64,
391        moves: watch::Receiver<u64>,
392        recheck: bool,
393        ceiling: CallCeiling,
394        answer_by: Answerer,
395    ) -> Result<DuplexCall, DuplexRefusal> {
396        let place = match calls.take_place() {
397            Ok(p) => p,
398            Err(max) => return Err(self.audited(at, caller.as_deref(), &grant, DuplexRefusal::TooManyCalls { max })),
399        };
400        Ok(DuplexCall {
401            dg: self.clone(),
402            conn: ConnId(at.conn),
403            at,
404            caller,
405            grant,
406            targets,
407            recheck,
408            seen,
409            moves,
410            ceiling,
411            credit: CreditLine(Arc::new(AtomicU64::new(ceiling.credit))),
412            items: 0,
413            bytes: 0,
414            closed: None,
415            answer_by,
416            _place: place,
417        })
418    }
419}
420
421/// One open duplex call, holding its caller (the module docs).
422pub struct DuplexCall {
423    dg: DuplexGate,
424    conn: ConnId,
425    at: CallRef,
426    caller: Option<Arc<AuthContext>>,
427    grant: Grant,
428    targets: Vec<String>,
429    recheck: bool,
430    seen: u64,
431    moves: watch::Receiver<u64>,
432    ceiling: CallCeiling,
433    credit: CreditLine,
434    items: u64,
435    bytes: u64,
436    closed: Option<DuplexRefusal>,
437    answer_by: Answerer,
438    _place: CallPlace,
439}
440
441impl DuplexCall {
442    /// Which call this is: its connection and subscription.
443    pub fn call(&self) -> CallRef {
444        self.at
445    }
446
447    /// Who may answer its questions.
448    pub fn answer_by(&self) -> &Answerer {
449        &self.answer_by
450    }
451
452    /// Why its input half closed, once it has.
453    pub fn closed(&self) -> Option<&DuplexRefusal> {
454        self.closed.as_ref()
455    }
456
457    /// The callee grants `n` more items (the `credit { n }` output item).
458    pub fn grant_credit(&mut self, n: u64) {
459        self.credit.grant(n);
460    }
461
462    /// The handle to go on granting by, once [`input`](Self::input) has the
463    /// call.
464    pub fn credit_line(&self) -> CreditLine {
465        self.credit.clone()
466    }
467
468    fn refuse(&self, why: DuplexRefusal) -> DuplexRefusal {
469        self.dg.audited(self.at, self.caller.as_deref(), &self.grant, why)
470    }
471
472    fn close(&mut self, why: DuplexRefusal) -> DuplexRefusal {
473        let why = self.refuse(why);
474        self.closed = Some(why.clone());
475        why
476    }
477
478    /// The caller, verified again (the generation moved): one gate check.
479    pub fn reverify(&mut self) -> Result<(), DuplexRefusal> {
480        let now = self.dg.gate.generation().current();
481        let asked = if !self.recheck {
482            Ok(())
483        } else if self.targets.is_empty() {
484            self.dg.check(self.caller.as_deref(), &self.grant, None)
485        } else {
486            self.targets.iter().try_for_each(|t| self.dg.check(self.caller.as_deref(), &self.grant, Some(t)))
487        };
488        match asked {
489            Ok(()) => {
490                self.seen = now;
491                Ok(())
492            }
493            Err(e) => Err(self.close(e)),
494        }
495    }
496
497    /// The sign-in's expiry came: the caller proves no one now (the gate
498    /// would say the same — [`Gate::alive`] refuses a context past its
499    /// `expires_at`), so no check is asked. The input half closes.
500    pub fn expire(&mut self) -> DuplexRefusal {
501        self.close(DuplexRefusal::Gate(PlexusError::Unauthenticated("your sign-in has expired: sign in again".into())))
502    }
503
504    /// Admit one input frame — no gate check unless the generation moved.
505    pub fn admit<I>(&mut self, f: &InputFrame<I>) -> Result<(), DuplexRefusal> {
506        if self.closed.is_some() {
507            return Err(self.refuse(DuplexRefusal::InputClosed));
508        }
509        if f.from != self.conn {
510            return Err(self.refuse(DuplexRefusal::NotThisCall));
511        }
512        if self.dg.gate.generation().current() != self.seen {
513            self.reverify()?;
514        }
515        let credit = self.credit.granted();
516        match f.overrun {
517            None => {}
518            Some(Overrun::Credit) => return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit })),
519            Some(Overrun::Sequence { expected }) => return Err(self.close(DuplexRefusal::OutOfSequence { seq: f.seq, expected })),
520            Some(Overrun::Empty) => return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() })),
521        }
522        if f.items == 0 {
523            return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() }));
524        }
525        if self.items.saturating_add(f.items) > credit {
526            return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit }));
527        }
528        if self.items.saturating_add(f.items) > self.ceiling.max_items {
529            return Err(self.close(DuplexRefusal::TooMuchInput { limit: "items", max: self.ceiling.max_items }));
530        }
531        if self.bytes.saturating_add(f.bytes) > self.ceiling.max_bytes {
532            return Err(self.close(DuplexRefusal::TooMuchInput { limit: "bytes", max: self.ceiling.max_bytes }));
533        }
534        self.items = self.items.saturating_add(f.items);
535        self.bytes = self.bytes.saturating_add(f.bytes);
536        Ok(())
537    }
538
539    /// May `who`, on connection `from`, answer a question this call asked?
540    /// By the method's [`Answerer`]; a refusal is audited as `who`'s.
541    pub fn answer(&self, from: ConnId, who: Option<&AuthContext>) -> Result<(), DuplexRefusal> {
542        let refused = |why| Err(self.dg.audited(self.at, who, &self.grant, why));
543        if self.closed.is_some() {
544            return refused(DuplexRefusal::InputClosed);
545        }
546        match &self.answer_by {
547            Answerer::Caller if from == self.conn => Ok(()),
548            Answerer::Person if from == self.conn => match who {
549                Some(w) if is_person(w) => Ok(()),
550                _ => refused(DuplexRefusal::PersonRequired),
551            },
552            Answerer::Caller | Answerer::Person => refused(DuplexRefusal::NotThisCall),
553            Answerer::Grant(g) => match self.dg.check(who, &Grant::new(g.clone()), self.targets.first().map(String::as_str)) {
554                Ok(()) => Ok(()),
555                Err(e) => refused(e),
556            },
557        }
558    }
559
560    /// The handler's input: the frames as they come, each admitted; the
561    /// generation and the sign-in's expiry selected beside them, so a quiet
562    /// call ends at a revoke. A frame from another connection is refused to
563    /// its sender on `refused` and the call runs on; any other refusal is
564    /// the stream's last item, and what follows is never read (dropped).
565    pub fn input<S, I>(mut self, frames: S, refused: mpsc::UnboundedSender<(ConnId, Value)>) -> impl Stream<Item = Result<I, DuplexRefusal>> + Send + 'static
566    where
567        S: Stream<Item = InputFrame<I>> + Send + 'static,
568        I: Send + 'static,
569    {
570        let ns = self.grant.as_str().split('.').next().unwrap_or("").to_string();
571        let expires = self
572            .caller
573            .as_ref()
574            .and_then(|c| c.metadata.get(plexus_auth_core::auth::EXPIRES_AT_KEY))
575            .and_then(Value::as_i64);
576        let now = (self.dg.clock)();
577        async_stream::stream! {
578            let frames = frames;
579            futures::pin_mut!(frames);
580            let expiry = async move {
581                match expires {
582                    Some(at) => {
583                        let secs = at.saturating_sub(now).max(0) as u64;
584                        tokio::time::sleep(std::time::Duration::from_secs(secs)).await
585                    }
586                    None => std::future::pending().await,
587                }
588            };
589            futures::pin_mut!(expiry);
590            loop {
591                tokio::select! {
592                    biased;
593                    moved = self.moves.changed() => {
594                        // Already verified at this generation (a frame
595                        // found the move first): nothing to ask again.
596                        if moved.is_err() || self.dg.gate.generation().current() == self.seen { continue; }
597                        if let Err(e) = self.reverify() { yield Err(e); break; }
598                    }
599                    () = &mut expiry => {
600                        yield Err(self.expire());
601                        break;
602                    }
603                    f = frames.next() => match f {
604                        None => break,
605                        Some(f) => match self.admit(&f) {
606                            Ok(()) => yield Ok(f.item),
607                            Err(e) if !e.ends_input() => { let _ = refused.send((f.from, e.to_item(&ns))); }
608                            Err(e) => { yield Err(e); break; }
609                        },
610                    },
611                }
612            }
613        }
614    }
615}