1- using IdGen ;
1+ using System . IO . Hashing ;
2+ using System . Text ;
3+ using IdGen ;
24using IdGen . DependencyInjection ;
35
46namespace Fossa . API . Web . DependencyInjection ;
@@ -13,12 +15,12 @@ public static IServiceCollection AddIdGen(
1315 var epoch = new DateTimeOffset ( initialReleaseDate . ToDateTime ( TimeOnly . MinValue , DateTimeKind . Utc ) ) ;
1416 var idGeneratorOptions = new IdGeneratorOptions ( timeSource : new DefaultTimeSource ( epoch ) ) ;
1517
16- var generatorId = GetGeneratorId ( configuration ) ;
18+ var generatorId = GetGeneratorId ( configuration , idGeneratorOptions . IdStructure . MaxGenerators ) ;
1719
1820 return services . AddIdGen ( generatorId , ( ) => idGeneratorOptions ) ;
1921 }
2022
21- private static int GetGeneratorId ( IConfiguration configuration )
23+ private static int GetGeneratorId ( IConfiguration configuration , int maxGenerators )
2224 {
2325 var generatorIdConfiguration = configuration . GetValue < int ? > ( "GeneratorId" ) ;
2426
@@ -27,6 +29,29 @@ private static int GetGeneratorId(IConfiguration configuration)
2729 return generatorIdConfiguration . Value ;
2830 }
2931
30- throw new InvalidOperationException ( "GeneratorId Configuration is missing" ) ;
32+ var generatorKeyConfiguration = configuration . GetValue < string ? > ( "GeneratorKey" ) ;
33+ if ( ! string . IsNullOrWhiteSpace ( generatorKeyConfiguration ) )
34+ {
35+ if ( uint . TryParse ( generatorKeyConfiguration , out uint uintKey ) )
36+ {
37+ return ( int ) ( uintKey % maxGenerators ) ;
38+ }
39+ else if ( ulong . TryParse ( generatorKeyConfiguration , out ulong ulongKey ) )
40+ {
41+ return ( int ) ( ulongKey % ( ulong ) maxGenerators ) ;
42+ }
43+ else if ( Guid . TryParse ( generatorKeyConfiguration , out Guid guidKey ) )
44+ {
45+ byte [ ] bytes = guidKey . ToByteArray ( ) ;
46+ return ( int ) ( XxHash32 . HashToUInt32 ( bytes ) % maxGenerators ) ;
47+ }
48+ else
49+ {
50+ byte [ ] bytes = Encoding . UTF8 . GetBytes ( generatorKeyConfiguration ) ;
51+ return ( int ) ( XxHash32 . HashToUInt32 ( bytes ) % maxGenerators ) ;
52+ }
53+ }
54+
55+ throw new InvalidOperationException ( "GeneratorId and or GeneratorKey Configuration is missing" ) ;
3156 }
3257}
0 commit comments