apis 0.5.13

Reactive, session-oriented, asynchronous process-calculus framework
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
use {std, either, log, smallvec};
use crate::{channel, message, session, Message};

use std::convert::TryFrom;
use std::sync::mpsc;
use std::time;
use vec_map::VecMap;

pub mod inner;
pub mod presult;

pub use self::inner::Inner;
pub use self::presult::Presult;

////////////////////////////////////////////////////////////////////////////////
//  structs                                                                   //
////////////////////////////////////////////////////////////////////////////////

/// Process definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Def <CTX : session::Context> {
  id           : CTX::PID,
  kind         : Kind,
  sourcepoints : Vec <CTX::CID>,
  endpoints    : Vec <CTX::CID>
}

/// Handle to a process held by the session.
pub struct Handle <CTX : session::Context> {
  pub result_rx        : mpsc::Receiver <CTX::GPRES>,
  pub continuation_tx  : mpsc::Sender <session::Continuation <CTX>>,
  /// When the session drops, the `finish` method will either join or send
  /// a continuation depending on the contents of this field.
  pub join_or_continue : either::Either <
    std::thread::JoinHandle <Option <()>>, Option <session::Continuation <CTX>>>
}

////////////////////////////////////////////////////////////////////////////////
//  enums                                                                     //
////////////////////////////////////////////////////////////////////////////////

/// Specifies the loop behavior of a process.
///
/// - `Asynchronous` is a loop that blocks waiting on exactly one channel
///   endpoint.
/// - `Isochronous` is a fixed-timestep loop in which endpoints are polled
///   once per 'tick' and will attempt to "catch up" if it falls behind.
/// - `Mesochronous` is a rate-limited loop that polls processes and loops
///   immediately if enough time has passed and otherwise sleeps for the
///   remaining duration until the next 'tick'.
/// - `Anisochronous` is an un-timed polling loop which always loops immediately
///   and always processes one update per tick.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Kind {
  /// Block waiting on one or more endpoints.
  ///
  /// Asynchronous processes can only hold multiple endpoints of compatible
  /// kinds of channels. Currently this is either any number of sink endpoints,
  /// or else any number and combination of simplex or source endpoints. This is
  /// validated internally when defining an `Def` struct with the provided
  /// kind and endpoints.
  Asynchronous {
    messages_per_update : u32
  },

  /// A fixed-time step polling loop that will try to "catch up" if it falls
  /// behind.
  Isochronous {
    tick_ms          : u32,
    ticks_per_update : u32
  },

  /// A rate-limited polling loop.
  Mesochronous {
    tick_ms          : u32,
    ticks_per_update : u32
  },

  /// Poll to exhaustion and update immediately.
  ///
  /// This is useful for blocking update functions as in a readline loop or a
  /// rendering loop.
  ///
  /// Note that unlike other polling process kinds (`Isochronous` and
  /// `Mesochronous`), ticks and updates are always one-to-one since an
  /// external blocking mechanism is expected to be used in the `update`
  /// function.
  Anisochronous
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ControlFlow {
  Continue,
  Break
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum KindError {
  AsynchronousZeroMessagesPerUpdate,
  IsochronousZeroTickMs,
  IsochronousZeroTicksPerUpdate,
  MesochronousZeroTickMs,
  MesochronousZeroTicksPerUpdate
}

/// Error in `Def`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum DefineError {
  DuplicateSourcepoint,
  DuplicateEndpoint,
  SourcepointEqEndpoint,
  AsynchronousZeroEndpoints,
  AsynchronousMultipleEndpoints
}

////////////////////////////////////////////////////////////////////////////////
//  traits                                                                    //
////////////////////////////////////////////////////////////////////////////////

