ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
//! THE HOUSE CHANNEL: one bounded transport with a door on each side for each engine, and the
//! select a loop waiting on several of them parks in.
//!
//! # What it is for
//!
//! A node whose body runs its OWN loop does not wait on framework edges alone. It has a worker
//! return line, a stop signal, a timer, whatever else it wired for itself — and it waits on all of
//! them at once, in one select. An opaque seam cannot serve that: a select needs the RECEIVERS, so
//! hiding them would force a thread or a poll where an arm suffices. What such a body is owed is
//! therefore a channel rather than a protocol, and this module is it.
//!
//! It is not the data edge. [`Outbox`](crate::Outbox) and [`Inbox`](crate::Inbox) carry the
//! [`Wake`](crate::Wake) vocabulary between two DECLARED nodes and are opened by the wiring walk at
//! a resolved [`ChannelOptions`](crate::ChannelOptions); this is the plain transport a body opens
//! for itself, and the framework never sees one.
//!
//! # BOUNDED ONLY, and the law is in the type
//!
//! [`bounded`] is the only constructor there is. No unbounded door exists on this face, so
//! backpressure is a property of the TYPE rather than a discipline every caller has to keep: a full
//! channel makes its producer wait, and a producer that waits is a pipeline that cannot outrun its
//! own consumer into memory. [`Sender::capacity`] answers a `usize` and not an option, which is the
//! same sentence written in a signature.
//!
//! Zero is legal and means a RENDEZVOUS — the sender waits until a receiver takes the item. That is
//! the strongest bound rather than an escape from the law, and it is the same reading
//! [`channel`](crate::channel) gives the number one layer over.
//!
//! # ONE channel, both doors on each half
//!
//! This is the property the wrapper exists to keep, and it is why one transport carries the whole
//! module instead of a blocking crate and an asynchronous one meeting at a bridge. Each half wears
//! both spellings — [`send`](Sender::send) beside [`send_async`](Sender::send_async),
//! [`recv`](Receiver::recv) beside [`recv_async`](Receiver::recv_async) — so all four combinations
//! are the same channel:
//!
//! | producer | consumer | what crosses |
//! |---|---|---|
//! | `send` | `recv` | a thread feeding a thread |
//! | `send` | `recv_async` | a thread feeding a task |
//! | `send_async` | `recv` | a task feeding a thread |
//! | `send_async` | `recv_async` | a task feeding a task |
//!
//! Two disjoint channel families cannot express the middle two rows without a bridge that is itself
//! a third channel. This graph's edges cross modes — a node's blocking main loop feeding an
//! asynchronous engine and the reverse — so the crossing is the requirement rather than a
//! convenience, and it is what picked one dual-mode transport.
//!
//! The verbs are paired rather than split into a blocking trait and an awaited one, which is the
//! framework-seam spelling: these are values a body HOLDS, nobody implements them, and a half that
//! cannot know which engine will drive it must answer to both.
//!
//! # WAITING IS NOT TAKING, and the two are separate doors
//!
//! [`Receiver::readable`] and [`readable_async`](Receiver::readable_async) wait for the channel to
//! have something and take NOTHING. That is not a convenience — it is what a body needs when it
//! waits in one place and reads in another.
//!
//! A receive that waits registers its caller as the queue's next reader, and a sender may then hand
//! its item straight to that reader instead of putting it in the queue. With ONE reader that is
//! only a shortcut. A body that parks on an arm while its own code takes items with
//! [`try_recv`](Receiver::try_recv) has TWO readers on one channel, and the handed item skips
//! whatever the queue is still holding — one producer's stream comes out of the two doors in the
//! wrong order. A probe registers nothing that can be handed anything, so a body may wait here and
//! take there, and the queue stays the only order there is.
//!
//! # The select
//!
//! [`select`] is this tree's own replacement for a channel crate's selector: per-arm receives and a
//! CALLER-HELD turn cursor, so the rotation belongs to the loop that already holds state rather
//! than to a knob here. [`arm`] builds one arm, [`park_on`] is the blocking engine's driver for the
//! whole select, and an asynchronous body awaits [`select`] directly.
//!
//! # The sync main loop
//!
//! ```
//! use core::{pin::pin, time::Duration};
//!
//! use ingraph::conduit::{self, Arm};
//!
//! // What the loop waits FOR. Each arm wraps its own message into this, which is how a select over
//! // several channels of different types answers exactly one.
//! enum Turn {
//!   Doubled(u32),
//!   ShutdownSignal,
//! }
//!
//! let (jobs, to_do) = conduit::bounded::<u32>(4);
//! let (done, doubled) = conduit::bounded::<u32>(4);
//! let (halt, stop) = conduit::bounded::<()>(1);
//!
//! // The node's OWN worker: threads inside a node are the node's business, and the framework sees
//! // only the edges, never the crew behind them.
//! let worker = std::thread::spawn(move || {
//!   while let Some(job) = to_do.recv() {
//!     if done.send(job * 2).is_err() {
//!       break;
//!     }
//!   }
//! });
//!
//! jobs.send(20).unwrap();
//! jobs.send(21).unwrap();
//!
//! let mut turn = 0;
//! let mut collected = Vec::new();
//! loop {
//!   // The arms are rebuilt each turn and dropped when one wins. That loses nothing: a receive
//!   // future that goes away passes its wake on, and the message it was waiting for is in the
//!   // channel's queue rather than in the future.
//!   let mut work = pin!(conduit::arm(true, &doubled, Turn::Doubled));
//!   let mut halting = pin!(conduit::arm(true, &stop, |()| Turn::ShutdownSignal));
//!   let mut arms: [Arm<'_, Option<Turn>>; 2] = [work.as_mut(), halting.as_mut()];
//!
//!   // The blocking engine DRIVES the same select an asynchronous body awaits. This call is the
//!   // whole of the difference between them.
//!   let Some(Some((index, heard))) =
//!     conduit::park_on(conduit::select(turn, &mut arms), Duration::from_secs(5))
//!   else {
//!     break;
//!   };
//!   // Past the winner, so a busy arm cannot starve a quiet one.
//!   turn = index + 1;
//!
//!   match heard {
//!     Some(Turn::Doubled(value)) => {
//!       collected.push(value);
//!       if collected.len() == 2 {
//!         halt.send(()).unwrap();
//!       }
//!     }
//!     Some(Turn::ShutdownSignal) | None => break,
//!   }
//! }
//!
//! drop(jobs);
//! worker.join().unwrap();
//! assert_eq!(collected, [40, 42]);
//! ```

