ixa/
external_api.rs

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
use crate::context::Context;
use crate::error::IxaError;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

pub(crate) trait ExtApi {
    type Args: DeserializeOwned;
    type Retval: Serialize;

    fn run(context: &mut Context, args: &Self::Args) -> Result<Self::Retval, IxaError>;
}

#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct EmptyArgs {}

pub(crate) fn run_ext_api<T: ExtApi>(
    context: &mut Context,
    args: &T::Args,
) -> Result<T::Retval, IxaError> {
    T::run(context, args)
}

pub(crate) mod population {
    use crate::context::Context;
    use crate::external_api::EmptyArgs;
    use crate::people::ContextPeopleExt;
    use crate::IxaError;
    use clap::Parser;
    use serde::{Deserialize, Serialize};

    pub(crate) struct Api {}
    #[derive(Parser, Debug, Deserialize)]
    pub(crate) enum Args {
        /// Get the total number of people
        Population,
    }

    #[derive(Serialize)]
    pub(crate) struct Retval {
        pub population: usize,
    }
    impl super::ExtApi for Api {
        type Args = EmptyArgs;
        type Retval = Retval;

        fn run(context: &mut Context, _args: &EmptyArgs) -> Result<Retval, IxaError> {
            Ok(Retval {
                population: context.get_current_population(),
            })
        }
    }
}

pub(crate) mod global_properties {
    use crate::context::Context;
    use crate::global_properties::ContextGlobalPropertiesExt;
    use crate::IxaError;
    use clap::{Parser, Subcommand};
    use serde::{Deserialize, Serialize};

    pub(crate) struct Api {}
    #[derive(Serialize, Deserialize, Debug)]
    pub(crate) enum Retval {
        List(Vec<String>),
        Value(String),
    }
    #[derive(Subcommand, Clone, Debug, Serialize, Deserialize)]
    /// Access global properties
    pub(crate) enum ArgsEnum {
        /// List all global properties
        List,

        /// Get the value of a global property
        Get {
            /// The property name
            property: String,
        },
    }

    #[derive(Parser, Debug, Serialize, Deserialize)]
    pub(crate) enum Args {
        #[command(subcommand)]
        Global(ArgsEnum),
    }
    impl super::ExtApi for Api {
        type Args = Args;
        type Retval = Retval;

        fn run(context: &mut Context, args: &Args) -> Result<Retval, IxaError> {
            let Args::Global(global_args) = args;

            match global_args {
                ArgsEnum::List => Ok(Retval::List(context.list_registered_global_properties())),
                ArgsEnum::Get { property: name } => {
                    let output = context.get_serialized_value_by_string(name)?;
                    match output {
                        Some(value) => Ok(Retval::Value(value)),
                        None => Err(IxaError::IxaError(format!("Property {name} is not set"))),
                    }
                }
            }
        }
    }
}

pub(crate) mod breakpoint {
    use crate::context::Context;
    use crate::debugger::enter_debugger;
    use crate::web_api::enter_web_debugger;
    use crate::{info, trace, IxaError};
    use clap::{Parser, Subcommand};
    use serde::{Deserialize, Serialize};

    #[derive(Subcommand, Clone, Debug, Serialize, Deserialize)]
    /// Manipulate Debugger Breakpoints
    pub(crate) enum ArgsEnum {
        /// List all scheduled breakpoints
        List,
        /// Set a breakpoint at a given time
        Set {
            #[arg(required = true)]
            time: f64,
            #[arg(long, hide = true, default_value_t = true)]
            console: bool,
        },
        /// Delete the breakpoint with the specified id.
        /// Providing the `--all` option removes all breakpoints.
        #[group(multiple = false, required = true)]
        Delete {
            /// The ID of the breakpoint to delete
            #[arg(value_name = "ID")]
            id: Option<u32>,

            /// Remove all breakpoints
            #[arg(long, action)]
            all: bool,
        },
        /// Disables but does not delete breakpoints globally
        Disable,
        /// Enables breakpoints globally
        Enable,
    }

