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    /// KEEL-54 (R4): `reach` asked again by the rule it was given by — every
324    /// target the dispatch checked, or (none) the reach whole. KEEL-59: the
325    /// one rule a plain call is held to as well ([`super::held::redecide`]),
326    /// so a reach that lost a scope ends a duplex call as it ends any other.
327    fn recheck(&self, reach: &plexus_auth_core::grants::Reach, targets: &[String]) -> Result<(), DuplexRefusal> {
328        self.checks.fetch_add(1, Ordering::Relaxed);
329        super::held::redecide(&self.gate, reach, targets).map_err(|r| DuplexRefusal::Gate(r.into()))
330    }
331
332    /// The refusal, audited: one record, built here and only here.
333    fn audited(&self, call: CallRef, who: Option<&AuthContext>, grant: &Grant, why: DuplexRefusal) -> DuplexRefusal {
334        if let Some(q) = &self.audit {
335            q.offer(AuditRecord::duplex_refused(call, why.code(), who, grant.as_str()));
336        }
337        why
338    }
339
340    /// Open a duplex call: the gate first (a refusal takes no place), then
341    /// the call's place on its connection. `at` is the call — its
342    /// connection and subscription (a [`ConnId`] alone is subscription 0).
343    #[allow(clippy::too_many_arguments)]
344    pub fn open(
345        &self,
346        at: impl Into<CallRef>,
347        calls: &dyn CallCounter,
348        caller: Option<Arc<AuthContext>>,
349        grant: &str,
350        target: Option<&str>,
351        ceiling: CallCeiling,
352        answer_by: Answerer,
353    ) -> Result<DuplexCall, DuplexRefusal> {
354        let at = at.into();
355        // Subscribe before deciding: a move after the check is a wake.
356        let mut moves = self.gate.generation().subscribe();
357        let seen = *moves.borrow_and_update();
358        let grant = Grant::new(grant);
359        if let Err(e) = self.check(caller.as_deref(), &grant, target) {
360            return Err(self.audited(at, caller.as_deref(), &grant, e));
361        }
362        let targets = target.map(str::to_string).into_iter().collect();
363        self.opened(at, calls, caller, grant, targets, seen, moves, true, ceiling, answer_by)
364    }
365
366    /// BIDIR-6: open a call the service's dispatch has already decided, so
367    /// the decision is still made once. `seen` is the generation read before
368    /// that decision: a move since is found at the first frame (or at once,
369    /// by [`DuplexCall::input`]). `recheck` false: the method is one the gate
370    /// admits whoever calls (`public`, a signed-in grant), so a move asks
371    /// nothing; the sign-in's expiry still holds. `targets`: every value the
372    /// dispatch checked, asked again together.
373    #[allow(clippy::too_many_arguments)]
374    pub fn admitted(
375        &self,
376        at: impl Into<CallRef>,
377        calls: &dyn CallCounter,
378        caller: Option<Arc<AuthContext>>,
379        grant: &str,
380        targets: Vec<String>,
381        seen: u64,
382        recheck: bool,
383        ceiling: CallCeiling,
384        answer_by: Answerer,
385    ) -> Result<DuplexCall, DuplexRefusal> {
386        let mut moves = self.gate.generation().subscribe();
387        moves.mark_changed();
388        let grant = Grant::new(grant);
389        // KEEL-54 (R4): the decision the dispatch made, kept — the reach the
390        // call runs under, when it is for this grant — so a move asks the
391        // gate again by the rule it was admitted by (`*` alone, a door, a
392        // target), never "held anywhere" re-derived from the terms.
393        let ctx = crate::call::context().ok();
394        let decided = ctx.as_ref().and_then(|c| c.reach().cloned()).filter(|r| r.grant() == Some(&grant));
395        // KEEL-59 (H1): the dispatch's hold keeps the call for its whole
396        // life — after the client ended its input, and after the handler let
397        // it go, when nothing polls this half any more; this half's own
398        // check, asked by the same rule (`held::redecide`), only says it
399        // sooner while it is open. Whichever ends first, the call ends once.
400        let mut call = self.opened(at.into(), calls, caller, grant, targets, seen, moves, recheck, ceiling, answer_by)?;
401        call.decided = decided;
402        Ok(call)
403    }
404
405    #[allow(clippy::too_many_arguments)]
406    fn opened(
407        &self,
408        at: CallRef,
409        calls: &dyn CallCounter,
410        caller: Option<Arc<AuthContext>>,
411        grant: Grant,
412        targets: Vec<String>,
413        seen: u64,
414        moves: watch::Receiver<u64>,
415        recheck: bool,
416        ceiling: CallCeiling,
417        answer_by: Answerer,
418    ) -> Result<DuplexCall, DuplexRefusal> {
419        let place = match calls.take_place() {
420            Ok(p) => p,
421            Err(max) => return Err(self.audited(at, caller.as_deref(), &grant, DuplexRefusal::TooManyCalls { max })),
422        };
423        Ok(DuplexCall {
424            dg: self.clone(),
425            conn: ConnId(at.conn),
426            at,
427            caller,
428            grant,
429            targets,
430            recheck,
431            seen,
432            moves,
433            ceiling,
434            credit: CreditLine(Arc::new(AtomicU64::new(ceiling.credit))),
435            items: 0,
436            bytes: 0,
437            closed: None,
438            answer_by,
439            decided: None,
440            _place: place,
441        })
442    }
443}
444
445/// One open duplex call, holding its caller (the module docs).
446pub struct DuplexCall {
447    dg: DuplexGate,
448    conn: ConnId,
449    at: CallRef,
450    caller: Option<Arc<AuthContext>>,
451    grant: Grant,
452    targets: Vec<String>,
453    recheck: bool,
454    seen: u64,
455    moves: watch::Receiver<u64>,
456    ceiling: CallCeiling,
457    credit: CreditLine,
458    items: u64,
459    bytes: u64,
460    closed: Option<DuplexRefusal>,
461    answer_by: Answerer,
462    /// KEEL-54 (R4): the reach the dispatch admitted the call under, asked
463    /// again by its own rule at a move.
464    decided: Option<plexus_auth_core::grants::Reach>,
465    _place: CallPlace,
466}
467
468impl DuplexCall {
469    /// Which call this is: its connection and subscription.
470    pub fn call(&self) -> CallRef {
471        self.at
472    }
473
474    /// Who may answer its questions.
475    pub fn answer_by(&self) -> &Answerer {
476        &self.answer_by
477    }
478
479    /// Why its input half closed, once it has.
480    pub fn closed(&self) -> Option<&DuplexRefusal> {
481        self.closed.as_ref()
482    }
483
484    /// The callee grants `n` more items (the `credit { n }` output item).
485    pub fn grant_credit(&mut self, n: u64) {
486        self.credit.grant(n);
487    }
488
489    /// The handle to go on granting by, once [`input`](Self::input) has the
490    /// call.
491    pub fn credit_line(&self) -> CreditLine {
492        self.credit.clone()
493    }
494
495    fn refuse(&self, why: DuplexRefusal) -> DuplexRefusal {
496        self.dg.audited(self.at, self.caller.as_deref(), &self.grant, why)
497    }
498
499    fn close(&mut self, why: DuplexRefusal) -> DuplexRefusal {
500        let why = self.refuse(why);
501        self.closed = Some(why.clone());
502        why
503    }
504
505    /// The caller, verified again (the generation moved): one gate check.
506    pub fn reverify(&mut self) -> Result<(), DuplexRefusal> {
507        let now = self.dg.gate.generation().current();
508        let asked = if !self.recheck {
509            Ok(())
510        } else if let Some(reach) = &self.decided {
511            self.dg.recheck(reach, &self.targets)
512        } else if self.targets.is_empty() {
513            self.dg.check(self.caller.as_deref(), &self.grant, None)
514        } else {
515            self.targets.iter().try_for_each(|t| self.dg.check(self.caller.as_deref(), &self.grant, Some(t)))
516        };
517        match asked {
518            Ok(()) => {
519                self.seen = now;
520                Ok(())
521            }
522            Err(e) => Err(self.close(e)),
523        }
524    }
525
526    /// The sign-in's expiry came: the caller proves no one now (the gate
527    /// would say the same — [`Gate::alive`] refuses a context past its
528    /// `expires_at`), so no check is asked. The input half closes.
529    pub fn expire(&mut self) -> DuplexRefusal {
530        self.close(DuplexRefusal::Gate(PlexusError::Unauthenticated("your sign-in has expired: sign in again".into())))
531    }
532
533    /// Admit one input frame — no gate check unless the generation moved.
534    pub fn admit<I>(&mut self, f: &InputFrame<I>) -> Result<(), DuplexRefusal> {
535        if self.closed.is_some() {
536            return Err(self.refuse(DuplexRefusal::InputClosed));
537        }
538        if f.from != self.conn {
539            return Err(self.refuse(DuplexRefusal::NotThisCall));
540        }
541        if self.dg.gate.generation().current() != self.seen {
542            self.reverify()?;
543        }
544        let credit = self.credit.granted();
545        match f.overrun {
546            None => {}
547            Some(Overrun::Credit) => return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit })),
548            Some(Overrun::Sequence { expected }) => return Err(self.close(DuplexRefusal::OutOfSequence { seq: f.seq, expected })),
549            Some(Overrun::Empty) => return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() })),
550        }
551        if f.items == 0 {
552            return Err(self.close(DuplexRefusal::InvalidInput { seq: f.seq, message: "an input frame with no items".into() }));
553        }
554        if self.items.saturating_add(f.items) > credit {
555            return Err(self.close(DuplexRefusal::PastCredit { seq: f.seq, credit }));
556        }
557        if self.items.saturating_add(f.items) > self.ceiling.max_items {
558            return Err(self.close(DuplexRefusal::TooMuchInput { limit: "items", max: self.ceiling.max_items }));
559        }
560        if self.bytes.saturating_add(f.bytes) > self.ceiling.max_bytes {
561            return Err(self.close(DuplexRefusal::TooMuchInput { limit: "bytes", max: self.ceiling.max_bytes }));
562        }
563        self.items = self.items.saturating_add(f.items);
564        self.bytes = self.bytes.saturating_add(f.bytes);
565        Ok(())
566    }
567
568    /// May `who`, on connection `from`, answer a question this call asked?
569    /// By the method's [`Answerer`]; a refusal is audited as `who`'s.
570    pub fn answer(&self, from: ConnId, who: Option<&AuthContext>) -> Result<(), DuplexRefusal> {
571        let refused = |why| Err(self.dg.audited(self.at, who, &self.grant, why));
572        if self.closed.is_some() {
573            return refused(DuplexRefusal::InputClosed);
574        }
575        match &self.answer_by {
576            Answerer::Caller if from == self.conn => Ok(()),
577            Answerer::Person if from == self.conn => match who {
578                Some(w) if is_person(w) => Ok(()),
579                _ => refused(DuplexRefusal::PersonRequired),
580            },
581            Answerer::Caller | Answerer::Person => refused(DuplexRefusal::NotThisCall),
582            Answerer::Grant(g) => match self.dg.check(who, &Grant::new(g.clone()), self.targets.first().map(String::as_str)) {
583                Ok(()) => Ok(()),
584                Err(e) => refused(e),
585            },
586        }
587    }
588
589    /// The handler's input: the frames as they come, each admitted; the
590    /// generation and the sign-in's expiry selected beside them, so a quiet
591    /// call ends at a revoke. A frame from another connection is refused to
592    /// its sender on `refused` and the call runs on; any other refusal is
593    /// the stream's last item, and what follows is never read (dropped).
594    pub fn input<S, I>(mut self, frames: S, refused: mpsc::UnboundedSender<(ConnId, Value)>) -> impl Stream<Item = Result<I, DuplexRefusal>> + Send + 'static
595    where
596        S: Stream<Item = InputFrame<I>> + Send + 'static,
597        I: Send + 'static,
598    {
599        let ns = self.grant.as_str().split('.').next().unwrap_or("").to_string();
600        let expires = self
601            .caller
602            .as_ref()
603            .and_then(|c| c.metadata.get(plexus_auth_core::auth::EXPIRES_AT_KEY))
604            .and_then(Value::as_i64);
605        let now = (self.dg.clock)();
606        async_stream::stream! {
607            let frames = frames;
608            futures::pin_mut!(frames);
609            let expiry = async move {
610                match expires {
611                    Some(at) => {
612                        let secs = at.saturating_sub(now).max(0) as u64;
613                        crate::rt::sleep(std::time::Duration::from_secs(secs)).await
614                    }
615                    None => std::future::pending().await,
616                }
617            };
618            futures::pin_mut!(expiry);
619            loop {
620                tokio::select! {
621                    biased;
622                    moved = self.moves.changed() => {
623                        // Already verified at this generation (a frame
624                        // found the move first): nothing to ask again.
625                        if moved.is_err() || self.dg.gate.generation().current() == self.seen { continue; }
626                        if let Err(e) = self.reverify() { yield Err(e); break; }
627                    }
628                    () = &mut expiry => {
629                        yield Err(self.expire());
630                        break;
631                    }
632                    f = frames.next() => match f {
633                        None => break,
634                        Some(f) => match self.admit(&f) {
635                            Ok(()) => yield Ok(f.item),
636                            Err(e) if !e.ends_input() => { let _ = refused.send((f.from, e.to_item(&ns))); }
637                            Err(e) => { yield Err(e); break; }
638                        },
639                    },
640                }
641            }
642        }
643    }
644}