use core::{
  future::{Future, pending, poll_fn},
  pin::Pin,
  sync::atomic::{AtomicBool, AtomicUsize, Ordering},
  task::{Poll, Waker},
  time::Duration,
};

use std::{sync::Mutex, time::Instant};

use crate::drive::block_until;

/// WHETHER THERE IS SOMETHING TO TAKE — the state a probe waits on, kept beside the queue rather
/// than inside it.
///
/// # Why the transport's own wait could not answer this
///
/// A channel's receive REGISTERS the caller as the queue's next reader, and a registered reader is
/// eligible for a sender's direct handoff — the item is put into the reader's own slot instead of
/// into the queue, and the queue's order stops being the delivery order. That is fine for the one
/// reader a channel usually has and wrong for a body that waits in one place and TAKES in another:
/// two registered readers make the second one a door the first one's queue does not pass through.
///
/// So readiness is its own state. Nothing here ever holds an item, which is the whole of the
/// property: a probe cannot be handed anything, so the queue stays the only order there is.
///
/// # It costs a load on a channel nobody probes
///
/// [`landed`](Self::landed) reads one atomic and returns. The waker list is touched only while
/// somebody is parked, which is also the only time a transport would have paid for a wake anyway.
#[derive(Debug)]
struct Ready {
  /// How many senders the channel has, counted HERE rather than read off the transport.
  ///
  /// A sender's own count falls as its handle drops, and a probe woken by that drop would race the
  /// drop itself. This number falls in [`left`](Self::left) BEFORE the wake, so a probe that wakes
  /// on the last sender's going sees the end rather than a channel that is one instruction from
  /// having ended.
  senders: AtomicUsize,
  /// Whether anyone is parked. The senders' fast path is this and nothing else.
  probing: AtomicBool,
  /// What the next probe is called. A probe re-parks under ITS OWN name every poll and gives the
  /// name back when it goes, which is what keeps the list the length of the probes that exist: a
  /// blocking driver mints a fresh waker per call, so a list keyed on
  /// [`will_wake`](Waker::will_wake) alone would grow by one for every expiry of a wait nobody ever
  /// answered.
  next_seat: AtomicUsize,
  /// Who to wake. A list rather than a slot, because nothing about a receiving half says only one
  /// task may hold it.
  wakers: Mutex<Vec<(usize, Waker)>>,
}

