Resolve Concelier/Excititor merge conflicts

This commit is contained in:
master
2025-10-20 14:19:25 +03:00
2687 changed files with 212646 additions and 85913 deletions

View File

@@ -0,0 +1,39 @@
namespace StellaOps.Scheduler.Models.Tests;
public sealed class AuditRecordTests
{
[Fact]
public void AuditRecordNormalizesMetadataAndIdentifiers()
{
var actor = new AuditActor(actorId: "user_admin", displayName: "Cluster Admin", kind: "user");
var metadata = new[]
{
new KeyValuePair<string, string>("details", "schedule paused"),
new KeyValuePair<string, string>("Details", "should be overridden"), // duplicate with different casing
new KeyValuePair<string, string>("reason", "maintenance"),
};
var record = new AuditRecord(
id: "audit_001",
tenantId: "tenant-alpha",
category: "scheduler",
action: "pause",
occurredAt: DateTimeOffset.Parse("2025-10-18T05:00:00Z"),
actor: actor,
scheduleId: "sch_001",
runId: null,
correlationId: "corr-123",
metadata: metadata,
message: "Paused via API");
Assert.Equal("tenant-alpha", record.TenantId);
Assert.Equal("scheduler", record.Category);
Assert.Equal(2, record.Metadata.Count);
Assert.Equal("schedule paused", record.Metadata["details"]);
Assert.Equal("maintenance", record.Metadata["reason"]);
var json = CanonicalJsonSerializer.Serialize(record);
Assert.Contains("\"category\":\"scheduler\"", json, StringComparison.Ordinal);
Assert.Contains("\"metadata\":{\"details\":\"schedule paused\",\"reason\":\"maintenance\"}", json, StringComparison.Ordinal);
}
}

View File

