objets_metier_rs 1.0.2

Bibliothèque Rust moderne et sûre pour l'API COM Objets Métier Sage 100c - Production Ready
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
//! Implémentation du cache pour factories
//!
//! Ce module fournit un cache thread-safe avec gestion automatique du TTL (Time-To-Live).

use std::collections::HashMap;
use std::hash::Hash;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

type SerializedCacheStore = Arc<RwLock<HashMap<String, Vec<u8>>>>;

/// Entrée de cache avec timestamp pour gestion du TTL
#[derive(Debug, Clone)]
pub struct CacheEntry<V> {
    /// Valeur cachée
    pub value: V,
    /// Instant de création de l'entrée
    pub created_at: Instant,
}

impl<V> CacheEntry<V> {
    /// Crée une nouvelle entrée de cache
    pub fn new(value: V) -> Self {
        Self {
            value,
            created_at: Instant::now(),
        }
    }

    /// Vérifie si l'entrée a expiré
    pub fn is_expired(&self, ttl: Duration) -> bool {
        self.created_at.elapsed() > ttl
    }
}

/// Cache thread-safe avec TTL pour factories
///
/// # Type Parameters
///
/// * `K` - Type de la clé (doit implémenter Hash + Eq)
/// * `V` - Type de la valeur cachée (doit implémenter Clone)
///
/// # Exemple
///
/// ```rust,ignore
/// use objets_metier_rs::cache::FactoryCache;
/// use std::time::Duration;
///
/// let cache = FactoryCache::new(Duration::from_secs(300));
///
/// // Insertion
/// cache.insert(1, journal.clone());
///
/// // Récupération
/// if let Some(journal) = cache.get(&1) {
///     println!("Journal depuis cache: {:?}", journal);
/// }
///
/// // Invalidation
/// cache.invalidate(&1);
///
/// // Nettoyage complet
/// cache.clear();
/// ```
pub struct FactoryCache<K, V>
where
    K: Hash + Eq,
    V: Clone,
{
    /// Stockage interne thread-safe
    store: Arc<RwLock<HashMap<K, CacheEntry<V>>>>,
    /// Durée de vie des entrées (Time-To-Live)
    ttl: Duration,
}