impl Ready {
  /// A gate over a channel with ONE sender — what [`bounded`] opens.
  fn new() -> Self {
    Self {
      senders: AtomicUsize::new(1),
      probing: AtomicBool::new(false),
      next_seat: AtomicUsize::new(0),
      wakers: Mutex::new(Vec::new()),
    }
  }

  /// A sender was cloned.
  #[inline]
  fn joined(&self) {
    self.senders.fetch_add(1, Ordering::SeqCst);
  }

  /// A sender went. The LAST one is what makes a probe answer *ended*.
  #[inline]
  fn left(&self) {
    if self.senders.fetch_sub(1, Ordering::SeqCst) == 1 {
      self.wake();
    }
  }

  /// Whether any sender is left to speak.
  #[inline]
  fn open(&self) -> bool {
    self.senders.load(Ordering::SeqCst) > 0
  }

  /// An item was queued. The load is the whole cost where nobody is probing.
  #[inline]
  fn landed(&self) {
    if self.probing.load(Ordering::SeqCst) {
      self.wake();
    }
  }

  /// Wake everyone parked, and take them off the list — a woken probe re-parks itself.
  fn wake(&self) {
    self.probing.store(false, Ordering::SeqCst);
    let woken = core::mem::take(&mut *self.held());
    for (_, waker) in woken {
      waker.wake();
    }
  }

  /// A name for one probe, held for that probe's life.
  fn seat(&self) -> usize {
    self.next_seat.fetch_add(1, Ordering::Relaxed)
  }

  /// Park `waker` under `seat`, and say so where a sender will see it.
  ///
  /// The store comes AFTER the push and is [`SeqCst`](Ordering::SeqCst) for the reason the whole
  /// gate rests on: a sender queues its item and then reads this flag, so of the two orders one
  /// must see the other — either the probe's re-check finds the item, or the sender's read finds
  /// the probe.
  fn park(&self, seat: usize, waker: &Waker) {
    let mut held = self.held();
    match held.iter_mut().find(|(taken, _)| *taken == seat) {
      Some((_, parked)) => {
        if !parked.will_wake(waker) {
          *parked = waker.clone();
        }
      }
      None => held.push((seat, waker.clone())),
    }
    drop(held);
    self.probing.store(true, Ordering::SeqCst);
  }

  /// Give `seat` back — what a probe that is dropped or answered does.
  fn leave(&self, seat: usize) {
    let mut held = self.held();
    held.retain(|(taken, _)| *taken != seat);
    let alone = held.is_empty();
    drop(held);
    if alone {
      self.probing.store(false, Ordering::SeqCst);
    }
  }

  /// The waker list. A poisoned lock is taken anyway: what it guards is a wake list, and refusing
  /// to wake a body because another one panicked would turn one failure into a hang.
  fn held(&self) -> std::sync::MutexGuard<'_, Vec<(usize, Waker)>> {
    self.wakers.lock().unwrap_or_else(|held| held.into_inner())
  }

  /// HOW MANY PROBES ARE PARKED, for the lane that asserts the list does not grow.
  #[cfg(test)]
  fn parked(&self) -> usize {
    self.held().len()
  }
}

/// ONE PROBE'S SEAT, given back when the probe goes.
///
/// A guard rather than a call at the end of the wait, because a probe most often does NOT reach an
/// end: it is a select arm, and an arm that loses is dropped where it stands. What the guard buys is
/// that the list is the length of the probes that EXIST — see [`Ready::next_seat`] for the growth it
/// is there to prevent.
struct Seat<'a> {
  ready: &'a Ready,
  taken: usize,
}

impl<'a> Seat<'a> {
  fn take(ready: &'a Ready) -> Self {
    Self {
      taken: ready.seat(),
      ready,
    }
  }

  fn park(&self, waker: &Waker) {
    self.ready.park(self.taken, waker);
  }
}

impl Drop for Seat<'_> {
  fn drop(&mut self) {
    self.ready.leave(self.taken);
  }
}