/// Main process trait.
///
/// Process run loop will end after either all endpoint channels have returned
/// `ControlFlow::Break` from `handle_message()` or else if `update()` returns
/// `ControlFlow::Break`. Note that after the last endpoint channel has closed a
/// final `update()` will still be processed. When `update()` returns
/// `ControlFlow::Break`, no further `handle_message()` calls will be made.
pub trait Process <CTX, RES> where
  CTX  : session::Context,
  RES  : Presult <CTX, Self>,
  Self : TryFrom <CTX::GPROC> + Into <CTX::GPROC>
{
  //
  //  required
  //
  fn new            (inner : Inner <CTX>)            -> Self;
  fn inner_ref      (&self)                          -> &Inner <CTX>;
  fn inner_mut      (&mut self)                      -> &mut Inner <CTX>;
  fn result_ref     (&self)                          -> &RES;
  fn result_mut     (&mut self)                      -> &mut RES;
  fn global_result  (&mut self)                      -> CTX::GPRES;
  fn extract_result (session_results : &mut VecMap <CTX::GPRES>)
    -> Result <RES, String>;
  fn handle_message (&mut self, message : CTX::GMSG) -> ControlFlow;
  fn update         (&mut self)                      -> ControlFlow;

  /// Does nothing by default, may be overridden.
  fn initialize (&mut self) { }
  /// Does nothing by default, may be overridden.
  fn terminate  (&mut self) { }

  //
  //  provided
  //
  #[inline]
  fn id (&self) -> &CTX::PID where CTX : 'static {
    self.def().id()
  }

  #[inline]
  fn kind (&self) -> &Kind where CTX : 'static {
    self.def().kind()
  }

  #[inline]
  fn state_id (&self) -> inner::StateId {
    self.inner_ref().state().id().clone()
  }

  #[inline]
  fn def (&self) -> &Def <CTX> {
    &self.inner_ref().extended_state().def
  }

  #[inline]
  fn sourcepoints (&self) -> &VecMap <Box <dyn channel::Sourcepoint <CTX>>> {
    &self.inner_ref().extended_state().sourcepoints
  }

  #[inline]
  fn sourcepoints_mut (&mut self)
    -> &mut VecMap <Box <dyn channel::Sourcepoint <CTX>>>
  {
    &mut self.inner_mut().extended_state_mut().sourcepoints
  }

  /// This method returns a `Ref <Option <...>>` because during the run loop
  /// the endpoints will be unavailable as they are being iterated over.
  /// Endpoints are automatically waited on or polled in the appropriate
  /// `run_*` function. Endpoints will be present for the calls to `terminate`
  /// or `initialize`, either before or after the run loop, respectively.
  #[inline]
  #[expect(mismatched_lifetime_syntaxes)]
  fn endpoints (&self)
    -> std::cell::Ref <Option <VecMap <Box <dyn channel::Endpoint <CTX>>>>>
  {
    self.inner_ref().extended_state().endpoints.borrow()
  }

  /// This method returns a `Ref <Option <...>>` because during the run loop
  /// the endpoints will be unavailable as they are being iterated over.
  /// Endpoints are automatically waited on or polled in the appropriate
  /// `run_*` function. Endpoints will be present for the calls to `terminate`
  /// or `initialize`, either before or after the run loop, respectively.
  #[inline]
  #[expect(mismatched_lifetime_syntaxes)]
  fn endpoints_mut (&mut self) -> std::cell::RefMut
    <Option <VecMap <Box <dyn channel::Endpoint <CTX>>>>>
  {
    self.inner_ref().extended_state().endpoints.borrow_mut()
  }

  /// This method is used within the process `run_*` methods to get the
  /// endpoints without borrowing the process. Endpoints will then be replaced
  /// with `None` and unavailable within the run loop.
  ///
  /// # Errors
  ///
  /// Taking twice is a fatal error.
  // TODO: error doctest
  #[inline]
  fn take_endpoints (&self) -> VecMap <Box <dyn channel::Endpoint <CTX>>> {
    self.inner_ref().extended_state().endpoints.borrow_mut().take().unwrap()
  }

  /// # Errors
  ///
  /// Error if current endpoints are not `None`.
  #[inline]
  fn put_endpoints (&self,
    endpoints : VecMap <Box <dyn channel::Endpoint <CTX>>>
  ) {
    *self.inner_ref().extended_state().endpoints.borrow_mut()
      = Some (endpoints);
  }

  fn send <M : Message <CTX>> (&self, channel_id : CTX::CID, message : M)
    -> Result <(), channel::SendError <CTX::GMSG>>
  where CTX : 'static {
    let message_name = message.name();
    log::debug!(
      process:?=self.id(), channel:?=channel_id, message=message_name.as_str();
      "process sending message");
    let cid : usize = channel_id.clone().into();
    self.sourcepoints()[cid].send (message.into()).inspect_err (|_|
      log::warn!(
        process:?=self.id(), channel:?=channel_id, message=message_name.as_str();
        "process send error: receiver disconnected"))
  }

  fn send_to <M : Message <CTX>> (
    &self, channel_id : CTX::CID, recipient : CTX::PID, message : M
  ) -> Result <(), channel::SendError <CTX::GMSG>>
    where CTX : 'static
  {
    let message_name = message.name();
    log::debug!(
      process:?=self.id(),
      channel:?=channel_id,
      peer:?=recipient,
      message=message_name.as_str();
      "process sending message to peer");
    let cid : usize = channel_id.clone().into();
    self.sourcepoints()[cid].send_to (message.into(), recipient.clone()).inspect_err (
      |_| log::warn!(
        process:?=self.id(),
        channel:?=channel_id,
        peer:?=recipient,
        message=message_name.as_str();
        "process send to peer error: receiver disconnected"))
  }

  /// Run a process to completion and send the result on the result channel.
  #[inline]
  fn run (&mut self) where
    Self : Sized + 'static,
    CTX  : 'static
  {
    use message::Global;
    debug_assert_eq!(self.state_id(), inner::StateId::Ready);
    self.initialize();
    match *self.kind() {
      Kind::Asynchronous  {..} => self.run_asynchronous(),
      Kind::Isochronous   {..} => self.run_isochronous(),
      Kind::Mesochronous  {..} => self.run_mesochronous(),
      Kind::Anisochronous      => self.run_anisochronous()
    }
    debug_assert_eq!(self.state_id(), inner::StateId::Ended);
    self.terminate();
    // at this point no further messages will be sent or processed so
    // sourcepoints and endpoints are dropped
    self.sourcepoints_mut().clear();
    { // warn of unhandled messages
      let endpoints = self.take_endpoints();
      let mut unhandled_count = 0;
      for (cid, endpoint) in endpoints.iter() {
        #[expect(clippy::cast_possible_truncation)]
        // NOTE: unwrap requires that err is debug
        let Ok (channel_id) = CTX::CID::try_from (cid as channel::IdReprType)
          else { unreachable!() };
        while let Ok (message) = endpoint.try_recv() {
          log::warn!(
            process:?=self.id(),
            channel:?=channel_id,
            message=format!("{:?}({})", message.id(), message.inner_name()).as_str();
            "process unhandled message");
          unhandled_count += 1;
        }
      }
      if unhandled_count > 0 {
        log::warn!(process:?=self.id(), unhandled_message_count=unhandled_count;
          "process ended with unhandled messages");
      }
    }
    debug_assert!(self.sourcepoints().is_empty());
    debug_assert!(self.endpoints().is_none());
    let gpresult = self.global_result();
    let session_handle = &self.inner_ref().as_ref().session_handle;
    session_handle.result_tx.send (gpresult).unwrap();
  }

  /// Run a process to completion, send the result to the session, and proceed
  /// with the continuation received from the session.
  #[inline]
  fn run_continue (mut self) -> Option <()> where
    Self : Sized + 'static,
    CTX  : 'static
  {
    self.run();
    let continuation : session::Continuation <CTX> = {
      let session_handle = &self.inner_ref().as_ref().session_handle;
      session_handle.continuation_rx.recv().unwrap()
    };
    continuation (self.into())
  }

  /// Asynchronous run loop waits for messages on the single endpoint held by
  /// this process and calls the process update method for every $n >= 1$
  /// messages as specified by the process kind.
  fn run_asynchronous (&mut self) where
    Self : Sized,
    CTX  : 'static
  {
    use message::Global;

    self.inner_mut().handle_event (inner::EventParams::Run{}.into()).unwrap();

    let messages_per_update = {
      match *self.kind() {
        Kind::Asynchronous { messages_per_update } => messages_per_update,
        _ => unreachable!(
          "run asynchronous: process kind does not match run function")
      }
    };
    let _t_start = time::Instant::now();
    log::debug!(process:?=self.id(), kind="asynchronous", messages_per_update;
      "process start");
    debug_assert!(1 <= messages_per_update);
    let mut _message_count        = 0;
    let mut update_count          = 0;
    let mut messages_since_update = 0;

    let endpoints = self.take_endpoints();
    { // create a scope here so the endpoints can be returned after this borrow
    let (cid, endpoint) = endpoints.iter().next().unwrap();
    #[expect(clippy::cast_possible_truncation)]
    // NOTE: unwrap requires that err is debug
    let Ok (channel_id) = CTX::CID::try_from (cid as channel::IdReprType)
      else { unreachable!() };
    '_run_loop: while self.state_id() == inner::StateId::Running {
      // wait on message
      match endpoint.recv() {
        Ok (message) => {
          log::debug!(
            process:?=self.id(),
            channel:?=channel_id,
            message=message.inner_name().as_str();
            "process received message");
          let handle_message_result = self.handle_message (message);
          match handle_message_result {
            ControlFlow::Continue => {}
            ControlFlow::Break    => {
              if self.state_id() == inner::StateId::Running {
                self.inner_mut().handle_event (inner::EventParams::End{}.into())
                  .unwrap();
              }
            }
          }
          _message_count         += 1;
          messages_since_update += 1;
        }
        Err (channel::RecvError) => {
          log::info!(process:?=self.id(), channel:?=channel_id;
            "process receive failed: sender disconnected");
          if self.state_id() == inner::StateId::Running {
            self.inner_mut().handle_event (inner::EventParams::End{}.into())
              .unwrap();
          }
        }
      }
      if messages_per_update <= messages_since_update {
        // update
        log::trace!(process:?=self.id(), update=update_count;
          "process update");
        let update_result = self.update();
        match update_result {
          ControlFlow::Continue => {}
          ControlFlow::Break    => {
            if self.state_id() == inner::StateId::Running {
              self.inner_mut().handle_event (inner::EventParams::End{}.into())
                .unwrap();
            }
          }
        }
        update_count += 1;
        messages_since_update = 0;
      }
    } // end 'run_loop
    } // end borrow endpoint
    self.put_endpoints (endpoints);
  } // end fn run_asynchronous

  /// This function implements a fixed-timestep update loop.
  ///
  /// Time is checked immediately after update and the thread is put to sleep
  /// for the time remaining until the next update, plus 1 ms since the thread
  /// usually wakes up slightly before the set time. In practice this means
  /// that the update time lags behind the target time by about 1ms or so, but
  /// the time between updates is consistent. If the thread does somehow wake
  /// up too early, then no update will be done and the thread will sleep or
  /// else loop immediately depending on the result of a second time query.
  ///
  /// After an update, if the next (absolute) tick time has already passed,
  /// then the thread will not sleep and instead will loop immediately. Note
  /// that the tick time is measured on an absolute clock, allowing the thread
  /// to "catch up" in case of a long update by processing the "backlog" of
  /// ticks as fast as possible.
  fn run_isochronous (&mut self) where
    Self : Sized,
    CTX  : 'static
  {
    self.inner_mut().handle_event (inner::EventParams::Run{}.into()).unwrap();

    let t_start = time::Instant::now();
    let (tick_ms, ticks_per_update) = {
      match *self.kind() {
        Kind::Isochronous { tick_ms, ticks_per_update }
          => (tick_ms, ticks_per_update),
        _ => unreachable!(
          "run synchronous: process kind does not match run function")
      }
    };
    log::debug!(
      process:?=self.id(), kind="isochronous", tick_ms, ticks_per_update;
      "process start");
    debug_assert!(1 <= tick_ms);
    debug_assert!(1 <= ticks_per_update);
    let tick_dur = time::Duration::from_millis (tick_ms as u64);
    let mut t_last             = t_start - tick_dur;
    let mut t_next             = t_start;
    let mut ticks_since_update = 0;
    let mut tick_count         = 0;
    let mut message_count      = 0;
    let mut update_count       = 0;

    let endpoints              = self.take_endpoints();
    let mut num_open_channels  = endpoints.len();
    let mut open_channels      = smallvec::SmallVec::<[bool; 8]>::from_vec ({
      let mut v = Vec::with_capacity (num_open_channels);
      v.resize (num_open_channels, true);
      v
    });
    '_run_loop: while self.state_id() == inner::StateId::Running {
      let t_now = time::Instant::now();
      if t_next < t_now {
        log::trace!(
          process:?=self.id(),
          tick=tick_count,
          since_ns=t_now.duration_since (t_next).as_nanos();
          "process tick");
        t_last += tick_dur;
        t_next += tick_dur;

        // poll messages
        poll_messages (self,
          &endpoints, &mut open_channels, &mut num_open_channels, &mut message_count);

        tick_count += 1;
        ticks_since_update += 1;
        debug_assert!(ticks_since_update <= ticks_per_update);
        if ticks_since_update == ticks_per_update {
          log::trace!(process:?=self.id(), update=update_count;
            "process update");
          let update_result = self.update();
          match update_result {
            ControlFlow::Continue => {}
            ControlFlow::Break    => {
              if self.state_id() == inner::StateId::Running {
                self.inner_mut().handle_event (inner::EventParams::End{}.into())
                  .unwrap();
              }
            }
          }
          update_count += 1;
          ticks_since_update = 0;
        }
      } else {
        log::warn!(
          process:?=self.id(),
          tick=tick_count,
          until_ns=t_next.duration_since (t_now).as_nanos();
          "process tick too early");
      }

      let t_after = time::Instant::now();
      if t_after < t_next {
        // must be positive
        let t_until = t_next.duration_since (t_after);
        std::thread::sleep (time::Duration::from_millis (
          1 +  // add 1ms to avoid too-early update
          t_until.as_secs()*1000 +
          t_until.subsec_nanos() as u64/1_000_000))
      } else {
        log::warn!(
          process:?=self.id(),
          tick=tick_count,
          after_ns=t_after.duration_since (t_next).as_nanos();
          "process late tick");
      }

    } // end 'run_loop
    self.put_endpoints (endpoints);
  } // end fn run_isochronous

  /// This function implements a rate-limited update loop.
  ///
  /// Time is checked immediately after update and the thread is put to sleep
  /// for the time remaining until the next update, plus 1 ms since the thread
  /// usually wakes up slightly before the set time. In practice this means
  /// that the update time lags behind the target time by about 1ms or so, but
  /// the time between updates is consistent. If the thread does somehow wake
  /// up too early, then no update will be done and the thread will sleep, or
  /// else loop immediately depending on the result of a second time query.
  ///
  /// After a tick, if the next tick time has already passed, then the thread
  /// will not sleep and instead will loop immediately.
  fn run_mesochronous (&mut self) where
    Self : Sized,
    CTX  : 'static
  {
    self.inner_mut().handle_event (inner::EventParams::Run{}.into()).unwrap();

    let t_start = time::Instant::now();
    let (tick_ms, ticks_per_update) = {
      match *self.kind() {
        Kind::Mesochronous { tick_ms, ticks_per_update }
          => (tick_ms, ticks_per_update),
        _ => unreachable!(
          "run synchronous: process kind does not match run function")
      }
    };
    log::debug!(
      process:?=self.id(), kind="mesochronous", tick_ms, ticks_per_update;
      "process start");
    debug_assert!(1 <= tick_ms);
    debug_assert!(1 <= ticks_per_update);
    let tick_dur = time::Duration::from_millis (tick_ms as u64);
    let mut _t_last            = t_start - tick_dur;
    let mut t_next             = t_start;
    let mut ticks_since_update = 0;
    let mut tick_count         = 0;
    let mut message_count      = 0;
    let mut update_count       = 0;

    let endpoints              = self.take_endpoints();
    let mut num_open_channels  = endpoints.len();
    let mut open_channels      = smallvec::SmallVec::<[bool; 8]>::from_vec ({
      let mut v = Vec::with_capacity (num_open_channels);
      v.resize (num_open_channels, true);
      v
    });
    '_run_loop: while self.state_id() == inner::StateId::Running {
      let t_now = time::Instant::now();
      if t_next < t_now {
        log::trace!(
          process:?=self.id(),
          tick=tick_count,
          since_ns=t_now.duration_since (t_next).as_nanos();
          "process tick");
        _t_last = t_now;
        t_next  = t_now + tick_dur;

        // poll messages
        poll_messages (self,
          &endpoints, &mut open_channels, &mut num_open_channels, &mut message_count);

        tick_count += 1;
        ticks_since_update += 1;
        debug_assert!(ticks_since_update <= ticks_per_update);
        if ticks_since_update == ticks_per_update {
          log::trace!(process:?=self.id(), update=update_count;
            "process update");
          let update_result = self.update();
          match update_result {
            ControlFlow::Continue => {}
            ControlFlow::Break    => {
              if self.state_id() == inner::StateId::Running {
                self.inner_mut().handle_event (inner::EventParams::End{}.into())
                  .unwrap();
              }
            }
          }
          update_count += 1;
          ticks_since_update = 0;
        }
      } else {
        log::warn!(
          process:?=self.id(),
          tick=tick_count,
          until_ns=t_next.duration_since (t_now).as_nanos();
          "process tick too early");
      }

      let t_after = time::Instant::now();
      if t_after < t_next {
        // must be positive
        let t_until = t_next.duration_since (t_after);
        std::thread::sleep (time::Duration::from_millis (
          1 +  // add 1ms to avoid too-early update
          t_until.as_secs()*1000 +
          t_until.subsec_nanos() as u64/1_000_000))
      } else {
        log::warn!(
          process:?=self.id(),
          tick=tick_count,
          after_ns=t_after.duration_since (t_next).as_nanos();
          "process late tick");
      }

    } // end 'run_loop
    self.put_endpoints (endpoints);
  } // end fn run_mesochronous

  /// An un-timed run loop that polls for messages.
  fn run_anisochronous (&mut self) where
    Self : Sized,
    CTX  : 'static
  {
    self.inner_mut().handle_event (inner::EventParams::Run{}.into()).unwrap();

    let _t_start = time::Instant::now();
    debug_assert_eq!(Kind::Anisochronous, *self.kind());
    log::debug!(process:?=self.id(), kind="anisochronous"; "process start");
    let mut message_count = 0;
    let mut update_count  = 0;

    let endpoints = self.take_endpoints();
    let mut num_open_channels = endpoints.len();
    let mut open_channels     = smallvec::SmallVec::<[bool; 8]>::from_vec ({
      let mut v = Vec::with_capacity (num_open_channels);
      v.resize (num_open_channels, true);
      v
    });
    '_run_loop: while self.state_id() == inner::StateId::Running {
      // poll messages
      poll_messages (self,
        &endpoints, &mut open_channels, &mut num_open_channels, &mut message_count);
      // update
      log::trace!(process:?=self.id(), update=update_count; "process update");
      let update_result = self.update();
      match update_result {
        ControlFlow::Continue => {}
        ControlFlow::Break    => {
          if self.state_id() == inner::StateId::Running {
            self.inner_mut().handle_event (inner::EventParams::End{}.into())
              .unwrap()
          }
        }
      }
      update_count += 1;

    } // end 'run_loop
    self.put_endpoints (endpoints);
  } // end fn run_anisochronous

} // end trait Process

