Skip to content

Commit 5af78df

Browse files
committed
Generate ID from Key
1 parent cc122a5 commit 5af78df

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/API.Web/DependencyInjection/ServiceCollectionExtensions.cs

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using IdGen;
1+
using System.IO.Hashing;
2+
using System.Text;
3+
using IdGen;
24
using IdGen.DependencyInjection;
35

46
namespace 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

Comments
 (0)