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
/*
 * This file is part of ids_service
 *
 * ids_service is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * ids_service is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with ids_service.  If not, see <http://www.gnu.org/licenses/>
 */

//! Library that allows generating unique ids. It loads ids in cache if the cache
//! reaches a lower limit then a fill thread is started.
//! If the cache is empty (the number of requests is too high) an id is calculated on the fly.
//! This will slow down obtaining the id but there is no error when the cache is empty.
//! To generate unique ids the library uses a random number generator and a SHA256 hash for the id
//! as String type. For type u128 it's from the random number generator.
//!
//! # Quick Start
//! ```
//! extern crate ids_service;
//! use ids_service::ids::*;
//!
//! let mut z: IdsService<String> = IdsService::new( ConfigIdsService::default());
//! println!("Get an id as String:"); z.get_id();
//!
//! // Use iterator
//! for z in z.iter() {
//!     println!("Id: {}",z);
//! }
//! ```
//!
//! The lib use simplelog see for configuration:
//! [crates.io Rust Package Registry SimpleLog ](https://crates.io/crates/simplelog).
//#![feature(test)]
//#![feature(get_type_id)]
//extern crate test;
extern crate log;
extern crate rand;
extern crate simplelog;
extern crate crypto;



/// Module ids with all implementation
pub mod ids {
    use rand::prelude::*;
    use log::*;
    use std::collections::VecDeque;
    use std::thread;
    use std::sync::{mpsc,Arc, Mutex};
    use crypto::digest::Digest;
    use crypto::sha2::Sha256;

    // On new a initial size is generated
    const INITIAL_FILL_IN_SIZE : usize = 100;

    /// Configuration struct
    /// rand_data_size is used with String it's the number of bytes generated before hash SHA256
    #[derive(Debug, Copy, Clone)]
    pub struct ConfigIdsService {
        pub cache_size: usize,
        pub cache_size_low: usize,
        pub rand_data_size: usize
    }

    /// Default configuration
    impl Default for ConfigIdsService {
        fn default() -> ConfigIdsService {
            ConfigIdsService {
                cache_size: 5000 as usize,
                cache_size_low: 500 as usize,
                rand_data_size: 1024 as usize,
            }
        }
    }

    /// Struct for internal use of IdsService
    pub struct IdsService <T>
        where
            T: FillIn + std::marker::Send,
    {
        ids_cache: Arc<Mutex<VecDeque<T>>>,
        config: ConfigIdsService,
        sender : mpsc::Sender<IdsCmd>
    }


    /*
     * Iterator implementation example from:
     * https://blog.guillaume-gomez.fr/articles/2017-03-09+Little+tour+of+multiple+iterators+implementation+in+Rust
     */

    /// Inner data for iterator
    pub struct IterIdsService<T:  FillIn + std::marker::Send> {
        inner: VecDeque<T>
    }

    /// Implementation of iterator
    impl<T> Iterator for IterIdsService<T>
        where
            T: FillIn + std::marker::Send,
    {
        type Item = T;

        fn next(&mut self) -> Option<Self::Item> {
            self.inner.pop_front()
        }
    }

    /// Trait FillIn has 2 purposes:
    /// 1) Limit <T> to String or u128
    /// 2) Implement fill_in and create_id functions for specified types
    pub trait FillIn: Sized {
        fn fill_in(v: &mut Vec<Self>, data_size : Option<usize>,nb_item : usize);
        fn create_id(data_size : Option<usize>) -> Self;
    }

    /// String implementation
    impl FillIn for String {
        fn fill_in(v: &mut Vec<Self>, data_size : Option<usize>,nb_item : usize) {
            for _i in 0..nb_item {
                let id = Self::create_id(data_size);
                v.push(id);
            }
        }

        fn create_id(data_size : Option<usize>) -> Self {
            let arr_size = data_size.unwrap_or(1024 as usize);
            let mut arr = vec![0u8;arr_size];
            thread_rng().fill(arr.as_mut_slice());
            let mut hasher = Sha256::new();
            hasher.input(arr.as_slice());
            hasher.result_str()
        }
    }

    /// u128 implementation
    impl FillIn for u128 {
        fn fill_in(v: &mut Vec<Self>, _data_size : Option<usize>,nb_item : usize) {
            let mut arr = vec![0u128;nb_item];
            thread_rng().fill(arr.as_mut_slice());
            v.extend(arr.as_slice());
        }

        fn create_id(_data_size : Option<usize>) -> Self {
            let mut rng = rand::thread_rng();
            let r:u128 = rng.gen();
            r
        }
    }





