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
//! This is an example of an interactive command-line program that transitions
//! between two sessions and passes a state token between them.
//!
//! Each mode (session) is a readline loop sending messages to an echo server
//! and receiving replies on a pair of one-way channels. In the first mode, the
//! echo server will convert the message to ALL CAPS before sending the reply.
//! In the second mode the echo server will reverse the message before sending
//! the reply. Use the ':quit' command to transition from the first mode to the
//! second, and to quit the program from the second mode.
//!
//! Note that it is possible to generate orphan message ('unhandled message')
//! warnings. If the readline loop iterates to wait on user input before the
//! echo server reply is received, then that message will stay in the queue
//! until the user presses 'Enter', at which point the readline update function
//! ends and a message handling round is initiated. If instead the user types in
//! a quit command ':quit' before pressing 'Enter', readline process will end
//! immediately after the update and will *not* handle messages, resulting in an
//! orphan message warning.
//!
//! Running this example will produce a DOT file representing the program state
//! transition diagram. To create a PNG image from the generated DOT file:
//!
//! ```bash
//! make -f MakefileDot interactive
//! ```

#![feature(pattern)]

use colored;
use env_logger;
use log;

use apis;

////////////////////////////////////////////////////////////////////////////////
//  constants                                                                 //
////////////////////////////////////////////////////////////////////////////////

//  Off, Error, Warn, Info, Debug, Trace
pub const LOG_LEVEL : log::LevelFilter = log::LevelFilter::Info;

////////////////////////////////////////////////////////////////////////////////
//  globals                                                                   //
////////////////////////////////////////////////////////////////////////////////

static THING_DROPPED : std::sync::atomic::AtomicBool =
  std::sync::atomic::AtomicBool::new (false);

////////////////////////////////////////////////////////////////////////////////
//  datatypes                                                                 //
////////////////////////////////////////////////////////////////////////////////

/// We use this to demonstrate transferring a value from a process in one
/// session to a process in the following session.
#[derive(Debug,Default)]
pub struct Dropthing;
impl Drop for Dropthing {
  fn drop (&mut self) {
    println!("dropping...");
    let already_dropped
      = THING_DROPPED.swap (true, std::sync::atomic::Ordering::SeqCst);
    assert!(!already_dropped);
  }
}

////////////////////////////////////////////////////////////////////////////////
//  program                                                                   //
////////////////////////////////////////////////////////////////////////////////

apis::def_program! {
  program Interactive where
    let result = session.run()
  {
    MODES [
      mode readline_echoup::ReadlineEchoup {
        println!("result: {result:?}");
        Some (EventId::ToReadlineEchorev)
      }
      mode readline_echorev::ReadlineEchorev
    ]
    TRANSITIONS  [
      transition ToReadlineEchorev
        <readline_echoup::ReadlineEchoup> => <readline_echorev::ReadlineEchorev> [
          Readline (readline_up) => Readline (readline_rev) {
            readline_rev.dropthing = readline_up.dropthing.take();
          }
        ]
    ]
    initial_mode: ReadlineEchoup
  }
}

////////////////////////////////////////////////////////////////////////////////
//  mode ReadlineEchoup                                                       //
////////////////////////////////////////////////////////////////////////////////

pub mod readline_echoup {
  use std;
  use apis;
  use crate::Dropthing;

  apis::def_session! {
    context ReadlineEchoup {
      PROCESSES where
        let process    = self,
        let message_in = message_in
      [
        process Readline (
          dropthing : Option <Dropthing> = Some (Default::default())
        ) -> (Option <()>) {
          kind           { apis::process::Kind::Anisochronous }
          sourcepoints   [Toecho]
          endpoints      [Fromecho]
          handle_message { process.readline_handle_message (message_in) }
          update         { process.readline_update() }
        }
        process Echoup () -> (Option <()>) {
          kind           { apis::process::Kind::asynchronous_default() }
          sourcepoints   [Fromecho]
          endpoints      [Toecho]
          handle_message { process.echoup_handle_message (message_in) }
          update         { process.echoup_update() }
        }
      ]
      CHANNELS  [
        channel Toecho <ToechoMsg> (Simplex) {
          producers [Readline]
          consumers [Echoup]
        }
        channel Fromecho <FromechoMsg> (Simplex) {
          producers [Echoup]
          consumers [Readline]
        }
      ]
      MESSAGES [
        message ToechoMsg {
          Astring (String),
          Quit
        }
        message FromechoMsg {
          Echo (String)
        }
      ]
      main: Readline
    }
  }

