nexosim 1.0.0

A high performance asynchronous compute framework for system simulation.
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
//! Model components.
//!
//! # Models and model prototypes
//!
//! Every model must implement the [`trait@Model`] trait. This trait defines an
//! asynchronous initialization method, [`Model::init`], which main purpose is
//! to enable models to perform specific actions when the simulation starts,
//! *i.e.* after all models have been connected and added to the simulation.
//!
//! It is frequently convenient to expose to users a model builder type—called a
//! *model prototype*—rather than the final model. This can be done by
//! implementing the [`ProtoModel`] trait, which defines the associated model
//! type and a [`ProtoModel::build`] method invoked when a model is added the
//! simulation.
//!
//! Prototype models can be used whenever the Rust builder pattern is helpful,
//! for instance to set optional parameters. One of the use-cases that may
//! benefit from the use of prototype models is hierarchical model building.
//! When a parent model contains submodels, these submodels are often an
//! implementation detail that needs not be exposed to the user. One may then
//! define a prototype model that contains all outputs and requestors ports,
//! while the model itself contains the input and replier ports. Upon invocation
//! of [`ProtoModel::build`], the exit ports are moved to the model or its
//! submodels, and those submodels are added to the simulation.
//!
//! A trivial [`ProtoModel`] implementation is generated by default for any
//! object implementing the [`trait@Model`] trait, provided its [`Model::Env`]
//! associated type implements [`Default`] trait. In such case, the associated
//! [`ProtoModel::Model`] type is the model type itself. This is what makes it
//! possible to use either an explicitly-defined [`ProtoModel`] as argument to
//! the [`SimInit::add_model`](crate::simulation::SimInit::add_model) method, or
//! a plain [`trait@Model`] type.
//!
//! The [`trait@Model`] trait is most frequently implemented by annotating the
//! main `impl` block of the model with the [`#[Model]`](`macro@Model`) macro.
//!
//! The [`Model::init`] method can be provided via a private method annotated
//! with the `#[nexosim(init)]` attribute. Note that unlike [`Model::init`], it
//! takes an `&mut self` receiver argument and the remaining arguments can be
//! omitted.
//!
//! Input methods can in turn be annotated with the `#[nexosim(schedulable)]`
//! attribute, which enables the use of the [`schedulable!`] macro for
//! scheduling. Alternatively, methods that need to be scheduled by the model
//! can be registered within [`ProtoModel::build`] with
//! [`BuildContext::register_schedulable`].
//!
//! # Derivation of the `Model` trait
//!
//! A model that does not require initialization or building can use the default
//! implementation of the [`trait@Model`] trait with `()` as the [`Model::Env`]:
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use nexosim::model::Model;
//!
//! #[derive(Serialize, Deserialize)]
//! pub struct SimpleModel {
//!     // ...
//! }
//! #[Model]
//! impl SimpleModel {
//!     // ...
//! }
//! ```
//!
//! or, equivalently:
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use nexosim::model::Model;
//!
//! #[derive(Serialize, Deserialize)]
//! pub struct SimpleModel {
//!     // ...
//! }
//! impl Model for SimpleModel {
//!     type Env = ();
//! }
//! ```
//!
//! If a default action is required during simulation initialization, the
//! [`Model::init`] method must be explicitly implemented. This is most commonly
//! done by annotating a private method with the `#[nexosim(init)]` attribute,
//! in which case the `Context` and environment arguments can be omitted (note
//! the `&mut self` receiver):
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use nexosim::model::{Context, Model};
//!
//! #[derive(Serialize, Deserialize)]
//! pub struct SimpleModel {
//!     // ...
//! }
//! #[Model]
//! impl SimpleModel {
//!     // While it is idiomatic for this method to shadow the trait's method, it
//!     // can be named something other than `init`.
//!     #[nexosim(init)]
//!     async fn init(&mut self) {
//!         println!("...initialization...");
//!     }
//! }
//! ```
//!
//! When a model needs to schedule its own inputs, a `#[nexosim(schedulable)]`
//! attribute can be used to automatically register the method so it can be
//! conveniently scheduled with the [`schedulable!`] macro:
//!
//! ```
//! use std::time::Duration;
//! use serde::{Deserialize, Serialize};
//! use nexosim::model::{schedulable, Context, Model};
//!
//! #[derive(Serialize, Deserialize)]
//! pub struct SchedulingModel {
//!     // ...
//! }
//! #[Model]
//! impl SchedulingModel {
//!     #[nexosim(schedulable)]
//!     pub async fn input(&mut self) {
//!         // ...
//!     }
//!     #[nexosim(init)]
//!     async fn init(&mut self, cx: &Context<Self>) {
//!         println!("...initialization...");
//!
//!         cx.schedule_event(Duration::from_secs(2), schedulable!(Self::input), ())
//!             .unwrap();
//!     }
//! }
//! ```
//!
//! # Model prototypes
//!
//! If a model builder is required, this builder must implement the
//! [`ProtoModel`] trait. The [`ProtoModel`] builder will typically contain all
//! output and requestor ports; the associated [`trait@Model`] will always
//! contain all input and replier methods.
//!
//!
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use nexosim::model::{BuildContext, Model, ProtoModel};
//! use nexosim::ports::Output;
//!
//! /// The final model.
//! #[derive(Serialize, Deserialize)]
//! pub struct Multiplier {
//!     // Private outputs and requestors stored in a form that constitutes an
//!     // implementation detail and should not be exposed to the user.
//!     my_outputs: Vec<Output<usize>>
//! }
//! #[Model]
//! impl Multiplier {
//!     // Private constructor: the final model is built by the prototype model.
//!     fn new(
//!         value_times_1: Output<usize>,
//!         value_times_2: Output<usize>,
//!         value_times_3: Output<usize>,
//!     ) -> Self {
//!         Self {
//!             my_outputs: vec![value_times_1, value_times_2, value_times_3]
//!         }
//!     }
//!
//!     // Public input to be used during bench construction.
//!     pub async fn my_input(&mut self, my_data: usize) {
//!         for (i, output) in self.my_outputs.iter_mut().enumerate() {
//!             output.send(my_data*(i + 1)).await;
//!         }
//!     }
//! }
//!
//! // The model builder.
//! pub struct ProtoMultiplier {
//!     // Prettyfied outputs exposed to the user.
//!     pub value_times_1: Output<usize>,
//!     pub value_times_2: Output<usize>,
//!     pub value_times_3: Output<usize>,
//! }
//! impl ProtoModel for ProtoMultiplier {
//!     type Model = Multiplier;
//!
//!     fn build(
//!         mut self,
//!         _: &mut BuildContext<Self>
//!     ) -> (Multiplier, ()) {
//!         (Multiplier::new(self.value_times_1, self.value_times_2, self.value_times_3), ())
//!     }
//! }
//! ```
//!
//! # Model environment
//!
//! There are cases where it is not possible and/or not desirable to serialize a
//! part of the model's state. This can happen in particular if the model keeps
//! handles to system resources such as files or drivers.
//!
//! For such use-cases, the non-serializable part of the model state can be
//! moved to the environment, which type is defined by [`Model::Env`]. This
//! environment is then made available via a mutable reference provided as the
//! fourth, optional argument to input and requestor methods. The environment is
//! also made available to [`Model::init`].
//!
//! If [`Model::Env`] implements [`Default`], a default implementation of
//! [`ProtoModel`] on the model itself automatically initializes the environment
//! in [`ProtoModel::build`]. Otherwise, [`ProtoModel::build`] must perform this
//! initialization explicitly, such as in the following example:
//!
//! ```
//! use std::fs::File;
//! use std::io::Read;
//! use serde::{Deserialize, Serialize};
//! use nexosim::model::{BuildContext, Model, ProtoModel};
//!
//! #[derive(Serialize, Deserialize)]
//! pub struct LoggingModel {
//!     // ...
//! }
//!
//! #[Model(type Env=File)]
//! impl LoggingModel {
//!     // ...
//! }
//!
//! pub struct ProtoLoggingModel {
//!     log_file: File,
//!     // ...
//! }
//! impl ProtoLoggingModel {
//!     pub fn new(log_file: File) -> Self {
//!         Self {
//!             log_file,
//!             // ...
//!         }
//!     }
//! }
//! impl ProtoModel for ProtoLoggingModel {
//!     type Model = LoggingModel;
//!
//!     fn build(
//!         self,
//!         cx: &mut BuildContext<'_, Self>,
//!     ) -> (Self::Model, File) {
//!         let model = LoggingModel { /* ... */ };
//!         
//!         (model, self.log_file)
//!     }
//! }
//! ```
//!
//! # Hierarchical models
//!
//! Hierarchical models are models which prototypes spawn submodels within the
//! [`ProtoModel::build`] method. From a formal point of view, however,
//! hierarchical models are just plain [`trait@Model`]s, as are their submodels.
//!
//! The following shows a parent model that forwards its input data to its child
//! model; the child sends in turn the processed data directly to the output of
//! the parent, making the existence of the child an implementation detail
//! hidden from the parent model's users.
//!
//! For a more comprehensive example of hierarchical model assemblies, see the
//! [`assembly`][assembly] example.
//!
//! [assembly]:
//!     https://github.com/asynchronics/nexosim/tree/main/nexosim/examples/assembly.rs
//!
//! ```
//! use serde::{Deserialize, Serialize};
//! use nexosim::model::{BuildContext, Model, ProtoModel};
//! use nexosim::ports::Output;
//! use nexosim::simulation::Mailbox;
//!
//! #[derive(Serialize, Deserialize)]
//! pub struct ParentModel {
//!     // Private internal port connected to the submodel.
//!     to_child: Output<u64>,
//! }
//! #[Model]
//! impl ParentModel {
//!     async fn add_one(&mut self, my_data: u64) {
//!         // Forward to the submodel.
//!         self.to_child.send(my_data).await;
//!     }
//! }
//!
//! pub struct ProtoParentModel {
//!     pub output: Output<u64>,
//! }
//! impl ProtoModel for ProtoParentModel {
//!     type Model = ParentModel;
//!
//!     fn build(self, cx: &mut BuildContext<Self>) -> (ParentModel, ()) {
//!         // Move the output to the child model. Alternatively, we could clone the
//!         // output if it was also needed by the parent.
//!         
//!         let child = ChildModel { output: self.output };
//!         let mut parent = ParentModel {
//!             to_child: Output::default(),
//!         };
//!
//!         // Establish an internal Parent -> Child connection.
//!         let child_mailbox = Mailbox::new();
//!         parent
//!             .to_child
//!             .connect(ChildModel::add_one, &child_mailbox);
//!
//!         // Add the child model to the simulation.
//!         cx.add_submodel(child, child_mailbox, "child");
//!
//!         (parent, ())
//!     }
//! }
//!
//! #[derive(Serialize, Deserialize)]
//! struct ChildModel {
//!     output: Output<u64>,
//! }
//! #[Model]
//! impl ChildModel {
//!     async fn add_one(&mut self, my_data: u64) {
//!         self.output.send(my_data + 1).await;
//!     }
//! }
//! ```
use std::any::type_name;
use std::collections::VecDeque;
use std::future::Future;
use std::sync::Mutex;

