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
//! This is an example of a minimal program that transitions between two
//! sessions and passes a state token between them.
//!
//! Running this example will produce a DOT file representing the program state
//! transition diagram. To create an SVG image from the generated DOT file:
//!
//! ```bash
//! make -f MakefileDot program
//! ```

use std::sync::atomic;

use colored;
use env_logger;
use log;
//use rand;

use apis;

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

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

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

static THING_DROPPED : atomic::AtomicBool = 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, atomic::Ordering::SeqCst);
    assert!(!already_dropped);
  }
}

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

apis::def_program! {
  program Myprogram where
    let result = session.run()
  {
    MODES [
      mode chargen_upcase::ChargenUpcase {
        println!("result: {result:?}");
        Some (EventId::ToRandSource)
      }
      mode rand_source::RandSource
    ]
    TRANSITIONS  [
      transition ToRandSource
        <chargen_upcase::ChargenUpcase> => <rand_source::RandSource> [
          Upcase (upcase) => RandGen (randgen) {
            randgen.dropthing = upcase.dropthing.take();
          }
        ]
    ]
    initial_mode: ChargenUpcase
  }
}

////////////////////////////////////////////////////////////////////////////////
//  mode ChargenUpcase                                                        //
////////////////////////////////////////////////////////////////////////////////

pub mod chargen_upcase {
  use apis;
  use crate::Dropthing;

  apis::def_session! {
    //
    //  context ChargenUpcase
    //
    context ChargenUpcase {
      PROCESSES where
        let process    = self,
        let message_in = message_in
      [
        //
        //  process Chargen
        //
        process Chargen (update_count : u64) {
          kind {
            apis::process::Kind::Isochronous { tick_ms: 20, ticks_per_update: 1 }
          }
          sourcepoints   [Charstream]
          endpoints      []
          handle_message { unreachable!() }
          update {
            #[expect(clippy::useless_let_if_seq)]
            let mut result = apis::process::ControlFlow::Continue;
            if process.update_count % 5 == 0 {
              result = process.send (
                ChannelId::Charstream, Charstreammessage::Achar ('z')
              ).into();
            }
            if process.update_count % 7 == 0 {
              result = process.send (
                ChannelId::Charstream, Charstreammessage::Achar ('y')
              ).into();
            }
            if process.update_count % 9 == 0 {
              result = process.send (
                ChannelId::Charstream, Charstreammessage::Achar ('x')
              ).into();
            }
            process.update_count += 1;
            const MAX_UPDATES : u64 = 5;
            assert!(process.update_count <= MAX_UPDATES);
            if result == apis::process::ControlFlow::Continue
              && process.update_count == MAX_UPDATES
            {
              let _
                = process.send (ChannelId::Charstream, Charstreammessage::Quit);
              result = apis::process::ControlFlow::Break;
            }
            result
          }
        }
        //
        //  process Upcase
        //
        process Upcase (
          history   : String,
          dropthing : Option <Dropthing> = Some (Default::default())
        ) {
          kind           { apis::process::Kind::asynchronous_default() }
          sourcepoints   []
          endpoints      [Charstream]
          handle_message {
            match message_in {
              GlobalMessage::Charstreammessage (charstreammessage) => {
                match charstreammessage {
                  Charstreammessage::Quit => {
                    apis::process::ControlFlow::Break
                  }
                  Charstreammessage::Achar (ch) => {
                    process.history.push (ch.to_uppercase().next().unwrap());
                    apis::process::ControlFlow::Continue
                  }
                }
              }
            }
          }
          update {
            if *process.inner.state().id() == apis::process::inner::StateId::Ended {
              println!("upcase history final: {}", process.history);
            } else {
              println!("upcase history: {}", process.history);
            }
            apis::process::ControlFlow::Continue
          }
        }
      ]
      CHANNELS  [
        channel Charstream <Charstreammessage> (Simplex) {
          producers [Chargen]
          consumers [Upcase]
        }
      ]
      MESSAGES [
        message Charstreammessage {
          Achar (char),
          Quit
        }
      ]
    }
  }

} // end context ChargenUpcase

////////////////////////////////////////////////////////////////////////////////
//  mode RandSource                                                           //
////////////////////////////////////////////////////////////////////////////////

pub mod rand_source {
  use rand;
  use apis;
  use crate::Dropthing;

