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
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use std::any::{Any, TypeId};
use std::borrow::Cow;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use crate::shared::meta::Metadata;
use crate::shared::ItemID;

/// Number of available words for trivial entity value.
///
/// Value `5` makes [`EntityData`] in 32-byte align (96 byte size).
const TRIVIAL_ENTITY_NUM_WORDS: usize = 5;

///
/// Config entity type must satisfy this constraint
///
pub trait Entity: Send + Sync + Any + 'static {
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn as_serialize(&self) -> &dyn erased_serde::Serialize;
    fn deserialize(
        &mut self,
        de: &mut dyn erased_serde::Deserializer,
    ) -> Result<(), erased_serde::Error>;
    fn duplicated(&self) -> Arc<dyn Entity>;
}

impl<T> Entity for T
where
    T: Send + Sync + Any + serde::Serialize + DeserializeOwned + Clone + 'static,
{
    fn as_any(&self) -> &dyn Any {
        self as &dyn Any
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self as &mut dyn Any
    }

    fn deserialize(
        &mut self,
        de: &mut dyn erased_serde::Deserializer,
    ) -> Result<(), erased_serde::Error> {
        T::deserialize_in_place(de, self)?;
        Ok(())
    }

    fn as_serialize(&self) -> &dyn erased_serde::Serialize {
        self as &dyn erased_serde::Serialize
    }

    fn duplicated(&self) -> Arc<dyn Entity> {
        Arc::new(self.clone())
    }
}

///
///
/// Metadata for configuration entity. This can be used as template for multiple config entity
///  instances.
///
///
#[derive(Debug)]
pub struct PropertyInfo {
    pub(crate) type_id: TypeId,
    pub(crate) index: usize,
    pub(crate) metadata: Metadata,
    pub(crate) vtable: &'static dyn MetadataVTable,
}

impl PropertyInfo {
    #[doc(hidden)]
    pub fn new(
        type_id: TypeId,
        index: usize,
        metadata: Metadata,
        vtable: &'static dyn MetadataVTable,
    ) -> Self {
        Self { type_id, index, metadata, vtable }
    }
}

impl std::ops::Deref for PropertyInfo {
    type Target = Metadata;

    fn deref(&self) -> &Self::Target {
        &self.metadata
    }
}

/// Validation result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Validation {
    /// Data was valid. No change was made.
    Valid,

    /// Data was valid. Value was modified to satisfy validator constraint.
    Modified,
}

/// Validation result. Error type is plain string to inform user.
pub type ValidationResult = Result<Validation, std::borrow::Cow<'static, str>>;

/// Signature of function to validate config entity
pub type ValidateFn<T> = fn(&mut T) -> ValidationResult;

pub trait MetadataVTable: Send + Sync + 'static + std::fmt::Debug {
    /// Does implement `Copy`?
    fn implements_copy(&self) -> bool;

    /// Creates default value for this config entity.
    fn create_default(&self) -> EntityValue;

    /// Create new deserialized entity instance from given deserializer
    fn deserialize(
        &self,
        de: &mut dyn erased_serde::Deserializer,
    ) -> Result<EntityValue, erased_serde::Error>;

    /// Copy one value from another. Panics when called with unmatched type!
    fn clone_in_place(&self, src: &dyn Any, dst: &mut dyn Any);

    /// Returns None if validation failed. Some(false) when source value was corrected.
    ///  Some(true) when value was correct.
    fn validate(&self, value: &mut dyn Any) -> ValidationResult;
}

#[derive(cs::Debug)]
#[doc(hidden)]
pub struct MetadataVTableImpl<T: 'static> {
    pub impl_copy: bool,
    pub fn_default: fn() -> T,
    pub fn_validate: ValidateFn<T>,
}

impl<T: Entity + Clone> MetadataVTable for MetadataVTableImpl<T> {
    fn implements_copy(&self) -> bool {
        self.impl_copy
    }

    fn create_default(&self) -> EntityValue {
        // SAFETY: We know that `vtable.implements_copy()` is strictly managed.
        unsafe { EntityValue::from_value((self.fn_default)(), self.impl_copy) }
    }

    fn deserialize(
        &self,
        de: &mut dyn erased_serde::Deserializer,
    ) -> Result<EntityValue, erased_serde::Error> {
        let mut default = (self.fn_default)();
        default.deserialize(de)?;

        // SAFETY: We know that `vtable.implements_copy()` is strictly managed.
        Ok(unsafe { EntityValue::from_value(default, self.impl_copy) })
    }

    fn clone_in_place(&self, src: &dyn Any, dst: &mut dyn Any) {
        let src = src.downcast_ref::<T>().unwrap();
        let dst = dst.downcast_mut::<T>().unwrap();

        dst.clone_from(src);
    }