use serde::{Serialize, de::DeserializeOwned};

use crate::path::Path;
use crate::ports::PORT_REG;
use crate::simulation::{
    Address, EVENT_KEY_REG, EventKeyReg, ExecutionError, RestoreError, SaveError, Simulation,
};
use crate::util::serialization::serialization_config;

pub use context::{BuildContext, Context, ModelRegistry, SchedulableId};

/// [`Model`](trait@Model) trait generation macro.
///
/// This macro is to be used as an attribute on the `impl` block of a model. It
/// accepts an optional `Env` type argument that defines the [`Model::Env`]
/// associated type. If omitted, `Env` is assumed to be the unit type `()`.
///
/// The implementation of the [`Model::init`] method can be specified by
/// annotating a model method with `#[nexosim(init)]`. For convenience, this
/// method can omit the [`Context`] and environment arguments.
///
/// Methods to be scheduled with the [`schedulable!`] macro should be annotated
/// with `#[nexosim(schedulable)]`.
///
/// # Example
///
/// Simple model with a trivial [`Model::init`] and the unit type as
/// [`Model::Env`]:
///
/// ```
/// use serde::{Deserialize, Serialize};
/// use nexosim::model::Model;
///
/// #[derive(Serialize, Deserialize)]
/// pub struct SimpleModel {
///     // ...
/// }
///
/// #[Model]
/// impl SimpleModel {
///     // ...
/// }
/// ```
///
/// Model with a custom [`Model::init`], a non-serializable environment and a
/// [schedulable] input:
///
/// ```
/// use std::fs::File;
/// use std::io::Read;
/// use serde::{Deserialize, Serialize};
/// use nexosim::model::{Context, Model};
/// use nexosim::ports::Output;
///
/// #[derive(Serialize, Deserialize)]
/// pub struct NonTrivialModel {
///     output: Output<String>,
/// }
///
/// #[Model(type Env=File)]
/// impl NonTrivialModel {
///     // While it is idiomatic for this method to shadow the trait's method, it
///     // can be named something other than `init`.
///     // The `Context` and environment arguments can be omitted if unused.
///     // This method should always be private.
///     #[nexosim(init)]
///     async fn init(&mut self, cx: &Context<Self>, env: &mut File) {
///         // Use the environment to initialize the model.
///         let mut out = String::new();
///         env.read_to_string(&mut out).unwrap();
///         self.output.send(out).await;
///     }
///
///     #[nexosim(schedulable)]
///     pub async fn input(&mut self, arg: u32, cx: &Context<Self>, env: &mut File) {
///         // ...
///     }
/// }
/// ```
pub use nexosim_macros::Model;

