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 ;
use ;
use crateblock_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.
/// 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.
/// 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.
/// 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.
// Hand-written so `T` need not be `Clone`: a sender is a handle, and cloning one is what fan-in IS.
/// 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.
/// 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.
// Hand-written for [`Sender`]'s reason, one half over.
/// 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.
/// 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.
/// 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
/// 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> = ;
/// 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
/// 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.