    #[derive(Parser, Debug, Serialize, Deserialize)]
    pub(crate) enum Args {
        #[command(subcommand)]
        Breakpoint(ArgsEnum),
    }

    #[derive(Serialize, Deserialize, Debug)]
    pub(crate) enum Retval {
        List(Vec<String>),
        Ok,
    }

    pub(crate) struct Api {}
    impl super::ExtApi for Api {
        type Args = Args;
        type Retval = Retval;

        fn run(context: &mut Context, args: &Args) -> Result<Retval, IxaError> {
            let Args::Breakpoint(breakpoint_args) = args;

            match breakpoint_args {
                ArgsEnum::List => {
                    trace!("Listing breakpoints");
                    let list = context.list_breakpoints(0);
                    let list = list
                        .iter()
                        .map(|schedule| {
                            format!(
                                "{}: t={} ({})",
                                schedule.plan_id, schedule.time, schedule.priority
                            )
                        })
                        .collect::<Vec<String>>();
                    Ok(Retval::List(list))
                }

                ArgsEnum::Set { time, console } => {
                    if *time < context.get_current_time() {
                        return Err(IxaError::from(format!(
                            "Breakpoint time {time} is in the past"
                        )));
                    }

                    if *console {
                        context.schedule_debugger(*time, None, Box::new(enter_debugger));
                    } else {
                        context.schedule_debugger(*time, None, Box::new(enter_web_debugger));
                    }

                    info!("Breakpoint set at t={time}");
                    Ok(Retval::Ok)
                }

                ArgsEnum::Delete { id, all } => {
                    if let Some(id) = id {
                        assert!(!all);
                        trace!("Deleting breakpoint {id}");
                        let cancelled = context.delete_breakpoint(u64::from(*id));
                        if cancelled.is_none() {
                            Err(IxaError::from(format!(
                                "Attempted to delete a nonexistent breakpoint {id}",
                            )))
                        } else {
                            Ok(Retval::Ok)
                        }
                    } else {
                        assert!(all);
                        trace!("Deleting all breakpoints");
                        context.clear_breakpoints();
                        Ok(Retval::Ok)
                    }
                }

                ArgsEnum::Disable => {
                    trace!("Disabling all breakpoints");
                    context.disable_breakpoints();
                    Ok(Retval::Ok)
                }

                ArgsEnum::Enable => {
                    trace!("Enabling all breakpoints");
                    context.enable_breakpoints();
                    Ok(Retval::Ok)
                }
            }
        }
    }
}

pub(crate) mod next {
    use crate::context::Context;
    use crate::external_api::EmptyArgs;
    use crate::IxaError;
    use clap::Parser;
    use serde::Serialize;
    use serde_derive::Deserialize;

    #[derive(Parser, Debug, Serialize, Deserialize)]
    pub enum Args {
        /// Execute the next item in the event loop
        Next,
    }

    #[derive(Serialize)]
    pub(crate) enum Retval {
        Ok,
    }
    #[allow(unused)]
    pub(crate) struct Api {}
    impl super::ExtApi for Api {
        type Args = EmptyArgs;
        type Retval = Retval;

        fn run(_context: &mut Context, _args: &EmptyArgs) -> Result<Retval, IxaError> {
            // This is a no-op which allows for arg checking.
            Ok(Retval::Ok)
        }
    }
}

pub(crate) mod halt {
    use crate::context::Context;
    use crate::external_api::EmptyArgs;
    use crate::IxaError;
    use clap::Parser;
    use serde::Serialize;
    use serde_derive::Deserialize;

    #[derive(Parser, Debug, Serialize, Deserialize)]
    pub enum Args {
        /// End the simulation
        Halt,
    }

    #[derive(Serialize)]
    pub(crate) enum Retval {
        Ok,
    }
    #[allow(unused)]
    pub(crate) struct Api {}
    impl super::ExtApi for Api {
        type Args = EmptyArgs;
        type Retval = Retval;

        fn run(_context: &mut Context, _args: &EmptyArgs) -> Result<Retval, IxaError> {
            // This is a no-op which allows for arg checking.
            Ok(Retval::Ok)
        }
    }
}