/// A macro returning a [`SchedulableId`] reference from the qualified name of
/// an input method.
///
/// # Example
///
/// The `schedulable!` macro can also be used within inputs that schedule
/// themselves, *e.g.*:
///
/// ```
/// use std::time::Duration;
/// use serde::{Deserialize, Serialize};
/// use nexosim::model::{Context, Model, schedulable};
///
/// #[derive(Serialize, Deserialize)]
/// struct MyModel {}
///
/// #[Model]
/// impl MyModel {
///     #[nexosim(schedulable)]
///     fn self_schedulable_input(&mut self, _: (), cx: &Context<Self>) {
///         cx.schedule_event(
///             Duration::from_secs(1),
///             schedulable!(Self::self_schedulable_input),
///             ()
///         ).unwrap();
///     }
/// }
/// ```
pub use nexosim_macros::schedulable;

mod context;

/// Trait to be implemented by simulation models.
///
/// This trait enables models to perform specific actions during initialization.
/// The [`Model::init`] method runs only once all models have been connected and
/// migrated to the simulation bench, before the first increment of simulation
/// time. A common use for `init` is to send messages to connected models at the
/// beginning of the simulation.
///
/// The [`Model::Env`] associated type can be used to define the environment of
/// the model, *i.e.* the non-serialized part of its state. This environment is
/// then made available via a mutable reference provided as the fourth, optional
/// argument to input and requestor methods. If [`Model::Env`] implements
/// [`Default`], a default implementation of [`ProtoModel`] on the model itself
/// automatically initializes the environment in [`ProtoModel::build`].
/// Otherwise, [`ProtoModel::build`] must perform this initialization
/// explicitly.
///
/// While this trait can be implemented manually, it is most frequently
/// implemented by annotating the main `impl` block of a model with the
/// [`#[Model]`](`macro@Model`) macro. In that case, the [`Model::init`] method
/// can be provided via a private method annotated with the `#[nexosim(init)]`
/// attribute which, unlike [`Model::init`], takes an `&mut self` receiver
/// argument and allows the remaining arguments to be omitted.
///
/// See [the module-level documentation](self) for more.
pub trait Model: Serialize + DeserializeOwned + Sized + Send + 'static {
    /// Helper struct for internal non-state model data that cannot (or should
    /// not) be serialized and persisted.
    type Env: Send + 'static;

    /// Performs asynchronous model initialization.
    ///
    /// This asynchronous method is executed exactly once for all models of the
    /// simulation when the [`SimInit::init`](crate::simulation::SimInit::init)
    /// method is called. Since `InitializedModel` is an opaque type, it cannot
    /// be called by the user before the model is added to the simulation.
    ///
    /// This method is not called when the model is restored from a serialized
    /// state.
    ///
    /// The default implementation simply converts the model to an
    /// [`InitializedModel`] without any side effect.
    ///
    /// # Implementation Note
    ///
    /// This method can be implemented within a manual trait implementation with
    /// the standard `async fn` notation:
    ///
    /// ```
    /// # use serde::{Deserialize, Serialize};
    /// # use nexosim::model::{Context, InitializedModel, Model};
    /// # #[derive(Serialize, Deserialize)]
    /// # struct MyModel;
    /// # impl Model for MyModel {
    /// #     type Env = ();
    /// async fn init(self, cx: &Context<Self>, env: &mut Self::Env) -> InitializedModel<Self> {
    ///     // ...
    ///     self.into()
    /// }
    /// # }
    /// ```
    /// or within an `impl` block annotated with the [`#[Model]`](macro@Model)
    /// macro (note the `&mut self` receiver and absence of return type):
    ///
    /// ```
    /// # use serde::{Deserialize, Serialize};
    /// # use nexosim::model::{Context, Model};
    /// # #[derive(Serialize, Deserialize)]
    /// # struct MyModel;
    /// # #[Model]
    /// # impl MyModel {
    /// // The `cx` and `env` argument are optional. It is idiomatic but not mandated
    /// // to shadow the name of the trait's method.
    /// #[nexosim(init)]
    /// async fn init(&mut self, cx: &Context<Self>, env: &mut <Self as Model>::Env) {
    ///     // ...
    /// }
    /// # }
    /// ```
    fn init(
        self,
        _: &Context<Self>,
        _: &mut Self::Env,
    ) -> impl Future<Output = InitializedModel<Self>> + Send {
        async { self.into() }
    }

    /// Generates a registry of inputs schedulable with the [`schedulable!`]
    /// macro.
    ///
    /// This is exclusively used by the [`#[Model]`](`macro@Model`) procedural
    /// macro. A default implementation generating an empty registry is provided
    /// for the case where the `Model` trait is implemented manually.
    fn register_schedulables(_: &mut BuildContext<impl ProtoModel<Model = Self>>) -> ModelRegistry {
        ModelRegistry::default()
    }
}