pub type IdReprType = u16;
/// Unique identifier with a total mapping to process defs.
pub trait Id <CTX> : Clone + Ord + Into <usize> + TryFrom <IdReprType> +
  std::fmt::Debug + strum::IntoEnumIterator + strum::EnumCount
where
  CTX : session::Context <PID=Self>
{
  fn def (&self) -> Def <CTX>;
  /// Must initialize the concrete process type start running the initial closure.
  fn spawn (inner : Inner <CTX>) -> std::thread::JoinHandle <Option <()>>;
  /// Initialize the concrete proces type and return in a `CTX::GPROC`.
  fn gproc (inner : Inner <CTX>) -> CTX::GPROC;
}

/// The global process type.
pub trait Global <CTX> where
  Self : Sized,
  CTX  : session::Context <GPROC=Self>
{
  fn id (&self) -> CTX::PID;
  fn run (&mut self);
  //fn run_continue (mut self) -> Option <()>;
}

////////////////////////////////////////////////////////////////////////////////
//  impls                                                                     //
////////////////////////////////////////////////////////////////////////////////

impl <CTX : session::Context> Def <CTX> {
  /// The only method to create a valid process def struct. Checks for
  /// duplicate sourcepoints or endpoints, self-loops, and restrictions on
  /// process kind (asynchronous processes are incompatible with certain
  /// combinations of backends).
  ///
  /// # Errors
  ///
  /// Duplicate sourcepoint:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = process::Def::<Mycontext>::define (
  ///   ProcessId::A,
  ///   process::Kind::isochronous_default(),
  ///   vec![ChannelId::X, ChannelId::Z, ChannelId::X],
  ///   vec![ChannelId::Y]);
  /// assert_eq!(
  ///   result, Err (vec![process::DefineError::DuplicateSourcepoint]));
  /// # }
  /// ```
  ///
  /// Duplicate endpoint:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = process::Def::<Mycontext>::define (
  ///   ProcessId::A,
  ///   process::Kind::isochronous_default(),
  ///   vec![ChannelId::X, ChannelId::Z],
  ///   vec![ChannelId::Y, ChannelId::Y]);
  /// assert_eq!(
  ///   result, Err (vec![process::DefineError::DuplicateEndpoint]));
  /// # }
  /// ```
  ///
  /// Self-loop:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # fn main() {
  /// let result = process::Def::<Mycontext>::define (
  ///   ProcessId::A,
  ///   process::Kind::isochronous_default(),
  ///   vec![ChannelId::X, ChannelId::Z],
  ///   vec![ChannelId::Y, ChannelId::Z]);
  /// assert_eq!(
  ///   result, Err (vec![process::DefineError::SourcepointEqEndpoint]));
  /// # }
  /// ```
  ///
  /// Asynchronous process zero endpoints:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # use channel::Id;
  /// # fn main() {
  /// let result = process::Def::<Mycontext>::define (
  ///   ProcessId::A,
  ///   process::Kind::asynchronous_default(),
  ///   vec![ChannelId::Z],
  ///   vec![]);
  /// assert_eq!(
  ///   result,
  ///   Err (vec![process::DefineError::AsynchronousZeroEndpoints]));
  /// # }
  /// ```
  ///
  /// Asynchronous process multiple endpoints:
  ///
  /// ```
  /// # extern crate apis;
  /// # use apis::{channel,message,process};
  /// # use apis::session::mock::*;
  /// # use channel::Id;
  /// # fn main() {
  /// let result = process::Def::<Mycontext>::define (
  ///   ProcessId::A,
  ///   process::Kind::asynchronous_default(),
  ///   vec![ChannelId::Z],
  ///   vec![ChannelId::X, ChannelId::Y]);
  /// assert_eq!(
  ///   result,
  ///   Err (vec![process::DefineError::AsynchronousMultipleEndpoints]));
  /// # }
  /// ```
  ///
  pub fn define (
    id           : CTX::PID,
    kind         : Kind,
    sourcepoints : Vec <CTX::CID>,
    endpoints    : Vec <CTX::CID>
  ) -> Result <Self, Vec <DefineError>> {
    let def = Def {
      id, kind, sourcepoints, endpoints
    };
    def.validate_role() ?;
    Ok (def)
  }