    fn validate(&self, value: &mut dyn Any) -> ValidationResult {
        let value = value.downcast_mut::<T>().unwrap();
        (self.fn_validate)(value)
    }
}

/* ---------------------------------------- Entity Value ---------------------------------------- */
#[derive(Clone)]
pub enum EntityValue {
    Trivial(TrivialEntityValue),
    Complex(Arc<dyn Entity>),
}

impl std::fmt::Debug for EntityValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Trivial(_) => f.debug_struct("Trivial"),
            Self::Complex(_) => f.debug_struct("Complex"),
        }
        .finish()
    }
}

type ReinterpretInput<'a> = Result<&'a [usize], &'a mut [usize]>;
type ReinterpretOutput<'a> = Result<&'a dyn Entity, &'a mut dyn Entity>;

/// Pair of function pointer to retrieve entity trait from given pointer and actual payload.
#[derive(Clone, Copy)]
#[doc(hidden)]
pub struct TrivialEntityValue(
    for<'a> unsafe fn(ReinterpretInput) -> ReinterpretOutput,
    [usize; TRIVIAL_ENTITY_NUM_WORDS],
);

impl Entity for EntityValue {
    fn as_any(&self) -> &dyn Any {
        self.as_entity().as_any()
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self.as_entity_mut().as_any_mut()
    }

    fn as_serialize(&self) -> &dyn erased_serde::Serialize {
        self.as_entity().as_serialize()
    }

    fn deserialize(
        &mut self,
        de: &mut dyn erased_serde::Deserializer,
    ) -> Result<(), erased_serde::Error> {
        self.as_entity_mut().deserialize(de)
    }

    fn duplicated(&self) -> Arc<dyn Entity> {
        self.as_entity().duplicated()
    }
}

impl EntityValue {
    pub fn as_entity(&self) -> &dyn Entity {
        match self {
            EntityValue::Trivial(t) => unsafe { (t.0)(Ok(&t.1)).unwrap_unchecked() },
            EntityValue::Complex(v) => v.as_ref(),
        }
    }

    pub fn as_entity_mut(&mut self) -> &mut dyn Entity {
        match self {
            EntityValue::Trivial(t) => unsafe { (t.0)(Err(&mut t.1)).unwrap_err_unchecked() },
            EntityValue::Complex(v) => {
                if Arc::strong_count(v) == 1 {
                    Arc::get_mut(v).unwrap()
                } else {
                    *v = v.duplicated();
                    Arc::get_mut(v).unwrap()
                }
            }
        }
    }

    pub fn from_trivial<T: Copy + Entity>(value: T) -> Self {
        // SAFETY: This is safe as long as `T` is trivially copyable.
        unsafe { Self::from_trivial_unchecked(value) }
    }

    #[doc(hidden)]
    pub(crate) unsafe fn from_trivial_unchecked<T: Entity>(value: T) -> Self {
        if std::mem::size_of::<T>() <= std::mem::size_of::<usize>() * TRIVIAL_ENTITY_NUM_WORDS {
            let mut buffer = [0usize; TRIVIAL_ENTITY_NUM_WORDS];

            // SAFETY: This is safe as long as `T` is trivially copyable.
            unsafe {
                std::ptr::copy_nonoverlapping(&value, buffer.as_mut_ptr() as _, 1);
            }

            // SAFETY: Won't be used outside of delivered context.
            unsafe fn retrieve_function<T: Entity>(i: ReinterpretInput) -> ReinterpretOutput {
                match i {
                    Ok(x) => Ok(&*(x.as_ptr() as *const T)),
                    Err(x) => Err(&mut *(x.as_mut_ptr() as *mut T)),
                }
            }

            Self::Trivial(TrivialEntityValue(retrieve_function::<T>, buffer))
        } else {
            Self::from_complex(value)
        }
    }

    pub fn from_complex<T: Entity>(value: T) -> Self {
        Self::Complex(Arc::new(value))
    }

    pub(crate) unsafe fn from_value<T: Entity>(value: T, implements_copy: bool) -> Self {
        if implements_copy {
            // SAFETY: `implements_copy` must be managed very carefully to make this safe.
            unsafe { Self::from_trivial_unchecked(value) }
        } else {
            Self::from_complex(value)
        }
    }
}

/* ---------------------------------------------------------------------------------------------- */
/*                                           ENTITY DATA                                          */
/* ---------------------------------------------------------------------------------------------- */

///
/// Events are two directional ...
///
/// 1. Remote commit entity / Local commit entity
///     - 'on update' user observer hooked
///     - 'any value update' observer hooked
///
/// 2. Local commit entity silent
///     - 'any value update' observer hooked
///
/// 3. Local set retrieves entity update
///
#[derive(cs::Debug)]
pub struct EntityData {
    /// Unique entity id for program run-time
    pub id: ItemID,
    pub meta: &'static PropertyInfo,

