w4c-workflows-api/Services/DeterministicGuid.cs

23 lines
776 B
C#
Raw Permalink Normal View History

using System.Security.Cryptography;
using System.Text;
namespace w4c_workflows.Services;
/// <summary>
/// Deterministic, name-based GUIDs so recompiling the same YAML yields the same
/// entity ids — this makes the git sync (re-compile to DB) idempotent.
/// UUIDv5-style: SHA-256 of the seed, truncated to 16 bytes with version bits.
/// </summary>
public static class DeterministicGuid
{
public static Guid For(string seed)
{
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(seed));
Span<byte> bytes = stackalloc byte[16];
hash.AsSpan(0, 16).CopyTo(bytes);
bytes[6] = (byte)((bytes[6] & 0x0F) | 0x50); // version 5
bytes[8] = (byte)((bytes[8] & 0x3F) | 0x80); // RFC 4122 variant
return new Guid(bytes);
}
}