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}
116
117/// A factory for generating deterministic UUIDs that are guaranteed unique
118/// across different generator types within the same seed.
119///
120/// # UUID Structure (16 bytes)
121///
122/// ```text
123/// Bytes 0-5:   Seed (lower 48 bits)
124/// Byte  6:     Generator type discriminator
125/// Byte  7:     Version nibble (0x4_) | Sub-discriminator
126/// Bytes 8-15:  Counter (64-bit, with variant bits set)
127/// ```
128///
129/// # Thread Safety
130///
131/// The counter uses `AtomicU64` for thread-safe increments, allowing
132/// concurrent UUID generation from multiple threads.
133#[derive(Debug)]
134pub struct DeterministicUuidFactory {
135    seed: u64,
136    generator_type: GeneratorType,
137    counter: AtomicU64,
138    /// Optional sub-discriminator for further namespace separation
139    sub_discriminator: u8,
140}
141
142impl DeterministicUuidFactory {
143    /// Create a new UUID factory for a specific generator type.
144    ///
145    /// # Arguments
146    ///
147    /// * `seed` - The global seed for deterministic generation
148    /// * `generator_type` - The type of generator using this factory
149    ///
150    /// # Example
151    ///
152    /// ```
153    /// use datasynth_core::uuid_factory::{DeterministicUuidFactory, GeneratorType};
154    ///
155    /// let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
156    /// let uuid = factory.next();
157    /// ```
158    pub fn new(seed: u64, generator_type: GeneratorType) -> Self {
159        Self {
160            seed,
161            generator_type,
162            counter: AtomicU64::new(0),
163            sub_discriminator: 0,
164        }
165    }
166
167    /// Create a factory with a sub-discriminator for additional namespace separation.
168    ///
169    /// Useful when the same generator type needs multiple independent UUID streams.
170    pub fn with_sub_discriminator(
171        seed: u64,
172        generator_type: GeneratorType,
173        sub_discriminator: u8,
174    ) -> Self {
175        Self {
176            seed,
177            generator_type,
178            counter: AtomicU64::new(0),
179            sub_discriminator,
180        }
181    }
182
183    /// Create a factory starting from a specific counter value.
184    ///
185    /// Useful for resuming generation from a checkpoint.
186    pub fn with_counter(seed: u64, generator_type: GeneratorType, start_counter: u64) -> Self {
187        Self {
188            seed,
189            generator_type,
190            counter: AtomicU64::new(start_counter),
191            sub_discriminator: 0,
192        }
193    }
194
195    /// Generate the next UUID in the sequence.
196    ///
197    /// This method is thread-safe and can be called from multiple threads.
198    pub fn next(&self) -> Uuid {
199        let counter = self.counter.fetch_add(1, Ordering::Relaxed);
200        self.generate_uuid(counter)
201    }
202
203    /// Generate a UUID for a specific counter value without incrementing.
204    ///
205    /// Useful for deterministic regeneration of specific UUIDs.
206    pub fn generate_at(&self, counter: u64) -> Uuid {
207        self.generate_uuid(counter)
208    }
209
210    /// Get the current counter value.
211    pub fn current_counter(&self) -> u64 {
212        self.counter.load(Ordering::Relaxed)
213    }
214
215    /// Reset the counter to zero.
216    pub fn reset(&self) {
217        self.counter.store(0, Ordering::Relaxed);
218    }
219
220    /// Set the counter to a specific value.
221    pub fn set_counter(&self, value: u64) {
222        self.counter.store(value, Ordering::Relaxed);
223    }
224
225    /// Generate a UUID from the seed, generator type, and counter.
226    ///
227    /// Uses a simple hash-based approach to ensure uniqueness while maintaining
228    /// determinism. The hash function is designed to spread entropy across all
229    /// bytes while preserving the UUID v4 format.
230    fn generate_uuid(&self, counter: u64) -> Uuid {
231        // Create a unique input by combining all distinguishing factors
232        // Use FNV-1a style hashing for simplicity and determinism
233        let mut hash: u64 = 14695981039346656037; // FNV offset basis
234
235        // Mix in seed
236        for byte in self.seed.to_le_bytes() {
237            hash ^= byte as u64;
238            hash = hash.wrapping_mul(1099511628211); // FNV prime
239        }
240
241        // Mix in generator type
242        hash ^= self.generator_type as u64;
243        hash = hash.wrapping_mul(1099511628211);
244
245        // Mix in sub-discriminator
246        hash ^= self.sub_discriminator as u64;
247        hash = hash.wrapping_mul(1099511628211);
248
249        // Mix in counter (most important for uniqueness within same factory)
250        for byte in counter.to_le_bytes() {
251            hash ^= byte as u64;
252            hash = hash.wrapping_mul(1099511628211);
253        }
254
255        // Create second hash for remaining bytes
256        let mut hash2: u64 = hash;
257        hash2 ^= self.seed.rotate_left(32);
258        hash2 = hash2.wrapping_mul(1099511628211);
259        hash2 ^= counter.rotate_left(32);
260        hash2 = hash2.wrapping_mul(1099511628211);
261
262        let mut bytes = [0u8; 16];
263
264        // First 8 bytes from hash
265        bytes[0..8].copy_from_slice(&hash.to_le_bytes());
266        // Second 8 bytes from hash2
267        bytes[8..16].copy_from_slice(&hash2.to_le_bytes());
268
269        // Set UUID version 4 (bits 12-15 of time_hi_and_version)
270        // Byte 6: xxxx0100 -> set bits 4-7 to 0100
271        bytes[6] = (bytes[6] & 0x0f) | 0x40;
272
273        // Set variant to RFC 4122 (bits 6-7 of clock_seq_hi_and_reserved)
274        // Byte 8: 10xxxxxx -> set bits 6-7 to 10
275        bytes[8] = (bytes[8] & 0x3f) | 0x80;
276
277        Uuid::from_bytes(bytes)
278    }
279}
280
281impl Clone for DeterministicUuidFactory {
282    fn clone(&self) -> Self {
283        Self {
284            seed: self.seed,
285            generator_type: self.generator_type,
286            counter: AtomicU64::new(self.counter.load(Ordering::Relaxed)),
287            sub_discriminator: self.sub_discriminator,
288        }
289    }
290}
291
292/// A registry that manages multiple UUID factories for different generator types.
293///
294/// This ensures a single source of truth for UUID generation across the system.
295#[derive(Debug)]
296pub struct UuidFactoryRegistry {
297    seed: u64,
298    factories: std::collections::HashMap<GeneratorType, DeterministicUuidFactory>,
299}
300
301impl UuidFactoryRegistry {
302    /// Create a new registry with a global seed.
303    pub fn new(seed: u64) -> Self {
304        Self {
305            seed,
306            factories: std::collections::HashMap::new(),
307        }
308    }
309
310    /// Get or create a factory for a specific generator type.
311    pub fn get_factory(&mut self, generator_type: GeneratorType) -> &DeterministicUuidFactory {
312        self.factories
313            .entry(generator_type)
314            .or_insert_with(|| DeterministicUuidFactory::new(self.seed, generator_type))
315    }
316
317    /// Generate the next UUID for a specific generator type.
318    pub fn next_uuid(&mut self, generator_type: GeneratorType) -> Uuid {
319        self.get_factory(generator_type).next()
320    }
321
322    /// Reset all factories.
323    pub fn reset_all(&self) {
324        for factory in self.factories.values() {
325            factory.reset();
326        }
327    }
328
329    /// Get the current counter for a generator type.
330    pub fn get_counter(&self, generator_type: GeneratorType) -> Option<u64> {
331        self.factories
332            .get(&generator_type)
333            .map(|f| f.current_counter())
334    }
335}
336
337#[cfg(test)]
338#[allow(clippy::unwrap_used)]
339mod tests {
340    use super::*;
341    use std::collections::HashSet;
342    use std::thread;
343
344    #[test]
345    fn test_uuid_uniqueness_same_generator() {
346        let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
347
348        let mut uuids = HashSet::new();
349        for _ in 0..10000 {
350            let uuid = factory.next();
351            assert!(uuids.insert(uuid), "Duplicate UUID generated");
352        }
353    }
354
355    #[test]
356    fn test_uuid_uniqueness_different_generators() {
357        let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
358        let factory2 = DeterministicUuidFactory::new(12345, GeneratorType::DocumentFlow);
359
360        let mut uuids = HashSet::new();
361
362        for _ in 0..5000 {
363            let uuid1 = factory1.next();
364            let uuid2 = factory2.next();
365            assert!(uuids.insert(uuid1), "Duplicate UUID from JE generator");
366            assert!(uuids.insert(uuid2), "Duplicate UUID from DocFlow generator");
367        }
368    }
369
370    #[test]
371    fn test_uuid_determinism() {
372        let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
373        let factory2 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
374
375        for _ in 0..100 {
376            assert_eq!(factory1.next(), factory2.next());
377        }
378    }
379
380    #[test]
381    fn test_uuid_different_seeds() {
382        let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
383        let factory2 = DeterministicUuidFactory::new(67890, GeneratorType::JournalEntry);
384
385        // Different seeds should produce different UUIDs
386        assert_ne!(factory1.next(), factory2.next());
387    }
388
389    #[test]
390    fn test_thread_safety() {
391        use std::sync::Arc;
392
393        let factory = Arc::new(DeterministicUuidFactory::new(
394            12345,
395            GeneratorType::JournalEntry,
396        ));
397        let mut handles = vec![];
398
399        for _ in 0..4 {
400            let factory_clone = Arc::clone(&factory);
401            handles.push(thread::spawn(move || {
402                let mut uuids = Vec::new();
403                for _ in 0..1000 {
404                    uuids.push(factory_clone.next());
405                }
406                uuids
407            }));
408        }
409
410        let mut all_uuids = HashSet::new();
411        for handle in handles {
412            let uuids = handle.join().unwrap();
413            for uuid in uuids {
414                assert!(all_uuids.insert(uuid), "Thread-generated UUID collision");
415            }
416        }
417
418        assert_eq!(all_uuids.len(), 4000);
419    }
420
421    #[test]
422    fn test_sub_discriminator() {
423        let factory1 =
424            DeterministicUuidFactory::with_sub_discriminator(12345, GeneratorType::JournalEntry, 0);
425        let factory2 =
426            DeterministicUuidFactory::with_sub_discriminator(12345, GeneratorType::JournalEntry, 1);
427
428        // Different sub-discriminators should produce different UUIDs
429        let uuid1 = factory1.next();
430        factory1.reset();
431        let uuid2 = factory2.next();
432
433        assert_ne!(uuid1, uuid2);
434    }
435
436    #[test]
437    fn test_generate_at() {
438        let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
439
440        // Generate at specific counter
441        let uuid_at_5 = factory.generate_at(5);
442
443        // Generate sequentially to reach counter 5
444        for _ in 0..5 {
445            factory.next();
446        }
447        let _uuid_sequential = factory.next();
448
449        // The UUID at counter 5 should match
450        assert_eq!(uuid_at_5, factory.generate_at(5));
451    }
452
453    #[test]
454    fn test_registry() {
455        let mut registry = UuidFactoryRegistry::new(12345);
456
457        let uuid1 = registry.next_uuid(GeneratorType::JournalEntry);
458        let uuid2 = registry.next_uuid(GeneratorType::JournalEntry);
459        let uuid3 = registry.next_uuid(GeneratorType::DocumentFlow);
460
461        // All should be unique
462        assert_ne!(uuid1, uuid2);
463        assert_ne!(uuid1, uuid3);
464        assert_ne!(uuid2, uuid3);
465
466        // Counter should be tracked
467        assert_eq!(registry.get_counter(GeneratorType::JournalEntry), Some(2));
468        assert_eq!(registry.get_counter(GeneratorType::DocumentFlow), Some(1));
469    }
470
471    #[test]
472    fn test_uuid_is_valid_v4() {
473        let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
474        let uuid = factory.next();
475
476        // Check version is 4
477        assert_eq!(uuid.get_version_num(), 4);
478
479        // Check variant is RFC 4122
480        assert_eq!(uuid.get_variant(), uuid::Variant::RFC4122);
481    }
482}