1use std::sync::atomic::{AtomicU64, Ordering};
9use uuid::Uuid;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[repr(u8)]
14pub enum GeneratorType {
15 JournalEntry = 0x01,
17 DocumentFlow = 0x02,
19 Vendor = 0x03,
21 Customer = 0x04,
23 Material = 0x05,
25 Asset = 0x06,
27 Employee = 0x07,
29 ARSubledger = 0x08,
31 APSubledger = 0x09,
33 FASubledger = 0x0A,
35 InventorySubledger = 0x0B,
37 Intercompany = 0x0C,
39 Anomaly = 0x0D,
41 PeriodClose = 0x0E,
43 FxRate = 0x0F,
45 Accrual = 0x10,
47 Depreciation = 0x11,
49 Control = 0x12,
51 OpeningBalance = 0x13,
53 TrialBalance = 0x14,
55 PurchaseOrder = 0x20,
57 GoodsReceipt = 0x21,
59 VendorInvoice = 0x22,
61 Payment = 0x23,
63 SalesOrder = 0x24,
65 Delivery = 0x25,
67 CustomerInvoice = 0x26,
69 CustomerReceipt = 0x27,
71
72 SourcingProject = 0x28,
75 RfxEvent = 0x29,
77 SupplierBid = 0x2A,
79 ProcurementContract = 0x2B,
81 CatalogItem = 0x2C,
83 BankReconciliation = 0x2D,
85 FinancialStatement = 0x2E,
87 PayrollRun = 0x2F,
89 TimeEntry = 0x30,
91 ExpenseReport = 0x31,
93 ProductionOrder = 0x32,
95 CycleCount = 0x33,
97 QualityInspection = 0x34,
99 SalesQuote = 0x35,
101 BudgetLine = 0x36,
103 RevenueRecognition = 0x37,
105 ImpairmentTest = 0x38,
107 Kpi = 0x39,
109 Tax = 0x3A,
111 ProjectAccounting = 0x3B,
113 Esg = 0x3C,
115 SupplierQualification = 0x3D,
117 SupplierScorecard = 0x3E,
119 BomComponent = 0x3F,
121 InventoryMovement = 0x40,
123 BenefitEnrollment = 0x41,
125 Disruption = 0x42,
127 BusinessCombination = 0x43,
129 SegmentReport = 0x44,
131 ExpectedCreditLoss = 0x45,
133 Pension = 0x46,
135 Provision = 0x47,
137 StockCompensation = 0x48,
139 IndustryBenchmark = 0x49,
141 Governance = 0x4A,
143 OrganizationalProfile = 0x4B,
145 ItControls = 0x4C,
147 ManagementReport = 0x4D,
149 PriorYear = 0x4E,
151 LegalDocument = 0x4F,
153}
154
155#[derive(Debug)]
172pub struct DeterministicUuidFactory {
173 seed: u64,
174 generator_type: GeneratorType,
175 counter: AtomicU64,
176 sub_discriminator: u8,
178}
179
180impl DeterministicUuidFactory {
181 pub fn new(seed: u64, generator_type: GeneratorType) -> Self {
197 Self {
198 seed,
199 generator_type,
200 counter: AtomicU64::new(0),
201 sub_discriminator: 0,
202 }
203 }
204
205 pub fn with_sub_discriminator(
209 seed: u64,
210 generator_type: GeneratorType,
211 sub_discriminator: u8,
212 ) -> Self {
213 Self {
214 seed,
215 generator_type,
216 counter: AtomicU64::new(0),
217 sub_discriminator,
218 }
219 }
220
221 pub fn with_counter(seed: u64, generator_type: GeneratorType, start_counter: u64) -> Self {
226 Self {
227 seed,
228 generator_type,
229 counter: AtomicU64::new(start_counter),
230 sub_discriminator: 0,
231 }
232 }
233
234 pub fn for_partition(seed: u64, generator_type: GeneratorType, partition_index: u8) -> Self {
240 Self {
241 seed,
242 generator_type,
243 counter: AtomicU64::new(0),
244 sub_discriminator: partition_index,
245 }
246 }
247
248 #[inline]
252 pub fn next(&self) -> Uuid {
253 let counter = self.counter.fetch_add(1, Ordering::Relaxed);
254 self.generate_uuid(counter)
255 }
256
257 pub fn generate_at(&self, counter: u64) -> Uuid {
261 self.generate_uuid(counter)
262 }
263
264 pub fn current_counter(&self) -> u64 {
266 self.counter.load(Ordering::Relaxed)
267 }
268
269 pub fn reset(&self) {
271 self.counter.store(0, Ordering::Relaxed);
272 }
273
274 pub fn set_counter(&self, value: u64) {
276 self.counter.store(value, Ordering::Relaxed);
277 }
278
279 #[inline]
285 fn generate_uuid(&self, counter: u64) -> Uuid {
286 let mut hash: u64 = 14695981039346656037; for byte in self.seed.to_le_bytes() {
292 hash ^= byte as u64;
293 hash = hash.wrapping_mul(1099511628211); }
295
296 hash ^= self.generator_type as u64;
298 hash = hash.wrapping_mul(1099511628211);
299
300 hash ^= self.sub_discriminator as u64;
302 hash = hash.wrapping_mul(1099511628211);
303
304 for byte in counter.to_le_bytes() {
306 hash ^= byte as u64;
307 hash = hash.wrapping_mul(1099511628211);
308 }
309
310 let mut hash2: u64 = hash;
312 hash2 ^= self.seed.rotate_left(32);
313 hash2 = hash2.wrapping_mul(1099511628211);
314 hash2 ^= counter.rotate_left(32);
315 hash2 = hash2.wrapping_mul(1099511628211);
316
317 let mut bytes = [0u8; 16];
318
319 bytes[0..8].copy_from_slice(&hash.to_le_bytes());
321 bytes[8..16].copy_from_slice(&hash2.to_le_bytes());
323
324 bytes[6] = (bytes[6] & 0x0f) | 0x40;
327
328 bytes[8] = (bytes[8] & 0x3f) | 0x80;
331
332 Uuid::from_bytes(bytes)
333 }
334}
335
336impl Clone for DeterministicUuidFactory {
337 fn clone(&self) -> Self {
338 Self {
339 seed: self.seed,
340 generator_type: self.generator_type,
341 counter: AtomicU64::new(self.counter.load(Ordering::Relaxed)),
342 sub_discriminator: self.sub_discriminator,
343 }
344 }
345}
346
347#[derive(Debug)]
351pub struct UuidFactoryRegistry {
352 seed: u64,
353 factories: std::collections::HashMap<GeneratorType, DeterministicUuidFactory>,
354}
355
356impl UuidFactoryRegistry {
357 pub fn new(seed: u64) -> Self {
359 Self {
360 seed,
361 factories: std::collections::HashMap::new(),
362 }
363 }
364
365 pub fn get_factory(&mut self, generator_type: GeneratorType) -> &DeterministicUuidFactory {
367 self.factories
368 .entry(generator_type)
369 .or_insert_with(|| DeterministicUuidFactory::new(self.seed, generator_type))
370 }
371
372 pub fn next_uuid(&mut self, generator_type: GeneratorType) -> Uuid {
374 self.get_factory(generator_type).next()
375 }
376
377 pub fn reset_all(&self) {
379 for factory in self.factories.values() {
380 factory.reset();
381 }
382 }
383
384 pub fn get_counter(&self, generator_type: GeneratorType) -> Option<u64> {
386 self.factories
387 .get(&generator_type)
388 .map(DeterministicUuidFactory::current_counter)
389 }
390}
391
392#[cfg(test)]
393#[allow(clippy::unwrap_used)]
394mod tests {
395 use super::*;
396 use std::collections::HashSet;
397 use std::thread;
398
399 #[test]
400 fn test_uuid_uniqueness_same_generator() {
401 let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
402
403 let mut uuids = HashSet::new();
404 for _ in 0..10000 {
405 let uuid = factory.next();
406 assert!(uuids.insert(uuid), "Duplicate UUID generated");
407 }
408 }
409
410 #[test]
411 fn test_uuid_uniqueness_different_generators() {
412 let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
413 let factory2 = DeterministicUuidFactory::new(12345, GeneratorType::DocumentFlow);
414
415 let mut uuids = HashSet::new();
416
417 for _ in 0..5000 {
418 let uuid1 = factory1.next();
419 let uuid2 = factory2.next();
420 assert!(uuids.insert(uuid1), "Duplicate UUID from JE generator");
421 assert!(uuids.insert(uuid2), "Duplicate UUID from DocFlow generator");
422 }
423 }
424
425 #[test]
426 fn test_uuid_determinism() {
427 let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
428 let factory2 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
429
430 for _ in 0..100 {
431 assert_eq!(factory1.next(), factory2.next());
432 }
433 }
434
435 #[test]
436 fn test_uuid_different_seeds() {
437 let factory1 = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
438 let factory2 = DeterministicUuidFactory::new(67890, GeneratorType::JournalEntry);
439
440 assert_ne!(factory1.next(), factory2.next());
442 }
443
444 #[test]
445 fn test_thread_safety() {
446 use std::sync::Arc;
447
448 let factory = Arc::new(DeterministicUuidFactory::new(
449 12345,
450 GeneratorType::JournalEntry,
451 ));
452 let mut handles = vec![];
453
454 for _ in 0..4 {
455 let factory_clone = Arc::clone(&factory);
456 handles.push(thread::spawn(move || {
457 let mut uuids = Vec::new();
458 for _ in 0..1000 {
459 uuids.push(factory_clone.next());
460 }
461 uuids
462 }));
463 }
464
465 let mut all_uuids = HashSet::new();
466 for handle in handles {
467 let uuids = handle.join().unwrap();
468 for uuid in uuids {
469 assert!(all_uuids.insert(uuid), "Thread-generated UUID collision");
470 }
471 }
472
473 assert_eq!(all_uuids.len(), 4000);
474 }
475
476 #[test]
477 fn test_sub_discriminator() {
478 let factory1 =
479 DeterministicUuidFactory::with_sub_discriminator(12345, GeneratorType::JournalEntry, 0);
480 let factory2 =
481 DeterministicUuidFactory::with_sub_discriminator(12345, GeneratorType::JournalEntry, 1);
482
483 let uuid1 = factory1.next();
485 factory1.reset();
486 let uuid2 = factory2.next();
487
488 assert_ne!(uuid1, uuid2);
489 }
490
491 #[test]
492 fn test_generate_at() {
493 let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
494
495 let uuid_at_5 = factory.generate_at(5);
497
498 for _ in 0..5 {
500 factory.next();
501 }
502 let _uuid_sequential = factory.next();
503
504 assert_eq!(uuid_at_5, factory.generate_at(5));
506 }
507
508 #[test]
509 fn test_registry() {
510 let mut registry = UuidFactoryRegistry::new(12345);
511
512 let uuid1 = registry.next_uuid(GeneratorType::JournalEntry);
513 let uuid2 = registry.next_uuid(GeneratorType::JournalEntry);
514 let uuid3 = registry.next_uuid(GeneratorType::DocumentFlow);
515
516 assert_ne!(uuid1, uuid2);
518 assert_ne!(uuid1, uuid3);
519 assert_ne!(uuid2, uuid3);
520
521 assert_eq!(registry.get_counter(GeneratorType::JournalEntry), Some(2));
523 assert_eq!(registry.get_counter(GeneratorType::DocumentFlow), Some(1));
524 }
525
526 #[test]
527 fn test_uuid_is_valid_v4() {
528 let factory = DeterministicUuidFactory::new(12345, GeneratorType::JournalEntry);
529 let uuid = factory.next();
530
531 assert_eq!(uuid.get_version_num(), 4);
533
534 assert_eq!(uuid.get_variant(), uuid::Variant::RFC4122);
536 }
537}