Refactor code structure for improved readability and maintainability; optimize performance in key functions.
This commit is contained in:
184
src/__Libraries/StellaOps.Replay/Engine/ReplayEngine.cs
Normal file
184
src/__Libraries/StellaOps.Replay/Engine/ReplayEngine.cs
Normal file
@@ -0,0 +1,184 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StellaOps.Canonicalization.Json;
|
||||
using StellaOps.Canonicalization.Verification;
|
||||
using StellaOps.Replay.Models;
|
||||
using StellaOps.Testing.Manifests.Models;
|
||||
|
||||
namespace StellaOps.Replay.Engine;
|
||||
|
||||
/// <summary>
|
||||
/// Executes scans deterministically from run manifests.
|
||||
/// Enables time-travel replay for verification and auditing.
|
||||
/// </summary>
|
||||
public sealed class ReplayEngine : IReplayEngine
|
||||
{
|
||||
private readonly IFeedLoader _feedLoader;
|
||||
private readonly IPolicyLoader _policyLoader;
|
||||
private readonly IScannerFactory _scannerFactory;
|
||||
private readonly ILogger<ReplayEngine> _logger;
|
||||
|
||||
public ReplayEngine(
|
||||
IFeedLoader feedLoader,
|
||||
IPolicyLoader policyLoader,
|
||||
IScannerFactory scannerFactory,
|
||||
ILogger<ReplayEngine> logger)
|
||||
{
|
||||
_feedLoader = feedLoader;
|
||||
_policyLoader = policyLoader;
|
||||
_scannerFactory = scannerFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<ReplayResult> ReplayAsync(
|
||||
RunManifest manifest,
|
||||
ReplayOptions options,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
_logger.LogInformation("Starting replay for run {RunId}", manifest.RunId);
|
||||
|
||||
var validationResult = ValidateManifest(manifest);
|
||||
if (!validationResult.IsValid)
|
||||
{
|
||||
return ReplayResult.Failed(manifest.RunId, "Manifest validation failed", validationResult.Errors);
|
||||
}
|
||||
|
||||
var feedResult = await LoadFeedSnapshotAsync(manifest.FeedSnapshot, ct).ConfigureAwait(false);
|
||||
if (!feedResult.Success)
|
||||
return ReplayResult.Failed(manifest.RunId, "Failed to load feed snapshot", [feedResult.Error ?? "Unknown error"]);
|
||||
|
||||
var policyResult = await LoadPolicySnapshotAsync(manifest.PolicySnapshot, ct).ConfigureAwait(false);
|
||||
if (!policyResult.Success)
|
||||
return ReplayResult.Failed(manifest.RunId, "Failed to load policy snapshot", [policyResult.Error ?? "Unknown error"]);
|
||||
|
||||
var scannerOptions = new ScannerOptions
|
||||
{
|
||||
FeedSnapshot = feedResult.Value!,
|
||||
PolicySnapshot = policyResult.Value!,
|
||||
CryptoProfile = manifest.CryptoProfile,
|
||||
PrngSeed = manifest.PrngSeed,
|
||||
FrozenTime = options.UseFrozenTime ? manifest.InitiatedAt : null,
|
||||
CanonicalizationVersion = manifest.CanonicalizationVersion
|
||||
};
|
||||
|
||||
var scanner = _scannerFactory.Create(scannerOptions);
|
||||
var scanResult = await scanner.ScanAsync(manifest.ArtifactDigests, ct).ConfigureAwait(false);
|
||||
|
||||
var (verdictJson, verdictDigest) = CanonicalJsonSerializer.SerializeWithDigest(scanResult.Verdict);
|
||||
|
||||
return new ReplayResult
|
||||
{
|
||||
RunId = manifest.RunId,
|
||||
Success = true,
|
||||
VerdictJson = verdictJson,
|
||||
VerdictDigest = verdictDigest,
|
||||
EvidenceIndex = scanResult.EvidenceIndex,
|
||||
ExecutedAt = DateTimeOffset.UtcNow,
|
||||
DurationMs = scanResult.DurationMs
|
||||
};
|
||||
}
|
||||
|
||||
public DeterminismCheckResult CheckDeterminism(ReplayResult a, ReplayResult b)
|
||||
{
|
||||
if (a.VerdictDigest == b.VerdictDigest)
|
||||
{
|
||||
return new DeterminismCheckResult
|
||||
{
|
||||
IsDeterministic = true,
|
||||
DigestA = a.VerdictDigest,
|
||||
DigestB = b.VerdictDigest,
|
||||
Differences = []
|
||||
};
|
||||
}
|
||||
|
||||
var differences = FindJsonDifferences(a.VerdictJson, b.VerdictJson);
|
||||
return new DeterminismCheckResult
|
||||
{
|
||||
IsDeterministic = false,
|
||||
DigestA = a.VerdictDigest,
|
||||
DigestB = b.VerdictDigest,
|
||||
Differences = differences
|
||||
};
|
||||
}
|
||||
|
||||
private static ValidationResult ValidateManifest(RunManifest manifest)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifest.RunId))
|
||||
errors.Add("RunId is required");
|
||||
|
||||
if (manifest.ArtifactDigests.Length == 0)
|
||||
errors.Add("At least one artifact digest required");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(manifest.FeedSnapshot.Digest))
|
||||
errors.Add("Feed snapshot digest required");
|
||||
|
||||
return new ValidationResult(errors.Count == 0, errors);
|
||||
}
|
||||
|
||||
private async Task<LoadResult<FeedSnapshot>> LoadFeedSnapshotAsync(
|
||||
FeedSnapshot snapshot, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var feed = await _feedLoader.LoadByDigestAsync(snapshot.Digest, ct).ConfigureAwait(false);
|
||||
if (!string.Equals(feed.Digest, snapshot.Digest, StringComparison.OrdinalIgnoreCase))
|
||||
return LoadResult<FeedSnapshot>.Fail($"Feed digest mismatch: expected {snapshot.Digest}");
|
||||
return LoadResult<FeedSnapshot>.Ok(feed);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return LoadResult<FeedSnapshot>.Fail($"Failed to load feed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<LoadResult<PolicySnapshot>> LoadPolicySnapshotAsync(
|
||||
PolicySnapshot snapshot, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var policy = await _policyLoader.LoadByDigestAsync(snapshot.LatticeRulesDigest, ct).ConfigureAwait(false);
|
||||
return LoadResult<PolicySnapshot>.Ok(policy);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return LoadResult<PolicySnapshot>.Fail($"Failed to load policy: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private static IReadOnlyList<JsonDifference> FindJsonDifferences(string? a, string? b)
|
||||
{
|
||||
if (a is null || b is null)
|
||||
return [new JsonDifference("$", "One or both values are null")];
|
||||
|
||||
var verifier = new DeterminismVerifier();
|
||||
var result = verifier.Compare(a, b);
|
||||
return result.Differences.Select(d => new JsonDifference(d, "Value mismatch")).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public interface IReplayEngine
|
||||
{
|
||||
Task<ReplayResult> ReplayAsync(RunManifest manifest, ReplayOptions options, CancellationToken ct = default);
|
||||
DeterminismCheckResult CheckDeterminism(ReplayResult a, ReplayResult b);
|
||||
}
|
||||
|
||||
public interface IScannerFactory
|
||||
{
|
||||
IScanner Create(ScannerOptions options);
|
||||
}
|
||||
|
||||
public interface IScanner
|
||||
{
|
||||
Task<ScanResult> ScanAsync(ImmutableArray<ArtifactDigest> artifacts, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IFeedLoader
|
||||
{
|
||||
Task<FeedSnapshot> LoadByDigestAsync(string digest, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public interface IPolicyLoader
|
||||
{
|
||||
Task<PolicySnapshot> LoadByDigestAsync(string digest, CancellationToken ct = default);
|
||||
}
|
||||
Reference in New Issue
Block a user