pub(crate) mod r#continue {
    use crate::context::Context;
    use crate::external_api::EmptyArgs;
    use crate::IxaError;
    use clap::Parser;
    use serde_derive::{Deserialize, Serialize};

    #[derive(Parser, Debug, Serialize, Deserialize)]
    pub enum Args {
        /// Continue running the simulation
        Continue,
    }

    #[derive(Serialize)]
    pub(crate) enum Retval {
        Ok,
    }
    #[allow(unused)]
    pub(crate) struct Api {}
    impl super::ExtApi for Api {
        type Args = EmptyArgs;
        type Retval = Retval;

        fn run(_context: &mut Context, _args: &EmptyArgs) -> Result<Retval, IxaError> {
            // This is a no-op which allows for arg checking.
            Ok(Retval::Ok)
        }
    }
}

pub(crate) mod people {
    use std::cell::RefCell;
    use std::collections::HashMap;

    use crate::people::{external_api::ContextPeopleExtCrate, ContextPeopleExt, PersonId};
    use crate::Context;
    use crate::IxaError;
    use clap::{Parser, Subcommand};
    use serde::{Deserialize, Serialize};

    fn person_id_from_str(s: &str) -> Result<PersonId, String> {
        match s.parse::<usize>() {
            Ok(id) => Ok(PersonId(id)),
            Err(_) => Err("Person id must be an integer".to_string()),
        }
    }

    #[derive(Subcommand, Clone, Debug, Serialize, Deserialize)]
    pub(crate) enum ArgsEnum {
        /// Get the value of a property for a person
        Get {
            #[arg(value_parser = person_id_from_str)]
            person_id: PersonId,
            property: String,
        },
        Query {
            #[clap(skip)]
            properties: Vec<(String, String)>,
        },
        /// Tabulate the values of a set of properties
        Tabulate {
            properties: Vec<String>,
        },
        Properties,
    }

    #[derive(Parser, Debug, Serialize, Deserialize)]
    pub(crate) enum Args {
        /// Access people properties
        #[command(subcommand)]
        People(ArgsEnum),
    }

    #[derive(Serialize, Debug, Eq, PartialEq)]
    pub(crate) enum Retval {
        Properties(Vec<(String, String)>),
        Tabulated(Vec<(HashMap<String, String>, usize)>),
        PropertyNames(Vec<String>),
    }
    pub(crate) struct Api {}

    impl super::ExtApi for Api {
        type Args = Args;
        type Retval = Retval;

        fn run(context: &mut Context, args: &Args) -> Result<Retval, IxaError> {
            match args {
                Args::People(args_enum) => match args_enum {
                    ArgsEnum::Get {
                        person_id,
                        property,
                    } => {
                        if person_id.0 >= context.get_current_population() {
                            return Err(IxaError::IxaError(format!(
                                "No person with id {person_id:?}"
                            )));
                        }
                        let value = context.get_person_property_by_name(property, *person_id)?;
                        Ok(Retval::Properties(vec![(property.clone(), value)]))
                    }
                    ArgsEnum::Query { properties: _ } => Err(IxaError::IxaError(String::from(
                        "People querying not implemented",
                    ))),
                    ArgsEnum::Tabulate { properties } => {
                        let results = RefCell::new(Vec::new());

                        context.tabulate_person_properties_by_name(
                            properties.clone(),
                            |_, values, count| {
                                let mut hm = HashMap::new();
                                for (key, value) in properties.iter().zip(values.iter()) {
                                    hm.insert(key.clone(), value.clone());
                                }
                                results.borrow_mut().push((hm, count));
                            },
                        )?;
                        Ok(Retval::Tabulated(results.take()))
                    }
                    ArgsEnum::Properties => {
                        Ok(Retval::PropertyNames(context.get_person_property_names()))
                    }
                },
            }
        }
    }