  pub const fn id (&self) -> &CTX::PID {
    &self.id
  }

  pub const fn kind (&self) -> &Kind {
    &self.kind
  }

  pub const fn sourcepoints (&self) -> &Vec <CTX::CID> {
    &self.sourcepoints
  }

  pub const fn endpoints (&self) -> &Vec <CTX::CID> {
    &self.endpoints
  }

  fn validate_role (&self) -> Result <(), Vec <DefineError>> {
    let mut errors = Vec::new();

    // we will not check that a process has zero sourcepoints or endpoints

    // duplicate sourcepoints
    let mut producers_dedup = self.sourcepoints.clone();
    producers_dedup.as_mut_slice().sort();
    producers_dedup.dedup_by (|x,y| x == y);
    if producers_dedup.len() < self.sourcepoints.len() {
      errors.push (DefineError::DuplicateSourcepoint);
    }

    // duplicate endpoints
    let mut consumers_dedup = self.endpoints.clone();
    consumers_dedup.as_mut_slice().sort();
    consumers_dedup.dedup_by (|x,y| x == y);
    if consumers_dedup.len() < self.endpoints.len() {
      errors.push (DefineError::DuplicateEndpoint);
    }

    // self-loops
    let mut producers_and_consumers = producers_dedup.clone();
    producers_and_consumers.append (&mut consumers_dedup.clone());
    producers_and_consumers.as_mut_slice().sort();
    producers_and_consumers.dedup_by (|x,y| x == y);
    if producers_and_consumers.len()
      < producers_dedup.len() + consumers_dedup.len()
    {
      errors.push (DefineError::SourcepointEqEndpoint);
    }

    // validate process kind
    if let Err (mut errs)
      = self.kind.validate_role::<CTX> (&self.sourcepoints, &self.endpoints)
    {
      errors.append (&mut errs);
    }

    if !errors.is_empty() {
      Err (errors)
    } else {
      Ok (())
    }
  }
}