/// A bounded channel of `capacity` items: the sending half and the receiving half.
///
/// THE ONLY CONSTRUCTOR, which is the module's whole backpressure claim — there is no unbounded
/// door to reach for, so an edge opened here bounds the memory between the two parties by
/// construction.
///
/// Zero is legal and means a RENDEZVOUS: a send waits until a receive takes the item, which is the
/// strongest bound rather than an exception to the rule.
#[inline]
#[must_use]
pub fn bounded<T>(capacity: usize) -> (Sender<T>, Receiver<T>) {
  let (tx, rx) = flume::bounded(capacity);
  let ready = std::sync::Arc::new(Ready::new());
  (
    Sender {
      tx,
      ready: std::sync::Arc::clone(&ready),
    },
    Receiver { rx, ready },
  )
}

/// The sending half.
///
/// BOUNDED and BLOCKING is the posture: [`send`](Self::send) waits for room rather than dropping,
/// so a slow consumer becomes backpressure on its producer and nothing is lost on the way.
/// [`try_send`](Self::try_send) is the door for a producer that would rather do something else than
/// wait, and it is the caller's decision because only the caller knows what that something else is.
///
/// CLONEABLE, and cloning one is what fan-in is: several producers holding the same consumer's
/// queue. The channel stays open while any clone lives, and the receiving half sees its
/// disconnection when the last of them goes.
pub struct Sender<T> {
  tx: flume::Sender<T>,
  ready: std::sync::Arc<Ready>,
}

impl<T> Sender<T> {
  /// Hand `item` over, WAITING for room.
  ///
  /// The blocking engine's door, and the plain one: this is what a body writes unless it has
  /// decided otherwise.
  ///
  /// # Errors
  ///
  /// [`Unsent`], carrying the item back, where every receiver is gone — nothing will ever take it,
  /// so waiting would be waiting on nobody.
  #[inline]
  pub fn send(&self, item: T) -> Result<(), Unsent<T>> {
    let given = self.tx.send(item).map_err(|refused| Unsent::of(refused.0));
    if given.is_ok() {
      self.ready.landed();
    }
    given
  }

  /// [`send`](Self::send) for the awaited face — the same wait for room, expressed as backpressure
  /// a task can park on.
  ///
  /// # Errors
  ///
  /// [`send`](Self::send)'s, unchanged.
  #[inline]
  pub async fn send_async(&self, item: T) -> Result<(), Unsent<T>> {
    let given = self
      .tx
      .send_async(item)
      .await
      .map_err(|refused| Unsent::of(refused.0));
    if given.is_ok() {
      self.ready.landed();
    }
    given
  }

  /// Hand `item` over WITHOUT waiting.
  ///
  /// # Errors
  ///
  /// [`Unsent`] for either of the two reasons a send can fail at once — no room, or nobody there —
  /// and [`is_disconnected`](Self::is_disconnected) is what tells them apart. They are one arm for
  /// [`Feed::try_give`](crate::Feed::try_give)'s reason: the caller that wants the distinction is
  /// the one that has to decide about it.
  #[inline]
  pub fn try_send(&self, item: T) -> Result<(), Unsent<T>> {
    let given = self
      .tx
      .try_send(item)
      .map_err(|refused| Unsent::of(refused.into_inner()));
    if given.is_ok() {
      self.ready.landed();
    }
    given
  }

  /// How many items are queued and not yet taken.
  #[inline]
  #[must_use]
  pub fn len(&self) -> usize {
    self.tx.len()
  }

  /// Whether none is.
  #[inline]
  #[must_use]
  pub fn is_empty(&self) -> bool {
    self.tx.is_empty()
  }

  /// What bounds this channel.
  ///
  /// A `usize` and not an option, which is the type's own law in a signature: [`bounded`] is the
  /// only constructor, so there is no unbounded case for a caller to have to handle.
  #[inline]
  #[must_use]
  pub fn capacity(&self) -> usize {
    self
      .tx
      .capacity()
      // Unreachable by construction: `bounded` is this module's only constructor and it opens a
      // bounded channel. `expect` rather than a fallback, because a number invented here would be a
      // quiet lie about the bound rather than a loud absence of one.
      .expect("a conduit is opened by `bounded`, which always names a capacity")
  }

  /// Whether every receiver has hung up.
  #[inline]
  #[must_use]
  pub fn is_disconnected(&self) -> bool {
    self.tx.is_disconnected()
  }
}

