58 lines
2.0 KiB
C#
58 lines
2.0 KiB
C#
// Copyright (c) StellaOps. Licensed under the BUSL-1.1.
|
|
|
|
|
|
using StellaOps.HybridLogicalClock;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace StellaOps.Eventing.Internal;
|
|
|
|
/// <summary>
|
|
/// Generates deterministic event IDs from event content.
|
|
/// </summary>
|
|
internal static class EventIdGenerator
|
|
{
|
|
/// <summary>
|
|
/// Generates a deterministic event ID using SHA-256 hash of inputs.
|
|
/// </summary>
|
|
/// <param name="correlationId">The correlation ID.</param>
|
|
/// <param name="tHlc">The HLC timestamp.</param>
|
|
/// <param name="service">The service name.</param>
|
|
/// <param name="kind">The event kind.</param>
|
|
/// <returns>First 32 hex characters of SHA-256 hash (128 bits).</returns>
|
|
public static string Generate(
|
|
string correlationId,
|
|
HlcTimestamp tHlc,
|
|
string service,
|
|
string kind)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(correlationId);
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(service);
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(kind);
|
|
|
|
using var hasher = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
|
|
|
// Append all inputs in deterministic order
|
|
hasher.AppendData(Encoding.UTF8.GetBytes(correlationId));
|
|
hasher.AppendData(Encoding.UTF8.GetBytes(tHlc.ToSortableString()));
|
|
hasher.AppendData(Encoding.UTF8.GetBytes(service));
|
|
hasher.AppendData(Encoding.UTF8.GetBytes(kind));
|
|
|
|
var hash = hasher.GetHashAndReset();
|
|
|
|
// Return first 16 bytes (128 bits) as lowercase hex (32 chars)
|
|
return Convert.ToHexString(hash.AsSpan(0, 16)).ToLowerInvariant();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Computes SHA-256 digest of the payload.
|
|
/// </summary>
|
|
/// <param name="payload">The canonicalized JSON payload.</param>
|
|
/// <returns>SHA-256 digest bytes.</returns>
|
|
public static byte[] ComputePayloadDigest(string payload)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(payload);
|
|
return SHA256.HashData(Encoding.UTF8.GetBytes(payload));
|
|
}
|
|
}
|