impl Kind {
  pub fn asynchronous_default() -> Self {
    const MESSAGES_PER_UPDATE : u32 = 1;
    Kind::new_asynchronous (MESSAGES_PER_UPDATE).unwrap()
  }

  pub fn isochronous_default() -> Self {
    const TICK_MS          : u32 = 1000;
    const TICKS_PER_UPDATE : u32 = 1;
    Kind::new_isochronous (TICK_MS, TICKS_PER_UPDATE).unwrap()
  }

  pub fn mesochronous_default() -> Self {
    const TICK_MS          : u32 = 1000;
    const TICKS_PER_UPDATE : u32 = 1;
    Kind::new_mesochronous (TICK_MS, TICKS_PER_UPDATE).unwrap()
  }

  pub const fn anisochronous_default() -> Self {
    Kind::new_anisochronous()
  }

  pub fn new_asynchronous (messages_per_update : u32)
    -> Result <Self, Vec <KindError>>
  {
    let mut errors = Vec::new();
    if messages_per_update == 0 {
      errors.push (KindError::AsynchronousZeroMessagesPerUpdate)
    }
    if !errors.is_empty() {
      Err (errors)
    } else {
      Ok (Kind::Asynchronous { messages_per_update })
    }
  }

  pub fn new_isochronous (tick_ms : u32, ticks_per_update : u32)
    -> Result <Self, Vec <KindError>>
  {
    let mut errors = Vec::new();
    if tick_ms == 0 {
      errors.push (KindError::IsochronousZeroTickMs)
    }
    if ticks_per_update == 0 {
      errors.push (KindError::IsochronousZeroTicksPerUpdate)
    }
    if !errors.is_empty() {
      Err (errors)
    } else {
      Ok (Kind::Isochronous { tick_ms, ticks_per_update })
    }
  }