    // channel command
    enum IdsCmd {
        FillInIds
    }


    /// Main implementation during creation a thread to fill in cache is started
    /// # Examples
    ///
    /// ```
    /// extern crate ids_service;
    /// use ids_service::ids::*;
    ///
    /// let mut x: IdsService<String> = IdsService::new(ConfigIdsService::default());
    /// println!("x:{}",x.get_id().unwrap_or("None".to_string()));
    /// ```
    ///
    /// ```
    /// extern crate ids_service;
    /// use ids_service::ids::*;
    ///
    /// let mut y: IdsService<String> = IdsService::new(ConfigIdsService::default());
    /// println!("y:{}",y.get_id().unwrap_or("None".to_string()));
    /// ```
    impl <T: 'static>IdsService <T>
        where T: FillIn + std::marker::Send {
        pub fn new(cnf: ConfigIdsService) -> IdsService <T>{
            trace!("Create a new IdsService with ConfigIdsService {:?}",cnf);
            let cache: Arc<Mutex<VecDeque<T>>> = Arc::new(Mutex::new(VecDeque::with_capacity(cnf.cache_size)));
            let cmd_chn : (mpsc::Sender<IdsCmd>,mpsc::Receiver<IdsCmd>) = mpsc::channel();
            let result = IdsService {
                ids_cache: cache,
                config: cnf,
                sender: cmd_chn.0.clone()
            };
            let conf = result.config;
            if conf.cache_size<= conf.cache_size_low {
                let value = format!("Bad values for ConfigIdsService: cache_size ({}) is smaller cache_size_low ({})",conf.cache_size,conf.cache_size_low );
                error!("{}",value);
                panic!("{}",value);
            }
            let builder = thread::Builder::new().name("IdsGenerator".to_string());
            let ids_cache_ref = &result.ids_cache.clone();
            let ids_cache_ref_clone = Arc::clone(&ids_cache_ref);

            let _handle = builder.spawn(move || {
                let receiver = cmd_chn.1;
                for ids_cmd in receiver.iter()  {
                    match ids_cmd {
                        IdsCmd::FillInIds => {
                            let x = ids_cache_ref_clone.lock().unwrap().len();
                            if x < conf.cache_size_low {
                                trace!("Start fill in");
                                let mut data = Vec::new();
                                T::fill_in(&mut data,Some(conf.rand_data_size),conf.cache_size-x);
                                ids_cache_ref_clone.lock().unwrap().extend(data);
                                trace!("End fill in new size:{}",ids_cache_ref_clone.lock().unwrap().len());
                            }
                        }
                    }
                }
            }).unwrap();

            // synchrone fill in to initial size
            let mut data = Vec::new();
            T::fill_in(&mut data,Some(result.config.rand_data_size),INITIAL_FILL_IN_SIZE);
            result.ids_cache.lock().unwrap().extend(data);
            // Start an asynchrone fill in
            result.sender.send(IdsCmd::FillInIds).expect("Could'nt send a fill in message");
            result
        }

        /// Get an id from cache.
        /// if cache is low it request background fill in.
        /// If the cache is empty it generate on fly an id
        pub fn get_id(&mut self) -> Option<T> {
            let id = self.ids_cache.lock().unwrap().pop_front();
            let ids_left = self.ids_cache.lock().unwrap().len();
            if ids_left < self.config.cache_size_low {
                self.sender.send(IdsCmd::FillInIds).expect("Could'nt send a fill in message");
            }
            match id {
                Some(i) => Some(i),
                None => {
                    info!("The ids_cache is empty, create on fly an id");
                    Some(T::create_id(Some(self.config.rand_data_size)))
                },
            }

        }

        /// Force a fill in to a new_size.
        /// If new_size isn't specified the size is from configuration
        ///
        /// # Example
        ///
        /// ```
        /// extern crate ids_service;
        /// use ids_service::ids::*;
        ///
        /// let mut y: IdsService<String> = IdsService::new(ConfigIdsService::default());
        /// println!("y:{}",y.get_id().unwrap_or("None".to_string()));
        ///
        /// y.sync_fill_in(Some(15000));
        /// ```
        pub fn sync_fill_in(&mut self, new_size : Option<usize>) {
            trace!("Start sync_fill_in");
            let len = self.ids_cache.lock().unwrap().len();
            let capacity = new_size.unwrap_or(self.config.cache_size) - len;
            let mut data = Vec::with_capacity(capacity);
            T::fill_in(&mut data,Some(self.config.rand_data_size),capacity);
            self.ids_cache.lock().unwrap().extend(data);
            trace!("End sync_fill_in size:{}",self.ids_cache.lock().unwrap().len());
        }

        /// Get the current cache size
        pub fn get_current_cache_size(&mut self) -> usize {
            self.ids_cache.lock().unwrap().len()
        }

        /// return an iterator on the entire cache
        /// # Examples
        ///
        /// ```
        /// extern crate ids_service;
        /// use ids_service::ids::*;
        ///
        /// let mut x: IdsService<String> = IdsService::new(ConfigIdsService::default());
        /// for x in x.iter() {
        ///    println!("Read id: {}",x);
        /// }
        /// ```
        pub fn iter(&mut  self) -> IterIdsService<T> {
            let slice = self.ids_cache.lock().unwrap().split_off(0);
            trace!("iter slice size: {}",slice.len());
            self.sender.send(IdsCmd::FillInIds).expect("Couldn't send a fill in message");
            IterIdsService {
                inner: slice
            }
        }
    }
}



