Skip to main content

datasynth_core/
uuid_factory.rs

1//! Deterministic UUID generation factory for reproducible synthetic data.
2//!
3//! This module provides a centralized UUID generation system that ensures:
4//! - No collisions between different generator types
5//! - Reproducible output given the same seed
6//! - Thread-safe counter increments
7
8use std::sync::atomic::{AtomicU64, Ordering};
9use uuid::Uuid;
10
11/// Generator type discriminators to prevent UUID collisions across generators.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[repr(u8)]
14pub enum GeneratorType {
15    /// Journal Entry generator
16    JournalEntry = 0x01,
17    /// Document Flow (P2P/O2C) generator
18    DocumentFlow = 0x02,
19    /// Master Data - Vendor generator
20    Vendor = 0x03,
21    /// Master Data - Customer generator
22    Customer = 0x04,
23    /// Master Data - Material generator
24    Material = 0x05,
25    /// Master Data - Asset generator
26    Asset = 0x06,
27    /// Master Data - Employee generator
28    Employee = 0x07,
29    /// Subledger - AR generator
30    ARSubledger = 0x08,
31    /// Subledger - AP generator
32    APSubledger = 0x09,
33    /// Subledger - FA generator
34    FASubledger = 0x0A,
35    /// Subledger - Inventory generator
36    InventorySubledger = 0x0B,
37    /// Intercompany generator
38    Intercompany = 0x0C,
39    /// Anomaly injection
40    Anomaly = 0x0D,
41    /// Period close generator
42    PeriodClose = 0x0E,
43    /// FX rate generator
44    FxRate = 0x0F,
45    /// Accrual generator
46    Accrual = 0x10,
47    /// Depreciation generator
48    Depreciation = 0x11,
49    /// Control generator
50    Control = 0x12,
51    /// Opening balance generator
52    OpeningBalance = 0x13,
53    /// Trial balance generator
54    TrialBalance = 0x14,
55    /// Purchase Order document
56    PurchaseOrder = 0x20,
57    /// Goods Receipt document
58    GoodsReceipt = 0x21,
59    /// Vendor Invoice document
60    VendorInvoice = 0x22,
61    /// Payment document
62    Payment = 0x23,
63    /// Sales Order document
64    SalesOrder = 0x24,
65    /// Delivery document
66    Delivery = 0x25,
67    /// Customer Invoice document
68    CustomerInvoice = 0x26,
69    /// Customer Receipt document
70    CustomerReceipt = 0x27,
71
72    // ===== Enterprise Process Chain generators =====
73    /// Sourcing project generator
74    SourcingProject = 0x28,
75    /// RFx event generator
76    RfxEvent = 0x29,
77    /// Supplier bid generator
78    SupplierBid = 0x2A,
79    /// Procurement contract generator
80    ProcurementContract = 0x2B,
81    /// Catalog item generator
82    CatalogItem = 0x2C,
83    /// Bank reconciliation generator
84    BankReconciliation = 0x2D,
85    /// Financial statement generator
86    FinancialStatement = 0x2E,
87    /// Payroll run generator
88    PayrollRun = 0x2F,
89    /// Time entry generator
90    TimeEntry = 0x30,
91    /// Expense report generator
92    ExpenseReport = 0x31,
93    /// Production order generator
94    ProductionOrder = 0x32,
95    /// Cycle count generator
96    CycleCount = 0x33,
97    /// Quality inspection generator
98    QualityInspection = 0x34,
99    /// Sales quote generator
100    SalesQuote = 0x35,
101    /// Budget line generator
102    BudgetLine = 0x36,
103    /// Revenue recognition contract generator
104    RevenueRecognition = 0x37,
105    /// Impairment test generator
106    ImpairmentTest = 0x38,
107    /// Management KPI generator
108    Kpi = 0x39,
109    /// Tax code / jurisdiction generator
110    Tax = 0x3A,
111    /// Project accounting (cost lines, revenue, milestones, change orders, EVM)
112    ProjectAccounting = 0x3B,
113    /// ESG / Sustainability (emissions, energy, water, waste, diversity, safety)
114    Esg = 0x3C,
115    /// Supplier qualification generator
116    SupplierQualification = 0x3D,
117    /// Supplier scorecard generator
118    SupplierScorecard = 0x3E,
119}
120
121/// A factory for generating deterministic UUIDs that are guaranteed unique
122/// across different generator types within the same seed.
123///
124/// # UUID Structure (16 bytes)
125///
126/// ```text
127/// Bytes 0-5:   Seed (lower 48 bits)
128/// Byte  6:     Generator type discriminator
129/// Byte  7:     Version nibble (0x4_) | Sub-discriminator
130/// Bytes 8-15:  Counter (64-bit, with variant bits set)
131/// ```
132///
133/// # Thread Safety
134///
135/// The counter uses `AtomicU64` for thread-safe increments, allowing
136/// concurrent UUID generation from multiple threads.
137#[derive(Debug)]
138pub struct DeterministicUuidFactory {
139    seed: u64,
140    generator_type: GeneratorType,
141    counter: AtomicU64,
142    /// Optional sub-discriminator for further namespace separation
143    sub_discriminator: u8,
144}
145
146impl DeterministicUuidFactory {
147    /// Create a new UUID factory for a specific generator type.
148    ///
149    /// # Arguments
150    ///
151    /// * `seed` - The global seed for deterministic generation
152    /// * `generator_type` - The type of generator using this factory
153    ///
154    /// # Example
155    ///
156    /// ```
157    /// use datasynth_core::uuid_factory::{DeterministicUuidFactory, GeneratorType};
158    ///
159    /// let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
160    /// let uuid = factory.next();
161    /// ```
162    pub fn new(seed: u64, generator_type: GeneratorType) -> Self {
163        Self {
164            seed,
165            generator_type,
166            counter: AtomicU64::new(0),
167            sub_discriminator: 0,
168        }
169    }
170
171    /// Create a factory with a sub-discriminator for additional namespace separation.
172    ///
173    /// Useful when the same generator type needs multiple independent UUID streams.
174    pub fn with_sub_discriminator(
175        seed: u64,
176        generator_type: GeneratorType,
177        sub_discriminator: u8,
178    ) -> Self {
179        Self {
180            seed,
181            generator_type,
182            counter: AtomicU64::new(0),
183            sub_discriminator,
184        }
185    }
186
187    /// Create a factory starting from a specific counter value.
188    ///
189    /// Useful for resuming generation from a checkpoint.
190    pub fn with_counter(seed: u64, generator_type: GeneratorType, start_counter: u64) -> Self {
191        Self {
192            seed,
193            generator_type,
194            counter: AtomicU64::new(start_counter),
195            sub_discriminator: 0,
196        }
197    }
198
199    /// Generate the next UUID in the sequence.
200    ///
201    /// This method is thread-safe and can be called from multiple threads.
202    pub fn next(&self) -> Uuid {
203        let counter = self.counter.fetch_add(1, Ordering::Relaxed);
204        self.generate_uuid(counter)
205    }
206
207    /// Generate a UUID for a specific counter value without incrementing.
208    ///
209    /// Useful for deterministic regeneration of specific UUIDs.
210    pub fn generate_at(&self, counter: u64) -> Uuid {
211        self.generate_uuid(counter)
212    }
213
214    /// Get the current counter value.
215    pub fn current_counter(&self) -> u64 {
216        self.counter.load(Ordering::Relaxed)
217    }
218
219    /// Reset the counter to zero.
220    pub fn reset(&self) {
221        self.counter.store(0, Ordering::Relaxed);
222    }
223
224    /// Set the counter to a specific value.
225    pub fn set_counter(&self, value: u64) {
226        self.counter.store(value, Ordering::Relaxed);
227    }
228
229    /// Generate a UUID from the seed, generator type, and counter.
230    ///
231    /// Uses a simple hash-based approach to ensure uniqueness while maintaining
232    /// determinism. The hash function is designed to spread entropy across all
233    /// bytes while preserving the UUID v4 format.
234    fn generate_uuid(&self, counter: u64) -> Uuid {
235        // Create a unique input by combining all distinguishing factors
236        // Use FNV-1a style hashing for simplicity and determinism
237        let mut hash: u64 = 14695981039346656037; // FNV offset basis
238
239        // Mix in seed
240        for byte in self.seed.to_le_bytes() {
241            hash ^= byte as u64;
242            hash = hash.wrapping_mul(1099511628211); // FNV prime
243        }
244
245        // Mix in generator type
246        hash ^= self.generator_type as u64;
247        hash = hash.wrapping_mul(1099511628211);
248
249        // Mix in sub-discriminator
250        hash ^= self.sub_discriminator as u64;
251        hash = hash.wrapping_mul(1099511628211);
252
253        // Mix in counter (most important for uniqueness within same factory)
254        for byte in counter.to_le_bytes() {
255            hash ^= byte as u64;
256            hash = hash.wrapping_mul(1099511628211);
257        }
258
259        // Create second hash for remaining bytes
260        let mut hash2: u64 = hash;
261        hash2 ^= self.seed.rotate_left(32);
262        hash2 = hash2.wrapping_mul(1099511628211);
263        hash2 ^= counter.rotate_left(32);
264        hash2 = hash2.wrapping_mul(1099511628211);
265
266        let mut bytes = [0u8; 16];
267
268        // First 8 bytes from hash
269        bytes[0..8].copy_from_slice(&hash.to_le_bytes());
270        // Second 8 bytes from hash2
271        bytes[8..16].copy_from_slice(&hash2.to_le_bytes());
272
273        // Set UUID version 4 (bits 12-15 of time_hi_and_version)
274        // Byte 6: xxxx0100 -> set bits 4-7 to 0100
275        bytes[6] = (bytes[6] & 0x0f) | 0x40;
276
277        // Set variant to RFC 4122 (bits 6-7 of clock_seq_hi_and_reserved)
278        // Byte 8: 10xxxxxx -> set bits 6-7 to 10
279        bytes[8] = (bytes[8] & 0x3f) | 0x80;
280
281        Uuid::from_bytes(bytes)
282    }
283}
284
285impl Clone for DeterministicUuidFactory {
286    fn clone(&self) -> Self {
287        Self {
288            seed: self.seed,
289            generator_type: self.generator_type,
290            counter: AtomicU64::new(self.counter.load(Ordering::Relaxed)),
291            sub_discriminator: self.sub_discriminator,
292        }
293    }
294}
295
296/// A registry that manages multiple UUID factories for different generator types.
297///
298/// This ensures a single source of truth for UUID generation across the system.
299#[derive(Debug)]
300pub struct UuidFactoryRegistry {
301    seed: u64,
302    factories: std::collections::HashMap<GeneratorType, DeterministicUuidFactory>,
303}
304
305impl UuidFactoryRegistry {
306    /// Create a new registry with a global seed.
307    pub fn new(seed: u64) -> Self {
308        Self {
309            seed,
310            factories: std::collections::HashMap::new(),
311        }
312    }
313
314    /// Get or create a factory for a specific generator type.
315    pub fn get_factory(&mut self, generator_type: GeneratorType) -> &DeterministicUuidFactory {
316        self.factories
317            .entry(generator_type)
318            .or_insert_with(|| DeterministicUuidFactory::new(self.seed, generator_type))
319    }
320
321    /// Generate the next UUID for a specific generator type.
322    pub fn next_uuid(&mut self, generator_type: GeneratorType) -> Uuid {
323        self.get_factory(generator_type).next()
324    }
325
326    /// Reset all factories.
327    pub fn reset_all(&self) {
328        for factory in self.factories.values() {
329            factory.reset();
330        }
331    }
332
333    /// Get the current counter for a generator type.
334    pub fn get_counter(&self, generator_type: GeneratorType) -> Option<u64> {
335        self.factories
336            .get(&generator_type)
337            .map(|f| f.current_counter())
338    }
339}
340
341#[cfg(test)]
342#[allow(clippy::unwrap_used)]
343mod tests {
344    use super::*;
345    use std::collections::HashSet;
346    use std::thread;
347
348    #[test]
349    fn test_uuid_uniqueness_same_generator() {
350        let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
351
352        let mut uuids = HashSet::new();
353        for _ in 0..10000 {
354            let uuid = factory.next();
355            assert!(uuids.insert(uuid), "Duplicate UUID generated");
356        }
357    }
358
359    #[test]
360    fn test_uuid_uniqueness_different_generators() {
361        let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
362        let factory2 = DeterministicUuidFactory::new(12345, GeneratorType::DocumentFlow);
363
364        let mut uuids = HashSet::new();
365
366        for _ in 0..5000 {
367            let uuid1 = factory1.next();
368            let uuid2 = factory2.next();
369            assert!(uuids.insert(uuid1), "Duplicate UUID from JE generator");
370            assert!(uuids.insert(uuid2), "Duplicate UUID from DocFlow generator");
371        }
372    }
373
374    #[test]
375    fn test_uuid_determinism() {
376        let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
377        let factory2 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
378
379        for _ in 0..100 {
380            assert_eq!(factory1.next(), factory2.next());
381        }
382    }
383
384    #[test]
385    fn test_uuid_different_seeds() {
386        let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
387        let factory2 = DeterministicUuidFactory::new(67890, GeneratorType::JournalEntry);
388
389        // Different seeds should produce different UUIDs
390        assert_ne!(factory1.next(), factory2.next());
391    }
392
393    #[test]
394    fn test_thread_safety() {
395        use std::sync::Arc;
396
397        let factory = Arc::new(DeterministicUuidFactory::new(
398            12345,
399            GeneratorType::JournalEntry,
400        ));
401        let mut handles = vec![];
402
403        for _ in 0..4 {
404            let factory_clone = Arc::clone(&factory);
405            handles.push(thread::spawn(move || {
406                let mut uuids = Vec::new();
407                for _ in 0..1000 {
408                    uuids.push(factory_clone.next());
409                }
410                uuids
411            }));
412        }
413
414        let mut all_uuids = HashSet::new();
415        for handle in handles {
416            let uuids = handle.join().unwrap();
417            for uuid in uuids {
418                assert!(all_uuids.insert(uuid), "Thread-generated UUID collision");
419            }
420        }
421
422        assert_eq!(all_uuids.len(), 4000);
423    }
424
425    #[test]
426    fn test_sub_discriminator() {
427        let factory1 =
428            DeterministicUuidFactory::with_sub_discriminator(12345, GeneratorType::JournalEntry, 0);
429        let factory2 =
430            DeterministicUuidFactory::with_sub_discriminator(12345, GeneratorType::JournalEntry, 1);
431
432        // Different sub-discriminators should produce different UUIDs
433        let uuid1 = factory1.next();
434        factory1.reset();
435        let uuid2 = factory2.next();
436
437        assert_ne!(uuid1, uuid2);
438    }
439
440    #[test]
441    fn test_generate_at() {
442        let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
443
444        // Generate at specific counter
445        let uuid_at_5 = factory.generate_at(5);
446
447        // Generate sequentially to reach counter 5
448        for _ in 0..5 {
449            factory.next();
450        }
451        let _uuid_sequential = factory.next();
452
453        // The UUID at counter 5 should match
454        assert_eq!(uuid_at_5, factory.generate_at(5));
455    }
456
457    #[test]
458    fn test_registry() {
459        let mut registry = UuidFactoryRegistry::new(12345);
460
461        let uuid1 = registry.next_uuid(GeneratorType::JournalEntry);
462        let uuid2 = registry.next_uuid(GeneratorType::JournalEntry);
463        let uuid3 = registry.next_uuid(GeneratorType::DocumentFlow);
464
465        // All should be unique
466        assert_ne!(uuid1, uuid2);
467        assert_ne!(uuid1, uuid3);
468        assert_ne!(uuid2, uuid3);
469
470        // Counter should be tracked
471        assert_eq!(registry.get_counter(GeneratorType::JournalEntry), Some(2));
472        assert_eq!(registry.get_counter(GeneratorType::DocumentFlow), Some(1));
473    }
474
475    #[test]
476    fn test_uuid_is_valid_v4() {
477        let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
478        let uuid = factory.next();
479
480        // Check version is 4
481        assert_eq!(uuid.get_version_num(), 4);
482
483        // Check variant is RFC 4122
484        assert_eq!(uuid.get_variant(), uuid::Variant::RFC4122);
485    }
486}