catwalk/
model.rs

1//! Representation of the actual data.
2
3use semver::Version;
4
5/// A Model is a representation of data.
6///
7/// A model (as you probably guessed) models data. Specifically, a Model implementation describes:
8///     1. Describes what the data will look like (structure, types, etcetera)
9///     2. The model's name
10///     3. The model's version
11///
12/// Actual instances of implementations will hold the data.
13///
14/// ## Describing the data
15///
16/// Describing the data structure is easy: add fields to the struct implementing the model.
17pub trait Model {
18    /// The name of the model.
19    /// Each type of model has a name (not to be confused with a model instance's key), this is the
20    /// used by the PersistenceEngine to determine which Persister to use when storing or retrieving
21    /// the model.
22    ///
23    /// While not required, it is recommended that the name of the model be the same as the name of
24    /// the implementing type, but in kebab-case instead of PascalCase.
25    fn model_name() -> &'static str;
26
27    /// Each model implementation has a version. When the structure of that model changes, the
28    /// version also needs to change. As of right now, the model implementation must handle
29    /// converting from an older version to a newer version when deserializing from bytes.
30    ///
31    /// You may notice that this is defined on a `Self` level and not a `self` level. This is
32    /// because all loaded models of a single type should have the same version, and that version
33    /// should not change without changes in the code as well.
34    fn model_version() -> &'static Version;
35
36    /// Gets the key for the model instance. As you can probably guess, the key uniquely identifies
37    /// a model instance (as opposed to the `model_name` which uniquely identifies a model type).
38    fn get_key(&self) -> &str;
39}
40
41/// A representation of a stored [model](Model). While every [model](Model) type has it's own
42/// version when loaded, the same cannot be said before they're loaded, or while they're in the
43/// process of being loaded. This acts as representation of that.
44#[derive(Debug)]
45pub struct StoredModel<M: Model> {
46    pub version: Version,
47    pub model: M,
48}
49
50impl<M: Model> From<(Version, M)> for StoredModel<M> {
51    fn from((version, model): (Version, M)) -> Self {
52        Self { version, model }
53    }
54}