// Hand-written so `T` need not be `Clone`: a sender is a handle, and cloning one is what fan-in IS.
impl<T> Clone for Sender<T> {
  #[inline]
  fn clone(&self) -> Self {
    self.ready.joined();
    Self {
      tx: self.tx.clone(),
      ready: std::sync::Arc::clone(&self.ready),
    }
  }
}

/// WHAT THE LAST SENDER'S GOING MEANS — the end, said where a probe is waiting for it.
///
/// [`readable`](Receiver::readable) answers *ended* off this count rather than off the transport's
/// own disconnection, so the two cannot disagree: the number falls here, and the wake that follows
/// finds a channel that has already ended rather than one about to.
impl<T> Drop for Sender<T> {
  #[inline]
  fn drop(&mut self) {
    self.ready.left();
  }
}

impl<T> core::fmt::Debug for Sender<T> {
  /// The DEPTH and the bound — never the items. `T` is the caller's own type and demanding a
  /// [`Debug`](core::fmt::Debug) of it would bound every body for the benefit of this line.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Sender")
      .field("queued", &self.len())
      .field("capacity", &self.capacity())
      .finish()
  }
}

/// The receiving half.
///
/// CLONEABLE like its twin, and the two clones mean different things: a second sender is another
/// producer, while a second receiver is another CONSUMER of the same queue — an item reaches
/// exactly one of them. That is what lets a pool of the node's own workers share one in-queue
/// instead of needing one channel each.
pub struct Receiver<T> {
  rx: flume::Receiver<T>,
  ready: std::sync::Arc<Ready>,
}

impl<T> Receiver<T> {
  /// WAIT UNTIL THERE IS SOMETHING TO TAKE — and take NOTHING.
  ///
  /// `true` is *there is at least one item queued*; `false` is the END — every sender is gone and
  /// nothing is left, so no later call can ever answer `true`. The blocking engine's door;
  /// [`readable_async`](Self::readable_async) is the awaited one, as [`recv`](Self::recv) and
  /// [`recv_async`](Self::recv_async) are.
  ///
  /// # It is a PROBE, and that is a different thing from a receive
  ///
  /// A receive that waits makes the caller the queue's next reader, and a sender may then hand its
  /// item STRAIGHT to that reader rather than to the queue. With one reader that is only a
  /// shortcut. With two — a body parked HERE while its own code takes items THERE — it is a second
  /// door: the handed item skips everything the queue is still holding, and the two doors deliver
  /// one producer's stream out of order.
  ///
  /// This call registers nothing a sender can hand anything to. It reads the depth, and where the
  /// depth is zero it parks on a wake the senders ring beside the queue. So a body may wait here
  /// and take with [`try_recv`](Self::try_recv), and the QUEUE stays the only order there is.
  ///
  /// # A `true` may be stale by the time the caller looks
  ///
  /// Nothing is reserved, so another consumer of the same queue may take the item first. It is a
  /// READINESS and not a claim, which is what a caller that answers it with a drain wants: the
  /// honest loop is `while readable() { for item in drain() { … } }`.
  #[inline]
  #[must_use]
  pub fn readable(&self) -> bool {
    block_until(self.readable_async(), None)
      .expect("a wait with no deadline ends only when the future answers")
  }