/// An opaque type containing an initialized model.
///
/// `InitializedModel` serves to guarantee that a user cannot add a model to the
/// simulation after a call to [`Model::init`]. The implementation of the
/// simulation guarantees in turn that [`Model::init`] is called only once.
///
/// A model can be converted to an `InitializedModel` using [`Into::into`].
#[derive(Debug)]
pub struct InitializedModel<M: Model>(pub(crate) M);

impl<M: Model> From<M> for InitializedModel<M> {
    fn from(model: M) -> Self {
        InitializedModel(model)
    }
}

/// Trait to be implemented by simulation model prototypes.
///
/// This trait makes it possible to build the final model from a builder type
/// when it is added to the simulation.
///
/// The [`ProtoModel::build`] method consumes the prototype. It is automatically
/// called when a model prototype is added to the simulation using
/// [`Simulation::add_model`](crate::simulation::SimInit::add_model) or
/// [`BuildContext::add_submodel`].
///
/// See [the module-level documentation](self) for more.
pub trait ProtoModel: Sized {
    /// Type of the model to be built.
    type Model: Model;

    /// Builds the model.
    ///
    /// This method is invoked when the
    /// [`SimInit::add_model`](crate::simulation::SimInit::add_model) or
    /// [`BuildContext::add_submodel`] method are called.
    fn build(self, cx: &mut BuildContext<Self>) -> (Self::Model, <Self::Model as Model>::Env);
}