#[cfg(test)]
mod tests {

    use crate::ids::*;
    use super::*;
    //use test::Bencher;
    use log::*;
    use simplelog::*;
    use std::sync::{Once, ONCE_INIT};

    static INIT: Once = ONCE_INIT;

    /// Setup function that is only run once, even if called multiple times.
    fn setup(){
        INIT.call_once(|| {
            CombinedLogger::init(
                vec![
                    TermLogger::new(LevelFilter::Info, Config::default()).unwrap(),
                ]
            ).unwrap();
        });
    }


    #[test]
    fn test_get_new_string_id() {
        setup();
        let mut ids : IdsService<String> = IdsService::new(ConfigIdsService::default());
        let id = ids.get_id();
        assert!(id.is_some());
    }

    #[test]
    fn test_get_new_u128_id() {
        setup();
        let mut ids : IdsService<u128> = IdsService::new(ConfigIdsService::default());
        let id = ids.get_id();
        assert!(id.is_some());
    }

    // should not see log like:
    // 22:10:43 [INFO] The ids_cache is empty, create on fly an id
    #[test]
    fn test_sync_fill_in_none() {
        setup();
        let mut ids : IdsService<String> = IdsService::new(ConfigIdsService::default());
        ids.sync_fill_in(None);
        assert!(ids.get_current_cache_size()>=5000);
    }

    // should not see log like:
    // 22:10:43 [INFO] The ids_cache is empty, create on fly an id
    #[test]
    fn test_sync_fill_in_20000() {
        setup();
        let mut ids : IdsService<String> = IdsService::new(ConfigIdsService::default());
        ids.sync_fill_in(Some(6000));
        assert!(ids.get_current_cache_size()>=6000);
    }

    #[test]
    fn test_iter_20000() {
        setup();
        let mut ids : IdsService<String> = IdsService::new(ConfigIdsService::default());
        ids.sync_fill_in(Some(20000));
        let mut i = 0;
        for _id in ids.iter() {
            i+=1;
        }
        assert!(i>=20000);
    }

    /*
    #[bench]
    fn bench_get_new_id(b: &mut Bencher) {
        setup();
        let cnf = ConfigIdsService {
            cache_size: 100000 as usize,
            cache_size_low: 20000 as usize,
            rand_data_size: 1024 as usize,
        };
        let mut ids : IdsService<u128> = IdsService::new(cnf);
        ids.sync_fill_in(None);
        b.iter(  || {
            trace!("size : {}",ids.get_current_cache_size());
            ids.get_id().unwrap()
        })
    }

    #[bench]
    fn bench_get_id_fori(b: &mut Bencher) {
        setup();
        let cnf = ConfigIdsService {
            cache_size: 5000 as usize,
            cache_size_low: 500 as usize,
            rand_data_size: 1024 as usize,
        };
        let mut ids : IdsService<u128> = IdsService::new(cnf);
        ids.sync_fill_in(None);
        b.iter(  || {
            for _i in 0..5000 {
               let _z=ids.get_id().unwrap();
            }
        })
    }

    #[bench]
    fn bench_get_id_iter(b: &mut Bencher) {
        setup();
        let cnf = ConfigIdsService {
            cache_size: 5000 as usize,
            cache_size_low: 500 as usize,
            rand_data_size: 1024 as usize,
        };
        let mut ids : IdsService<u128> = IdsService::new(cnf);
        ids.sync_fill_in(None);
        b.iter(  || {
            for id in ids.iter() {
                let _z=id;
            }
        })
    }

    */
}