  apis::def_session! {
    //
    //  context RandSource
    //
    context RandSource {
      PROCESSES where
        let process    = self,
        let message_in = message_in
      [
        //
        //  process RandGen
        //
        process RandGen (
          update_count : u64,
          dropthing    : Option <Dropthing> = None
        ) {
          kind {
            apis::process::Kind::Isochronous { tick_ms: 20, ticks_per_update: 1 }
          }
          sourcepoints   [Randints]
          endpoints      []
          handle_message { unreachable!() }
          update {
            use rand::Rng;
            let mut rng = rand::rng();
            let rand_id = ProcessId::try_from (rng.random_range (1..5)).unwrap();
            let rand_int = rng.random_range (1..100);
            let mut result = process.send_to (
              ChannelId::Randints, rand_id, Randintsmessage::Anint (rand_int)
            ).into();
            process.update_count += 1;
            const MAX_UPDATES : u64 = 5;
            if result == apis::process::ControlFlow::Break
              || MAX_UPDATES < process.update_count
            {
              // quit
              let _ = process.send_to (
                ChannelId::Randints, ProcessId::Sum1, Randintsmessage::Quit);
              let _ = process.send_to (
                ChannelId::Randints, ProcessId::Sum2, Randintsmessage::Quit);
              let _ = process.send_to (
                ChannelId::Randints, ProcessId::Sum3, Randintsmessage::Quit);
              let _ = process.send_to (
                ChannelId::Randints, ProcessId::Sum4, Randintsmessage::Quit);
              result = apis::process::ControlFlow::Break
            }
            result
          }
        }
        //
        //  process Sum1
        //
        process Sum1 (sum : u64) {
          kind           { apis::process::Kind::asynchronous_default() }
          sourcepoints   []
          endpoints      [Randints]
          handle_message {
            match message_in {
              GlobalMessage::Randintsmessage (Randintsmessage::Anint (anint)) => {
                // continue
                process.sum += anint;
                apis::process::ControlFlow::Continue
              }
              GlobalMessage::Randintsmessage (Randintsmessage::Quit) => {
                // quit
                apis::process::ControlFlow::Break
              }
            }
          }
          update {
            if *process.inner.state().id() == apis::process::inner::StateId::Ended {
              println!("sum 1 final: {}", process.sum);
            } else {
              println!("sum 1: {}", process.sum);
            }
            apis::process::ControlFlow::Continue
          }
        }
        //
        //  process Sum2
        //
        process Sum2 (sum : u64) {
          kind           { apis::process::Kind::asynchronous_default() }
          sourcepoints   []
          endpoints      [Randints]
          handle_message {
            match message_in {
              GlobalMessage::Randintsmessage (Randintsmessage::Anint (anint)) => {
                // continue
                process.sum += anint;
                apis::process::ControlFlow::Continue
              }
              GlobalMessage::Randintsmessage (Randintsmessage::Quit) => {
                // quit
                apis::process::ControlFlow::Break
              }
            }
          }
          update {
            if *process.inner.state().id() == apis::process::inner::StateId::Ended {
              println!("sum 2 final: {}", process.sum);
            } else {
              println!("sum 2: {}", process.sum);
            }
            apis::process::ControlFlow::Continue
          }
        }
        //
        //  process Sum3
        //
        process Sum3 (sum : u64) {
          kind           { apis::process::Kind::asynchronous_default() }
          sourcepoints   []
          endpoints      [Randints]
          handle_message {
            match message_in {
              GlobalMessage::Randintsmessage (Randintsmessage::Anint (anint)) => {
                // continue
                process.sum += anint;
                apis::process::ControlFlow::Continue
              }
              GlobalMessage::Randintsmessage (Randintsmessage::Quit) => {
                // quit
                apis::process::ControlFlow::Break
              }
            }
          }
          update {
            if *process.inner.state().id() == apis::process::inner::StateId::Ended {
              println!("sum 3 final: {}", process.sum);
            } else {
              println!("sum 3: {}", process.sum);
            }
            apis::process::ControlFlow::Continue
          }
        }
        //
        //  process Sum4
        //
        process Sum4 (sum : u64) {
          kind           { apis::process::Kind::asynchronous_default() }
          sourcepoints   []
          endpoints      [Randints]
          handle_message {
            match message_in {
              GlobalMessage::Randintsmessage (Randintsmessage::Anint (anint)) => {
                // continue
                process.sum += anint;
                apis::process::ControlFlow::Continue
              }
              GlobalMessage::Randintsmessage (Randintsmessage::Quit) => {
                // quit
                apis::process::ControlFlow::Break
              }
            }
          }
          update {
            if *process.inner.state().id() == apis::process::inner::StateId::Ended {
              println!("sum 4 final: {}", process.sum);
            } else {
              println!("sum 4: {}", process.sum);
            }
            apis::process::ControlFlow::Continue
          }
        }
      ]
      CHANNELS  [
        channel Randints <Randintsmessage> (Source) {
          producers [RandGen]
          consumers [Sum1, Sum2, Sum3, Sum4]
        }
      ]
      MESSAGES [
        message Randintsmessage {
          Anint (u64),
          Quit
        }
      ]
    }
  } // end context RandSource
}

////////////////////////////////////////////////////////////////////////////////
//  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 (Myprogram::dotfile().as_bytes()).unwrap();
  drop (f);

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

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