    version: AtomicU64,
    value: RwLock<EntityValue>,

    #[debug(skip)]
    hook: Arc<dyn EntityEventHook>,
}

#[derive(Debug, thiserror::Error)]
pub enum EntityUpdateError {
    #[error("Validation failed: {0}")]
    ValueValidationFailed(Cow<'static, str>),

    #[error("Deserialization failed")]
    DeserializeFailed(#[from] erased_serde::Error),
}

impl EntityData {
    pub(crate) fn new(
        property_info: &'static PropertyInfo,
        hook: Arc<dyn EntityEventHook>,
    ) -> Self {
        Self {
            id: ItemID::new_unique_incremental(),
            version: AtomicU64::new(0),
            value: RwLock::new(property_info.vtable.create_default()),
            meta: property_info,
            hook,
        }
    }

    pub(crate) fn version(&self) -> u64 {
        self.version.load(Ordering::Relaxed)
    }

    pub(crate) fn property_value(&self) -> (&'static PropertyInfo, EntityValue) {
        (self.meta, self.value.read().clone())
    }

    /// Serialize this property into given serializer.
    pub fn serialize_into<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        serde::Serialize::serialize(&self.value.read().as_serialize(), ser)
    }

    /// If `silent` option is disabled, increase config set and source argument's fence
    ///  by 1, to make self and other instances of config set which shares the same core
    ///  be aware of this change.
    pub(crate) fn __apply_value(&self, value: EntityValue) {
        debug_assert!(self.meta.type_id == value.as_any().type_id());

        *self.value.write() = value;
        self.version.fetch_add(1, Ordering::Release);
    }

    /// Attempts to update the central value of a config entity by deserializing the provided input.
    ///
    /// This function first deserializes the input to the expected data structure. After successful
    /// deserialization, it validates the value to ensure it conforms to the expected constraints.
    /// The method offers three potential outcomes:
    ///
    /// 1. Successful deserialization and validation: the value is perfectly valid and requires no
    ///    alterations.
    /// 2. Successful deserialization but failed validation: the value needed adjustments to meet
    ///    the validator's constraints.
    /// 3. Failed deserialization or validation: an error occurred during the process.
    ///
    /// # Returns
    ///
    /// * `Ok(true)` - Both deserialization and validation were successful without the need for any
    ///   modifications.
    /// * `Ok(false)` - Deserialization succeeded, but the value was adjusted during validation to
    ///   meet constraints.
    /// * `Err(_)` - Either the deserialization process or validation failed.
    ///
    /// # Type Parameters
    ///
    /// * `T`: Represents the type of the deserializer.
    ///
    /// # Parameters
    ///
    /// * `de`: An instance of the deserializer used to update the central value.
    pub fn update_value_from<'a, T>(&self, de: T) -> Result<Validation, EntityUpdateError>
    where
        T: serde::Deserializer<'a>,
    {
        let meta = &self.meta;
        let vt = &meta.vtable;
        let mut erased = <dyn erased_serde::Deserializer>::erase(de);

        match vt.deserialize(&mut erased) {
            Ok(mut built) => {
                let is_perfect = match vt.validate(built.as_any_mut()) {
                    Ok(clean) => clean,
                    Err(e) => return Err(EntityUpdateError::ValueValidationFailed(e)),
                };

                self.__apply_value(built);
                Ok(is_perfect)
            }
            Err(error) => {
                tr::debug!(
                    %error,
                    name = meta.varname,
                    r#type = meta.type_name,
                    "(Deserialization Failed)",
                );
                Err(error.into())
            }
        }
    }

    /// Notifies the underlying storage that a field within this group has been updated.
    ///
    /// The `touch` method serves as a mechanism to propagate changes to the appropriate parts of
    /// the system. Depending on the `make_storage_dirty` flag:
    ///
    /// - If set to `true`, the notification of change will be broadcasted to all group instances
    ///   that share the same group context, ensuring synchronization across shared contexts.
    ///
    /// - If set to `false`, only the monitor will be notified of the value update, without
    ///   affecting other group instances.
    ///
    /// # Arguments
    ///
    /// * `make_storage_dirty`: A boolean flag that determines the scope of the update notification.
    ///   When set to `true`, it affects all group instances sharing the same context. When `false`,
    ///   only the monitor is alerted of the change.
    pub fn touch(&self, make_storage_dirty: bool) {
        self.hook.on_value_changed(self, !make_storage_dirty);
    }
}

pub(crate) trait EntityEventHook: Send + Sync {
    fn on_value_changed(&self, data: &EntityData, silent: bool);
}