  impl Readline {
    #[expect(clippy::unused_self)]
    fn readline_handle_message (&self, message : GlobalMessage)
      -> apis::process::ControlFlow
    {
      log::trace!("readline handle message...");
      match message {
        GlobalMessage::FromechoMsg (FromechoMsg::Echo (echo)) => {
          log::info!("Readline: received echo \"{echo}\"");
        },
        _ => unreachable!()
      }
      log::trace!("...readline handle message");
      apis::process::ControlFlow::Continue
    }

    fn readline_update (&self) -> apis::process::ControlFlow {
      use std::io::Write;
      use apis::Process;

      log::trace!("readline update...");

      assert_eq!("main", std::thread::current().name().unwrap());

      let mut result = apis::process::ControlFlow::Continue;
      print!(" > ");
      let _     = std::io::stdout().flush();
      let mut s = String::new();
      let _     = std::io::stdin().read_line (&mut s);
      if !s.trim_end().is_empty() {
        let word_ct = s.as_str().split_whitespace().count();
        match word_ct {
          0 => unreachable!("zero words in server input readline parse"),
          _ => {
            let command = {
              let mut words = s.as_str().split_whitespace();
              let mut first = words.next().unwrap().to_string();
              if first.starts_with (':') {
                use std::str::pattern::Pattern;
                debug_assert!(0 < first.len());
                let _ = first.remove (0);
                if 0 < first.len() && first.is_prefix_of ("quit") {
                  let _ = self.send (ChannelId::Toecho, ToechoMsg::Quit);
                  result = apis::process::ControlFlow::Break;
                } else {
                  println!("unrecognized command: \"{}\"", s.trim());
                }
                true
              } else {
                false
              }
            };
            if !command {
              result = self.send (
                ChannelId::Toecho, ToechoMsg::Astring (s.trim().to_string())
              ).into();
            }
          }
        } // end match word count
      } // end input not empty

      log::trace!("...readline update");

      result
    }
  }
  // end impl Readline

  impl Echoup {
    fn echoup_handle_message (&self, message : GlobalMessage)
      -> apis::process::ControlFlow
    {
      use apis::Process;
      log::trace!("echoup handle message...");
      let GlobalMessage::ToechoMsg (msg) = message else { unreachable!() };
      let result = match msg {
        ToechoMsg::Astring (string) => {
          let echo = string.as_str().to_uppercase();
          self.send (ChannelId::Fromecho, FromechoMsg::Echo (echo)).into()
        }
        ToechoMsg::Quit => apis::process::ControlFlow::Break
      };
      log::trace!("...echoup handle message");
      result
    }

    #[expect(clippy::unused_self)]
    fn echoup_update  (&self) -> apis::process::ControlFlow {
      log::trace!("echoup update...");
      /* do nothing */
      log::trace!("...echoup update");
      apis::process::ControlFlow::Continue
    }
  }
  // end impl Echoup

} // end mod readline_echoup

////////////////////////////////////////////////////////////////////////////////
//  mode ReadlineEchorev                                                      //
////////////////////////////////////////////////////////////////////////////////

pub mod readline_echorev {
  use std;
  use apis;
  use crate::Dropthing;

  apis::def_session! {
    context ReadlineEchorev {
      PROCESSES where
        let process    = self,
        let message_in = message_in
      [
        process Echorev () -> (Option <()>) {
          kind           { apis::process::Kind::asynchronous_default() }
          sourcepoints   [Fromecho]
          endpoints      [Toecho]
          handle_message { process.echorev_handle_message (message_in) }
          update         { process.echorev_update() }
        }
        process Readline (
          dropthing : Option <Dropthing> = None
        ) -> (Option <()>) {
          kind           { apis::process::Kind::Anisochronous }
          sourcepoints   [Toecho]
          endpoints      [Fromecho]
          handle_message { process.readline_handle_message (message_in) }
          update         { process.readline_update() }
        }
      ]
      CHANNELS  [
        channel Toecho <ToechoMsg> (Simplex) {
          producers [Readline]
          consumers [Echorev]
        }
        channel Fromecho <FromechoMsg> (Simplex) {
          producers [Echorev]
          consumers [Readline]
        }
      ]
      MESSAGES [
        message ToechoMsg {
          Astring (String),
          Quit
        }
        message FromechoMsg {
          Echo (String)
        }
      ]
      main: Readline
    }
  }