@@ -0,0 +1,55 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ImpactSetTests
{
[Fact]
public void ImpactSetSortsImagesByDigest()
{
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
var images = new[]
{
new ImpactImage(
imageDigest: "sha256:bbbb",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod", "latest" },
usedByEntrypoint: true,
labels: new Dictionary<string, string>
{
["env"] = "prod",
}),
new ImpactImage(
imageDigest: "sha256:aaaa",
registry: "registry.internal",
repository: "app/api",
namespaces: new[] { "team-a" },
tags: new[] { "prod" },
usedByEntrypoint: false),
};
var impactSet = new ImpactSet(
selector,
images,
usageOnly: true,
generatedAt: DateTimeOffset.Parse("2025-10-18T05:04:03Z"),
total: 2,
snapshotId: "snap-001");
Assert.Equal(SchedulerSchemaVersions.ImpactSet, impactSet.SchemaVersion);
Assert.Equal(new[] { "sha256:aaaa", "sha256:bbbb" }, impactSet.Images.Select(i => i.ImageDigest));
Assert.True(impactSet.UsageOnly);
Assert.Equal(2, impactSet.Total);
var json = CanonicalJsonSerializer.Serialize(impactSet);
Assert.Contains("\"snapshotId\":\"snap-001\"", json, StringComparison.Ordinal);
}
[Fact]
public void ImpactImageRejectsInvalidDigest()
{
Assert.Throws<ArgumentException>(() => new ImpactImage("sha1:not-supported", "registry", "repo"));
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using StellaOps.Notify.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RescanDeltaEventSampleTests
{
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web);
[Fact]
public void RescanDeltaEventSampleAlignsWithContracts()
{
const string fileName = "scheduler.rescan.delta@1.sample.json";
var json = LoadSample(fileName);
var notifyEvent = JsonSerializer.Deserialize<NotifyEvent>(json, SerializerOptions);
Assert.NotNull(notifyEvent);
Assert.Equal(NotifyEventKinds.SchedulerRescanDelta, notifyEvent!.Kind);
Assert.NotEqual(Guid.Empty, notifyEvent.EventId);
Assert.NotNull(notifyEvent.Payload);
Assert.Null(notifyEvent.Scope);
var payload = Assert.IsType<JsonObject>(notifyEvent.Payload);
var scheduleId = Assert.IsAssignableFrom<JsonValue>(payload["scheduleId"]).GetValue<string>();
Assert.Equal("rescan-weekly-critical", scheduleId);
var digests = Assert.IsType<JsonArray>(payload["impactedDigests"]);
Assert.Equal(2, digests.Count);
foreach (var digestNode in digests)
{
var digest = Assert.IsAssignableFrom<JsonValue>(digestNode).GetValue<string>();
Assert.StartsWith("sha256:", digest, StringComparison.Ordinal);
}
var summary = Assert.IsType<JsonObject>(payload["summary"]);
Assert.Equal(0, summary["newCritical"]!.GetValue<int>());
Assert.Equal(1, summary["newHigh"]!.GetValue<int>());
Assert.Equal(4, summary["total"]!.GetValue<int>());
var canonicalJson = NotifyCanonicalJsonSerializer.Serialize(notifyEvent);
var canonicalNode = JsonNode.Parse(canonicalJson) ?? throw new InvalidOperationException("Canonical JSON null.");
var sampleNode = JsonNode.Parse(json) ?? throw new InvalidOperationException("Sample JSON null.");
Assert.True(JsonNode.DeepEquals(sampleNode, canonicalNode), "Rescan delta event sample must remain canonical.");
}
private static string LoadSample(string fileName)
{
var path = Path.Combine(AppContext.BaseDirectory, fileName);
if (!File.Exists(path))
{
throw new FileNotFoundException($"Unable to locate sample '{fileName}'.", path);
}
return File.ReadAllText(path);
}
}

View File

@@ -0,0 +1,108 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RunStateMachineTests
{
[Fact]
public void EnsureTransition_FromQueuedToRunningSetsStartedAt()
{
var run = new Run(
id: "run-queued",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"));
var transitionTime = DateTimeOffset.Parse("2025-10-18T03:05:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Running,
transitionTime,
mutateStats: builder => builder.SetQueued(1));
Assert.Equal(RunState.Running, updated.State);
Assert.Equal(transitionTime.ToUniversalTime(), updated.StartedAt);
Assert.Equal(1, updated.Stats.Queued);
Assert.Null(updated.Error);
}
[Fact]
public void EnsureTransition_ToCompletedPopulatesFinishedAt()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var completedAt = DateTimeOffset.Parse("2025-10-18T03:10:00Z");
var updated = RunStateMachine.EnsureTransition(
run,
RunState.Completed,
completedAt,
mutateStats: builder =>
{
builder.SetQueued(1);
builder.SetCompleted(1);
});
Assert.Equal(RunState.Completed, updated.State);
Assert.Equal(completedAt.ToUniversalTime(), updated.FinishedAt);
Assert.Equal(1, updated.Stats.Completed);
}
[Fact]
public void EnsureTransition_ErrorRequiresMessage()
{
var run = new Run(
id: "run-running",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Running,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
var timestamp = DateTimeOffset.Parse("2025-10-18T03:06:00Z");
var ex = Assert.Throws<InvalidOperationException>(
() => RunStateMachine.EnsureTransition(run, RunState.Error, timestamp));
Assert.Contains("requires a non-empty error message", ex.Message, StringComparison.Ordinal);
}
[Fact]
public void Validate_ThrowsWhenTerminalWithoutFinishedAt()
{
var run = new Run(
id: "run-bad",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Completed,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T03:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T03:05:00Z"));
Assert.Throws<InvalidOperationException>(() => RunStateMachine.Validate(run));
}
[Fact]
public void RunReasonExtension_NormalizesImpactWindow()
{
var reason = new RunReason(manualReason: "delta");
var from = DateTimeOffset.Parse("2025-10-18T01:00:00+02:00");
var to = DateTimeOffset.Parse("2025-10-18T03:30:00+02:00");
var updated = reason.WithImpactWindow(from, to);
Assert.Equal(from.ToUniversalTime().ToString("O"), updated.ImpactWindowFrom);
Assert.Equal(to.ToUniversalTime().ToString("O"), updated.ImpactWindowTo);
}
}

View File

@@ -0,0 +1,78 @@
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class RunValidationTests
{
[Fact]
public void RunStatsRejectsNegativeValues()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(candidates: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(deduped: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(queued: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(completed: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(deltas: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newCriticals: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newHigh: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newMedium: -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new RunStats(newLow: -1));
}
[Fact]
public void DeltaSummarySortsTopFindingsBySeverityThenId()
{
var summary = new DeltaSummary(
imageDigest: "sha256:0011",
newFindings: 3,
newCriticals: 1,
newHigh: 1,
newMedium: 1,
newLow: 0,
kevHits: new[] { "CVE-2025-0002", "CVE-2025-0001" },
topFindings: new[]
{
new DeltaFinding("pkg:maven/b", "CVE-2025-0002", SeverityRank.High),
new DeltaFinding("pkg:maven/a", "CVE-2024-0001", SeverityRank.Critical),
new DeltaFinding("pkg:maven/c", "CVE-2025-0008", SeverityRank.Medium),
},
reportUrl: "https://ui.example/reports/sha256:0011",
attestation: new DeltaAttestation(uuid: "rekor-1", verified: true),
detectedAt: DateTimeOffset.Parse("2025-10-18T00:01:02Z"));
Assert.Equal(new[] { "pkg:maven/a", "pkg:maven/b", "pkg:maven/c" }, summary.TopFindings.Select(f => f.Purl));
Assert.Equal(new[] { "CVE-2025-0001", "CVE-2025-0002" }, summary.KevHits);
}
[Fact]
public void RunSerializationIncludesDeterministicOrdering()
{
var stats = new RunStats(candidates: 10, deduped: 8, queued: 8, completed: 5, deltas: 3, newCriticals: 2);
var run = new Run(
id: "run_001",
tenantId: "tenant-alpha",
trigger: RunTrigger.Feedser,
state: RunState.Running,
stats: stats,
reason: new RunReason(feedserExportId: "exp-123"),
scheduleId: "sch_001",
createdAt: DateTimeOffset.Parse("2025-10-18T01:00:00Z"),
startedAt: DateTimeOffset.Parse("2025-10-18T01:00:05Z"),
finishedAt: null,
error: null,
deltas: new[]
{
new DeltaSummary(
imageDigest: "sha256:aaa",
newFindings: 1,
newCriticals: 1,
newHigh: 0,
newMedium: 0,
newLow: 0)
});
var json = CanonicalJsonSerializer.Serialize(run);
Assert.Equal(SchedulerSchemaVersions.Run, run.SchemaVersion);
Assert.Contains("\"trigger\":\"feedser\"", json, StringComparison.Ordinal);
Assert.Contains("\"stats\":{\"candidates\":10,\"deduped\":8,\"queued\":8,\"completed\":5,\"deltas\":3,\"newCriticals\":2,\"newHigh\":0,\"newMedium\":0,\"newLow\":0}", json, StringComparison.Ordinal);
}
}

View File

@@ -0,0 +1,105 @@
using System.Text.Json;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class SamplePayloadTests
{
private static readonly string SamplesRoot = LocateSamplesRoot();
[Fact]
public void ScheduleSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("schedule.json");
var schedule = CanonicalJsonSerializer.Deserialize<Schedule>(json);
Assert.Equal("sch_20251018a", schedule.Id);
Assert.Equal("tenant-alpha", schedule.TenantId);
var canonical = CanonicalJsonSerializer.Serialize(schedule);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void RunSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("run.json");
var run = CanonicalJsonSerializer.Deserialize<Run>(json);
Assert.Equal(RunState.Running, run.State);
Assert.Equal(42, run.Stats.Deltas);
var canonical = CanonicalJsonSerializer.Serialize(run);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void ImpactSetSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("impact-set.json");
var impact = CanonicalJsonSerializer.Deserialize<ImpactSet>(json);
Assert.True(impact.UsageOnly);
Assert.Single(impact.Images);
var canonical = CanonicalJsonSerializer.Serialize(impact);
AssertJsonEquivalent(json, canonical);
}
[Fact]
public void AuditSample_RoundtripsThroughCanonicalSerializer()
{
var json = ReadSample("audit.json");
var audit = CanonicalJsonSerializer.Deserialize<AuditRecord>(json);
Assert.Equal("scheduler", audit.Category);
Assert.Equal("pause", audit.Action);
var canonical = CanonicalJsonSerializer.Serialize(audit);
AssertJsonEquivalent(json, canonical);
}
private static string ReadSample(string fileName)
{
var path = Path.Combine(SamplesRoot, fileName);
return File.ReadAllText(path);
}
private static string LocateSamplesRoot()
{
var current = AppContext.BaseDirectory;
while (!string.IsNullOrEmpty(current))
{
var candidate = Path.Combine(current, "samples", "api", "scheduler");
if (Directory.Exists(candidate))
{
return candidate;
}
var parent = Path.GetDirectoryName(current.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
if (string.Equals(parent, current, StringComparison.Ordinal))
{
break;
}
current = parent;
}
throw new DirectoryNotFoundException("Unable to locate samples/api/scheduler in repository tree.");
}
private static void AssertJsonEquivalent(string expected, string actual)
{
var normalizedExpected = NormalizeJson(expected);
var normalizedActual = NormalizeJson(actual);
Assert.Equal(normalizedExpected, normalizedActual);
}
private static string NormalizeJson(string json)
{
using var document = JsonDocument.Parse(json);
return JsonSerializer.Serialize(document.RootElement, new JsonSerializerOptions
{
WriteIndented = false
});
}
}

View File

@@ -0,0 +1,113 @@
using System.Text.Json;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class ScheduleSerializationTests
{
[Fact]
public void ScheduleSerialization_IsDeterministicRegardlessOfInputOrdering()
{
var selectionA = new Selector(
SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-b", "team-a" },
repositories: new[] { "app/service-api", "app/service-web" },
digests: new[] { "sha256:bb", "sha256:aa" },
includeTags: new[] { "prod", "canary" },
labels: new[]
{
new LabelSelector("env", new[] { "prod", "staging" }),
new LabelSelector("app", new[] { "web", "api" }),
},
resolvesTags: true);
var selectionB = new Selector(
scope: SelectorScope.ByNamespace,
tenantId: "tenant-alpha",
namespaces: new[] { "team-a", "team-b" },
repositories: new[] { "app/service-web", "app/service-api" },
digests: new[] { "sha256:aa", "sha256:bb" },
includeTags: new[] { "canary", "prod" },
labels: new[]
{
new LabelSelector("app", new[] { "api", "web" }),
new LabelSelector("env", new[] { "staging", "prod" }),
},
resolvesTags: true);
var scheduleA = new Schedule(
id: "sch_001",
tenantId: "tenant-alpha",
name: "Nightly Prod",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: selectionA,
onlyIf: new ScheduleOnlyIf(lastReportOlderThanDays: 7, policyRevision: "policy@42"),
notify: new ScheduleNotify(onNewFindings: true, SeverityRank.High, includeKev: true),
limits: new ScheduleLimits(maxJobs: 1000, ratePerSecond: 25, parallelism: 4),
createdAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
createdBy: "svc_scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T23:00:00Z"),
updatedBy: "svc_scheduler");
var scheduleB = new Schedule(
id: scheduleA.Id,
tenantId: scheduleA.TenantId,
name: scheduleA.Name,
enabled: scheduleA.Enabled,
cronExpression: scheduleA.CronExpression,
timezone: scheduleA.Timezone,
mode: scheduleA.Mode,
selection: selectionB,
onlyIf: scheduleA.OnlyIf,
notify: scheduleA.Notify,
limits: scheduleA.Limits,
createdAt: scheduleA.CreatedAt,
createdBy: scheduleA.CreatedBy,
updatedAt: scheduleA.UpdatedAt,
updatedBy: scheduleA.UpdatedBy,
subscribers: scheduleA.Subscribers);
var jsonA = CanonicalJsonSerializer.Serialize(scheduleA);
var jsonB = CanonicalJsonSerializer.Serialize(scheduleB);
Assert.Equal(jsonA, jsonB);
using var doc = JsonDocument.Parse(jsonA);
var root = doc.RootElement;
Assert.Equal(SchedulerSchemaVersions.Schedule, root.GetProperty("schemaVersion").GetString());
Assert.Equal("analysis-only", root.GetProperty("mode").GetString());
Assert.Equal("tenant-alpha", root.GetProperty("tenantId").GetString());
var namespaces = root.GetProperty("selection").GetProperty("namespaces").EnumerateArray().Select(e => e.GetString()).ToArray();
Assert.Equal(new[] { "team-a", "team-b" }, namespaces);
}
[Theory]
[InlineData("")]
[InlineData("not-a-timezone")]
public void Schedule_ThrowsWhenTimezoneInvalid(string timezone)
{
var selection = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
Assert.ThrowsAny<Exception>(() => new Schedule(
id: "sch_002",
tenantId: "tenant-alpha",
name: "Invalid timezone",
enabled: true,
cronExpression: "0 3 * * *",
timezone: timezone,
mode: ScheduleMode.AnalysisOnly,
selection: selection,
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.UtcNow,
createdBy: "svc",
updatedAt: DateTimeOffset.UtcNow,
updatedBy: "svc"));
}
}

View File

@@ -0,0 +1,72 @@
using System.Text.Json.Nodes;
using StellaOps.Scheduler.Models;
namespace StellaOps.Scheduler.Models.Tests;
public sealed class SchedulerSchemaMigrationTests
{
[Fact]
public void UpgradeSchedule_DefaultsSchemaVersionWhenMissing()
{
var schedule = new Schedule(
id: "sch-01",
tenantId: "tenant-alpha",
name: "Nightly",
enabled: true,
cronExpression: "0 2 * * *",
timezone: "UTC",
mode: ScheduleMode.AnalysisOnly,
selection: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
onlyIf: null,
notify: null,
limits: null,
createdAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
createdBy: "svc-scheduler",
updatedAt: DateTimeOffset.Parse("2025-10-18T00:00:00Z"),
updatedBy: "svc-scheduler");
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(schedule))!.AsObject();
json.Remove("schemaVersion");
var result = SchedulerSchemaMigration.UpgradeSchedule(json);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.Value.SchemaVersion);
Assert.Equal(SchedulerSchemaVersions.Schedule, result.ToVersion);
Assert.Empty(result.Warnings);
}
[Fact]
public void UpgradeRun_StrictModeRemovesUnknownProperties()
{
var run = new Run(
id: "run-01",
tenantId: "tenant-alpha",
trigger: RunTrigger.Manual,
state: RunState.Queued,
stats: RunStats.Empty,
createdAt: DateTimeOffset.Parse("2025-10-18T01:10:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(run))!.AsObject();
json["extraField"] = "to-be-removed";
var result = SchedulerSchemaMigration.UpgradeRun(json, strict: true);
Assert.Contains(result.Warnings, warning => warning.Contains("extraField", StringComparison.Ordinal));
}
[Fact]
public void UpgradeImpactSet_ThrowsForUnsupportedVersion()
{
var impactSet = new ImpactSet(
selector: new Selector(SelectorScope.AllImages, "tenant-alpha"),
images: Array.Empty<ImpactImage>(),
usageOnly: false,
generatedAt: DateTimeOffset.Parse("2025-10-18T02:00:00Z"));
var json = JsonNode.Parse(CanonicalJsonSerializer.Serialize(impactSet))!.AsObject();
json["schemaVersion"] = "scheduler.impact-set@99";
var ex = Assert.Throws<NotSupportedException>(() => SchedulerSchemaMigration.UpgradeImpactSet(json));
Assert.Contains("Unsupported scheduler schema version", ex.Message, StringComparison.Ordinal);
}
}

View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\StellaOps.Scheduler.Models\StellaOps.Scheduler.Models.csproj" />
<ProjectReference Include="..\StellaOps.Notify.Models\StellaOps.Notify.Models.csproj" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\docs\events\samples\scheduler.rescan.delta@1.sample.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>