impl<M: Model<Env = E>, E: Default> ProtoModel for M {
    type Model = Self;

    fn build(self, _: &mut BuildContext<Self>) -> (Self::Model, <Self::Model as Model>::Env) {
        (self, E::default())
    }
}

/// An internal helper struct used to handle (de)serialization of the models.
pub(crate) struct RegisteredModel {
    pub path: Path,
    #[allow(clippy::type_complexity)]
    pub serialize: Box<dyn Fn(&mut Simulation) -> Result<Vec<u8>, ExecutionError> + Send>,
    #[allow(clippy::type_complexity)]
    pub deserialize:
        Box<dyn Fn(&mut Simulation, (Vec<u8>, EventKeyReg)) -> Result<(), ExecutionError> + Send>,
}
impl RegisteredModel {
    pub(crate) fn new<M: Model>(path: Path, address: Address<M>) -> Self {
        let ser_address = address.clone();
        let de_address = address.clone();
        let ser_path = path.clone();
        let de_path = path.clone();

        let serialize = Box::new(move |sim: &mut Simulation| {
            sim.process_replier_fn(serialize_model, ser_path.clone(), &ser_address)?
        });
        let deserialize = Box::new(move |sim: &mut Simulation, state: (Vec<u8>, EventKeyReg)| {
            sim.process_replier_fn(
                deserialize_model,
                (state.0, state.1, de_path.clone()),
                &de_address,
            )?
        });
        Self {
            path,
            serialize,
            deserialize,
        }
    }
}

