1use std::cell::RefCell;
33use std::collections::HashMap;
34use std::pin::Pin;
35use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
36use std::sync::{Arc, Mutex, MutexGuard};
37use std::task::{Context, Poll};
38
39use bytes::Bytes;
40use futures::stream::Stream;
41use http::Extensions;
42use jsonrpsee::types::{Params, SubscriptionId};
43use jsonrpsee::{PendingSubscriptionSink, SubscriptionSink};
44use plexus_auth_core::duplex::{Answerer, CallCeiling, CallRef};
45use serde::de::DeserializeOwned;
46use serde::Deserialize;
47use serde_json::value::RawValue;
48use serde_json::Value;
49use tokio::sync::{mpsc, Notify};
50use tokio_stream::wrappers::UnboundedReceiverStream;
51
52use super::auth::AuthContext;
53use super::duplex_gate::{CallCounter, ConnId, CreditLine, DuplexCall, DuplexRefusal, InputFrame, Overrun};
54use super::plexus::{DynamicHub, PlexusError};
55use super::wire::FrameSink;
56
57#[derive(Debug)]
60pub(crate) struct Batch {
61 seq: u64,
62 items: Items,
63 bytes: u64,
64 raw: bool,
65}
66
67#[derive(Debug)]
70enum Items {
71 One(Option<Bytes>),
72 Many(std::vec::IntoIter<Bytes>),
73}
74
75impl Items {
76 fn len(&self) -> usize {
77 match self {
78 Items::One(o) => o.is_some() as usize,
79 Items::Many(m) => m.len(),
80 }
81 }
82
83 fn next(&mut self) -> Option<Bytes> {
84 match self {
85 Items::One(o) => o.take(),
86 Items::Many(m) => m.next(),
87 }
88 }
89}
90
91pub const BINARY_INPUT: u8 = 0x01;
94
95pub const BINARY_HEADER: usize = 17;
97
98#[doc(hidden)]
102pub fn item_schema<T: 'static>(schema: schemars::Schema) -> schemars::Schema {
103 if std::any::TypeId::of::<T>() != std::any::TypeId::of::<Bytes>() {
104 return schema;
105 }
106 schemars::json_schema!({
107 "type": "string",
108 "contentEncoding": "base64",
109 "contentMediaType": "application/octet-stream",
110 "x-plexus-binary": true,
111 })
112}
113
114fn decode<T: DeserializeOwned + 'static>(item: Bytes, raw: bool) -> Result<T, String> {
117 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<Bytes>() {
118 let bytes = if raw { item } else { from_base64(&item)? };
119 let mut slot = Some(bytes);
121 let any: &mut dyn std::any::Any = &mut slot;
122 return Ok(any.downcast_mut::<Option<T>>().and_then(Option::take).expect("T is Bytes"));
123 }
124 if raw {
125 return Err("a binary frame, for an input of JSON items".into());
126 }
127 serde_json::from_slice::<T>(&item).map_err(|e| e.to_string())
128}
129
130fn from_base64(item: &[u8]) -> Result<Bytes, String> {
131 use base64::Engine;
132 let text: std::borrow::Cow<'_, str> = match serde_json::from_slice::<&str>(item) {
133 Ok(s) => s.into(),
134 Err(_) => serde_json::from_slice::<String>(item).map_err(|e| format!("an item of binary input is a base64 string: {e}"))?.into(),
135 };
136 base64::engine::general_purpose::STANDARD.decode(text.as_bytes()).map(Bytes::from).map_err(|e| format!("an item of binary input is a base64 string: {e}"))
137}
138
139pub(crate) struct Ledger {
145 window: u64,
146 max_buffered: u64,
149 held_items: AtomicU64,
151 held_bytes: AtomicU64,
152 done: AtomicU64,
154 consumed: AtomicU64,
156 returned: AtomicU64,
158 ended: AtomicBool,
160 finished: AtomicBool,
162 abandoned: AtomicBool,
164 refused: AtomicBool,
165 refusal: Mutex<Option<DuplexRefusal>>,
166 wake: Notify,
167}
168
169impl Ledger {
170 fn new(window: u64, max_buffered: u64) -> Self {
171 Self {
172 window,
173 max_buffered,
174 held_items: AtomicU64::new(0),
175 held_bytes: AtomicU64::new(0),
176 done: AtomicU64::new(0),
177 consumed: AtomicU64::new(0),
178 returned: AtomicU64::new(0),
179 ended: AtomicBool::new(false),
180 finished: AtomicBool::new(false),
181 abandoned: AtomicBool::new(false),
182 refused: AtomicBool::new(false),
183 refusal: Mutex::new(None),
184 wake: Notify::new(),
185 }
186 }
187
188 fn half(&self) -> u64 {
189 (self.window / 2).max(1)
190 }
191
192 fn frame_done(&self, seq: u64, items: u64, bytes: u64) {
194 self.held_items.fetch_sub(items, Ordering::AcqRel);
195 self.held_bytes.fetch_sub(bytes, Ordering::AcqRel);
196 self.done.store(seq + 1, Ordering::Release);
197 let consumed = self.consumed.fetch_add(items, Ordering::AcqRel) + items;
198 if consumed - self.returned.load(Ordering::Acquire) >= self.half() {
199 self.wake.notify_one();
200 }
201 }
202
203 fn input_finished(&self) {
204 self.finished.store(true, Ordering::Release);
205 self.wake.notify_one();
206 }
207
208 fn abandon(&self) {
209 self.abandoned.store(true, Ordering::Release);
210 self.wake.notify_one();
211 }
212
213 fn refuse(&self, why: DuplexRefusal) {
214 *lock(&self.refusal) = Some(why);
215 self.refused.store(true, Ordering::Release);
216 self.wake.notify_one();
217 }
218
219 pub(crate) fn window(&self) -> u64 {
220 self.window
221 }
222
223 pub(crate) async fn woken(&self) {
224 self.wake.notified().await
225 }
226
227 pub(crate) fn take_refusal(&self) -> Option<DuplexRefusal> {
229 if !self.refused.load(Ordering::Acquire) {
230 return None;
231 }
232 lock(&self.refusal).take()
233 }
234
235 pub(crate) fn owed(&self, acked: u64) -> Option<Owed> {
241 let finished = self.finished.load(Ordering::Acquire);
242 let ended = self.ended.load(Ordering::Acquire);
243 if !finished && !ended && self.held_bytes.load(Ordering::Acquire) >= self.max_buffered {
244 return None;
245 }
246 let done = self.done.load(Ordering::Acquire);
247 let consumed = self.consumed.load(Ordering::Acquire);
248 let due = consumed - self.returned.load(Ordering::Acquire);
249 if due < self.half() && !(finished && done > acked) {
250 return None;
251 }
252 self.returned.store(consumed, Ordering::Release);
253 Some(Owed { ack: (done > acked).then(|| done - 1), done, credit: if finished || ended { 0 } else { due } })
254 }
255
256 pub(crate) fn last_done(&self) -> Option<u64> {
258 self.done.load(Ordering::Acquire).checked_sub(1)
259 }
260
261 pub(crate) fn client_ended(&self) -> bool {
262 self.ended.load(Ordering::Acquire)
263 }
264
265 pub(crate) fn abandoned(&self) -> bool {
266 self.abandoned.load(Ordering::Acquire)
267 }
268}
269
270pub(crate) struct Owed {
272 pub(crate) ack: Option<u64>,
273 pub(crate) done: u64,
274 pub(crate) credit: u64,
275}
276
277fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
278 m.lock().unwrap_or_else(|e| e.into_inner())
279}
280
281pub struct Input<T> {
306 source: Source<T>,
307}
308
309enum Source<T> {
310 Wire(WireInput),
312 Stream(Pin<Box<dyn Stream<Item = T> + Send + 'static>>),
314}
315
316struct WireInput {
317 rx: mpsc::UnboundedReceiver<Batch>,
318 cur: Option<Reading>,
319 ledger: Arc<Ledger>,
320 over: bool,
321 refused: bool,
324}
325
326struct Reading {
327 seq: u64,
328 items: Items,
329 count: u64,
330 bytes: u64,
331 raw: bool,
332}
333
334impl<T> Input<T> {
335 pub fn into_stream(self) -> Self {
337 self
338 }
339
340 pub fn from_stream(stream: impl Stream<Item = T> + Send + 'static) -> Self {
342 Self { source: Source::Stream(Box::pin(stream)) }
343 }
344}
345
346impl<T: DeserializeOwned + Send + 'static> Input<T> {
347 pub fn into_boxed(self) -> Pin<Box<dyn Stream<Item = T> + Send + 'static>> {
349 match self.source {
350 Source::Stream(s) => s,
351 wire => Box::pin(Input { source: wire }),
352 }
353 }
354}
355
356impl<T> From<Pin<Box<dyn Stream<Item = T> + Send + 'static>>> for Input<T> {
358 fn from(stream: Pin<Box<dyn Stream<Item = T> + Send + 'static>>) -> Self {
359 Self { source: Source::Stream(stream) }
360 }
361}
362
363impl<T> std::fmt::Debug for Input<T> {
364 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365 let mut d = f.debug_struct("Input");
366 match &self.source {
367 Source::Wire(w) => d.field("window", &w.ledger.window).field("over", &w.over),
368 Source::Stream(_) => d.field("window", &"none: a stream"),
369 };
370 d.finish()
371 }
372}
373
374impl<T: DeserializeOwned + 'static> Stream for Input<T> {
375 type Item = T;
376
377 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
378 match &mut self.get_mut().source {
379 Source::Wire(wire) => wire.poll_item(cx),
380 Source::Stream(stream) => stream.as_mut().poll_next(cx),
381 }
382 }
383}
384
385impl WireInput {
386 fn poll_item<T: DeserializeOwned + 'static>(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> {
387 loop {
388 if self.refused {
389 return Poll::Pending;
390 }
391 if self.over {
392 return Poll::Ready(None);
393 }
394 if let Some(r) = &mut self.cur {
395 if let Some(raw) = r.items.next() {
396 match decode::<T>(raw, r.raw) {
397 Ok(item) => return Poll::Ready(Some(item)),
398 Err(message) => {
399 self.over = true;
400 self.refused = true;
401 self.ledger.refuse(DuplexRefusal::InvalidInput { seq: r.seq, message });
402 return Poll::Pending;
403 }
404 }
405 }
406 self.ledger.frame_done(r.seq, r.count, r.bytes);
407 self.cur = None;
408 }
409 match self.rx.poll_recv(cx) {
410 Poll::Ready(Some(b)) => {
411 self.cur = Some(Reading { seq: b.seq, count: b.items.len() as u64, bytes: b.bytes, items: b.items, raw: b.raw });
412 }
413 Poll::Ready(None) => {
414 self.over = true;
415 self.ledger.input_finished();
416 return Poll::Ready(None);
417 }
418 Poll::Pending => return Poll::Pending,
419 }
420 }
421 }
422}
423
424impl Drop for WireInput {
425 fn drop(&mut self) {
426 if !self.over {
427 self.ledger.abandon();
428 }
429 }
430}
431
432#[derive(Deserialize)]
437struct InputParams<'a> {
438 subscription: u64,
439 seq: u64,
440 #[serde(borrow)]
441 items: Vec<&'a RawValue>,
442}
443
444#[derive(Deserialize)]
445struct EndParams {
446 subscription: u64,
447 seq: u64,
448}
449
450struct Slot {
451 ns: Arc<str>,
452 next_seq: u64,
453 tx: Option<mpsc::UnboundedSender<InputFrame<Batch>>>,
455 ledger: Arc<Ledger>,
456}
457
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
460pub enum Delivered {
461 Taken,
463 Dropped,
466 Refused,
469 NotThisCall,
471 Malformed,
473}
474
475pub struct InputTable {
479 conn: ConnId,
480 calls: Arc<dyn CallCounter>,
481 slots: Mutex<HashMap<u64, Slot>>,
482 closed: Mutex<std::collections::VecDeque<u64>>,
485 open: AtomicUsize,
486 strays: AtomicU64,
487}
488
489const CLOSED_KEPT: usize = 256;
492
493impl std::fmt::Debug for InputTable {
494 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
495 f.debug_struct("InputTable").field("conn", &self.conn).field("open", &self.open.load(Ordering::Relaxed)).finish()
496 }
497}
498
499impl InputTable {
500 pub fn new(conn: u64, calls: Arc<dyn CallCounter>) -> Arc<Self> {
502 Arc::new(Self { conn: ConnId(conn), calls, slots: Mutex::new(HashMap::new()), closed: Mutex::default(), open: AtomicUsize::new(0), strays: AtomicU64::new(0) })
503 }
504
505 pub fn idle(&self) -> bool {
508 self.open.load(Ordering::Acquire) == 0
509 }
510
511 pub fn strays(&self) -> u64 {
514 self.strays.load(Ordering::Relaxed)
515 }
516
517 pub fn take_frame(&self, data: &Bytes) -> bool {
521 #[derive(Deserialize)]
522 struct Shape<'a> {
523 #[serde(borrow)]
524 method: &'a str,
525 #[serde(borrow, default)]
526 id: Option<&'a RawValue>,
527 #[serde(borrow, default)]
528 params: Option<&'a RawValue>,
529 }
530 let Ok(shape) = serde_json::from_slice::<Shape>(data) else { return false };
531 if shape.id.is_some() {
532 return false;
533 }
534 let Some((ns, name)) = shape.method.rsplit_once('.') else { return false };
535 let params = shape.params.map_or(&b"null"[..], |p| p.get().as_bytes());
536 let delivered = match name {
537 "input" => self.input(ns, params, data),
538 "end" => self.end(ns, params),
539 _ => return false,
540 };
541 if matches!(delivered, Delivered::NotThisCall | Delivered::Malformed) {
542 self.strays.fetch_add(1, Ordering::Relaxed);
543 }
544 true
545 }
546
547 pub fn input(&self, ns: &str, params: &[u8], frame: &Bytes) -> Delivered {
549 let Ok(p) = serde_json::from_slice::<InputParams>(params) else { return Delivered::Malformed };
550 let count = p.items.len() as u64;
551 let bytes: u64 = p.items.iter().map(|i| i.get().len() as u64).sum();
552 self.arrive(p.subscription, Some(ns), p.seq, count, bytes, false, || match &p.items[..] {
553 [one] => Items::One(Some(shared(frame, one.get().as_bytes()))),
554 many => Items::Many(many.iter().map(|i| shared(frame, i.get().as_bytes())).collect::<Vec<_>>().into_iter()),
555 })
556 }
557
558 pub fn take_binary(&self, frame: &Bytes) -> Delivered {
564 if frame.len() < BINARY_HEADER || frame[0] != BINARY_INPUT {
565 return Delivered::Malformed;
566 }
567 let word = |at: usize| u64::from_be_bytes(frame[at..at + 8].try_into().expect("eight bytes"));
568 let (subscription, seq) = (word(1), word(9));
569 let bytes = (frame.len() - BINARY_HEADER) as u64;
570 let delivered = self.arrive(subscription, None, seq, 1, bytes, true, || Items::One(Some(frame.slice(BINARY_HEADER..))));
571 if delivered == Delivered::NotThisCall {
572 self.strays.fetch_add(1, Ordering::Relaxed);
573 }
574 delivered
575 }
576
577 #[allow(clippy::too_many_arguments)]
580 fn arrive(&self, subscription: u64, ns: Option<&str>, seq: u64, count: u64, bytes: u64, raw: bool, items: impl FnOnce() -> Items) -> Delivered {
581 let mut slots = lock(&self.slots);
582 let Some(slot) = slots.get_mut(&subscription).filter(|s| ns.is_none_or(|ns| &*s.ns == ns)) else { return self.gone(subscription) };
583 let Some(tx) = &slot.tx else { return Delivered::Dropped };
584 if seq < slot.next_seq {
585 return Delivered::Dropped;
586 }
587 if seq > slot.next_seq {
588 let last = InputFrame { from: self.conn, seq, item: empty(seq), items: 0, bytes: 0, overrun: Some(Overrun::Sequence { expected: slot.next_seq }) };
589 let _ = tx.send(last);
590 slot.tx = None;
591 return Delivered::Refused;
592 }
593 slot.next_seq += 1;
594 if count == 0 {
597 let last = InputFrame { from: self.conn, seq, item: empty(seq), items: 0, bytes: 0, overrun: Some(Overrun::Empty) };
598 let _ = tx.send(last);
599 slot.tx = None;
600 return Delivered::Refused;
601 }
602 let held_items = slot.ledger.held_items.load(Ordering::Acquire);
605 if held_items + count > slot.ledger.window {
606 let last = InputFrame { from: self.conn, seq, item: empty(seq), items: 0, bytes: 0, overrun: Some(Overrun::Credit) };
607 let _ = tx.send(last);
608 slot.tx = None;
609 return Delivered::Refused;
610 }
611 slot.ledger.held_items.fetch_add(count, Ordering::AcqRel);
612 slot.ledger.held_bytes.fetch_add(bytes, Ordering::AcqRel);
613 let _ = tx.send(InputFrame { from: self.conn, seq, item: Batch { seq, items: items(), bytes, raw }, items: count, bytes, overrun: None });
614 Delivered::Taken
615 }
616
617 pub fn end(&self, ns: &str, params: &[u8]) -> Delivered {
620 let Ok(p) = serde_json::from_slice::<EndParams>(params) else { return Delivered::Malformed };
621 let mut slots = lock(&self.slots);
622 let Some(slot) = slots.get_mut(&p.subscription).filter(|s| &*s.ns == ns) else { return self.gone(p.subscription) };
623 let Some(tx) = slot.tx.take() else { return Delivered::Dropped };
624 if p.seq == slot.next_seq {
625 slot.ledger.ended.store(true, Ordering::Release);
626 Delivered::Taken
627 } else {
628 let last = InputFrame { from: self.conn, seq: p.seq, item: empty(p.seq), items: 0, bytes: 0, overrun: Some(Overrun::Sequence { expected: slot.next_seq }) };
629 let _ = tx.send(last);
630 Delivered::Refused
631 }
632 }
633
634 fn gone(&self, subscription: u64) -> Delivered {
637 if lock(&self.closed).contains(&subscription) {
638 Delivered::Dropped
639 } else {
640 Delivered::NotThisCall
641 }
642 }
643
644 fn attach(self: &Arc<Self>, subscription: u64, slot: Slot) -> SlotGuard {
645 lock(&self.slots).insert(subscription, slot);
646 self.open.fetch_add(1, Ordering::AcqRel);
647 SlotGuard { table: self.clone(), subscription }
648 }
649}
650
651fn empty(seq: u64) -> Batch {
652 Batch { seq, items: Items::One(None), bytes: 0, raw: false }
653}
654
655fn shared(frame: &Bytes, part: &[u8]) -> Bytes {
658 let (start, end) = (frame.as_ptr() as usize, frame.as_ptr() as usize + frame.len());
659 let p = part.as_ptr() as usize;
660 if p >= start && p + part.len() <= end {
661 frame.slice_ref(part)
662 } else {
663 Bytes::copy_from_slice(part)
664 }
665}
666
667pub(crate) struct SlotGuard {
670 table: Arc<InputTable>,
671 subscription: u64,
672}
673
674impl Drop for SlotGuard {
675 fn drop(&mut self) {
676 lock(&self.table.slots).remove(&self.subscription);
677 let mut closed = lock(&self.table.closed);
678 if closed.len() == CLOSED_KEPT {
679 closed.pop_front();
680 }
681 closed.push_back(self.subscription);
682 drop(closed);
683 self.table.open.fetch_sub(1, Ordering::AcqRel);
684 }
685}
686
687pub(crate) struct Seam {
695 pub(crate) service: DynamicHub,
696 pub(crate) params: Params<'static>,
698 pub(crate) pending: Option<PendingSubscriptionSink>,
699 pub(crate) ext: Extensions,
700 pub(crate) seen: u64,
702 pub(crate) opened: Arc<Mutex<Option<Opened>>>,
706 pub(crate) refused: Option<Value>,
708}
709
710pub(crate) struct Opened {
712 pub(crate) sink: SubscriptionSink,
713 pub(crate) duplex: Duplex,
714}
715
716pub(crate) struct Duplex {
718 pub(crate) ledger: Arc<Ledger>,
719 pub(crate) gate: Pin<Box<dyn Stream<Item = Result<Batch, DuplexRefusal>> + Send>>,
720 pub(crate) inbox: mpsc::UnboundedSender<Batch>,
721 pub(crate) credit: CreditLine,
722 pub(crate) ns: Arc<str>,
723 pub(crate) to: FrameSink,
724 pub(crate) slot: SlotGuard,
725}
726
727tokio::task_local! {
728 pub(crate) static CALL: RefCell<Seam>;
729}
730
731fn unserved(method: &str) -> PlexusError {
733 PlexusError::ExecutionError(format!(
734 "`{method}` takes an input stream, and this transport carries none: call it over a WebSocket"
735 ))
736}
737
738impl Seam {
739 fn open<T>(&mut self, method: &str, ceiling: CallCeiling) -> Result<(Input<T>, PendingSubscriptionSink, Duplex), PlexusError> {
742 let Some(to) = self.ext.get::<FrameSink>().cloned() else {
743 return Err(unserved(method));
744 };
745 let Some(table) = to.inputs().cloned() else {
746 return Err(unserved(method));
747 };
748 let Some(pending) = self.pending.as_ref() else {
749 return Err(unserved(method));
750 };
751 let SubscriptionId::Num(subscription) = pending.subscription_id() else {
752 return Err(PlexusError::ExecutionError(format!("`{method}`: an input half needs integer subscription ids")));
753 };
754 let call: super::plexus::CallParams = self.params.parse().map_err(|e| PlexusError::invalid_params(e.to_string()))?;
755 if !call.method.ends_with(method) {
758 return Err(unserved(method));
759 }
760 let terms = self.service.input_terms(&call.method, call.params.as_ref().unwrap_or(&Value::Null))?;
761 let ns: Arc<str> = Arc::from(self.service.runtime_namespace());
762 let caller = self.ext.get::<Arc<AuthContext>>().cloned();
763 let at = CallRef { conn: table.conn.0, subscription };
764 let opened = self.service.duplex_gate().admitted(at, &*table.calls, caller, &terms.grant, terms.targets, self.seen, terms.recheck, ceiling, Answerer::Caller);
765 let call: DuplexCall = match opened {
766 Ok(c) => c,
767 Err(why) => {
768 let item = why.to_item(&ns);
769 let message = item.get("message").and_then(Value::as_str).unwrap_or("refused").to_string();
770 self.refused = Some(item);
771 return Err(PlexusError::ExecutionError(message));
772 }
773 };
774 let credit = call.credit_line();
775 let ledger = Arc::new(Ledger::new(ceiling.credit, ceiling.max_buffered));
776 let (tx, rx) = mpsc::unbounded_channel();
777 let (inbox, handler) = mpsc::unbounded_channel();
778 let slot = table.attach(
779 subscription,
780 Slot { ns: ns.clone(), next_seq: 0, tx: Some(tx), ledger: ledger.clone() },
781 );
782 let (not_ours, _) = mpsc::unbounded_channel();
785 let gate = Box::pin(call.input(UnboundedReceiverStream::new(rx), not_ours));
786 let pending = self.pending.take().expect("checked above");
787 let input = Input { source: Source::Wire(WireInput { rx: handler, cur: None, ledger: ledger.clone(), over: false, refused: false }) };
788 Ok((input, pending, Duplex { ledger, gate, inbox, credit, ns, to, slot }))
789 }
790}
791
792pub async fn open<T>(method: &'static str, ceiling: CallCeiling) -> Result<Input<T>, PlexusError> {
795 let (input, pending, duplex) = CALL
796 .try_with(|seam| seam.borrow_mut().open::<T>(method, ceiling))
797 .unwrap_or_else(|_| Err(unserved(method)))?;
798 let sink = pending.accept().await.map_err(|_| PlexusError::ExecutionError("the connection closed".into()))?;
801 let _ = CALL.try_with(|seam| *lock(&seam.borrow().opened) = Some(Opened { sink, duplex }));
802 Ok(input)
803}
804
805#[cfg(test)]
806mod tests {
807 use super::*;
808 use futures::StreamExt;
809
810 struct NoCalls;
811
812 impl CallCounter for NoCalls {
813 fn take_place(&self) -> Result<super::super::duplex_gate::CallPlace, usize> {
814 Err(0)
815 }
816 }
817
818 fn one_call<T: DeserializeOwned + Send + 'static>(subscription: u64) -> (Arc<InputTable>, SlotGuard, Input<T>) {
821 let table = InputTable::new(7, Arc::new(NoCalls));
822 let ledger = Arc::new(Ledger::new(64, u64::MAX));
823 let (tx, mut rx) = mpsc::unbounded_channel::<InputFrame<Batch>>();
824 let (inbox, handler) = mpsc::unbounded_channel();
825 let guard = table.attach(subscription, Slot { ns: Arc::from("menger"), next_seq: 0, tx: Some(tx), ledger: ledger.clone() });
826 tokio::spawn(async move {
827 while let Some(f) = rx.recv().await {
828 let _ = inbox.send(f.item);
829 }
830 });
831 (table, guard, Input { source: Source::Wire(WireInput { rx: handler, cur: None, ledger, over: false, refused: false }) })
832 }
833
834 fn frame(subscription: u64, seq: u64, payload: &[u8]) -> Bytes {
835 let mut f = vec![BINARY_INPUT];
836 f.extend_from_slice(&subscription.to_be_bytes());
837 f.extend_from_slice(&seq.to_be_bytes());
838 f.extend_from_slice(payload);
839 Bytes::from(f)
840 }
841
842 #[tokio::test]
845 async fn a_binary_payload_reaches_the_handler_without_a_copy() {
846 let (table, _slot, mut input) = one_call::<Bytes>(21);
847 let received = frame(21, 0, &[9; 640]);
848 assert_eq!(table.take_binary(&received), Delivered::Taken);
849 let item = input.next().await.unwrap();
850 assert_eq!(item.as_ptr(), received[BINARY_HEADER..].as_ptr(), "the same memory");
851 assert_eq!(item.len(), 640);
852 }
853
854 #[tokio::test]
857 async fn take_binary_says_what_became_of_a_frame() {
858 let (table, _slot, _input) = one_call::<Bytes>(21);
859 assert_eq!(table.take_binary(&Bytes::from_static(&[1, 0, 0])), Delivered::Malformed);
860 let mut other = frame(21, 0, b"x").to_vec();
861 other[0] = 2;
862 assert_eq!(table.take_binary(&Bytes::from(other)), Delivered::Malformed);
863 assert_eq!(table.take_binary(&frame(22, 0, b"x")), Delivered::NotThisCall);
864 assert_eq!(table.strays(), 1);
865 assert_eq!(table.take_binary(&frame(21, 0, b"x")), Delivered::Taken);
866 assert_eq!(table.take_binary(&frame(21, 0, b"x")), Delivered::Dropped);
867 }
868
869 #[test]
872 fn decode_by_the_inputs_type() {
873 assert_eq!(decode::<Bytes>(Bytes::from_static(br#""AAEC/w==""#), false).unwrap(), Bytes::from_static(&[0, 1, 2, 255]));
874 assert_eq!(decode::<Bytes>(Bytes::from_static(br#""AAEC\/w==""#), false).unwrap(), Bytes::from_static(&[0, 1, 2, 255]));
875 assert!(decode::<Bytes>(Bytes::from_static(br#""no!""#), false).is_err());
876 assert!(decode::<Bytes>(Bytes::from_static(b"[1,2]"), false).is_err());
877 assert_eq!(decode::<Bytes>(Bytes::from_static(b"{raw"), true).unwrap(), Bytes::from_static(b"{raw"));
878 assert_eq!(decode::<u32>(Bytes::from_static(b"7"), false).unwrap(), 7);
879 assert!(decode::<u32>(Bytes::from_static(b"7"), true).is_err());
880 }
881
882 #[tokio::test]
885 async fn the_table_says_refused_late_and_stranger_apart() {
886 let (table, slot, _input) = one_call::<u32>(21);
887 let empty = Bytes::from_static(br#"{"subscription":21,"seq":0,"items":[]}"#);
888 assert_eq!(table.input("menger", &empty, &empty), Delivered::Refused);
889 let next = Bytes::from_static(br#"{"subscription":21,"seq":1,"items":[1]}"#);
890 assert_eq!(table.input("menger", &next, &next), Delivered::Dropped, "the half closed with the refusal");
891 drop(slot);
892 assert_eq!(table.input("menger", &next, &next), Delivered::Dropped, "the call is over: late");
893 assert_eq!(table.end("menger", br#"{"subscription":21,"seq":2}"#), Delivered::Dropped);
894 let other = Bytes::from_static(br#"{"subscription":22,"seq":0,"items":[1]}"#);
895 assert_eq!(table.input("menger", &other, &other), Delivered::NotThisCall);
896 }
897
898 #[tokio::test]
901 async fn a_refused_item_leaves_the_input_pending() {
902 let (table, _slot, mut input) = one_call::<u32>(21);
903 let frame = Bytes::from_static(br#"{"subscription":21,"seq":0,"items":[1,"x"]}"#);
904 assert_eq!(table.input("menger", &frame, &frame), Delivered::Taken);
905 assert_eq!(input.next().await, Some(1));
906 let next = tokio::time::timeout(std::time::Duration::from_millis(50), input.next()).await;
907 assert!(next.is_err(), "pending, not an end: {next:?}");
908 let Source::Wire(wire) = &input.source else { unreachable!() };
909 assert!(matches!(wire.ledger.take_refusal(), Some(DuplexRefusal::InvalidInput { seq: 0, .. })));
910 }
911}