  /// [`readable`](Self::readable) for the awaited face — the same probe, expressed as a wait a task
  /// or a [`select`] arm can park on.
  ///
  /// This is the arm a body offers when it wants to be WOKEN by a channel it will read somewhere
  /// else. It resolves without taking, so nothing is lost when the arm loses a select and nothing
  /// jumps the queue while it is parked.
  /// # THE CLOSE IS RE-READ AGAINST THE QUEUE, and skipping that lost items
  ///
  /// *Empty* and *closed* are two reads of two words, and a sender that queues its last item and
  /// then goes lands BETWEEN them: the depth is read while the queue is still empty, the sender
  /// queues, the sender drops, and the count is read at zero. Both reads were true when they were
  /// taken and the answer they compose — *ended, with nothing on it* — was false the moment it was
  /// given.
  ///
  /// So the closed arm re-reads the DEPTH and answers that. It is exact rather than a narrowing,
  /// because the close is TERMINAL: a count at zero can never rise again — a sender is only minted
  /// by cloning one that exists — so what the queue holds after that read is final and one look at
  /// it is the whole truth.
  ///
  /// **ingraph #472's sibling, and it was silently losing results.** `Crew::wind_down` drains and
  /// then asks this whether to go round again; a `false` over a non-empty queue is a drain that
  /// stops with items on the line and a `close()` that hands back fewer results than the benches
  /// made. Measured under CPU contention at one item in roughly 20 rounds of the sharding device's
  /// own contended lane, with the probe caught answering `false` over a queue of depth 1.
  pub async fn readable_async(&self) -> bool {
    // The depth first, and BEFORE a seat is taken: a probe over a channel that already holds
    // something answers without ever joining the wake list.
    if !self.rx.is_empty() {
      return true;
    }
    if !self.ready.open() {
      return !self.rx.is_empty();
    }
    let seat = Seat::take(&self.ready);
    poll_fn(|cx| {
      if !self.rx.is_empty() {
        return Poll::Ready(true);
      }
      if !self.ready.open() {
        return Poll::Ready(!self.rx.is_empty());
      }
      seat.park(cx.waker());
      // And AGAIN, after parking. One of the two orders sees the other: either this finds what a
      // sender queued, or that sender's own read of the flag finds this waker.
      if !self.rx.is_empty() {
        return Poll::Ready(true);
      }
      if !self.ready.open() {
        return Poll::Ready(!self.rx.is_empty());
      }
      Poll::Pending
    })
    .await
  }

  /// Wait for an item — the blocking engine's door.
  ///
  /// `None` is the end: every sender is gone and the queue is drained, so nothing can arrive again.
  /// There is no third answer, because a wait with no deadline has nothing to report but the item
  /// or the end.
  #[inline]
  #[must_use]
  pub fn recv(&self) -> Option<T> {
    self.rx.recv().ok()
  }

  /// Wait for an item — the awaited door.
  ///
  /// `None` is the end, as above. No deadline: nothing runtime-neutral exists to time with, so a
  /// body that wants one arms a timer of its own beside this and lets [`select`] answer whichever
  /// speaks first.
  #[inline]
  pub async fn recv_async(&self) -> Option<T> {
    self.rx.recv_async().await.ok()
  }

  /// Wait for an item, giving up after `timeout` — the blocking engine's door WITH a deadline.
  ///
  /// The three-way answer is what the deadline buys: [`Taken::Empty`] is the expiry and says
  /// nothing about the channel, while [`Taken::HungUp`] is the end. A loop with a liveness floor
  /// spends this one — the expiry is its cue to look at whatever else it owns.
  #[inline]
  #[must_use]
  pub fn recv_timeout(&self, timeout: Duration) -> Taken<T> {
    match self.rx.recv_timeout(timeout) {
      Ok(item) => Taken::Item(item),
      Err(flume::RecvTimeoutError::Timeout) => Taken::Empty,
      Err(flume::RecvTimeoutError::Disconnected) => Taken::HungUp,
    }
  }

  /// Take an item if one is already queued, WITHOUT waiting.
  #[inline]
  #[must_use]
  pub fn try_recv(&self) -> Taken<T> {
    match self.rx.try_recv() {
      Ok(item) => Taken::Item(item),
      Err(flume::TryRecvError::Empty) => Taken::Empty,
      Err(flume::TryRecvError::Disconnected) => Taken::HungUp,
    }
  }

  /// Everything already queued, without waiting — what a woken loop takes before doing anything
  /// else, so one wake serves a whole burst.
  ///
  /// `impl Iterator` and not the transport's own drain type: which channel crate carries this
  /// module is an implementation choice, and a signature naming it would make the choice part of
  /// the API.
  #[inline]
  pub fn drain(&self) -> impl Iterator<Item = T> {
    self.rx.drain()
  }

  /// How many items are queued.
  #[inline]
  #[must_use]
  pub fn len(&self) -> usize {
    self.rx.len()
  }

  /// Whether none is.
  #[inline]
  #[must_use]
  pub fn is_empty(&self) -> bool {
    self.rx.is_empty()
  }

  /// What bounds this channel — [`Sender::capacity`]'s answer, from the other half.
  #[inline]
  #[must_use]
  pub fn capacity(&self) -> usize {
    self
      .rx
      .capacity()
      // Unreachable by construction, as [`Sender::capacity`]'s own is.
      .expect("a conduit is opened by `bounded`, which always names a capacity")
  }