    #[cfg(test)]
    mod test {
        use super::*;
        use crate::external_api::run_ext_api;
        use crate::{define_person_property, Context};
        use std::collections::HashSet;
        #[test]
        fn query_nonexistent_user() {
            let mut context = Context::new();

            let res = run_ext_api::<super::Api>(
                &mut context,
                &Args::People(ArgsEnum::Get {
                    person_id: PersonId(0),
                    property: String::from("abc"),
                }),
            );

            println!("{res:?}");
            assert!(matches!(res, Err(IxaError::IxaError(_))));
        }

        #[test]
        fn query_nonexistent_property() {
            let mut context = Context::new();
            let _ = context.add_person(());
            let res = run_ext_api::<super::Api>(
                &mut context,
                &Args::People(ArgsEnum::Get {
                    person_id: PersonId(0),
                    property: String::from("abc"),
                }),
            );

            println!("{res:?}");
            assert!(matches!(res, Err(IxaError::IxaError(_))));
        }

        define_person_property!(Age, u8);

        #[test]
        fn query_valid_property() {
            let mut context = Context::new();
            let _ = context.add_person((Age, 10));
            let res = run_ext_api::<super::Api>(
                &mut context,
                &Args::People(ArgsEnum::Get {
                    person_id: PersonId(0),
                    property: String::from("Age"),
                }),
            );

            println!("{res:?}");
            let res = res.unwrap();
            #[allow(clippy::match_wildcard_for_single_variants)]
            match res {
                Retval::Properties(val) => {
                    assert_eq!(val, vec![(String::from("Age"), String::from("10"))]);
                }
                _ => panic!("Unexpected result"),
            }
        }

        #[test]
        fn tabulate() {
            let mut context = Context::new();
            let _ = context.add_person((Age, 10));
            let _ = context.add_person((Age, 20));

            let res = run_ext_api::<super::Api>(
                &mut context,
                &Args::People(ArgsEnum::Tabulate {
                    properties: vec![String::from("Age")],
                }),
            );
            println!("{res:?}");
            let res = res.unwrap();
            let mut expected = HashSet::new();
            expected.insert(String::from("10"));
            expected.insert(String::from("20"));

            #[allow(clippy::match_wildcard_for_single_variants)]
            match res {
                Retval::Tabulated(val) => {
                    for (columns, ct) in val {
                        assert_eq!(ct, 1);
                        let age = columns.get("Age").unwrap();
                        assert!(expected.remove(age));
                    }
                    assert_eq!(expected.len(), 0);
                }
                _ => panic!("Unexpected result"),
            }
        }

        #[test]
        fn get_person_property_names() {
            let mut context = Context::new();
            let _ = context.add_person((Age, 10));
            let _ = context.add_person((Age, 20));

            let res = run_ext_api::<super::Api>(&mut context, &Args::People(ArgsEnum::Properties));
            println!("{res:?}");
            let res = res.unwrap();

            #[allow(clippy::match_wildcard_for_single_variants)]
            match res {
                Retval::PropertyNames(names) => assert_eq!(names, vec!["Age"]),
                _ => panic!("Unexpected result"),
            }
        }
    }
}

pub(crate) mod time {
    #![allow(clippy::float_cmp)]
    use crate::context::Context;
    use crate::external_api::EmptyArgs;
    use crate::IxaError;
    use clap::Parser;
    use serde::{Deserialize, Serialize};

    pub(crate) struct Api {}
    #[derive(Parser, Debug, Deserialize)]
    pub(crate) enum Args {
        /// Get the time of the simulation.
        Time,
    }

    #[derive(Serialize)]
    pub(crate) struct Retval {
        pub time: f64,
    }
    impl super::ExtApi for Api {
        type Args = super::EmptyArgs;
        type Retval = Retval;

        fn run(context: &mut Context, _args: &EmptyArgs) -> Result<Retval, IxaError> {
            Ok(Retval {
                time: context.get_current_time(),
            })
        }
    }

    #[cfg(test)]
    mod test {
        use crate::Context;

        #[test]
        fn test() {
            let mut context = Context::new();

            let result = crate::external_api::run_ext_api::<super::Api>(
                &mut context,
                &crate::external_api::EmptyArgs {},
            );

            assert_eq!(result.unwrap().time, 0.0);
        }
    }
}