  pub fn new_mesochronous (tick_ms : u32, ticks_per_update : u32)
    -> Result <Self, Vec <KindError>>
  {
    let mut errors = Vec::new();
    if tick_ms == 0 {
      errors.push (KindError::MesochronousZeroTickMs)
    }
    if ticks_per_update == 0 {
      errors.push (KindError::MesochronousZeroTicksPerUpdate)
    }
    if !errors.is_empty() {
      Err (errors)
    } else {
      Ok (Kind::Isochronous { tick_ms, ticks_per_update })
    }
  }

  #[inline]
  pub const fn new_anisochronous() -> Self {
    Kind::Anisochronous
  }

  fn validate_role <CTX : session::Context> (&self,
    _sourcepoints : &[CTX::CID],
    endpoints     : &[CTX::CID]
  ) -> Result <(), Vec <DefineError>> {
    let mut errors = Vec::new();

    match *self {
      Kind::Asynchronous {..} => {
        // asynchronous processes must have exactly one endpoint
        if endpoints.is_empty() {
          errors.push (DefineError::AsynchronousZeroEndpoints)
        } else if 1 < endpoints.len() {
          errors.push (DefineError::AsynchronousMultipleEndpoints)
        }
      }
      Kind::Isochronous   {..} |
      Kind::Mesochronous  {..} |
      Kind::Anisochronous      => { /* no restrictions */ }
    }

    if !errors.is_empty() {
      Err (errors)
    } else {
      Ok (())
    }
  }

} // end impl Kind