impl<K, V> FactoryCache<K, V>
where
    K: Hash + Eq,
    V: Clone,
{
    /// Crée un nouveau cache avec le TTL spécifié
    ///
    /// # Arguments
    ///
    /// * `ttl` - Durée de vie des entrées dans le cache
    ///
    /// # Exemple
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    ///
    /// // Cache avec TTL de 5 minutes
    /// let cache = FactoryCache::new(Duration::from_secs(300));
    /// ```
    pub fn new(ttl: Duration) -> Self {
        Self {
            store: Arc::new(RwLock::new(HashMap::new())),
            ttl,
        }
    }

    /// Récupère une valeur depuis le cache
    ///
    /// Retourne `None` si la clé n'existe pas ou si l'entrée a expiré.
    ///
    /// # Arguments
    ///
    /// * `key` - Clé à rechercher
    ///
    /// # Exemple
    ///
    /// ```rust,ignore
    /// if let Some(value) = cache.get(&key) {
    ///     println!("Trouvé dans le cache!");
    /// }
    /// ```
    pub fn get(&self, key: &K) -> Option<V> {
        let store = self.store.read().ok()?;
        let entry = store.get(key)?;

        if entry.is_expired(self.ttl) {
            drop(store);
            // L'entrée a expiré, la supprimer
            self.invalidate(key);
            None
        } else {
            Some(entry.value.clone())
        }
    }

    /// Insère une valeur dans le cache
    ///
    /// Si une entrée existe déjà pour cette clé, elle est remplacée.
    ///
    /// # Arguments
    ///
    /// * `key` - Clé d'insertion
    /// * `value` - Valeur à cacher
    ///
    /// # Exemple
    ///
    /// ```rust,ignore
    /// cache.insert(1, journal);
    /// ```
    pub fn insert(&self, key: K, value: V) {
        if let Ok(mut store) = self.store.write() {
            store.insert(key, CacheEntry::new(value));
        }
    }

    /// Invalide (supprime) une entrée du cache
    ///
    /// # Arguments
    ///
    /// * `key` - Clé à invalider
    ///
    /// # Exemple
    ///
    /// ```rust,ignore
    /// cache.invalidate(&1);
    /// ```
    pub fn invalidate(&self, key: &K) {
        if let Ok(mut store) = self.store.write() {
            store.remove(key);
        }
    }

    /// Vide complètement le cache
    ///
    /// # Exemple
    ///
    /// ```rust,ignore
    /// cache.clear();
    /// ```
    pub fn clear(&self) {
        if let Ok(mut store) = self.store.write() {
            store.clear();
        }
    }

    /// Nettoie les entrées expirées du cache
    ///
    /// Utile pour libérer de la mémoire périodiquement.
    ///
    /// # Returns
    ///
    /// Le nombre d'entrées supprimées
    ///
    /// # Exemple
    ///
    /// ```rust,ignore
    /// let removed = cache.cleanup_expired();
    /// println!("Entrées expirées supprimées: {}", removed);
    /// ```
    pub fn cleanup_expired(&self) -> usize {
        if let Ok(mut store) = self.store.write() {
            let initial_len = store.len();
            store.retain(|_, entry| !entry.is_expired(self.ttl));
            initial_len - store.len()
        } else {
            0
        }
    }

    /// Retourne le nombre d'entrées dans le cache
    ///
    /// # Exemple
    ///
    /// ```rust,ignore
    /// println!("Entrées en cache: {}", cache.len());
    /// ```
    pub fn len(&self) -> usize {
        self.store.read().map(|s| s.len()).unwrap_or(0)
    }

    /// Vérifie si le cache est vide
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Retourne les statistiques du cache
    ///
    /// # Returns
    ///
    /// `(total_entries, expired_entries)`
    pub fn stats(&self) -> (usize, usize) {
        if let Ok(store) = self.store.read() {
            let total = store.len();
            let expired = store.values().filter(|e| e.is_expired(self.ttl)).count();
            (total, expired)
        } else {
            (0, 0)
        }
    }
}

impl<K, V> Clone for FactoryCache<K, V>
where
    K: Hash + Eq,
    V: Clone,
{
    fn clone(&self) -> Self {
        Self {
            store: Arc::clone(&self.store),
            ttl: self.ttl,
        }
    }
}

/// Wrapper pour appliquer automatiquement le cache à une factory
///
/// # Type Parameters
///
/// * `F` - Type de la factory wrappée
///
/// # Exemple
///
/// ```rust,ignore
/// use objets_metier_rs::cache::{CachedFactory, FactoryCache};
/// use std::time::Duration;
///
/// let cache = FactoryCache::new(Duration::from_secs(300));
/// let cached_factory = CachedFactory::new(factory_journal, cache);
///
/// // Les lectures utiliseront le cache automatiquement
/// let journal = cached_factory.inner().read_numero(1)?;
/// ```
pub struct CachedFactory<F> {
    /// Factory originale
    factory: F,
    /// Cache partagé (peut être cloné pour partager entre factories)
    cache: Option<SerializedCacheStore>, // Cache sérialisé générique
}

impl<F> CachedFactory<F> {
    /// Crée un nouveau wrapper avec cache
    ///
    /// # Arguments
    ///
    /// * `factory` - Factory à wrapper
    pub fn new(factory: F) -> Self {
        Self {
            factory,
            cache: Some(Arc::new(RwLock::new(HashMap::new()))),
        }
    }

    /// Crée un wrapper sans cache (pass-through)
    pub fn without_cache(factory: F) -> Self {
        Self {
            factory,
            cache: None,
        }
    }

