Skip to content

Commit

Permalink
Implement Token Generation Algorithm using snowflakes algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
kentprince13 committed Sep 10, 2024
1 parent 81b55f7 commit 0317459
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/Blogger.Infrastructure/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// built-int
global using Microsoft.EntityFrameworkCore;
global using System.Collections.Immutable;
global using System.Text;

global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;

Expand Down
60 changes: 58 additions & 2 deletions src/Blogger.Infrastructure/Services/LinkGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,65 @@
namespace Blogger.Infrastructure.Services;
public class LinkGenerator : ILinkGenerator
{

private const string Characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private static readonly object LockObject = new object();
private static long _lastTimestamp = -1L;
private static long _sequence = 0L;
private const long MaxSequence = 4095; // 12-bit sequence

// implementing snowflakes algorithm to generate short and unique link
public string Generate()
{
// TODO: implement a generator algorithm
return Guid.NewGuid().ToString();
lock (LockObject)
{
long timestamp = GetTimestamp();

if (timestamp == _lastTimestamp)
{
_sequence = (_sequence + 1) & MaxSequence;
if (_sequence == 0)
{
// Wait for the next millisecond if the sequence is full
timestamp = WaitForNextMillis(_lastTimestamp);
}
}
else
{
_sequence = 0;
}

_lastTimestamp = timestamp;

string uniqueId = Base62Encode(timestamp) + Base62Encode(_sequence);
return uniqueId;
}
}

private static long GetTimestamp()
{
return DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
}

private static long WaitForNextMillis(long lastTimestamp)
{
long timestamp;
do
{
timestamp = GetTimestamp();
} while (timestamp <= lastTimestamp);
return timestamp;
}

private static string Base62Encode(long value)
{
var sb = new StringBuilder();
int baseSize = Characters.Length;
do
{
sb.Insert(0, Characters[(int)(value % baseSize)]);
value /= baseSize;
} while (value > 0);
return sb.ToString();
}
}

0 comments on commit 0317459

Please sign in to comment.