impl <M> From <Result <(), channel::SendError <M>>> for ControlFlow {
  fn from (send_result : Result <(), channel::SendError <M>>) -> Self {
    match send_result {
      Ok  (()) => ControlFlow::Continue,
      Err (_)  => ControlFlow::Break
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
//  functions                                                                 //
////////////////////////////////////////////////////////////////////////////////

//
//  public
//
pub fn report_sizes <CTX : session::Context + 'static> () {
  println!("process report sizes...");
  println!("  size of process::Def: {}", size_of::<Def <CTX>>());
  Inner::<CTX>::report_sizes();
  println!("...process report sizes");
}

//
//  private
//

//
//  fn poll_messages
//
/// Message polling loop for `Isochronous`, `Mesochronous`, and `Anisochronous`
/// processes.
#[inline]
fn poll_messages <CTX, P, RES> (
  process           : &mut P,
  endpoints         : &VecMap <Box <dyn channel::Endpoint <CTX>>>,
  open_channels     : &mut smallvec::SmallVec <[bool; 8]>,
  num_open_channels : &mut usize,
  message_count     : &mut usize)
where
  CTX : session::Context + 'static,
  P   : Process <CTX, RES> + Sized,
  RES : Presult <CTX, P>
{
  use message::Global;
  #[inline]
  fn channel_close (is_open : &mut bool, num_open : &mut usize) {
    debug_assert!(*is_open);
    debug_assert!(0 < *num_open);
    *is_open = false;
    *num_open -= 1;
  }

  // for each open channel (outer loop), poll for messages with try_recv (inner loop)
  // until "empty" or "disconnected" is encountered
  'poll_outer: for (open_index, (cid, endpoint)) in endpoints.iter().enumerate() {
    #[expect(clippy::cast_possible_truncation)]
    // NOTE: unwrap requires that err is debug
    let Ok (channel_id) = CTX::CID::try_from (cid as u16) else { unreachable!() };
    let channel_open = &mut open_channels[open_index];
    if !*channel_open {
      continue 'poll_outer
    }
    'poll_inner: loop {
      match endpoint.try_recv() {
        Ok (message) => {
          log::debug!(
            process:?=process.id(),
            channel:?=channel_id,
            message=message.inner_name().as_str();
            "process received message");
          *message_count += 1;
          match process.handle_message (message) {
            ControlFlow::Continue => {}
            ControlFlow::Break    => {
              channel_close (channel_open, num_open_channels);
              // only transition to "ended" if this is the last channel to close
              if *num_open_channels == 0 {
                process.inner_mut().handle_event (
                  inner::EventParams::End{}.into()
                ).unwrap();
              }
              break 'poll_inner
            }
          }
        }
        Err (channel::TryRecvError::Empty) => { break 'poll_inner }
        Err (channel::TryRecvError::Disconnected) => {
          log::info!(process:?=process.id(), channel:?=channel_id;
            "process receive failed: sender disconnected");
          channel_close (channel_open, num_open_channels);
          if *num_open_channels == 0 {
            process.inner_mut().handle_event (inner::EventParams::End{}.into())
              .unwrap();
          }
          break 'poll_inner
        }
      } // end match try_recv
    } // end 'poll_inner
  } // end 'poll_outer
} // end fn poll_messages