    /// Retourne une référence à la factory interne
    pub fn inner(&self) -> &F {
        &self.factory
    }

    /// Consomme le wrapper et retourne la factory originale
    pub fn into_inner(self) -> F {
        self.factory
    }

    /// Vérifie si le cache est activé
    pub fn is_cached(&self) -> bool {
        self.cache.is_some()
    }

    /// Vide le cache si présent
    pub fn clear_cache(&self) {
        if let Some(cache) = &self.cache {
            if let Ok(mut store) = cache.write() {
                store.clear();
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;

    #[test]
    fn test_cache_basic_operations() {
        let cache: FactoryCache<i32, String> = FactoryCache::new(Duration::from_secs(1));

        // Insertion
        cache.insert(1, "value1".to_string());
        cache.insert(2, "value2".to_string());

        // Récupération
        assert_eq!(cache.get(&1), Some("value1".to_string()));
        assert_eq!(cache.get(&2), Some("value2".to_string()));
        assert_eq!(cache.get(&3), None);

        // Taille
        assert_eq!(cache.len(), 2);
        assert!(!cache.is_empty());
    }

    #[test]
    fn test_cache_expiration() {
        let cache: FactoryCache<i32, String> = FactoryCache::new(Duration::from_millis(100));

        cache.insert(1, "value1".to_string());
        assert_eq!(cache.get(&1), Some("value1".to_string()));

        // Attendre l'expiration
        thread::sleep(Duration::from_millis(150));

        // L'entrée devrait avoir expiré
        assert_eq!(cache.get(&1), None);
    }

    #[test]
    fn test_cache_invalidation() {
        let cache: FactoryCache<i32, String> = FactoryCache::new(Duration::from_secs(60));

        cache.insert(1, "value1".to_string());
        assert_eq!(cache.get(&1), Some("value1".to_string()));

        cache.invalidate(&1);
        assert_eq!(cache.get(&1), None);
    }

    #[test]
    fn test_cache_clear() {
        let cache: FactoryCache<i32, String> = FactoryCache::new(Duration::from_secs(60));

        cache.insert(1, "value1".to_string());
        cache.insert(2, "value2".to_string());
        assert_eq!(cache.len(), 2);

        cache.clear();
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_cache_cleanup_expired() {
        let cache: FactoryCache<i32, String> = FactoryCache::new(Duration::from_millis(100));

        cache.insert(1, "value1".to_string());
        cache.insert(2, "value2".to_string());
        cache.insert(3, "value3".to_string());

        thread::sleep(Duration::from_millis(150));

        let removed = cache.cleanup_expired();
        assert_eq!(removed, 3);
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_cache_stats() {
        let cache: FactoryCache<i32, String> = FactoryCache::new(Duration::from_millis(100));

        cache.insert(1, "value1".to_string());
        cache.insert(2, "value2".to_string());

        let (total, expired) = cache.stats();
        assert_eq!(total, 2);
        assert_eq!(expired, 0);

        thread::sleep(Duration::from_millis(150));

        let (total, expired) = cache.stats();
        assert_eq!(total, 2);
        assert_eq!(expired, 2);
    }

    #[test]
    fn test_cache_thread_safety() {
        let cache: FactoryCache<i32, String> = FactoryCache::new(Duration::from_secs(60));
        let cache_clone = cache.clone();

        let handle = thread::spawn(move || {
            cache_clone.insert(1, "thread_value".to_string());
        });

        handle.join().unwrap();
        assert_eq!(cache.get(&1), Some("thread_value".to_string()));
    }

    #[test]
    fn test_cached_factory() {
        struct DummyFactory;

        let factory = DummyFactory;
        let cached = CachedFactory::new(factory);

        assert!(cached.is_cached());
        assert!(cached.inner() as *const _ == &cached.factory as *const _);

        let uncached = CachedFactory::without_cache(DummyFactory);
        assert!(!uncached.is_cached());
    }
}