feat: migrate snowflake ids and refresh migrations
This commit is contained in:
@@ -99,6 +99,65 @@ public sealed record ApiResponse<T>
|
||||
return TraceContext.TraceId;
|
||||
}
|
||||
|
||||
return Activity.Current?.Id ?? Guid.NewGuid().ToString("N");
|
||||
if (!string.IsNullOrWhiteSpace(TraceContext.TraceId))
|
||||
{
|
||||
return TraceContext.TraceId;
|
||||
}
|
||||
|
||||
if (Activity.Current?.Id is { } id && !string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
return IdFallbackGenerator.Instance.NextId().ToString();
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class IdFallbackGenerator
|
||||
{
|
||||
private static readonly Lazy<IdFallbackGenerator> Lazy = new(() => new IdFallbackGenerator());
|
||||
public static IdFallbackGenerator Instance => Lazy.Value;
|
||||
|
||||
private readonly object _sync = new();
|
||||
private long _lastTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
private long _sequence;
|
||||
|
||||
private IdFallbackGenerator()
|
||||
{
|
||||
}
|
||||
|
||||
public long NextId()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
if (timestamp == _lastTimestamp)
|
||||
{
|
||||
_sequence = (_sequence + 1) & 4095;
|
||||
if (_sequence == 0)
|
||||
{
|
||||
timestamp = WaitNextMillis(_lastTimestamp);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_sequence = 0;
|
||||
}
|
||||
|
||||
_lastTimestamp = timestamp;
|
||||
return ((timestamp - 1577836800000L) << 22) | _sequence;
|
||||
}
|
||||
}
|
||||
|
||||
private static long WaitNextMillis(long lastTimestamp)
|
||||
{
|
||||
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
while (timestamp <= lastTimestamp)
|
||||
{
|
||||
Thread.SpinWait(100);
|
||||
timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
|
||||
}
|
||||
|
||||
return timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user