  /// Whether every sender is gone.
  ///
  /// It says nothing about what is still QUEUED: a disconnected channel with items in it still
  /// answers them, and only then ends.
  #[inline]
  #[must_use]
  pub fn is_disconnected(&self) -> bool {
    self.rx.is_disconnected()
  }

  /// How many probes are parked on this channel, for the lane that asserts the list does not grow.
  #[cfg(test)]
  pub(crate) fn parked(&self) -> usize {
    self.ready.parked()
  }
}

// Hand-written for [`Sender`]'s reason, one half over.
impl<T> Clone for Receiver<T> {
  #[inline]
  fn clone(&self) -> Self {
    Self {
      rx: self.rx.clone(),
      ready: std::sync::Arc::clone(&self.ready),
    }
  }
}

impl<T> core::fmt::Debug for Receiver<T> {
  /// The DEPTH and the bound — never the items, for [`Sender`]'s own reason.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Receiver")
      .field("queued", &self.len())
      .field("capacity", &self.capacity())
      .finish()
  }
}

/// What a receive that could answer three ways found.
///
/// The variants are three FACTS and not three failures, which is why this is an enum rather than a
/// `Result`: an empty queue is the ordinary state of a channel nobody has written to yet, and a
/// loop reading it as an error would be treating its own liveness floor as a fault. It is
/// [`Rung`](crate::Rung)'s shape one layer down, carrying the item that a doorbell has none of.
#[derive(Debug, Clone, PartialEq, Eq, derive_more::IsVariant)]
pub enum Taken<T> {
  /// An item, taken out of the queue.
  Item(T),
  /// Nothing was there — the queue was empty, or the wait expired. Senders may still arrive.
  Empty,
  /// Every sender is gone AND the queue is drained. Nothing can ever arrive again.
  HungUp,
}

impl<T> Taken<T> {
  /// The item, where there was one.
  ///
  /// It collapses the two absences deliberately: a caller spelling this is one that treats *not
  /// yet* and *never again* alike, which is the honest reading for a poll that will come round
  /// again anyway.
  #[inline]
  #[must_use]
  pub fn into_item(self) -> Option<T> {
    match self {
      Self::Item(item) => Some(item),
      Self::Empty | Self::HungUp => None,
    }
  }
}

/// THE ITEM WAS NOT TAKEN, and here it is back.
///
/// One refusal for the two ways a send can fail — no room on an impatient door, or nobody there at
/// all — because [`Sender::is_disconnected`] is what tells them apart and the caller that wants the
/// distinction is the one that has to decide about it. [`send`](Sender::send) waits for room, so
/// the only way IT refuses is the second.
///
/// It carries the item because a refused send is not a loss until somebody decides it is: a body
/// holding the value can spool it, route it elsewhere, or end — and one handed a bare failure could
/// only end. This is [`Unfed`](crate::Unfed)'s reading at the general transport, and the two are
/// deliberately the same sentence.
pub struct Unsent<T> {
  item: T,
}

impl<T> Unsent<T> {
  /// The item nobody took.
  #[inline]
  #[must_use]
  pub fn into_inner(self) -> T {
    self.item
  }

  /// The refusal for an item the transport gave back — the one constructor, spent at every door.
  ///
  /// `pub(crate)` rather than private, because [`shard`](crate::shard) refuses with this type too:
  /// a crew's [`route`](crate::shard::Crew::route) waits for room exactly as [`send`](Sender::send)
  /// does, so the only way IT can refuse is the same one — nobody is there at all — and minting a
  /// second refusal saying the same sentence is a type nobody needed.
  #[inline]
  pub(crate) const fn of(item: T) -> Self {
    Self { item }
  }
}

impl<T> core::fmt::Debug for Unsent<T> {
  /// The FACT, never the item — [`Sender`]'s own reason: bounding `T` here would bound every body's
  /// message type on [`Debug`](core::fmt::Debug) for the benefit of this line.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Unsent").finish_non_exhaustive()
  }
}

impl<T> core::fmt::Display for Unsent<T> {
  /// ONE sentence for the two failures, for the type's own reason: which of them it was is a
  /// question [`Sender::is_disconnected`] answers, and a message that guessed would be wrong half
  /// the time.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("the item was not taken — the conduit is full, or every receiver has hung up")
  }
}