impl std::fmt::Debug for RegisteredModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Registered Model")
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

pub(crate) async fn serialize_model<M: Model>(
    model: &mut M,
    path: Path,
) -> Result<Vec<u8>, ExecutionError> {
    bincode::serde::encode_to_vec(model, serialization_config()).map_err(|e| {
        SaveError::ModelSerializationError {
            model: path,
            type_name: type_name::<M>(),
            cause: Box::new(e),
        }
        .into()
    })
}

pub(crate) async fn deserialize_model<M: Model>(
    model: &mut M,
    state: (Vec<u8>, EventKeyReg, Path),
) -> Result<(), ExecutionError> {
    let restored = PORT_REG
        .set(&Mutex::new(VecDeque::new()), || {
            EVENT_KEY_REG.set(&state.1, || {
                bincode::serde::encode_to_vec(&model, serialization_config()).map_err(|e| {
                    RestoreError::ModelSerializationError {
                        model: state.2.clone(),
                        type_name: type_name::<M>(),
                        cause: Box::new(e),
                    }
                })?;
                bincode::serde::borrow_decode_from_slice::<M, _>(&state.0, serialization_config())
                    .map_err(|e| RestoreError::ModelDeserializationError {
                        model: state.2,
                        type_name: type_name::<M>(),
                        cause: Box::new(e),
                    })
            })
        })?
        .0;
    let _ = std::mem::replace(model, restored);
    Ok(())
}

/// A type alias for the schema generated by the [`Message`] trait.
pub type MessageSchema = String;

/// Trait providing type introspection for events, queries and replies.
///
/// Deriving the `Message` trait on an event, query or reply automatically
/// generates a schema for this type. Because this type information can be
/// retrieved via gRPC to display, edit or reflect endpoint messages in the
/// front-end, users are strongly encouraged to derive `Message` whenever
/// possible.
///
/// The `Message` trait is derived for all primitive Rust types.
pub trait Message {
    /// Returns a schema of the message type.
    fn schema() -> MessageSchema;
}
impl<T> Message for T
where
    T: crate::JsonSchema,
{
    fn schema() -> MessageSchema {
        schemars::schema_for!(T).as_value().to_string()
    }
}