Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
55 lines
1.6 KiB
C#
55 lines
1.6 KiB
C#
namespace Febe.Core.Abstractions;
|
|
|
|
/// <summary>
|
|
/// The only source of time for the engine (spec §5). Engine code never uses
|
|
/// DateTime.Now, DateTimeOffset.Now or Task.Delay directly, so it can run under a virtual clock.
|
|
/// </summary>
|
|
public interface IClock
|
|
{
|
|
DateTimeOffset Now { get; }
|
|
|
|
/// <summary>The user's time zone (Alberto's): daily budgets and file names use it.</summary>
|
|
TimeZoneInfo LocalZone { get; }
|
|
|
|
Task Delay(TimeSpan time, CancellationToken ct);
|
|
}
|
|
|
|
/// <summary>The only source of randomness for the engine (spec §5).</summary>
|
|
public interface IRandomSource
|
|
{
|
|
/// <summary>Uniform value in [0, 1).</summary>
|
|
double NextDouble();
|
|
}
|
|
|
|
/// <summary>Real wall clock, used outside tests and simulation.</summary>
|
|
public sealed class SystemClock(TimeZoneInfo? zone = null) : IClock
|
|
{
|
|
public DateTimeOffset Now => DateTimeOffset.UtcNow;
|
|
|
|
public TimeZoneInfo LocalZone { get; } = zone ?? TimeZoneInfo.Local;
|
|
|
|
public Task Delay(TimeSpan time, CancellationToken ct) =>
|
|
time <= TimeSpan.Zero ? Task.CompletedTask : Task.Delay(time, ct);
|
|
}
|
|
|
|
/// <summary>Process-wide random source for production use.</summary>
|
|
public sealed class SystemRandom : IRandomSource
|
|
{
|
|
public double NextDouble() => Random.Shared.NextDouble();
|
|
}
|
|
|
|
/// <summary>Deterministic random source for tests and simulation (fixed seed).</summary>
|
|
public sealed class SeededRandom(int seed) : IRandomSource
|
|
{
|
|
private readonly Random _random = new(seed);
|
|
private readonly Lock _gate = new();
|
|
|
|
public double NextDouble()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _random.NextDouble();
|
|
}
|
|
}
|
|
}
|