impl<T> core::error::Error for Unsent<T> {}

/// ONE arm of a [`select`]: wait on `receiver` unless it has already hung up, wrapping what
/// arrives.
///
/// `None` is that channel's own end — the caller marks the arm closed and selects over what is
/// left. An arm that is already closed NEVER answers, which is what keeps a hung-up channel from
/// spinning the select: a receive on a disconnected channel returns immediately, so re-offering one
/// would be a busy loop rather than a wait.
///
/// `wrap` is what tells the arms apart. Each channel carries its own message type and a select
/// answers ONE, so the arms meet at whatever classification the loop wants — usually an enum of its
/// own turns.
///
/// [`arm`](crate::arm) is this same shape over an [`Inbox`](crate::Inbox) — the framework's own
/// declared edge, one vocabulary over — and a body selecting over both spends the two side by side.
pub async fn arm<T, R>(open: bool, receiver: &Receiver<T>, wrap: impl FnOnce(T) -> R) -> Option<R> {
  if !open {
    // Never resolves. The caller has already decided this channel is finished, and the whole select
    // answers shutdown when every arm is.
    pending::<()>().await;
  }
  receiver.recv_async().await.map(wrap)
}

/// ONE arm of a [`select`], as the slice holds it — a pinned future, erased so that arms of
/// different channels can sit side by side.
///
/// Erased because that is what the question forces: each channel's receive is its own concrete
/// future over its own message type, and a select waits on all of them at once. The values stay
/// where they were pinned — nothing is boxed and nothing is allocated — and `Send` is here because
/// an `&mut` to the slice crosses into an asynchronous body with the loop that holds it.
pub type Arm<'a, T> = Pin<&'a mut (dyn Future<Output = T> + Send + 'a)>;

/// Wait for the FIRST of `arms` to answer, and say WHICH answered.
///
/// `None` where there is nothing to wait on — an empty slice is not a future that hangs, it is the
/// honest "no channel left", which is what a loop whose every arm has closed answers.
///
/// # `from` is the caller's turn, and it is what keeps a busy arm from starving a quiet one
///
/// The walk starts at `from` and wraps, taking the first arm that is ready. A fixed order would let
/// arm zero, if it always has something waiting, mean arm two is never polled at all; a caller that
/// advances `from` past the winner each time gives every channel its turn. The cursor is the
/// CALLER'S because the loop already holds state and one more field there is cheaper than a knob
/// here — which is also why this replaces a channel crate's own randomised selector rather than
/// wrapping one.
///
/// # Dropping the losers loses nothing
///
/// The arms are polled where they lie and the whole set is dropped when one wins. A receive future
/// that is dropped mid-flight deregisters its waker and passes the wake on, and the message it was
/// waiting for is in the channel's own queue rather than in the future — so the next park sees it.
/// The same is true of the deadline in [`park_on`].
pub async fn select<T>(from: usize, arms: &mut [Arm<'_, T>]) -> Option<(usize, T)> {
  poll_fn(move |cx| {
    let count = arms.len();
    if count == 0 {
      return Poll::Ready(None);
    }
    for step in 0..count {
      let index = (from + step) % count;
      if let Poll::Ready(value) = arms[index].as_mut().poll(cx) {
        return Poll::Ready(Some((index, value)));
      }
    }
    Poll::Pending
  })
  .await
}

/// Drive `future` to completion on THIS thread, giving up after `sweep` — the blocking engine's
/// park, and the SYNC spelling of [`select`].
///
/// The select is written once, as a future, and this is the engine that runs it where there is no
/// runtime: an asynchronous body awaits [`select`] and a blocking one hands it here, so the two
/// differ in this one call and in nothing else. `None` is the expiry, which a loop reads as its own
/// sweep.
///
/// A DRIVER and not a runtime: one future, no reactor, no spawn and no dependency —
/// [`Wake`](std::task::Wake) makes the waker and [`park_timeout`](std::thread::park_timeout) is the
/// wait.
#[inline]
pub fn park_on<F>(future: F, sweep: Duration) -> Option<F::Output>
where
  F: Future,
{
  block_until(future, Instant::now().checked_add(sweep))
}

#[cfg(test)]
mod tests;