  impl Readline {
    #[expect(clippy::unused_self)]
    fn readline_handle_message (&self, message : GlobalMessage)
      -> apis::process::ControlFlow
    {
      log::trace!("readline handle message...");
      match message {
        GlobalMessage::FromechoMsg (FromechoMsg::Echo (echo)) => {
          log::info!("Readline: received echo \"{echo}\"");
        },
        _ => unreachable!()
      }
      log::trace!("...readline handle message");
      apis::process::ControlFlow::Continue
    }

    fn readline_update (&self) -> apis::process::ControlFlow {
      use std::io::Write;
      use apis::Process;

      log::trace!("readline update...");

      assert_eq!("main", std::thread::current().name().unwrap());

      let mut result = apis::process::ControlFlow::Continue;
      print!(" > ");
      let _     = std::io::stdout().flush();
      let mut s = String::new();
      let _     = std::io::stdin().read_line (&mut s);
      if !s.trim_end().is_empty() {
        let word_ct = s.as_str().split_whitespace().count();
        match word_ct {
          0 => unreachable!("zero words in server input readline parse"),
          _ => {
            let command = {
              let mut words = s.as_str().split_whitespace();
              let mut first = words.next().unwrap().to_string();
              if first.starts_with (':') {
                use std::str::pattern::Pattern;
                debug_assert!(0 < first.len());
                let _ = first.remove (0);
                if 0 < first.len() && first.is_prefix_of ("quit") {
                  let _ = self.send (ChannelId::Toecho, ToechoMsg::Quit);
                  result = apis::process::ControlFlow::Break;
                } else {
                  println!("unrecognized command: \"{}\"", s.trim());
                }
                true
              } else {
                false
              }
            };
            if !command {
              result = self.send (
                ChannelId::Toecho, ToechoMsg::Astring (s.trim().to_string())
              ).into();
            }
          }
        } // end match word count
      } // end input not empty

      log::trace!("...readline update");

      result
    }
  }
  // end impl Readline

  impl Echorev {
    fn echorev_handle_message (&self, message : GlobalMessage)
      -> apis::process::ControlFlow
    {
      use apis::Process;
      log::trace!("echorev handle message...");
      let GlobalMessage::ToechoMsg (msg) = message else { unreachable!() };
      let result = match msg {
        ToechoMsg::Astring (string) => {
          let echo = string.chars().rev().collect();
          self.send (ChannelId::Fromecho, FromechoMsg::Echo (echo)).into()
        }
        ToechoMsg::Quit => apis::process::ControlFlow::Break
      };
      log::trace!("...echorev handle message");
      result
    }

    #[expect(clippy::unused_self)]
    fn echorev_update  (&self) -> apis::process::ControlFlow {
      log::trace!("echorev update...");
      /* do nothing */
      log::trace!("...echorev update");
      apis::process::ControlFlow::Continue
    }
  }
  // end impl Echorev
} // end mod readline_echorev

////////////////////////////////////////////////////////////////////////////////
//  main                                                                      //
////////////////////////////////////////////////////////////////////////////////

fn main() {
  use colored::Colorize;
  let example_name = std::path::PathBuf::from (std::env::args().next().unwrap())
    .file_name().unwrap().to_str().unwrap().to_string();

  println!("{}", format!("{example_name} main...").green().bold());

  env_logger::Builder::new()
    .filter_level (LOG_LEVEL)
    .parse_default_env()
    .init();

  // create a dotfile for the program state machine
  use std::io::Write;
  let mut f = std::fs::File::create (format!("{example_name}.dot")).unwrap();
  f.write_all (Interactive::dotfile().as_bytes()).unwrap();
  drop (f);

  // show some information about the program
  Interactive::report_sizes();

  // create a program in the initial mode
  println!(":quit to quit");
  use apis::Program;
  let mut myprogram = Interactive::initial();
  //debug!("myprogram: {:#?}", myprogram);
  // run to completion
  myprogram.run();

  println!("{}", format!("...{example_name} main").green().bold());
}