up
Some checks failed
Docs CI / lint-and-preview (push) Has been cancelled
AOC Guard CI / aoc-guard (push) Has been cancelled
AOC Guard CI / aoc-verify (push) Has been cancelled
Concelier Attestation Tests / attestation-tests (push) Has been cancelled
Export Center CI / export-ci (push) Has been cancelled
Notify Smoke Test / Notify Unit Tests (push) Has been cancelled
Notify Smoke Test / Notifier Service Tests (push) Has been cancelled
Notify Smoke Test / Notification Smoke Test (push) Has been cancelled
Policy Lint & Smoke / policy-lint (push) Has been cancelled
Scanner Analyzers / Discover Analyzers (push) Has been cancelled
Scanner Analyzers / Build Analyzers (push) Has been cancelled
Scanner Analyzers / Test Language Analyzers (push) Has been cancelled
Scanner Analyzers / Validate Test Fixtures (push) Has been cancelled
Scanner Analyzers / Verify Deterministic Output (push) Has been cancelled
Signals CI & Image / signals-ci (push) Has been cancelled
Signals Reachability Scoring & Events / reachability-smoke (push) Has been cancelled
Signals Reachability Scoring & Events / sign-and-upload (push) Has been cancelled
Some checks failed
Docs CI / lint-and-preview (push) Has been cancelled
AOC Guard CI / aoc-guard (push) Has been cancelled
AOC Guard CI / aoc-verify (push) Has been cancelled
Concelier Attestation Tests / attestation-tests (push) Has been cancelled
Export Center CI / export-ci (push) Has been cancelled
Notify Smoke Test / Notify Unit Tests (push) Has been cancelled
Notify Smoke Test / Notifier Service Tests (push) Has been cancelled
Notify Smoke Test / Notification Smoke Test (push) Has been cancelled
Policy Lint & Smoke / policy-lint (push) Has been cancelled
Scanner Analyzers / Discover Analyzers (push) Has been cancelled
Scanner Analyzers / Build Analyzers (push) Has been cancelled
Scanner Analyzers / Test Language Analyzers (push) Has been cancelled
Scanner Analyzers / Validate Test Fixtures (push) Has been cancelled
Scanner Analyzers / Verify Deterministic Output (push) Has been cancelled
Signals CI & Image / signals-ci (push) Has been cancelled
Signals Reachability Scoring & Events / reachability-smoke (push) Has been cancelled
Signals Reachability Scoring & Events / sign-and-upload (push) Has been cancelled
This commit is contained in:
@@ -1,142 +1,142 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StellaOps.Scheduler.ImpactIndex;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.ImpactIndex.Tests;
|
||||
|
||||
public sealed class FixtureImpactIndexTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task ResolveByPurls_UsesEmbeddedFixtures()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var result = await impactIndex.ResolveByPurlsAsync(
|
||||
new[] { "pkg:apk/alpine/openssl@3.2.2-r0?arch=x86_64" },
|
||||
usageOnly: false,
|
||||
selector);
|
||||
|
||||
result.UsageOnly.Should().BeFalse();
|
||||
result.Images.Should().ContainSingle();
|
||||
|
||||
var image = result.Images.Single();
|
||||
image.ImageDigest.Should().Be("sha256:8f47d7c6b538c0d9533b78913cba3d5e671e7c4b4e7c6a2bb9a1a1c4d4f8e123");
|
||||
image.Registry.Should().Be("docker.io");
|
||||
image.Repository.Should().Be("library/nginx");
|
||||
image.Tags.Should().ContainSingle(tag => tag == "1.25.4");
|
||||
image.UsedByEntrypoint.Should().BeTrue();
|
||||
|
||||
result.GeneratedAt.Should().Be(DateTimeOffset.Parse("2025-10-19T00:00:00Z"));
|
||||
result.SchemaVersion.Should().Be(SchedulerSchemaVersions.ImpactSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveByPurls_UsageOnlyFiltersInventoryOnlyComponents()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var inventoryOnlyPurl = "pkg:apk/alpine/pcre2@10.42-r1?arch=x86_64";
|
||||
|
||||
var runtimeResult = await impactIndex.ResolveByPurlsAsync(
|
||||
new[] { inventoryOnlyPurl },
|
||||
usageOnly: true,
|
||||
selector);
|
||||
|
||||
runtimeResult.Images.Should().BeEmpty();
|
||||
|
||||
var inventoryResult = await impactIndex.ResolveByPurlsAsync(
|
||||
new[] { inventoryOnlyPurl },
|
||||
usageOnly: false,
|
||||
selector);
|
||||
|
||||
inventoryResult.Images.Should().ContainSingle();
|
||||
inventoryResult.Images.Single().UsedByEntrypoint.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAll_ReturnsDeterministicFixtureSet()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var first = await impactIndex.ResolveAllAsync(selector, usageOnly: false);
|
||||
first.Images.Should().HaveCount(6);
|
||||
|
||||
var second = await impactIndex.ResolveAllAsync(selector, usageOnly: false);
|
||||
second.Images.Should().HaveCount(6);
|
||||
second.Images.Should().Equal(first.Images);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveByVulnerabilities_ReturnsEmptySet()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var result = await impactIndex.ResolveByVulnerabilitiesAsync(
|
||||
new[] { "CVE-2025-0001" },
|
||||
usageOnly: false,
|
||||
selector);
|
||||
|
||||
result.Images.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FixtureDirectoryOption_LoadsFromFileSystem()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var samplesDirectory = LocateSamplesDirectory();
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex(options =>
|
||||
{
|
||||
options.FixtureDirectory = samplesDirectory;
|
||||
});
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var result = await impactIndex.ResolveAllAsync(selector, usageOnly: false);
|
||||
|
||||
result.Images.Should().HaveCount(6);
|
||||
}
|
||||
|
||||
private static (FixtureImpactIndex ImpactIndex, ILoggerFactory LoggerFactory) CreateImpactIndex(
|
||||
Action<ImpactIndexStubOptions>? configure = null)
|
||||
{
|
||||
var options = new ImpactIndexStubOptions();
|
||||
configure?.Invoke(options);
|
||||
|
||||
var loggerFactory = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug));
|
||||
var logger = loggerFactory.CreateLogger<FixtureImpactIndex>();
|
||||
|
||||
var impactIndex = new FixtureImpactIndex(options, TimeProvider.System, logger);
|
||||
return (impactIndex, loggerFactory);
|
||||
}
|
||||
|
||||
private static string LocateSamplesDirectory()
|
||||
{
|
||||
var current = AppContext.BaseDirectory;
|
||||
|
||||
while (!string.IsNullOrWhiteSpace(current))
|
||||
{
|
||||
var candidate = Path.Combine(current, "samples", "scanner", "images");
|
||||
if (Directory.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
|
||||
current = Directory.GetParent(current)?.FullName;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Unable to locate 'samples/scanner/images'.");
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using StellaOps.Scheduler.ImpactIndex;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.ImpactIndex.Tests;
|
||||
|
||||
public sealed class FixtureImpactIndexTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task ResolveByPurls_UsesEmbeddedFixtures()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var result = await impactIndex.ResolveByPurlsAsync(
|
||||
new[] { "pkg:apk/alpine/openssl@3.2.2-r0?arch=x86_64" },
|
||||
usageOnly: false,
|
||||
selector);
|
||||
|
||||
result.UsageOnly.Should().BeFalse();
|
||||
result.Images.Should().ContainSingle();
|
||||
|
||||
var image = result.Images.Single();
|
||||
image.ImageDigest.Should().Be("sha256:8f47d7c6b538c0d9533b78913cba3d5e671e7c4b4e7c6a2bb9a1a1c4d4f8e123");
|
||||
image.Registry.Should().Be("docker.io");
|
||||
image.Repository.Should().Be("library/nginx");
|
||||
image.Tags.Should().ContainSingle(tag => tag == "1.25.4");
|
||||
image.UsedByEntrypoint.Should().BeTrue();
|
||||
|
||||
result.GeneratedAt.Should().Be(DateTimeOffset.Parse("2025-10-19T00:00:00Z"));
|
||||
result.SchemaVersion.Should().Be(SchedulerSchemaVersions.ImpactSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveByPurls_UsageOnlyFiltersInventoryOnlyComponents()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var inventoryOnlyPurl = "pkg:apk/alpine/pcre2@10.42-r1?arch=x86_64";
|
||||
|
||||
var runtimeResult = await impactIndex.ResolveByPurlsAsync(
|
||||
new[] { inventoryOnlyPurl },
|
||||
usageOnly: true,
|
||||
selector);
|
||||
|
||||
runtimeResult.Images.Should().BeEmpty();
|
||||
|
||||
var inventoryResult = await impactIndex.ResolveByPurlsAsync(
|
||||
new[] { inventoryOnlyPurl },
|
||||
usageOnly: false,
|
||||
selector);
|
||||
|
||||
inventoryResult.Images.Should().ContainSingle();
|
||||
inventoryResult.Images.Single().UsedByEntrypoint.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAll_ReturnsDeterministicFixtureSet()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var first = await impactIndex.ResolveAllAsync(selector, usageOnly: false);
|
||||
first.Images.Should().HaveCount(6);
|
||||
|
||||
var second = await impactIndex.ResolveAllAsync(selector, usageOnly: false);
|
||||
second.Images.Should().HaveCount(6);
|
||||
second.Images.Should().Equal(first.Images);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveByVulnerabilities_ReturnsEmptySet()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex();
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var result = await impactIndex.ResolveByVulnerabilitiesAsync(
|
||||
new[] { "CVE-2025-0001" },
|
||||
usageOnly: false,
|
||||
selector);
|
||||
|
||||
result.Images.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FixtureDirectoryOption_LoadsFromFileSystem()
|
||||
{
|
||||
var selector = new Selector(SelectorScope.AllImages);
|
||||
var samplesDirectory = LocateSamplesDirectory();
|
||||
var (impactIndex, loggerFactory) = CreateImpactIndex(options =>
|
||||
{
|
||||
options.FixtureDirectory = samplesDirectory;
|
||||
});
|
||||
using var _ = loggerFactory;
|
||||
|
||||
var result = await impactIndex.ResolveAllAsync(selector, usageOnly: false);
|
||||
|
||||
result.Images.Should().HaveCount(6);
|
||||
}
|
||||
|
||||
private static (FixtureImpactIndex ImpactIndex, ILoggerFactory LoggerFactory) CreateImpactIndex(
|
||||
Action<ImpactIndexStubOptions>? configure = null)
|
||||
{
|
||||
var options = new ImpactIndexStubOptions();
|
||||
configure?.Invoke(options);
|
||||
|
||||
var loggerFactory = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug));
|
||||
var logger = loggerFactory.CreateLogger<FixtureImpactIndex>();
|
||||
|
||||
var impactIndex = new FixtureImpactIndex(options, TimeProvider.System, logger);
|
||||
return (impactIndex, loggerFactory);
|
||||
}
|
||||
|
||||
private static string LocateSamplesDirectory()
|
||||
{
|
||||
var current = AppContext.BaseDirectory;
|
||||
|
||||
while (!string.IsNullOrWhiteSpace(current))
|
||||
{
|
||||
var candidate = Path.Combine(current, "samples", "scanner", "images");
|
||||
if (Directory.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
|
||||
current = Directory.GetParent(current)?.FullName;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException("Unable to locate 'samples/scanner/images'.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,164 +1,164 @@
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.IO;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Scheduler.ImpactIndex.Ingestion;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scanner.Core.Contracts;
|
||||
using StellaOps.Scanner.Emit.Index;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.ImpactIndex.Tests;
|
||||
|
||||
public sealed class RoaringImpactIndexTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task IngestAsync_RegistersComponentsAndUsage()
|
||||
{
|
||||
var (stream, digest) = CreateBomIndex(
|
||||
ComponentIdentity.Create("pkg:npm/a@1.0.0", "a", "1.0.0", "pkg:npm/a@1.0.0"),
|
||||
ComponentUsage.Create(true, new[] { "/app/start.sh" }));
|
||||
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
var request = new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = digest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/alpine",
|
||||
Namespaces = ImmutableArray.Create("team-a"),
|
||||
Tags = ImmutableArray.Create("3.20"),
|
||||
Labels = ImmutableSortedDictionary.CreateRange(StringComparer.OrdinalIgnoreCase, new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("env", "prod")
|
||||
}),
|
||||
BomIndexStream = stream,
|
||||
};
|
||||
|
||||
await index.IngestAsync(request, CancellationToken.None);
|
||||
|
||||
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
|
||||
var impactSet = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: false, selector);
|
||||
|
||||
impactSet.Images.Should().HaveCount(1);
|
||||
impactSet.Images[0].ImageDigest.Should().Be(digest);
|
||||
impactSet.Images[0].Tags.Should().ContainSingle(tag => tag == "3.20");
|
||||
impactSet.Images[0].UsedByEntrypoint.Should().BeTrue();
|
||||
|
||||
var usageOnly = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: true, selector);
|
||||
usageOnly.Images.Should().HaveCount(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IngestAsync_ReplacesExistingImageData()
|
||||
{
|
||||
var component = ComponentIdentity.Create("pkg:npm/a@1.0.0", "a", "1.0.0", "pkg:npm/a@1.0.0");
|
||||
var (initialStream, digest) = CreateBomIndex(component, ComponentUsage.Create(false));
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = digest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/alpine",
|
||||
Tags = ImmutableArray.Create("v1"),
|
||||
BomIndexStream = initialStream,
|
||||
});
|
||||
|
||||
var (updatedStream, _) = CreateBomIndex(component, ComponentUsage.Create(true, new[] { "/start.sh" }), digest);
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = digest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/alpine",
|
||||
Tags = ImmutableArray.Create("v2"),
|
||||
BomIndexStream = updatedStream,
|
||||
});
|
||||
|
||||
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
|
||||
var impactSet = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: true, selector);
|
||||
|
||||
impactSet.Images.Should().HaveCount(1);
|
||||
impactSet.Images[0].Tags.Should().ContainSingle(tag => tag == "v2");
|
||||
impactSet.Images[0].UsedByEntrypoint.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveByPurlsAsync_RespectsTenantNamespaceAndTagFilters()
|
||||
{
|
||||
var component = ComponentIdentity.Create("pkg:npm/a@1.0.0", "a", "1.0.0", "pkg:npm/a@1.0.0");
|
||||
var (tenantStream, tenantDigest) = CreateBomIndex(component, ComponentUsage.Create(true, new[] { "/start.sh" }));
|
||||
var (otherStream, otherDigest) = CreateBomIndex(component, ComponentUsage.Create(false));
|
||||
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = tenantDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
Namespaces = ImmutableArray.Create("team-alpha"),
|
||||
Tags = ImmutableArray.Create("prod-eu"),
|
||||
BomIndexStream = tenantStream,
|
||||
});
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-beta",
|
||||
ImageDigest = otherDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
Namespaces = ImmutableArray.Create("team-beta"),
|
||||
Tags = ImmutableArray.Create("staging-us"),
|
||||
BomIndexStream = otherStream,
|
||||
});
|
||||
|
||||
var selector = new Selector(
|
||||
SelectorScope.AllImages,
|
||||
tenantId: "tenant-alpha",
|
||||
namespaces: new[] { "team-alpha" },
|
||||
includeTags: new[] { "prod-*" });
|
||||
|
||||
var result = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: true, selector);
|
||||
|
||||
result.Images.Should().ContainSingle(image => image.ImageDigest == tenantDigest);
|
||||
result.Images[0].Tags.Should().Contain("prod-eu");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
using System;
|
||||
using System.Collections.Immutable;
|
||||
using System.IO;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Scheduler.ImpactIndex.Ingestion;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scanner.Core.Contracts;
|
||||
using StellaOps.Scanner.Emit.Index;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.ImpactIndex.Tests;
|
||||
|
||||
public sealed class RoaringImpactIndexTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task IngestAsync_RegistersComponentsAndUsage()
|
||||
{
|
||||
var (stream, digest) = CreateBomIndex(
|
||||
ComponentIdentity.Create("pkg:npm/a@1.0.0", "a", "1.0.0", "pkg:npm/a@1.0.0"),
|
||||
ComponentUsage.Create(true, new[] { "/app/start.sh" }));
|
||||
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
var request = new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = digest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/alpine",
|
||||
Namespaces = ImmutableArray.Create("team-a"),
|
||||
Tags = ImmutableArray.Create("3.20"),
|
||||
Labels = ImmutableSortedDictionary.CreateRange(StringComparer.OrdinalIgnoreCase, new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("env", "prod")
|
||||
}),
|
||||
BomIndexStream = stream,
|
||||
};
|
||||
|
||||
await index.IngestAsync(request, CancellationToken.None);
|
||||
|
||||
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
|
||||
var impactSet = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: false, selector);
|
||||
|
||||
impactSet.Images.Should().HaveCount(1);
|
||||
impactSet.Images[0].ImageDigest.Should().Be(digest);
|
||||
impactSet.Images[0].Tags.Should().ContainSingle(tag => tag == "3.20");
|
||||
impactSet.Images[0].UsedByEntrypoint.Should().BeTrue();
|
||||
|
||||
var usageOnly = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: true, selector);
|
||||
usageOnly.Images.Should().HaveCount(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IngestAsync_ReplacesExistingImageData()
|
||||
{
|
||||
var component = ComponentIdentity.Create("pkg:npm/a@1.0.0", "a", "1.0.0", "pkg:npm/a@1.0.0");
|
||||
var (initialStream, digest) = CreateBomIndex(component, ComponentUsage.Create(false));
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = digest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/alpine",
|
||||
Tags = ImmutableArray.Create("v1"),
|
||||
BomIndexStream = initialStream,
|
||||
});
|
||||
|
||||
var (updatedStream, _) = CreateBomIndex(component, ComponentUsage.Create(true, new[] { "/start.sh" }), digest);
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = digest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/alpine",
|
||||
Tags = ImmutableArray.Create("v2"),
|
||||
BomIndexStream = updatedStream,
|
||||
});
|
||||
|
||||
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
|
||||
var impactSet = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: true, selector);
|
||||
|
||||
impactSet.Images.Should().HaveCount(1);
|
||||
impactSet.Images[0].Tags.Should().ContainSingle(tag => tag == "v2");
|
||||
impactSet.Images[0].UsedByEntrypoint.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveByPurlsAsync_RespectsTenantNamespaceAndTagFilters()
|
||||
{
|
||||
var component = ComponentIdentity.Create("pkg:npm/a@1.0.0", "a", "1.0.0", "pkg:npm/a@1.0.0");
|
||||
var (tenantStream, tenantDigest) = CreateBomIndex(component, ComponentUsage.Create(true, new[] { "/start.sh" }));
|
||||
var (otherStream, otherDigest) = CreateBomIndex(component, ComponentUsage.Create(false));
|
||||
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = tenantDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
Namespaces = ImmutableArray.Create("team-alpha"),
|
||||
Tags = ImmutableArray.Create("prod-eu"),
|
||||
BomIndexStream = tenantStream,
|
||||
});
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-beta",
|
||||
ImageDigest = otherDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
Namespaces = ImmutableArray.Create("team-beta"),
|
||||
Tags = ImmutableArray.Create("staging-us"),
|
||||
BomIndexStream = otherStream,
|
||||
});
|
||||
|
||||
var selector = new Selector(
|
||||
SelectorScope.AllImages,
|
||||
tenantId: "tenant-alpha",
|
||||
namespaces: new[] { "team-alpha" },
|
||||
includeTags: new[] { "prod-*" });
|
||||
|
||||
var result = await index.ResolveByPurlsAsync(new[] { "pkg:npm/a@1.0.0" }, usageOnly: true, selector);
|
||||
|
||||
result.Images.Should().ContainSingle(image => image.ImageDigest == tenantDigest);
|
||||
result.Images[0].Tags.Should().Contain("prod-eu");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ResolveAllAsync_UsageOnlyFiltersEntrypointImages()
|
||||
{
|
||||
var component = ComponentIdentity.Create("pkg:npm/a@1.0.0", "a", "1.0.0", "pkg:npm/a@1.0.0");
|
||||
var (entryStream, entryDigest) = CreateBomIndex(component, ComponentUsage.Create(true, new[] { "/start.sh" }));
|
||||
var nonEntryDigestValue = "sha256:" + new string('1', 64);
|
||||
var (nonEntryStream, nonEntryDigest) = CreateBomIndex(component, ComponentUsage.Create(false), nonEntryDigestValue);
|
||||
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = entryDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
BomIndexStream = entryStream,
|
||||
});
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = nonEntryDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
BomIndexStream = nonEntryStream,
|
||||
});
|
||||
|
||||
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
|
||||
|
||||
var (nonEntryStream, nonEntryDigest) = CreateBomIndex(component, ComponentUsage.Create(false), nonEntryDigestValue);
|
||||
|
||||
var index = new RoaringImpactIndex(NullLogger<RoaringImpactIndex>.Instance);
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = entryDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
BomIndexStream = entryStream,
|
||||
});
|
||||
|
||||
await index.IngestAsync(new ImpactIndexIngestionRequest
|
||||
{
|
||||
TenantId = "tenant-alpha",
|
||||
ImageDigest = nonEntryDigest,
|
||||
Registry = "docker.io",
|
||||
Repository = "library/service",
|
||||
BomIndexStream = nonEntryStream,
|
||||
});
|
||||
|
||||
var selector = new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha");
|
||||
|
||||
var usageOnly = await index.ResolveAllAsync(selector, usageOnly: true);
|
||||
usageOnly.Images.Should().ContainSingle(image => image.ImageDigest == entryDigest);
|
||||
|
||||
@@ -241,31 +241,31 @@ public sealed class RoaringImpactIndexTests
|
||||
resolved.Images.Should().ContainSingle(img => img.ImageDigest == digest2);
|
||||
resolved.SnapshotId.Should().Be(snapshot.SnapshotId);
|
||||
}
|
||||
|
||||
private static (Stream Stream, string Digest) CreateBomIndex(ComponentIdentity identity, ComponentUsage usage, string? digest = null)
|
||||
{
|
||||
var layer = LayerComponentFragment.Create(
|
||||
"sha256:layer1",
|
||||
new[]
|
||||
{
|
||||
new ComponentRecord
|
||||
{
|
||||
Identity = identity,
|
||||
LayerDigest = "sha256:layer1",
|
||||
Usage = usage,
|
||||
}
|
||||
});
|
||||
|
||||
var graph = ComponentGraphBuilder.Build(new[] { layer });
|
||||
var effectiveDigest = digest ?? "sha256:" + Guid.NewGuid().ToString("N");
|
||||
var builder = new BomIndexBuilder();
|
||||
var artifact = builder.Build(new BomIndexBuildRequest
|
||||
{
|
||||
ImageDigest = effectiveDigest,
|
||||
Graph = graph,
|
||||
GeneratedAt = DateTimeOffset.UtcNow,
|
||||
});
|
||||
|
||||
return (new MemoryStream(artifact.Bytes, writable: false), effectiveDigest);
|
||||
}
|
||||
}
|
||||
|
||||
private static (Stream Stream, string Digest) CreateBomIndex(ComponentIdentity identity, ComponentUsage usage, string? digest = null)
|
||||
{
|
||||
var layer = LayerComponentFragment.Create(
|
||||
"sha256:layer1",
|
||||
new[]
|
||||
{
|
||||
new ComponentRecord
|
||||
{
|
||||
Identity = identity,
|
||||
LayerDigest = "sha256:layer1",
|
||||
Usage = usage,
|
||||
}
|
||||
});
|
||||
|
||||
var graph = ComponentGraphBuilder.Build(new[] { layer });
|
||||
var effectiveDigest = digest ?? "sha256:" + Guid.NewGuid().ToString("N");
|
||||
var builder = new BomIndexBuilder();
|
||||
var artifact = builder.Build(new BomIndexBuildRequest
|
||||
{
|
||||
ImageDigest = effectiveDigest,
|
||||
Graph = graph,
|
||||
GeneratedAt = DateTimeOffset.UtcNow,
|
||||
});
|
||||
|
||||
return (new MemoryStream(artifact.Bytes, writable: false), effectiveDigest);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +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);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,171 +1,171 @@
|
||||
namespace StellaOps.Scheduler.Models.Tests;
|
||||
|
||||
public sealed class GraphJobStateMachineTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Pending, true)]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Queued, true)]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Running, true)]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Completed, false)]
|
||||
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Running, true)]
|
||||
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Completed, false)]
|
||||
[InlineData(GraphJobStatus.Running, GraphJobStatus.Completed, true)]
|
||||
[InlineData(GraphJobStatus.Running, GraphJobStatus.Pending, false)]
|
||||
[InlineData(GraphJobStatus.Completed, GraphJobStatus.Failed, false)]
|
||||
public void CanTransition_ReturnsExpectedResult(GraphJobStatus from, GraphJobStatus to, bool expected)
|
||||
{
|
||||
Assert.Equal(expected, GraphJobStateMachine.CanTransition(from, to));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureTransition_UpdatesBuildJobLifecycle()
|
||||
{
|
||||
var createdAt = new DateTimeOffset(2025, 10, 26, 12, 0, 0, TimeSpan.Zero);
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom_1",
|
||||
sbomVersionId: "sbom_ver_1",
|
||||
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: createdAt);
|
||||
|
||||
var queuedAt = createdAt.AddSeconds(5);
|
||||
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Queued, queuedAt);
|
||||
Assert.Equal(GraphJobStatus.Queued, job.Status);
|
||||
Assert.Null(job.StartedAt);
|
||||
Assert.Null(job.CompletedAt);
|
||||
|
||||
var runningAt = queuedAt.AddSeconds(5);
|
||||
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Running, runningAt, attempts: job.Attempts + 1);
|
||||
Assert.Equal(GraphJobStatus.Running, job.Status);
|
||||
Assert.Equal(runningAt, job.StartedAt);
|
||||
Assert.Null(job.CompletedAt);
|
||||
|
||||
var completedAt = runningAt.AddSeconds(30);
|
||||
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Completed, completedAt);
|
||||
Assert.Equal(GraphJobStatus.Completed, job.Status);
|
||||
Assert.Equal(runningAt, job.StartedAt);
|
||||
Assert.Equal(completedAt, job.CompletedAt);
|
||||
Assert.Null(job.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureTransition_ToFailedRequiresError()
|
||||
{
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom_1",
|
||||
sbomVersionId: "sbom_ver_1",
|
||||
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
status: GraphJobStatus.Running,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
startedAt: DateTimeOffset.UtcNow);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.EnsureTransition(
|
||||
job,
|
||||
GraphJobStatus.Failed,
|
||||
DateTimeOffset.UtcNow));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureTransition_ToFailedSetsError()
|
||||
{
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap_1",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@latest",
|
||||
status: GraphJobStatus.Running,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
startedAt: DateTimeOffset.UtcNow);
|
||||
|
||||
var failed = GraphJobStateMachine.EnsureTransition(
|
||||
job,
|
||||
GraphJobStatus.Failed,
|
||||
DateTimeOffset.UtcNow,
|
||||
errorMessage: "cartographer timeout");
|
||||
|
||||
Assert.Equal(GraphJobStatus.Failed, failed.Status);
|
||||
Assert.NotNull(failed.CompletedAt);
|
||||
Assert.Equal("cartographer timeout", failed.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RequiresCompletedAtForTerminalState()
|
||||
{
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap_1",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@latest",
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: DateTimeOffset.UtcNow);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.Validate(job));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GraphOverlayJob_NormalizesSubjectsAndMetadata()
|
||||
{
|
||||
var createdAt = DateTimeOffset.UtcNow;
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj_norm",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap_norm",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@norm",
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: createdAt,
|
||||
subjects: new[]
|
||||
{
|
||||
"artifact/service-api",
|
||||
"artifact/service-ui",
|
||||
"artifact/service-api"
|
||||
},
|
||||
metadata: new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("PolicyRunId", "run-123"),
|
||||
new KeyValuePair<string, string>("policyRunId", "run-123")
|
||||
});
|
||||
|
||||
Assert.Equal(2, job.Subjects.Length);
|
||||
Assert.Collection(
|
||||
job.Subjects,
|
||||
subject => Assert.Equal("artifact/service-api", subject),
|
||||
subject => Assert.Equal("artifact/service-ui", subject));
|
||||
|
||||
Assert.Single(job.Metadata);
|
||||
Assert.Equal("run-123", job.Metadata["policyrunid"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GraphBuildJob_NormalizesDigestAndMetadata()
|
||||
{
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_norm",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom_norm",
|
||||
sbomVersionId: "sbom_ver_norm",
|
||||
sbomDigest: "SHA256:ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890",
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphBuildJobTrigger.Manual,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
metadata: new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("SBoMEventId", "evt-42")
|
||||
});
|
||||
|
||||
Assert.Equal("sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", job.SbomDigest);
|
||||
Assert.Single(job.Metadata);
|
||||
Assert.Equal("evt-42", job.Metadata["sbomeventid"]);
|
||||
}
|
||||
}
|
||||
namespace StellaOps.Scheduler.Models.Tests;
|
||||
|
||||
public sealed class GraphJobStateMachineTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Pending, true)]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Queued, true)]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Running, true)]
|
||||
[InlineData(GraphJobStatus.Pending, GraphJobStatus.Completed, false)]
|
||||
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Running, true)]
|
||||
[InlineData(GraphJobStatus.Queued, GraphJobStatus.Completed, false)]
|
||||
[InlineData(GraphJobStatus.Running, GraphJobStatus.Completed, true)]
|
||||
[InlineData(GraphJobStatus.Running, GraphJobStatus.Pending, false)]
|
||||
[InlineData(GraphJobStatus.Completed, GraphJobStatus.Failed, false)]
|
||||
public void CanTransition_ReturnsExpectedResult(GraphJobStatus from, GraphJobStatus to, bool expected)
|
||||
{
|
||||
Assert.Equal(expected, GraphJobStateMachine.CanTransition(from, to));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureTransition_UpdatesBuildJobLifecycle()
|
||||
{
|
||||
var createdAt = new DateTimeOffset(2025, 10, 26, 12, 0, 0, TimeSpan.Zero);
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom_1",
|
||||
sbomVersionId: "sbom_ver_1",
|
||||
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: createdAt);
|
||||
|
||||
var queuedAt = createdAt.AddSeconds(5);
|
||||
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Queued, queuedAt);
|
||||
Assert.Equal(GraphJobStatus.Queued, job.Status);
|
||||
Assert.Null(job.StartedAt);
|
||||
Assert.Null(job.CompletedAt);
|
||||
|
||||
var runningAt = queuedAt.AddSeconds(5);
|
||||
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Running, runningAt, attempts: job.Attempts + 1);
|
||||
Assert.Equal(GraphJobStatus.Running, job.Status);
|
||||
Assert.Equal(runningAt, job.StartedAt);
|
||||
Assert.Null(job.CompletedAt);
|
||||
|
||||
var completedAt = runningAt.AddSeconds(30);
|
||||
job = GraphJobStateMachine.EnsureTransition(job, GraphJobStatus.Completed, completedAt);
|
||||
Assert.Equal(GraphJobStatus.Completed, job.Status);
|
||||
Assert.Equal(runningAt, job.StartedAt);
|
||||
Assert.Equal(completedAt, job.CompletedAt);
|
||||
Assert.Null(job.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureTransition_ToFailedRequiresError()
|
||||
{
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom_1",
|
||||
sbomVersionId: "sbom_ver_1",
|
||||
sbomDigest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
status: GraphJobStatus.Running,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
startedAt: DateTimeOffset.UtcNow);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.EnsureTransition(
|
||||
job,
|
||||
GraphJobStatus.Failed,
|
||||
DateTimeOffset.UtcNow));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnsureTransition_ToFailedSetsError()
|
||||
{
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap_1",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@latest",
|
||||
status: GraphJobStatus.Running,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
startedAt: DateTimeOffset.UtcNow);
|
||||
|
||||
var failed = GraphJobStateMachine.EnsureTransition(
|
||||
job,
|
||||
GraphJobStatus.Failed,
|
||||
DateTimeOffset.UtcNow,
|
||||
errorMessage: "cartographer timeout");
|
||||
|
||||
Assert.Equal(GraphJobStatus.Failed, failed.Status);
|
||||
Assert.NotNull(failed.CompletedAt);
|
||||
Assert.Equal("cartographer timeout", failed.Error);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_RequiresCompletedAtForTerminalState()
|
||||
{
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj_1",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap_1",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@latest",
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: DateTimeOffset.UtcNow);
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => GraphJobStateMachine.Validate(job));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GraphOverlayJob_NormalizesSubjectsAndMetadata()
|
||||
{
|
||||
var createdAt = DateTimeOffset.UtcNow;
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj_norm",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap_norm",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@norm",
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: createdAt,
|
||||
subjects: new[]
|
||||
{
|
||||
"artifact/service-api",
|
||||
"artifact/service-ui",
|
||||
"artifact/service-api"
|
||||
},
|
||||
metadata: new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("PolicyRunId", "run-123"),
|
||||
new KeyValuePair<string, string>("policyRunId", "run-123")
|
||||
});
|
||||
|
||||
Assert.Equal(2, job.Subjects.Length);
|
||||
Assert.Collection(
|
||||
job.Subjects,
|
||||
subject => Assert.Equal("artifact/service-api", subject),
|
||||
subject => Assert.Equal("artifact/service-ui", subject));
|
||||
|
||||
Assert.Single(job.Metadata);
|
||||
Assert.Equal("run-123", job.Metadata["policyrunid"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GraphBuildJob_NormalizesDigestAndMetadata()
|
||||
{
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_norm",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom_norm",
|
||||
sbomVersionId: "sbom_ver_norm",
|
||||
sbomDigest: "SHA256:ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890ABCDEF1234567890",
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphBuildJobTrigger.Manual,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
metadata: new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("SBoMEventId", "evt-42")
|
||||
});
|
||||
|
||||
Assert.Equal("sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", job.SbomDigest);
|
||||
Assert.Single(job.Metadata);
|
||||
Assert.Equal("evt-42", job.Metadata["sbomeventid"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,55 +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"));
|
||||
}
|
||||
}
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.Json;
|
||||
using StellaOps.Scheduler.Models;
|
||||
|
||||
namespace StellaOps.Scheduler.Models.Tests;
|
||||
|
||||
public sealed class PolicyRunModelsTests
|
||||
{
|
||||
[Fact]
|
||||
public void PolicyRunInputs_NormalizesEnvironmentKeys()
|
||||
{
|
||||
var inputs = new PolicyRunInputs(
|
||||
sbomSet: new[] { "sbom:two", "sbom:one" },
|
||||
env: new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("Sealed", true),
|
||||
new KeyValuePair<string, object?>("Exposure", "internet"),
|
||||
new KeyValuePair<string, object?>("region", JsonSerializer.SerializeToElement("global"))
|
||||
},
|
||||
captureExplain: true);
|
||||
|
||||
Assert.Equal(new[] { "sbom:one", "sbom:two" }, inputs.SbomSet);
|
||||
Assert.True(inputs.CaptureExplain);
|
||||
Assert.Equal(3, inputs.Environment.Count);
|
||||
Assert.True(inputs.Environment.ContainsKey("sealed"));
|
||||
Assert.Equal(JsonValueKind.True, inputs.Environment["sealed"].ValueKind);
|
||||
Assert.Equal("internet", inputs.Environment["exposure"].GetString());
|
||||
Assert.Equal("global", inputs.Environment["region"].GetString());
|
||||
using System.Collections.Immutable;
|
||||
using System.Text.Json;
|
||||
using StellaOps.Scheduler.Models;
|
||||
|
||||
namespace StellaOps.Scheduler.Models.Tests;
|
||||
|
||||
public sealed class PolicyRunModelsTests
|
||||
{
|
||||
[Fact]
|
||||
public void PolicyRunInputs_NormalizesEnvironmentKeys()
|
||||
{
|
||||
var inputs = new PolicyRunInputs(
|
||||
sbomSet: new[] { "sbom:two", "sbom:one" },
|
||||
env: new[]
|
||||
{
|
||||
new KeyValuePair<string, object?>("Sealed", true),
|
||||
new KeyValuePair<string, object?>("Exposure", "internet"),
|
||||
new KeyValuePair<string, object?>("region", JsonSerializer.SerializeToElement("global"))
|
||||
},
|
||||
captureExplain: true);
|
||||
|
||||
Assert.Equal(new[] { "sbom:one", "sbom:two" }, inputs.SbomSet);
|
||||
Assert.True(inputs.CaptureExplain);
|
||||
Assert.Equal(3, inputs.Environment.Count);
|
||||
Assert.True(inputs.Environment.ContainsKey("sealed"));
|
||||
Assert.Equal(JsonValueKind.True, inputs.Environment["sealed"].ValueKind);
|
||||
Assert.Equal("internet", inputs.Environment["exposure"].GetString());
|
||||
Assert.Equal("global", inputs.Environment["region"].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -90,56 +90,56 @@ public sealed class PolicyRunModelsTests
|
||||
CancelledAt: status == PolicyRunJobStatus.Cancelled ? timestamp : null);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PolicyRunStatus_ThrowsOnNegativeAttempts()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new PolicyRunStatus(
|
||||
runId: "run:test",
|
||||
tenantId: "tenant-alpha",
|
||||
policyId: "P-1",
|
||||
policyVersion: 1,
|
||||
mode: PolicyRunMode.Full,
|
||||
status: PolicyRunExecutionStatus.Queued,
|
||||
priority: PolicyRunPriority.Normal,
|
||||
queuedAt: DateTimeOffset.UtcNow,
|
||||
attempts: -1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PolicyDiffSummary_NormalizesSeverityKeys()
|
||||
{
|
||||
var summary = new PolicyDiffSummary(
|
||||
added: 1,
|
||||
removed: 2,
|
||||
unchanged: 3,
|
||||
bySeverity: new[]
|
||||
{
|
||||
new KeyValuePair<string, PolicyDiffSeverityDelta>("critical", new PolicyDiffSeverityDelta(1, 0)),
|
||||
new KeyValuePair<string, PolicyDiffSeverityDelta>("HIGH", new PolicyDiffSeverityDelta(0, 1))
|
||||
});
|
||||
|
||||
Assert.True(summary.BySeverity.ContainsKey("Critical"));
|
||||
Assert.True(summary.BySeverity.ContainsKey("High"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PolicyExplainTrace_LowercasesMetadataKeys()
|
||||
{
|
||||
var trace = new PolicyExplainTrace(
|
||||
findingId: "finding:alpha",
|
||||
policyId: "P-1",
|
||||
policyVersion: 1,
|
||||
tenantId: "tenant-alpha",
|
||||
runId: "run:test",
|
||||
verdict: new PolicyExplainVerdict(PolicyVerdictStatus.Passed, SeverityRank.Low, quiet: false, score: 0, rationale: "ok"),
|
||||
evaluatedAt: DateTimeOffset.UtcNow,
|
||||
metadata: ImmutableSortedDictionary.CreateRange(new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("TraceId", "trace-1"),
|
||||
new KeyValuePair<string, string>("ComponentPurl", "pkg:npm/a@1.0.0")
|
||||
}));
|
||||
|
||||
Assert.Equal("trace-1", trace.Metadata["traceid"]);
|
||||
Assert.Equal("pkg:npm/a@1.0.0", trace.Metadata["componentpurl"]);
|
||||
}
|
||||
}
|
||||
[Fact]
|
||||
public void PolicyRunStatus_ThrowsOnNegativeAttempts()
|
||||
{
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => new PolicyRunStatus(
|
||||
runId: "run:test",
|
||||
tenantId: "tenant-alpha",
|
||||
policyId: "P-1",
|
||||
policyVersion: 1,
|
||||
mode: PolicyRunMode.Full,
|
||||
status: PolicyRunExecutionStatus.Queued,
|
||||
priority: PolicyRunPriority.Normal,
|
||||
queuedAt: DateTimeOffset.UtcNow,
|
||||
attempts: -1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PolicyDiffSummary_NormalizesSeverityKeys()
|
||||
{
|
||||
var summary = new PolicyDiffSummary(
|
||||
added: 1,
|
||||
removed: 2,
|
||||
unchanged: 3,
|
||||
bySeverity: new[]
|
||||
{
|
||||
new KeyValuePair<string, PolicyDiffSeverityDelta>("critical", new PolicyDiffSeverityDelta(1, 0)),
|
||||
new KeyValuePair<string, PolicyDiffSeverityDelta>("HIGH", new PolicyDiffSeverityDelta(0, 1))
|
||||
});
|
||||
|
||||
Assert.True(summary.BySeverity.ContainsKey("Critical"));
|
||||
Assert.True(summary.BySeverity.ContainsKey("High"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PolicyExplainTrace_LowercasesMetadataKeys()
|
||||
{
|
||||
var trace = new PolicyExplainTrace(
|
||||
findingId: "finding:alpha",
|
||||
policyId: "P-1",
|
||||
policyVersion: 1,
|
||||
tenantId: "tenant-alpha",
|
||||
runId: "run:test",
|
||||
verdict: new PolicyExplainVerdict(PolicyVerdictStatus.Passed, SeverityRank.Low, quiet: false, score: 0, rationale: "ok"),
|
||||
evaluatedAt: DateTimeOffset.UtcNow,
|
||||
metadata: ImmutableSortedDictionary.CreateRange(new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("TraceId", "trace-1"),
|
||||
new KeyValuePair<string, string>("ComponentPurl", "pkg:npm/a@1.0.0")
|
||||
}));
|
||||
|
||||
Assert.Equal("trace-1", trace.Metadata["traceid"]);
|
||||
Assert.Equal("pkg:npm/a@1.0.0", trace.Metadata["componentpurl"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,59 +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);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,108 +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);
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,13 +145,13 @@ public sealed class SamplePayloadTests
|
||||
var canonical = CanonicalJsonSerializer.Serialize(trace);
|
||||
AssertJsonEquivalent(json, canonical);
|
||||
}
|
||||
[Fact]
|
||||
public void PolicyRunJob_RoundtripsThroughCanonicalSerializer()
|
||||
{
|
||||
var metadata = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
|
||||
metadata["source"] = "cli";
|
||||
metadata["trigger"] = "manual";
|
||||
|
||||
[Fact]
|
||||
public void PolicyRunJob_RoundtripsThroughCanonicalSerializer()
|
||||
{
|
||||
var metadata = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal);
|
||||
metadata["source"] = "cli";
|
||||
metadata["trigger"] = "manual";
|
||||
|
||||
var job = new PolicyRunJob(
|
||||
SchemaVersion: SchedulerSchemaVersions.PolicyRunJob,
|
||||
Id: "job_20251026T140500Z",
|
||||
@@ -185,7 +185,7 @@ public sealed class SamplePayloadTests
|
||||
CancellationRequestedAt: null,
|
||||
CancellationReason: null,
|
||||
CancelledAt: null);
|
||||
|
||||
|
||||
var canonical = CanonicalJsonSerializer.Serialize(job);
|
||||
var roundtrip = CanonicalJsonSerializer.Deserialize<PolicyRunJob>(canonical);
|
||||
|
||||
@@ -195,8 +195,8 @@ public sealed class SamplePayloadTests
|
||||
Assert.Equal(job.Status, roundtrip.Status);
|
||||
Assert.Equal(job.RunId, roundtrip.RunId);
|
||||
Assert.Equal("cli", roundtrip.Metadata!["source"]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static string ReadSample(string fileName)
|
||||
{
|
||||
|
||||
@@ -1,113 +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"));
|
||||
}
|
||||
}
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,70 +1,70 @@
|
||||
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]
|
||||
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";
|
||||
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);
|
||||
|
||||
@@ -1,157 +1,157 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DotNet.Testcontainers.Builders;
|
||||
using DotNet.Testcontainers.Containers;
|
||||
using DotNet.Testcontainers.Configurations;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StackExchange.Redis;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Queue.Redis;
|
||||
using System.Threading.Tasks;
|
||||
using DotNet.Testcontainers.Builders;
|
||||
using DotNet.Testcontainers.Containers;
|
||||
using DotNet.Testcontainers.Configurations;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StackExchange.Redis;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Queue.Redis;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.Queue.Tests;
|
||||
|
||||
public sealed class RedisSchedulerQueueTests : IAsyncLifetime
|
||||
{
|
||||
private readonly RedisTestcontainer _redis;
|
||||
private string? _skipReason;
|
||||
|
||||
public RedisSchedulerQueueTests()
|
||||
{
|
||||
var configuration = new RedisTestcontainerConfiguration();
|
||||
|
||||
_redis = new TestcontainersBuilder<RedisTestcontainer>()
|
||||
.WithDatabase(configuration)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _redis.StartAsync();
|
||||
}
|
||||
catch (Exception ex) when (IsDockerUnavailable(ex))
|
||||
{
|
||||
_skipReason = $"Docker engine is not available for Redis-backed tests: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
if (_skipReason is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _redis.DisposeAsync().AsTask();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlannerQueue_EnqueueLeaseAck_RemovesMessage()
|
||||
{
|
||||
|
||||
namespace StellaOps.Scheduler.Queue.Tests;
|
||||
|
||||
public sealed class RedisSchedulerQueueTests : IAsyncLifetime
|
||||
{
|
||||
private readonly RedisTestcontainer _redis;
|
||||
private string? _skipReason;
|
||||
|
||||
public RedisSchedulerQueueTests()
|
||||
{
|
||||
var configuration = new RedisTestcontainerConfiguration();
|
||||
|
||||
_redis = new TestcontainersBuilder<RedisTestcontainer>()
|
||||
.WithDatabase(configuration)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await _redis.StartAsync();
|
||||
}
|
||||
catch (Exception ex) when (IsDockerUnavailable(ex))
|
||||
{
|
||||
_skipReason = $"Docker engine is not available for Redis-backed tests: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
if (_skipReason is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _redis.DisposeAsync().AsTask();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlannerQueue_EnqueueLeaseAck_RemovesMessage()
|
||||
{
|
||||
if (SkipIfUnavailable())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var options = CreateOptions();
|
||||
|
||||
await using var queue = new RedisSchedulerPlannerQueue(
|
||||
options,
|
||||
options.Redis,
|
||||
NullLogger<RedisSchedulerPlannerQueue>.Instance,
|
||||
TimeProvider.System,
|
||||
async config => (IConnectionMultiplexer)await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false));
|
||||
|
||||
var message = TestData.CreatePlannerMessage();
|
||||
|
||||
var enqueue = await queue.EnqueueAsync(message);
|
||||
enqueue.Deduplicated.Should().BeFalse();
|
||||
|
||||
var leases = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("planner-1", batchSize: 5, options.DefaultLeaseDuration));
|
||||
leases.Should().HaveCount(1);
|
||||
|
||||
var lease = leases[0];
|
||||
lease.Message.Run.Id.Should().Be(message.Run.Id);
|
||||
lease.TenantId.Should().Be(message.TenantId);
|
||||
lease.ScheduleId.Should().Be(message.ScheduleId);
|
||||
|
||||
await lease.AcknowledgeAsync();
|
||||
|
||||
var afterAck = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("planner-1", 5, options.DefaultLeaseDuration));
|
||||
afterAck.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
var options = CreateOptions();
|
||||
|
||||
await using var queue = new RedisSchedulerPlannerQueue(
|
||||
options,
|
||||
options.Redis,
|
||||
NullLogger<RedisSchedulerPlannerQueue>.Instance,
|
||||
TimeProvider.System,
|
||||
async config => (IConnectionMultiplexer)await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false));
|
||||
|
||||
var message = TestData.CreatePlannerMessage();
|
||||
|
||||
var enqueue = await queue.EnqueueAsync(message);
|
||||
enqueue.Deduplicated.Should().BeFalse();
|
||||
|
||||
var leases = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("planner-1", batchSize: 5, options.DefaultLeaseDuration));
|
||||
leases.Should().HaveCount(1);
|
||||
|
||||
var lease = leases[0];
|
||||
lease.Message.Run.Id.Should().Be(message.Run.Id);
|
||||
lease.TenantId.Should().Be(message.TenantId);
|
||||
lease.ScheduleId.Should().Be(message.ScheduleId);
|
||||
|
||||
await lease.AcknowledgeAsync();
|
||||
|
||||
var afterAck = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("planner-1", 5, options.DefaultLeaseDuration));
|
||||
afterAck.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RunnerQueue_Retry_IncrementsDeliveryAttempt()
|
||||
{
|
||||
{
|
||||
if (SkipIfUnavailable())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var options = CreateOptions();
|
||||
options.RetryInitialBackoff = TimeSpan.Zero;
|
||||
options.RetryMaxBackoff = TimeSpan.Zero;
|
||||
|
||||
await using var queue = new RedisSchedulerRunnerQueue(
|
||||
options,
|
||||
options.Redis,
|
||||
NullLogger<RedisSchedulerRunnerQueue>.Instance,
|
||||
TimeProvider.System,
|
||||
async config => (IConnectionMultiplexer)await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false));
|
||||
|
||||
var message = TestData.CreateRunnerMessage();
|
||||
|
||||
await queue.EnqueueAsync(message);
|
||||
|
||||
var firstLease = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("runner-1", batchSize: 1, options.DefaultLeaseDuration));
|
||||
firstLease.Should().ContainSingle();
|
||||
|
||||
var lease = firstLease[0];
|
||||
lease.Attempt.Should().Be(1);
|
||||
|
||||
await lease.ReleaseAsync(SchedulerQueueReleaseDisposition.Retry);
|
||||
|
||||
var secondLease = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("runner-1", batchSize: 1, options.DefaultLeaseDuration));
|
||||
secondLease.Should().ContainSingle();
|
||||
secondLease[0].Attempt.Should().Be(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlannerQueue_ClaimExpired_ReassignsLease()
|
||||
{
|
||||
|
||||
var options = CreateOptions();
|
||||
options.RetryInitialBackoff = TimeSpan.Zero;
|
||||
options.RetryMaxBackoff = TimeSpan.Zero;
|
||||
|
||||
await using var queue = new RedisSchedulerRunnerQueue(
|
||||
options,
|
||||
options.Redis,
|
||||
NullLogger<RedisSchedulerRunnerQueue>.Instance,
|
||||
TimeProvider.System,
|
||||
async config => (IConnectionMultiplexer)await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false));
|
||||
|
||||
var message = TestData.CreateRunnerMessage();
|
||||
|
||||
await queue.EnqueueAsync(message);
|
||||
|
||||
var firstLease = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("runner-1", batchSize: 1, options.DefaultLeaseDuration));
|
||||
firstLease.Should().ContainSingle();
|
||||
|
||||
var lease = firstLease[0];
|
||||
lease.Attempt.Should().Be(1);
|
||||
|
||||
await lease.ReleaseAsync(SchedulerQueueReleaseDisposition.Retry);
|
||||
|
||||
var secondLease = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("runner-1", batchSize: 1, options.DefaultLeaseDuration));
|
||||
secondLease.Should().ContainSingle();
|
||||
secondLease[0].Attempt.Should().Be(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PlannerQueue_ClaimExpired_ReassignsLease()
|
||||
{
|
||||
if (SkipIfUnavailable())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var options = CreateOptions();
|
||||
|
||||
await using var queue = new RedisSchedulerPlannerQueue(
|
||||
options,
|
||||
options.Redis,
|
||||
NullLogger<RedisSchedulerPlannerQueue>.Instance,
|
||||
TimeProvider.System,
|
||||
async config => (IConnectionMultiplexer)await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false));
|
||||
|
||||
var message = TestData.CreatePlannerMessage();
|
||||
await queue.EnqueueAsync(message);
|
||||
|
||||
var leases = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("planner-a", 1, options.DefaultLeaseDuration));
|
||||
leases.Should().ContainSingle();
|
||||
|
||||
await Task.Delay(50);
|
||||
|
||||
var reclaimed = await queue.ClaimExpiredAsync(new SchedulerQueueClaimOptions("planner-b", batchSize: 1, minIdleTime: TimeSpan.Zero));
|
||||
reclaimed.Should().ContainSingle();
|
||||
reclaimed[0].Consumer.Should().Be("planner-b");
|
||||
reclaimed[0].RunId.Should().Be(message.Run.Id);
|
||||
|
||||
|
||||
var options = CreateOptions();
|
||||
|
||||
await using var queue = new RedisSchedulerPlannerQueue(
|
||||
options,
|
||||
options.Redis,
|
||||
NullLogger<RedisSchedulerPlannerQueue>.Instance,
|
||||
TimeProvider.System,
|
||||
async config => (IConnectionMultiplexer)await ConnectionMultiplexer.ConnectAsync(config).ConfigureAwait(false));
|
||||
|
||||
var message = TestData.CreatePlannerMessage();
|
||||
await queue.EnqueueAsync(message);
|
||||
|
||||
var leases = await queue.LeaseAsync(new SchedulerQueueLeaseRequest("planner-a", 1, options.DefaultLeaseDuration));
|
||||
leases.Should().ContainSingle();
|
||||
|
||||
await Task.Delay(50);
|
||||
|
||||
var reclaimed = await queue.ClaimExpiredAsync(new SchedulerQueueClaimOptions("planner-b", batchSize: 1, minIdleTime: TimeSpan.Zero));
|
||||
reclaimed.Should().ContainSingle();
|
||||
reclaimed[0].Consumer.Should().Be("planner-b");
|
||||
reclaimed[0].RunId.Should().Be(message.Run.Id);
|
||||
|
||||
await reclaimed[0].AcknowledgeAsync();
|
||||
}
|
||||
|
||||
@@ -220,43 +220,43 @@ public sealed class RedisSchedulerQueueTests : IAsyncLifetime
|
||||
depths.TryGetValue(("redis", "runner"), out var runnerDepth).Should().BeTrue();
|
||||
runnerDepth.Should().Be(0);
|
||||
}
|
||||
|
||||
private SchedulerQueueOptions CreateOptions()
|
||||
{
|
||||
var unique = Guid.NewGuid().ToString("N");
|
||||
|
||||
return new SchedulerQueueOptions
|
||||
{
|
||||
Kind = SchedulerQueueTransportKind.Redis,
|
||||
DefaultLeaseDuration = TimeSpan.FromSeconds(2),
|
||||
MaxDeliveryAttempts = 5,
|
||||
RetryInitialBackoff = TimeSpan.FromMilliseconds(10),
|
||||
RetryMaxBackoff = TimeSpan.FromMilliseconds(50),
|
||||
Redis = new SchedulerRedisQueueOptions
|
||||
{
|
||||
ConnectionString = _redis.ConnectionString,
|
||||
Database = 0,
|
||||
InitializationTimeout = TimeSpan.FromSeconds(10),
|
||||
Planner = new RedisSchedulerStreamOptions
|
||||
{
|
||||
Stream = $"scheduler:test:planner:{unique}",
|
||||
ConsumerGroup = $"planner-consumers-{unique}",
|
||||
DeadLetterStream = $"scheduler:test:planner:{unique}:dead",
|
||||
IdempotencyKeyPrefix = $"scheduler:test:planner:{unique}:idemp:",
|
||||
IdempotencyWindow = TimeSpan.FromMinutes(5)
|
||||
},
|
||||
Runner = new RedisSchedulerStreamOptions
|
||||
{
|
||||
Stream = $"scheduler:test:runner:{unique}",
|
||||
ConsumerGroup = $"runner-consumers-{unique}",
|
||||
DeadLetterStream = $"scheduler:test:runner:{unique}:dead",
|
||||
IdempotencyKeyPrefix = $"scheduler:test:runner:{unique}:idemp:",
|
||||
IdempotencyWindow = TimeSpan.FromMinutes(5)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private SchedulerQueueOptions CreateOptions()
|
||||
{
|
||||
var unique = Guid.NewGuid().ToString("N");
|
||||
|
||||
return new SchedulerQueueOptions
|
||||
{
|
||||
Kind = SchedulerQueueTransportKind.Redis,
|
||||
DefaultLeaseDuration = TimeSpan.FromSeconds(2),
|
||||
MaxDeliveryAttempts = 5,
|
||||
RetryInitialBackoff = TimeSpan.FromMilliseconds(10),
|
||||
RetryMaxBackoff = TimeSpan.FromMilliseconds(50),
|
||||
Redis = new SchedulerRedisQueueOptions
|
||||
{
|
||||
ConnectionString = _redis.ConnectionString,
|
||||
Database = 0,
|
||||
InitializationTimeout = TimeSpan.FromSeconds(10),
|
||||
Planner = new RedisSchedulerStreamOptions
|
||||
{
|
||||
Stream = $"scheduler:test:planner:{unique}",
|
||||
ConsumerGroup = $"planner-consumers-{unique}",
|
||||
DeadLetterStream = $"scheduler:test:planner:{unique}:dead",
|
||||
IdempotencyKeyPrefix = $"scheduler:test:planner:{unique}:idemp:",
|
||||
IdempotencyWindow = TimeSpan.FromMinutes(5)
|
||||
},
|
||||
Runner = new RedisSchedulerStreamOptions
|
||||
{
|
||||
Stream = $"scheduler:test:runner:{unique}",
|
||||
ConsumerGroup = $"runner-consumers-{unique}",
|
||||
DeadLetterStream = $"scheduler:test:runner:{unique}:dead",
|
||||
IdempotencyKeyPrefix = $"scheduler:test:runner:{unique}:idemp:",
|
||||
IdempotencyWindow = TimeSpan.FromMinutes(5)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private bool SkipIfUnavailable()
|
||||
{
|
||||
if (_skipReason is not null)
|
||||
@@ -265,82 +265,82 @@ public sealed class RedisSchedulerQueueTests : IAsyncLifetime
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsDockerUnavailable(Exception exception)
|
||||
{
|
||||
while (exception is AggregateException aggregate && aggregate.InnerException is not null)
|
||||
{
|
||||
exception = aggregate.InnerException;
|
||||
}
|
||||
|
||||
return exception is TimeoutException
|
||||
|| exception.GetType().Name.Contains("Docker", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static class TestData
|
||||
{
|
||||
public static PlannerQueueMessage CreatePlannerMessage()
|
||||
{
|
||||
var schedule = new Schedule(
|
||||
id: "sch-test",
|
||||
tenantId: "tenant-alpha",
|
||||
name: "Test",
|
||||
enabled: true,
|
||||
cronExpression: "0 0 * * *",
|
||||
timezone: "UTC",
|
||||
mode: ScheduleMode.AnalysisOnly,
|
||||
selection: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
|
||||
onlyIf: ScheduleOnlyIf.Default,
|
||||
notify: ScheduleNotify.Default,
|
||||
limits: ScheduleLimits.Default,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
createdBy: "tests",
|
||||
updatedAt: DateTimeOffset.UtcNow,
|
||||
updatedBy: "tests");
|
||||
|
||||
var run = new Run(
|
||||
id: "run-test",
|
||||
tenantId: "tenant-alpha",
|
||||
trigger: RunTrigger.Manual,
|
||||
state: RunState.Planning,
|
||||
stats: RunStats.Empty,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
reason: RunReason.Empty,
|
||||
scheduleId: schedule.Id);
|
||||
|
||||
var impactSet = new ImpactSet(
|
||||
selector: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
|
||||
images: new[]
|
||||
{
|
||||
new ImpactImage(
|
||||
imageDigest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
registry: "registry",
|
||||
repository: "repo",
|
||||
namespaces: new[] { "prod" },
|
||||
tags: new[] { "latest" })
|
||||
},
|
||||
usageOnly: true,
|
||||
generatedAt: DateTimeOffset.UtcNow,
|
||||
total: 1);
|
||||
|
||||
return new PlannerQueueMessage(run, impactSet, schedule, correlationId: "corr-test");
|
||||
}
|
||||
|
||||
public static RunnerSegmentQueueMessage CreateRunnerMessage()
|
||||
{
|
||||
return new RunnerSegmentQueueMessage(
|
||||
segmentId: "segment-test",
|
||||
runId: "run-test",
|
||||
tenantId: "tenant-alpha",
|
||||
imageDigests: new[]
|
||||
{
|
||||
"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
},
|
||||
scheduleId: "sch-test",
|
||||
ratePerSecond: 10,
|
||||
usageOnly: true,
|
||||
attributes: new Dictionary<string, string> { ["priority"] = "kev" },
|
||||
correlationId: "corr-runner");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsDockerUnavailable(Exception exception)
|
||||
{
|
||||
while (exception is AggregateException aggregate && aggregate.InnerException is not null)
|
||||
{
|
||||
exception = aggregate.InnerException;
|
||||
}
|
||||
|
||||
return exception is TimeoutException
|
||||
|| exception.GetType().Name.Contains("Docker", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private static class TestData
|
||||
{
|
||||
public static PlannerQueueMessage CreatePlannerMessage()
|
||||
{
|
||||
var schedule = new Schedule(
|
||||
id: "sch-test",
|
||||
tenantId: "tenant-alpha",
|
||||
name: "Test",
|
||||
enabled: true,
|
||||
cronExpression: "0 0 * * *",
|
||||
timezone: "UTC",
|
||||
mode: ScheduleMode.AnalysisOnly,
|
||||
selection: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
|
||||
onlyIf: ScheduleOnlyIf.Default,
|
||||
notify: ScheduleNotify.Default,
|
||||
limits: ScheduleLimits.Default,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
createdBy: "tests",
|
||||
updatedAt: DateTimeOffset.UtcNow,
|
||||
updatedBy: "tests");
|
||||
|
||||
var run = new Run(
|
||||
id: "run-test",
|
||||
tenantId: "tenant-alpha",
|
||||
trigger: RunTrigger.Manual,
|
||||
state: RunState.Planning,
|
||||
stats: RunStats.Empty,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
reason: RunReason.Empty,
|
||||
scheduleId: schedule.Id);
|
||||
|
||||
var impactSet = new ImpactSet(
|
||||
selector: new Selector(SelectorScope.AllImages, tenantId: "tenant-alpha"),
|
||||
images: new[]
|
||||
{
|
||||
new ImpactImage(
|
||||
imageDigest: "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
registry: "registry",
|
||||
repository: "repo",
|
||||
namespaces: new[] { "prod" },
|
||||
tags: new[] { "latest" })
|
||||
},
|
||||
usageOnly: true,
|
||||
generatedAt: DateTimeOffset.UtcNow,
|
||||
total: 1);
|
||||
|
||||
return new PlannerQueueMessage(run, impactSet, schedule, correlationId: "corr-test");
|
||||
}
|
||||
|
||||
public static RunnerSegmentQueueMessage CreateRunnerMessage()
|
||||
{
|
||||
return new RunnerSegmentQueueMessage(
|
||||
segmentId: "segment-test",
|
||||
runId: "run-test",
|
||||
tenantId: "tenant-alpha",
|
||||
imageDigests: new[]
|
||||
{
|
||||
"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
},
|
||||
scheduleId: "sch-test",
|
||||
ratePerSecond: 10,
|
||||
usageOnly: true,
|
||||
attributes: new Dictionary<string, string> { ["priority"] = "kev" },
|
||||
correlationId: "corr-runner");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,115 +1,115 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Queue;
|
||||
using StellaOps.Scheduler.Queue.Nats;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.Queue.Tests;
|
||||
|
||||
public sealed class SchedulerQueueServiceCollectionExtensionsTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task AddSchedulerQueues_RegistersNatsTransport()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<ILoggerFactory>(_ => NullLoggerFactory.Instance);
|
||||
services.AddSchedulerQueues(new ConfigurationBuilder().Build());
|
||||
|
||||
var optionsDescriptor = services.First(descriptor => descriptor.ServiceType == typeof(SchedulerQueueOptions));
|
||||
var options = (SchedulerQueueOptions)optionsDescriptor.ImplementationInstance!;
|
||||
options.Kind = SchedulerQueueTransportKind.Nats;
|
||||
options.Nats.Url = "nats://localhost:4222";
|
||||
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
|
||||
var plannerQueue = provider.GetRequiredService<ISchedulerPlannerQueue>();
|
||||
var runnerQueue = provider.GetRequiredService<ISchedulerRunnerQueue>();
|
||||
|
||||
plannerQueue.Should().BeOfType<NatsSchedulerPlannerQueue>();
|
||||
runnerQueue.Should().BeOfType<NatsSchedulerRunnerQueue>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SchedulerQueueHealthCheck_ReturnsHealthy_WhenTransportsReachable()
|
||||
{
|
||||
var healthCheck = new SchedulerQueueHealthCheck(
|
||||
new FakePlannerQueue(failPing: false),
|
||||
new FakeRunnerQueue(failPing: false),
|
||||
NullLogger<SchedulerQueueHealthCheck>.Instance);
|
||||
|
||||
var context = new HealthCheckContext
|
||||
{
|
||||
Registration = new HealthCheckRegistration("scheduler-queue", healthCheck, HealthStatus.Unhealthy, Array.Empty<string>())
|
||||
};
|
||||
|
||||
var result = await healthCheck.CheckHealthAsync(context);
|
||||
|
||||
result.Status.Should().Be(HealthStatus.Healthy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SchedulerQueueHealthCheck_ReturnsUnhealthy_WhenRunnerPingFails()
|
||||
{
|
||||
var healthCheck = new SchedulerQueueHealthCheck(
|
||||
new FakePlannerQueue(failPing: false),
|
||||
new FakeRunnerQueue(failPing: true),
|
||||
NullLogger<SchedulerQueueHealthCheck>.Instance);
|
||||
|
||||
var context = new HealthCheckContext
|
||||
{
|
||||
Registration = new HealthCheckRegistration("scheduler-queue", healthCheck, HealthStatus.Unhealthy, Array.Empty<string>())
|
||||
};
|
||||
|
||||
var result = await healthCheck.CheckHealthAsync(context);
|
||||
|
||||
result.Status.Should().Be(HealthStatus.Unhealthy);
|
||||
result.Description.Should().Contain("runner transport unreachable");
|
||||
}
|
||||
private abstract class FakeQueue<TMessage> : ISchedulerQueue<TMessage>, ISchedulerQueueTransportDiagnostics
|
||||
{
|
||||
private readonly bool _failPing;
|
||||
|
||||
protected FakeQueue(bool failPing)
|
||||
{
|
||||
_failPing = failPing;
|
||||
}
|
||||
|
||||
public ValueTask<SchedulerQueueEnqueueResult> EnqueueAsync(TMessage message, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult(new SchedulerQueueEnqueueResult("stub", false));
|
||||
|
||||
public ValueTask<IReadOnlyList<ISchedulerQueueLease<TMessage>>> LeaseAsync(SchedulerQueueLeaseRequest request, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<IReadOnlyList<ISchedulerQueueLease<TMessage>>>(Array.Empty<ISchedulerQueueLease<TMessage>>());
|
||||
|
||||
public ValueTask<IReadOnlyList<ISchedulerQueueLease<TMessage>>> ClaimExpiredAsync(SchedulerQueueClaimOptions options, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<IReadOnlyList<ISchedulerQueueLease<TMessage>>>(Array.Empty<ISchedulerQueueLease<TMessage>>());
|
||||
|
||||
public ValueTask PingAsync(CancellationToken cancellationToken)
|
||||
=> _failPing
|
||||
? ValueTask.FromException(new InvalidOperationException("ping failed"))
|
||||
: ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class FakePlannerQueue : FakeQueue<PlannerQueueMessage>, ISchedulerPlannerQueue
|
||||
{
|
||||
public FakePlannerQueue(bool failPing) : base(failPing)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeRunnerQueue : FakeQueue<RunnerSegmentQueueMessage>, ISchedulerRunnerQueue
|
||||
{
|
||||
public FakeRunnerQueue(bool failPing) : base(failPing)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Queue;
|
||||
using StellaOps.Scheduler.Queue.Nats;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.Queue.Tests;
|
||||
|
||||
public sealed class SchedulerQueueServiceCollectionExtensionsTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task AddSchedulerQueues_RegistersNatsTransport()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<ILoggerFactory>(_ => NullLoggerFactory.Instance);
|
||||
services.AddSchedulerQueues(new ConfigurationBuilder().Build());
|
||||
|
||||
var optionsDescriptor = services.First(descriptor => descriptor.ServiceType == typeof(SchedulerQueueOptions));
|
||||
var options = (SchedulerQueueOptions)optionsDescriptor.ImplementationInstance!;
|
||||
options.Kind = SchedulerQueueTransportKind.Nats;
|
||||
options.Nats.Url = "nats://localhost:4222";
|
||||
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
|
||||
var plannerQueue = provider.GetRequiredService<ISchedulerPlannerQueue>();
|
||||
var runnerQueue = provider.GetRequiredService<ISchedulerRunnerQueue>();
|
||||
|
||||
plannerQueue.Should().BeOfType<NatsSchedulerPlannerQueue>();
|
||||
runnerQueue.Should().BeOfType<NatsSchedulerRunnerQueue>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SchedulerQueueHealthCheck_ReturnsHealthy_WhenTransportsReachable()
|
||||
{
|
||||
var healthCheck = new SchedulerQueueHealthCheck(
|
||||
new FakePlannerQueue(failPing: false),
|
||||
new FakeRunnerQueue(failPing: false),
|
||||
NullLogger<SchedulerQueueHealthCheck>.Instance);
|
||||
|
||||
var context = new HealthCheckContext
|
||||
{
|
||||
Registration = new HealthCheckRegistration("scheduler-queue", healthCheck, HealthStatus.Unhealthy, Array.Empty<string>())
|
||||
};
|
||||
|
||||
var result = await healthCheck.CheckHealthAsync(context);
|
||||
|
||||
result.Status.Should().Be(HealthStatus.Healthy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SchedulerQueueHealthCheck_ReturnsUnhealthy_WhenRunnerPingFails()
|
||||
{
|
||||
var healthCheck = new SchedulerQueueHealthCheck(
|
||||
new FakePlannerQueue(failPing: false),
|
||||
new FakeRunnerQueue(failPing: true),
|
||||
NullLogger<SchedulerQueueHealthCheck>.Instance);
|
||||
|
||||
var context = new HealthCheckContext
|
||||
{
|
||||
Registration = new HealthCheckRegistration("scheduler-queue", healthCheck, HealthStatus.Unhealthy, Array.Empty<string>())
|
||||
};
|
||||
|
||||
var result = await healthCheck.CheckHealthAsync(context);
|
||||
|
||||
result.Status.Should().Be(HealthStatus.Unhealthy);
|
||||
result.Description.Should().Contain("runner transport unreachable");
|
||||
}
|
||||
private abstract class FakeQueue<TMessage> : ISchedulerQueue<TMessage>, ISchedulerQueueTransportDiagnostics
|
||||
{
|
||||
private readonly bool _failPing;
|
||||
|
||||
protected FakeQueue(bool failPing)
|
||||
{
|
||||
_failPing = failPing;
|
||||
}
|
||||
|
||||
public ValueTask<SchedulerQueueEnqueueResult> EnqueueAsync(TMessage message, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult(new SchedulerQueueEnqueueResult("stub", false));
|
||||
|
||||
public ValueTask<IReadOnlyList<ISchedulerQueueLease<TMessage>>> LeaseAsync(SchedulerQueueLeaseRequest request, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<IReadOnlyList<ISchedulerQueueLease<TMessage>>>(Array.Empty<ISchedulerQueueLease<TMessage>>());
|
||||
|
||||
public ValueTask<IReadOnlyList<ISchedulerQueueLease<TMessage>>> ClaimExpiredAsync(SchedulerQueueClaimOptions options, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult<IReadOnlyList<ISchedulerQueueLease<TMessage>>>(Array.Empty<ISchedulerQueueLease<TMessage>>());
|
||||
|
||||
public ValueTask PingAsync(CancellationToken cancellationToken)
|
||||
=> _failPing
|
||||
? ValueTask.FromException(new InvalidOperationException("ping failed"))
|
||||
: ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class FakePlannerQueue : FakeQueue<PlannerQueueMessage>, ISchedulerPlannerQueue
|
||||
{
|
||||
public FakePlannerQueue(bool failPing) : base(failPing)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeRunnerQueue : FakeQueue<RunnerSegmentQueueMessage>, ISchedulerRunnerQueue
|
||||
{
|
||||
public FakeRunnerQueue(bool failPing) : base(failPing)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,140 +1,140 @@
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.WebService.GraphJobs;
|
||||
using StellaOps.Scheduler.WebService.Options;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class CartographerWebhookClientTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task NotifyAsync_PostsPayload_WhenEnabled()
|
||||
{
|
||||
var handler = new RecordingHandler();
|
||||
var httpClient = new HttpClient(handler);
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions
|
||||
{
|
||||
Webhook =
|
||||
{
|
||||
Enabled = true,
|
||||
Endpoint = "https://cartographer.local/hooks/graph-completed",
|
||||
ApiKeyHeader = "X-Api-Key",
|
||||
ApiKey = "secret"
|
||||
}
|
||||
});
|
||||
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
|
||||
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
|
||||
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom",
|
||||
sbomVersionId: "sbom_v1",
|
||||
sbomDigest: "sha256:" + new string('a', 64),
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphBuildJobTrigger.Backfill,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
graphSnapshotId: "snap",
|
||||
attempts: 1,
|
||||
cartographerJobId: "carto-123",
|
||||
correlationId: "corr-1",
|
||||
startedAt: null,
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
job.TenantId,
|
||||
GraphJobQueryType.Build,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(job),
|
||||
"oras://snap/result",
|
||||
"corr-1",
|
||||
null);
|
||||
|
||||
await client.NotifyAsync(notification, CancellationToken.None);
|
||||
|
||||
Assert.NotNull(handler.LastRequest);
|
||||
Assert.Equal("https://cartographer.local/hooks/graph-completed", handler.LastRequest.RequestUri!.ToString());
|
||||
Assert.True(handler.LastRequest.Headers.TryGetValues("X-Api-Key", out var values) && values!.Single() == "secret");
|
||||
var json = JsonSerializer.Deserialize<JsonElement>(handler.LastPayload!);
|
||||
Assert.Equal("gbj_test", json.GetProperty("jobId").GetString());
|
||||
Assert.Equal("tenant-alpha", json.GetProperty("tenantId").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotifyAsync_Skips_WhenDisabled()
|
||||
{
|
||||
var handler = new RecordingHandler();
|
||||
var httpClient = new HttpClient(handler);
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions());
|
||||
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
|
||||
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
|
||||
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj-test",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "snap",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@1",
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphOverlayJobTrigger.Manual,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
subjects: Array.Empty<string>(),
|
||||
attempts: 1,
|
||||
correlationId: null,
|
||||
startedAt: null,
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
job.TenantId,
|
||||
GraphJobQueryType.Overlay,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(job),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
await client.NotifyAsync(notification, CancellationToken.None);
|
||||
|
||||
Assert.Null(handler.LastRequest);
|
||||
}
|
||||
|
||||
private sealed class RecordingHandler : HttpMessageHandler
|
||||
{
|
||||
public HttpRequestMessage? LastRequest { get; private set; }
|
||||
public string? LastPayload { get; private set; }
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
LastRequest = request;
|
||||
LastPayload = request.Content is null ? null : request.Content.ReadAsStringAsync(cancellationToken).Result;
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class OptionsMonitorStub<T> : IOptionsMonitor<T> where T : class
|
||||
{
|
||||
private readonly IOptions<T> _options;
|
||||
|
||||
public OptionsMonitorStub(IOptions<T> options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
public T CurrentValue => _options.Value;
|
||||
|
||||
public T Get(string? name) => _options.Value;
|
||||
|
||||
public IDisposable? OnChange(Action<T, string?> listener) => null;
|
||||
}
|
||||
}
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.WebService.GraphJobs;
|
||||
using StellaOps.Scheduler.WebService.Options;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class CartographerWebhookClientTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task NotifyAsync_PostsPayload_WhenEnabled()
|
||||
{
|
||||
var handler = new RecordingHandler();
|
||||
var httpClient = new HttpClient(handler);
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions
|
||||
{
|
||||
Webhook =
|
||||
{
|
||||
Enabled = true,
|
||||
Endpoint = "https://cartographer.local/hooks/graph-completed",
|
||||
ApiKeyHeader = "X-Api-Key",
|
||||
ApiKey = "secret"
|
||||
}
|
||||
});
|
||||
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
|
||||
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
|
||||
|
||||
var job = new GraphBuildJob(
|
||||
id: "gbj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom",
|
||||
sbomVersionId: "sbom_v1",
|
||||
sbomDigest: "sha256:" + new string('a', 64),
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphBuildJobTrigger.Backfill,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
graphSnapshotId: "snap",
|
||||
attempts: 1,
|
||||
cartographerJobId: "carto-123",
|
||||
correlationId: "corr-1",
|
||||
startedAt: null,
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
job.TenantId,
|
||||
GraphJobQueryType.Build,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(job),
|
||||
"oras://snap/result",
|
||||
"corr-1",
|
||||
null);
|
||||
|
||||
await client.NotifyAsync(notification, CancellationToken.None);
|
||||
|
||||
Assert.NotNull(handler.LastRequest);
|
||||
Assert.Equal("https://cartographer.local/hooks/graph-completed", handler.LastRequest.RequestUri!.ToString());
|
||||
Assert.True(handler.LastRequest.Headers.TryGetValues("X-Api-Key", out var values) && values!.Single() == "secret");
|
||||
var json = JsonSerializer.Deserialize<JsonElement>(handler.LastPayload!);
|
||||
Assert.Equal("gbj_test", json.GetProperty("jobId").GetString());
|
||||
Assert.Equal("tenant-alpha", json.GetProperty("tenantId").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotifyAsync_Skips_WhenDisabled()
|
||||
{
|
||||
var handler = new RecordingHandler();
|
||||
var httpClient = new HttpClient(handler);
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerCartographerOptions());
|
||||
using var loggerFactory = LoggerFactory.Create(builder => builder.AddDebug());
|
||||
var client = new CartographerWebhookClient(httpClient, new OptionsMonitorStub<SchedulerCartographerOptions>(options), loggerFactory.CreateLogger<CartographerWebhookClient>());
|
||||
|
||||
var job = new GraphOverlayJob(
|
||||
id: "goj-test",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "snap",
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@1",
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphOverlayJobTrigger.Manual,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
subjects: Array.Empty<string>(),
|
||||
attempts: 1,
|
||||
correlationId: null,
|
||||
startedAt: null,
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
job.TenantId,
|
||||
GraphJobQueryType.Overlay,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(job),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
await client.NotifyAsync(notification, CancellationToken.None);
|
||||
|
||||
Assert.Null(handler.LastRequest);
|
||||
}
|
||||
|
||||
private sealed class RecordingHandler : HttpMessageHandler
|
||||
{
|
||||
public HttpRequestMessage? LastRequest { get; private set; }
|
||||
public string? LastPayload { get; private set; }
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
LastRequest = request;
|
||||
LastPayload = request.Content is null ? null : request.Content.ReadAsStringAsync(cancellationToken).Result;
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class OptionsMonitorStub<T> : IOptionsMonitor<T> where T : class
|
||||
{
|
||||
private readonly IOptions<T> _options;
|
||||
|
||||
public OptionsMonitorStub(IOptions<T> options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
public T CurrentValue => _options.Value;
|
||||
|
||||
public T Get(string? name) => _options.Value;
|
||||
|
||||
public IDisposable? OnChange(Action<T, string?> listener) => null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
global using System.Net.Http.Json;
|
||||
global using System.Text.Json;
|
||||
global using System.Text.Json.Serialization;
|
||||
global using System.Threading.Tasks;
|
||||
global using Microsoft.AspNetCore.Mvc.Testing;
|
||||
global using Xunit;
|
||||
global using System.Net.Http.Json;
|
||||
global using System.Text.Json;
|
||||
global using System.Text.Json.Serialization;
|
||||
global using System.Threading.Tasks;
|
||||
global using Microsoft.AspNetCore.Mvc.Testing;
|
||||
global using Xunit;
|
||||
|
||||
@@ -1,110 +1,110 @@
|
||||
using StellaOps.Auth.Abstractions;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class GraphJobEndpointTests : IClassFixture<SchedulerWebApplicationFactory>
|
||||
{
|
||||
private readonly SchedulerWebApplicationFactory _factory;
|
||||
|
||||
public GraphJobEndpointTests(SchedulerWebApplicationFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateGraphBuildJob_RequiresGraphWriteScope()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
|
||||
|
||||
var response = await client.PostAsJsonAsync("/graphs/build", new
|
||||
{
|
||||
sbomId = "sbom-test",
|
||||
sbomVersionId = "sbom-ver",
|
||||
sbomDigest = "sha256:" + new string('a', 64)
|
||||
});
|
||||
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateGraphBuildJob_AndList()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
|
||||
|
||||
var createResponse = await client.PostAsJsonAsync("/graphs/build", new
|
||||
{
|
||||
sbomId = "sbom-alpha",
|
||||
sbomVersionId = "sbom-alpha-v1",
|
||||
sbomDigest = "sha256:" + new string('b', 64),
|
||||
metadata = new { source = "test" }
|
||||
});
|
||||
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
|
||||
var listResponse = await client.GetAsync("/graphs/jobs");
|
||||
listResponse.EnsureSuccessStatusCode();
|
||||
|
||||
var json = await listResponse.Content.ReadAsStringAsync();
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
Assert.True(root.TryGetProperty("jobs", out var jobs));
|
||||
Assert.True(jobs.GetArrayLength() >= 1);
|
||||
var first = jobs[0];
|
||||
Assert.Equal("build", first.GetProperty("kind").GetString());
|
||||
Assert.Equal("tenant-alpha", first.GetProperty("tenantId").GetString());
|
||||
Assert.Equal("pending", first.GetProperty("status").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteOverlayJob_UpdatesStatusAndMetrics()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-bravo");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
|
||||
|
||||
var createOverlay = await client.PostAsJsonAsync("/graphs/overlays", new
|
||||
{
|
||||
graphSnapshotId = "graph_snap_20251026",
|
||||
overlayKind = "policy",
|
||||
overlayKey = "policy@2025-10-01",
|
||||
subjects = new[] { "artifact/service-api" }
|
||||
});
|
||||
|
||||
createOverlay.EnsureSuccessStatusCode();
|
||||
var createdJson = await createOverlay.Content.ReadAsStringAsync();
|
||||
using var createdDoc = JsonDocument.Parse(createdJson);
|
||||
var jobId = createdDoc.RootElement.GetProperty("id").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(jobId));
|
||||
|
||||
var completeResponse = await client.PostAsJsonAsync("/graphs/hooks/completed", new
|
||||
{
|
||||
jobId = jobId,
|
||||
jobType = "Overlay",
|
||||
status = "Completed",
|
||||
occurredAt = DateTimeOffset.UtcNow,
|
||||
correlationId = "corr-123",
|
||||
resultUri = "oras://cartographer/snapshots/graph_snap_20251026"
|
||||
});
|
||||
|
||||
completeResponse.EnsureSuccessStatusCode();
|
||||
var completedJson = await completeResponse.Content.ReadAsStringAsync();
|
||||
using var completedDoc = JsonDocument.Parse(completedJson);
|
||||
Assert.Equal("completed", completedDoc.RootElement.GetProperty("status").GetString());
|
||||
|
||||
var metricsResponse = await client.GetAsync("/graphs/overlays/lag");
|
||||
metricsResponse.EnsureSuccessStatusCode();
|
||||
var metricsJson = await metricsResponse.Content.ReadAsStringAsync();
|
||||
using var metricsDoc = JsonDocument.Parse(metricsJson);
|
||||
var metricsRoot = metricsDoc.RootElement;
|
||||
Assert.Equal("tenant-bravo", metricsRoot.GetProperty("tenantId").GetString());
|
||||
Assert.True(metricsRoot.GetProperty("completed").GetInt32() >= 1);
|
||||
var recent = metricsRoot.GetProperty("recentCompleted");
|
||||
Assert.True(recent.GetArrayLength() >= 1);
|
||||
var entry = recent[0];
|
||||
Assert.Equal(jobId, entry.GetProperty("jobId").GetString());
|
||||
Assert.Equal("corr-123", entry.GetProperty("correlationId").GetString());
|
||||
}
|
||||
}
|
||||
using StellaOps.Auth.Abstractions;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class GraphJobEndpointTests : IClassFixture<SchedulerWebApplicationFactory>
|
||||
{
|
||||
private readonly SchedulerWebApplicationFactory _factory;
|
||||
|
||||
public GraphJobEndpointTests(SchedulerWebApplicationFactory factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateGraphBuildJob_RequiresGraphWriteScope()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
|
||||
|
||||
var response = await client.PostAsJsonAsync("/graphs/build", new
|
||||
{
|
||||
sbomId = "sbom-test",
|
||||
sbomVersionId = "sbom-ver",
|
||||
sbomDigest = "sha256:" + new string('a', 64)
|
||||
});
|
||||
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateGraphBuildJob_AndList()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-alpha");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
|
||||
|
||||
var createResponse = await client.PostAsJsonAsync("/graphs/build", new
|
||||
{
|
||||
sbomId = "sbom-alpha",
|
||||
sbomVersionId = "sbom-alpha-v1",
|
||||
sbomDigest = "sha256:" + new string('b', 64),
|
||||
metadata = new { source = "test" }
|
||||
});
|
||||
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
|
||||
var listResponse = await client.GetAsync("/graphs/jobs");
|
||||
listResponse.EnsureSuccessStatusCode();
|
||||
|
||||
var json = await listResponse.Content.ReadAsStringAsync();
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
Assert.True(root.TryGetProperty("jobs", out var jobs));
|
||||
Assert.True(jobs.GetArrayLength() >= 1);
|
||||
var first = jobs[0];
|
||||
Assert.Equal("build", first.GetProperty("kind").GetString());
|
||||
Assert.Equal("tenant-alpha", first.GetProperty("tenantId").GetString());
|
||||
Assert.Equal("pending", first.GetProperty("status").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteOverlayJob_UpdatesStatusAndMetrics()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-bravo");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", string.Join(' ', StellaOpsScopes.GraphWrite, StellaOpsScopes.GraphRead));
|
||||
|
||||
var createOverlay = await client.PostAsJsonAsync("/graphs/overlays", new
|
||||
{
|
||||
graphSnapshotId = "graph_snap_20251026",
|
||||
overlayKind = "policy",
|
||||
overlayKey = "policy@2025-10-01",
|
||||
subjects = new[] { "artifact/service-api" }
|
||||
});
|
||||
|
||||
createOverlay.EnsureSuccessStatusCode();
|
||||
var createdJson = await createOverlay.Content.ReadAsStringAsync();
|
||||
using var createdDoc = JsonDocument.Parse(createdJson);
|
||||
var jobId = createdDoc.RootElement.GetProperty("id").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(jobId));
|
||||
|
||||
var completeResponse = await client.PostAsJsonAsync("/graphs/hooks/completed", new
|
||||
{
|
||||
jobId = jobId,
|
||||
jobType = "Overlay",
|
||||
status = "Completed",
|
||||
occurredAt = DateTimeOffset.UtcNow,
|
||||
correlationId = "corr-123",
|
||||
resultUri = "oras://cartographer/snapshots/graph_snap_20251026"
|
||||
});
|
||||
|
||||
completeResponse.EnsureSuccessStatusCode();
|
||||
var completedJson = await completeResponse.Content.ReadAsStringAsync();
|
||||
using var completedDoc = JsonDocument.Parse(completedJson);
|
||||
Assert.Equal("completed", completedDoc.RootElement.GetProperty("status").GetString());
|
||||
|
||||
var metricsResponse = await client.GetAsync("/graphs/overlays/lag");
|
||||
metricsResponse.EnsureSuccessStatusCode();
|
||||
var metricsJson = await metricsResponse.Content.ReadAsStringAsync();
|
||||
using var metricsDoc = JsonDocument.Parse(metricsJson);
|
||||
var metricsRoot = metricsDoc.RootElement;
|
||||
Assert.Equal("tenant-bravo", metricsRoot.GetProperty("tenantId").GetString());
|
||||
Assert.True(metricsRoot.GetProperty("completed").GetInt32() >= 1);
|
||||
var recent = metricsRoot.GetProperty("recentCompleted");
|
||||
Assert.True(recent.GetArrayLength() >= 1);
|
||||
var entry = recent[0];
|
||||
Assert.Equal(jobId, entry.GetProperty("jobId").GetString());
|
||||
Assert.Equal("corr-123", entry.GetProperty("correlationId").GetString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,12 @@ using StellaOps.Scheduler.WebService.GraphJobs;
|
||||
using StellaOps.Scheduler.WebService.GraphJobs.Events;
|
||||
using StellaOps.Scheduler.WebService.Options;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class GraphJobEventPublisherTests
|
||||
{
|
||||
[Fact]
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class GraphJobEventPublisherTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task PublishAsync_LogsEvent_WhenDriverUnsupported()
|
||||
{
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerEventsOptions
|
||||
@@ -25,99 +25,99 @@ public sealed class GraphJobEventPublisherTests
|
||||
var loggerProvider = new ListLoggerProvider();
|
||||
using var loggerFactory = LoggerFactory.Create(builder => builder.AddProvider(loggerProvider));
|
||||
var publisher = new GraphJobEventPublisher(new OptionsMonitorStub<SchedulerEventsOptions>(options), new ThrowingRedisConnectionFactory(), loggerFactory.CreateLogger<GraphJobEventPublisher>());
|
||||
|
||||
var buildJob = new GraphBuildJob(
|
||||
id: "gbj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom",
|
||||
sbomVersionId: "sbom_v1",
|
||||
sbomDigest: "sha256:" + new string('a', 64),
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
graphSnapshotId: "graph_snap",
|
||||
attempts: 1,
|
||||
cartographerJobId: "carto",
|
||||
correlationId: "corr",
|
||||
startedAt: DateTimeOffset.UtcNow.AddSeconds(-30),
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
buildJob.TenantId,
|
||||
GraphJobQueryType.Build,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(buildJob),
|
||||
"oras://result",
|
||||
"corr",
|
||||
null);
|
||||
|
||||
await publisher.PublishAsync(notification, CancellationToken.None);
|
||||
|
||||
|
||||
var buildJob = new GraphBuildJob(
|
||||
id: "gbj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom",
|
||||
sbomVersionId: "sbom_v1",
|
||||
sbomDigest: "sha256:" + new string('a', 64),
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
graphSnapshotId: "graph_snap",
|
||||
attempts: 1,
|
||||
cartographerJobId: "carto",
|
||||
correlationId: "corr",
|
||||
startedAt: DateTimeOffset.UtcNow.AddSeconds(-30),
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
buildJob.TenantId,
|
||||
GraphJobQueryType.Build,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(buildJob),
|
||||
"oras://result",
|
||||
"corr",
|
||||
null);
|
||||
|
||||
await publisher.PublishAsync(notification, CancellationToken.None);
|
||||
|
||||
Assert.Contains(loggerProvider.Messages, message => message.Contains("unsupported driver", StringComparison.OrdinalIgnoreCase));
|
||||
var eventPayload = loggerProvider.Messages.FirstOrDefault(message => message.Contains("\"kind\":\"scheduler.graph.job.completed\"", StringComparison.Ordinal));
|
||||
Assert.NotNull(eventPayload);
|
||||
Assert.Contains("\"tenant\":\"tenant-alpha\"", eventPayload);
|
||||
Assert.Contains("\"resultUri\":\"oras://result\"", eventPayload);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PublishAsync_Suppressed_WhenDisabled()
|
||||
{
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new SchedulerEventsOptions());
|
||||
var loggerProvider = new ListLoggerProvider();
|
||||
using var loggerFactory = LoggerFactory.Create(builder => builder.AddProvider(loggerProvider));
|
||||
var publisher = new GraphJobEventPublisher(new OptionsMonitorStub<SchedulerEventsOptions>(options), new ThrowingRedisConnectionFactory(), loggerFactory.CreateLogger<GraphJobEventPublisher>());
|
||||
|
||||
var overlayJob = new GraphOverlayJob(
|
||||
id: "goj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap",
|
||||
buildJobId: null,
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@1",
|
||||
subjects: Array.Empty<string>(),
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
attempts: 1,
|
||||
correlationId: null,
|
||||
startedAt: DateTimeOffset.UtcNow.AddSeconds(-10),
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
overlayJob.TenantId,
|
||||
GraphJobQueryType.Overlay,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(overlayJob),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
await publisher.PublishAsync(notification, CancellationToken.None);
|
||||
|
||||
|
||||
var overlayJob = new GraphOverlayJob(
|
||||
id: "goj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
graphSnapshotId: "graph_snap",
|
||||
buildJobId: null,
|
||||
overlayKind: GraphOverlayKind.Policy,
|
||||
overlayKey: "policy@1",
|
||||
subjects: Array.Empty<string>(),
|
||||
status: GraphJobStatus.Completed,
|
||||
trigger: GraphOverlayJobTrigger.Policy,
|
||||
createdAt: DateTimeOffset.UtcNow,
|
||||
attempts: 1,
|
||||
correlationId: null,
|
||||
startedAt: DateTimeOffset.UtcNow.AddSeconds(-10),
|
||||
completedAt: DateTimeOffset.UtcNow,
|
||||
error: null,
|
||||
metadata: Array.Empty<KeyValuePair<string, string>>());
|
||||
|
||||
var notification = new GraphJobCompletionNotification(
|
||||
overlayJob.TenantId,
|
||||
GraphJobQueryType.Overlay,
|
||||
GraphJobStatus.Completed,
|
||||
DateTimeOffset.UtcNow,
|
||||
GraphJobResponse.From(overlayJob),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
await publisher.PublishAsync(notification, CancellationToken.None);
|
||||
|
||||
Assert.DoesNotContain(loggerProvider.Messages, message => message.Contains(GraphJobEventKinds.GraphJobCompleted, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private sealed class OptionsMonitorStub<T> : IOptionsMonitor<T> where T : class
|
||||
{
|
||||
private readonly IOptions<T> _options;
|
||||
|
||||
public OptionsMonitorStub(IOptions<T> options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
public T CurrentValue => _options.Value;
|
||||
|
||||
public T Get(string? name) => _options.Value;
|
||||
|
||||
public IDisposable? OnChange(Action<T, string?> listener) => null;
|
||||
|
||||
public OptionsMonitorStub(IOptions<T> options)
|
||||
{
|
||||
_options = options;
|
||||
}
|
||||
|
||||
public T CurrentValue => _options.Value;
|
||||
|
||||
public T Get(string? name) => _options.Value;
|
||||
|
||||
public IDisposable? OnChange(Action<T, string?> listener) => null;
|
||||
}
|
||||
|
||||
private sealed class ThrowingRedisConnectionFactory : IRedisConnectionFactory
|
||||
@@ -125,39 +125,39 @@ public sealed class GraphJobEventPublisherTests
|
||||
public Task<IConnectionMultiplexer> ConnectAsync(ConfigurationOptions options, CancellationToken cancellationToken)
|
||||
=> throw new InvalidOperationException("Redis connection should not be established in this test.");
|
||||
}
|
||||
|
||||
private sealed class ListLoggerProvider : ILoggerProvider
|
||||
{
|
||||
private readonly ListLogger _logger = new();
|
||||
|
||||
public IList<string> Messages => _logger.Messages;
|
||||
|
||||
public ILogger CreateLogger(string categoryName) => _logger;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
private sealed class ListLogger : ILogger
|
||||
{
|
||||
public IList<string> Messages { get; } = new List<string>();
|
||||
|
||||
public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullDisposable.Instance;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
Messages.Add(formatter(state, exception));
|
||||
}
|
||||
|
||||
private sealed class NullDisposable : IDisposable
|
||||
{
|
||||
public static readonly NullDisposable Instance = new();
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ListLoggerProvider : ILoggerProvider
|
||||
{
|
||||
private readonly ListLogger _logger = new();
|
||||
|
||||
public IList<string> Messages => _logger.Messages;
|
||||
|
||||
public ILogger CreateLogger(string categoryName) => _logger;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
private sealed class ListLogger : ILogger
|
||||
{
|
||||
public IList<string> Messages { get; } = new List<string>();
|
||||
|
||||
public IDisposable BeginScope<TState>(TState state) where TState : notnull => NullDisposable.Instance;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
Messages.Add(formatter(state, exception));
|
||||
}
|
||||
|
||||
private sealed class NullDisposable : IDisposable
|
||||
{
|
||||
public static readonly NullDisposable Instance = new();
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,218 +1,218 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.WebService.GraphJobs;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class GraphJobServiceTests
|
||||
{
|
||||
private static readonly DateTimeOffset FixedTime = new(2025, 11, 4, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteBuildJob_PersistsMetadataAndPublishesOnce()
|
||||
{
|
||||
var store = new TrackingGraphJobStore();
|
||||
var initial = CreateBuildJob();
|
||||
await store.AddAsync(initial, CancellationToken.None);
|
||||
|
||||
var clock = new FixedClock(FixedTime);
|
||||
var publisher = new RecordingPublisher();
|
||||
var webhook = new RecordingWebhookClient();
|
||||
var service = new GraphJobService(store, clock, publisher, webhook);
|
||||
|
||||
var request = new GraphJobCompletionRequest
|
||||
{
|
||||
JobId = initial.Id,
|
||||
JobType = GraphJobQueryType.Build,
|
||||
Status = GraphJobStatus.Completed,
|
||||
OccurredAt = FixedTime,
|
||||
GraphSnapshotId = "graph_snap_final ",
|
||||
ResultUri = "oras://cartographer/bundle ",
|
||||
CorrelationId = "corr-123 "
|
||||
};
|
||||
|
||||
var response = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
|
||||
|
||||
Assert.Equal(GraphJobStatus.Completed, response.Status);
|
||||
Assert.Equal(1, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
|
||||
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
|
||||
Assert.NotNull(stored);
|
||||
Assert.Equal("graph_snap_final", stored!.GraphSnapshotId);
|
||||
Assert.Equal("corr-123", stored.CorrelationId);
|
||||
Assert.True(stored.Metadata.TryGetValue("resultUri", out var resultUri));
|
||||
Assert.Equal("oras://cartographer/bundle", resultUri);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteBuildJob_IsIdempotentWhenAlreadyCompleted()
|
||||
{
|
||||
var store = new TrackingGraphJobStore();
|
||||
var initial = CreateBuildJob();
|
||||
await store.AddAsync(initial, CancellationToken.None);
|
||||
|
||||
var clock = new FixedClock(FixedTime);
|
||||
var publisher = new RecordingPublisher();
|
||||
var webhook = new RecordingWebhookClient();
|
||||
var service = new GraphJobService(store, clock, publisher, webhook);
|
||||
|
||||
var request = new GraphJobCompletionRequest
|
||||
{
|
||||
JobId = initial.Id,
|
||||
JobType = GraphJobQueryType.Build,
|
||||
Status = GraphJobStatus.Completed,
|
||||
OccurredAt = FixedTime,
|
||||
GraphSnapshotId = "graph_snap_final",
|
||||
ResultUri = "oras://cartographer/bundle",
|
||||
CorrelationId = "corr-123"
|
||||
};
|
||||
|
||||
await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
|
||||
var updateCountAfterFirst = store.BuildUpdateCount;
|
||||
|
||||
var secondResponse = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
|
||||
|
||||
Assert.Equal(GraphJobStatus.Completed, secondResponse.Status);
|
||||
Assert.Equal(updateCountAfterFirst, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteBuildJob_UpdatesResultUriWithoutReemittingEvent()
|
||||
{
|
||||
var store = new TrackingGraphJobStore();
|
||||
var initial = CreateBuildJob();
|
||||
await store.AddAsync(initial, CancellationToken.None);
|
||||
|
||||
var clock = new FixedClock(FixedTime);
|
||||
var publisher = new RecordingPublisher();
|
||||
var webhook = new RecordingWebhookClient();
|
||||
var service = new GraphJobService(store, clock, publisher, webhook);
|
||||
|
||||
var firstRequest = new GraphJobCompletionRequest
|
||||
{
|
||||
JobId = initial.Id,
|
||||
JobType = GraphJobQueryType.Build,
|
||||
Status = GraphJobStatus.Completed,
|
||||
OccurredAt = FixedTime,
|
||||
GraphSnapshotId = "graph_snap_final",
|
||||
ResultUri = null,
|
||||
CorrelationId = "corr-123"
|
||||
};
|
||||
|
||||
await service.CompleteJobAsync(initial.TenantId, firstRequest, CancellationToken.None);
|
||||
Assert.Equal(1, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
|
||||
var secondRequest = firstRequest with
|
||||
{
|
||||
ResultUri = "oras://cartographer/bundle-v2",
|
||||
OccurredAt = FixedTime.AddSeconds(30)
|
||||
};
|
||||
|
||||
var response = await service.CompleteJobAsync(initial.TenantId, secondRequest, CancellationToken.None);
|
||||
|
||||
Assert.Equal(GraphJobStatus.Completed, response.Status);
|
||||
Assert.Equal(2, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
|
||||
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
|
||||
Assert.NotNull(stored);
|
||||
Assert.True(stored!.Metadata.TryGetValue("resultUri", out var resultUri));
|
||||
Assert.Equal("oras://cartographer/bundle-v2", resultUri);
|
||||
}
|
||||
|
||||
private static GraphBuildJob CreateBuildJob()
|
||||
{
|
||||
var digest = "sha256:" + new string('a', 64);
|
||||
return new GraphBuildJob(
|
||||
id: "gbj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom-alpha",
|
||||
sbomVersionId: "sbom-alpha-v1",
|
||||
sbomDigest: digest,
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: FixedTime,
|
||||
metadata: null);
|
||||
}
|
||||
|
||||
private sealed class TrackingGraphJobStore : IGraphJobStore
|
||||
{
|
||||
private readonly InMemoryGraphJobStore _inner = new();
|
||||
|
||||
public int BuildUpdateCount { get; private set; }
|
||||
|
||||
public int OverlayUpdateCount { get; private set; }
|
||||
|
||||
public ValueTask<GraphBuildJob> AddAsync(GraphBuildJob job, CancellationToken cancellationToken)
|
||||
=> _inner.AddAsync(job, cancellationToken);
|
||||
|
||||
public ValueTask<GraphOverlayJob> AddAsync(GraphOverlayJob job, CancellationToken cancellationToken)
|
||||
=> _inner.AddAsync(job, cancellationToken);
|
||||
|
||||
public ValueTask<GraphJobCollection> GetJobsAsync(string tenantId, GraphJobQuery query, CancellationToken cancellationToken)
|
||||
=> _inner.GetJobsAsync(tenantId, query, cancellationToken);
|
||||
|
||||
public ValueTask<GraphBuildJob?> GetBuildJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
|
||||
=> _inner.GetBuildJobAsync(tenantId, jobId, cancellationToken);
|
||||
|
||||
public ValueTask<GraphOverlayJob?> GetOverlayJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
|
||||
=> _inner.GetOverlayJobAsync(tenantId, jobId, cancellationToken);
|
||||
|
||||
public async ValueTask<GraphJobUpdateResult<GraphBuildJob>> UpdateAsync(GraphBuildJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
BuildUpdateCount++;
|
||||
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
|
||||
}
|
||||
|
||||
public async ValueTask<GraphJobUpdateResult<GraphOverlayJob>> UpdateAsync(GraphOverlayJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
OverlayUpdateCount++;
|
||||
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
|
||||
}
|
||||
|
||||
public ValueTask<IReadOnlyCollection<GraphOverlayJob>> GetOverlayJobsAsync(string tenantId, CancellationToken cancellationToken)
|
||||
=> _inner.GetOverlayJobsAsync(tenantId, cancellationToken);
|
||||
}
|
||||
|
||||
private sealed class RecordingPublisher : IGraphJobCompletionPublisher
|
||||
{
|
||||
public List<GraphJobCompletionNotification> Notifications { get; } = new();
|
||||
|
||||
public Task PublishAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
Notifications.Add(notification);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RecordingWebhookClient : ICartographerWebhookClient
|
||||
{
|
||||
public List<GraphJobCompletionNotification> Notifications { get; } = new();
|
||||
|
||||
public Task NotifyAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
Notifications.Add(notification);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FixedClock : ISystemClock
|
||||
{
|
||||
public FixedClock(DateTimeOffset utcNow)
|
||||
{
|
||||
UtcNow = utcNow;
|
||||
}
|
||||
|
||||
public DateTimeOffset UtcNow { get; set; }
|
||||
}
|
||||
}
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.WebService.GraphJobs;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class GraphJobServiceTests
|
||||
{
|
||||
private static readonly DateTimeOffset FixedTime = new(2025, 11, 4, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteBuildJob_PersistsMetadataAndPublishesOnce()
|
||||
{
|
||||
var store = new TrackingGraphJobStore();
|
||||
var initial = CreateBuildJob();
|
||||
await store.AddAsync(initial, CancellationToken.None);
|
||||
|
||||
var clock = new FixedClock(FixedTime);
|
||||
var publisher = new RecordingPublisher();
|
||||
var webhook = new RecordingWebhookClient();
|
||||
var service = new GraphJobService(store, clock, publisher, webhook);
|
||||
|
||||
var request = new GraphJobCompletionRequest
|
||||
{
|
||||
JobId = initial.Id,
|
||||
JobType = GraphJobQueryType.Build,
|
||||
Status = GraphJobStatus.Completed,
|
||||
OccurredAt = FixedTime,
|
||||
GraphSnapshotId = "graph_snap_final ",
|
||||
ResultUri = "oras://cartographer/bundle ",
|
||||
CorrelationId = "corr-123 "
|
||||
};
|
||||
|
||||
var response = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
|
||||
|
||||
Assert.Equal(GraphJobStatus.Completed, response.Status);
|
||||
Assert.Equal(1, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
|
||||
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
|
||||
Assert.NotNull(stored);
|
||||
Assert.Equal("graph_snap_final", stored!.GraphSnapshotId);
|
||||
Assert.Equal("corr-123", stored.CorrelationId);
|
||||
Assert.True(stored.Metadata.TryGetValue("resultUri", out var resultUri));
|
||||
Assert.Equal("oras://cartographer/bundle", resultUri);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteBuildJob_IsIdempotentWhenAlreadyCompleted()
|
||||
{
|
||||
var store = new TrackingGraphJobStore();
|
||||
var initial = CreateBuildJob();
|
||||
await store.AddAsync(initial, CancellationToken.None);
|
||||
|
||||
var clock = new FixedClock(FixedTime);
|
||||
var publisher = new RecordingPublisher();
|
||||
var webhook = new RecordingWebhookClient();
|
||||
var service = new GraphJobService(store, clock, publisher, webhook);
|
||||
|
||||
var request = new GraphJobCompletionRequest
|
||||
{
|
||||
JobId = initial.Id,
|
||||
JobType = GraphJobQueryType.Build,
|
||||
Status = GraphJobStatus.Completed,
|
||||
OccurredAt = FixedTime,
|
||||
GraphSnapshotId = "graph_snap_final",
|
||||
ResultUri = "oras://cartographer/bundle",
|
||||
CorrelationId = "corr-123"
|
||||
};
|
||||
|
||||
await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
|
||||
var updateCountAfterFirst = store.BuildUpdateCount;
|
||||
|
||||
var secondResponse = await service.CompleteJobAsync(initial.TenantId, request, CancellationToken.None);
|
||||
|
||||
Assert.Equal(GraphJobStatus.Completed, secondResponse.Status);
|
||||
Assert.Equal(updateCountAfterFirst, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteBuildJob_UpdatesResultUriWithoutReemittingEvent()
|
||||
{
|
||||
var store = new TrackingGraphJobStore();
|
||||
var initial = CreateBuildJob();
|
||||
await store.AddAsync(initial, CancellationToken.None);
|
||||
|
||||
var clock = new FixedClock(FixedTime);
|
||||
var publisher = new RecordingPublisher();
|
||||
var webhook = new RecordingWebhookClient();
|
||||
var service = new GraphJobService(store, clock, publisher, webhook);
|
||||
|
||||
var firstRequest = new GraphJobCompletionRequest
|
||||
{
|
||||
JobId = initial.Id,
|
||||
JobType = GraphJobQueryType.Build,
|
||||
Status = GraphJobStatus.Completed,
|
||||
OccurredAt = FixedTime,
|
||||
GraphSnapshotId = "graph_snap_final",
|
||||
ResultUri = null,
|
||||
CorrelationId = "corr-123"
|
||||
};
|
||||
|
||||
await service.CompleteJobAsync(initial.TenantId, firstRequest, CancellationToken.None);
|
||||
Assert.Equal(1, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
|
||||
var secondRequest = firstRequest with
|
||||
{
|
||||
ResultUri = "oras://cartographer/bundle-v2",
|
||||
OccurredAt = FixedTime.AddSeconds(30)
|
||||
};
|
||||
|
||||
var response = await service.CompleteJobAsync(initial.TenantId, secondRequest, CancellationToken.None);
|
||||
|
||||
Assert.Equal(GraphJobStatus.Completed, response.Status);
|
||||
Assert.Equal(2, store.BuildUpdateCount);
|
||||
Assert.Single(publisher.Notifications);
|
||||
Assert.Single(webhook.Notifications);
|
||||
|
||||
var stored = await store.GetBuildJobAsync(initial.TenantId, initial.Id, CancellationToken.None);
|
||||
Assert.NotNull(stored);
|
||||
Assert.True(stored!.Metadata.TryGetValue("resultUri", out var resultUri));
|
||||
Assert.Equal("oras://cartographer/bundle-v2", resultUri);
|
||||
}
|
||||
|
||||
private static GraphBuildJob CreateBuildJob()
|
||||
{
|
||||
var digest = "sha256:" + new string('a', 64);
|
||||
return new GraphBuildJob(
|
||||
id: "gbj_test",
|
||||
tenantId: "tenant-alpha",
|
||||
sbomId: "sbom-alpha",
|
||||
sbomVersionId: "sbom-alpha-v1",
|
||||
sbomDigest: digest,
|
||||
status: GraphJobStatus.Pending,
|
||||
trigger: GraphBuildJobTrigger.SbomVersion,
|
||||
createdAt: FixedTime,
|
||||
metadata: null);
|
||||
}
|
||||
|
||||
private sealed class TrackingGraphJobStore : IGraphJobStore
|
||||
{
|
||||
private readonly InMemoryGraphJobStore _inner = new();
|
||||
|
||||
public int BuildUpdateCount { get; private set; }
|
||||
|
||||
public int OverlayUpdateCount { get; private set; }
|
||||
|
||||
public ValueTask<GraphBuildJob> AddAsync(GraphBuildJob job, CancellationToken cancellationToken)
|
||||
=> _inner.AddAsync(job, cancellationToken);
|
||||
|
||||
public ValueTask<GraphOverlayJob> AddAsync(GraphOverlayJob job, CancellationToken cancellationToken)
|
||||
=> _inner.AddAsync(job, cancellationToken);
|
||||
|
||||
public ValueTask<GraphJobCollection> GetJobsAsync(string tenantId, GraphJobQuery query, CancellationToken cancellationToken)
|
||||
=> _inner.GetJobsAsync(tenantId, query, cancellationToken);
|
||||
|
||||
public ValueTask<GraphBuildJob?> GetBuildJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
|
||||
=> _inner.GetBuildJobAsync(tenantId, jobId, cancellationToken);
|
||||
|
||||
public ValueTask<GraphOverlayJob?> GetOverlayJobAsync(string tenantId, string jobId, CancellationToken cancellationToken)
|
||||
=> _inner.GetOverlayJobAsync(tenantId, jobId, cancellationToken);
|
||||
|
||||
public async ValueTask<GraphJobUpdateResult<GraphBuildJob>> UpdateAsync(GraphBuildJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
BuildUpdateCount++;
|
||||
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
|
||||
}
|
||||
|
||||
public async ValueTask<GraphJobUpdateResult<GraphOverlayJob>> UpdateAsync(GraphOverlayJob job, GraphJobStatus expectedStatus, CancellationToken cancellationToken)
|
||||
{
|
||||
OverlayUpdateCount++;
|
||||
return await _inner.UpdateAsync(job, expectedStatus, cancellationToken);
|
||||
}
|
||||
|
||||
public ValueTask<IReadOnlyCollection<GraphOverlayJob>> GetOverlayJobsAsync(string tenantId, CancellationToken cancellationToken)
|
||||
=> _inner.GetOverlayJobsAsync(tenantId, cancellationToken);
|
||||
}
|
||||
|
||||
private sealed class RecordingPublisher : IGraphJobCompletionPublisher
|
||||
{
|
||||
public List<GraphJobCompletionNotification> Notifications { get; } = new();
|
||||
|
||||
public Task PublishAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
Notifications.Add(notification);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RecordingWebhookClient : ICartographerWebhookClient
|
||||
{
|
||||
public List<GraphJobCompletionNotification> Notifications { get; } = new();
|
||||
|
||||
public Task NotifyAsync(GraphJobCompletionNotification notification, CancellationToken cancellationToken)
|
||||
{
|
||||
Notifications.Add(notification);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FixedClock : ISystemClock
|
||||
{
|
||||
public FixedClock(DateTimeOffset utcNow)
|
||||
{
|
||||
UtcNow = utcNow;
|
||||
}
|
||||
|
||||
public DateTimeOffset UtcNow { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,71 +1,71 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class PolicyRunEndpointTests : IClassFixture<WebApplicationFactory<Program>>
|
||||
{
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public PolicyRunEndpointTests(WebApplicationFactory<Program> factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateListGetPolicyRun()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", "policy:run");
|
||||
|
||||
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/policy/runs", new
|
||||
{
|
||||
policyId = "P-7",
|
||||
policyVersion = 4,
|
||||
mode = "incremental",
|
||||
priority = "normal",
|
||||
metadata = new { source = "cli" },
|
||||
inputs = new
|
||||
{
|
||||
sbomSet = new[] { "sbom:S-42", "sbom:S-99" },
|
||||
advisoryCursor = "2025-10-26T13:59:00+00:00",
|
||||
vexCursor = "2025-10-26T13:58:30+00:00",
|
||||
environment = new { @sealed = false, exposure = "internet" },
|
||||
captureExplain = true
|
||||
}
|
||||
});
|
||||
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
Assert.Equal(System.Net.HttpStatusCode.Created, createResponse.StatusCode);
|
||||
|
||||
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var runJson = created.GetProperty("run");
|
||||
var runId = runJson.GetProperty("runId").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(runId));
|
||||
Assert.Equal("queued", runJson.GetProperty("status").GetString());
|
||||
Assert.Equal("P-7", runJson.GetProperty("policyId").GetString());
|
||||
Assert.True(runJson.GetProperty("inputs").GetProperty("captureExplain").GetBoolean());
|
||||
|
||||
var listResponse = await client.GetAsync("/api/v1/scheduler/policy/runs?policyId=P-7");
|
||||
listResponse.EnsureSuccessStatusCode();
|
||||
var list = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var runsArray = list.GetProperty("runs");
|
||||
Assert.True(runsArray.GetArrayLength() >= 1);
|
||||
|
||||
var getResponse = await client.GetAsync($"/api/v1/scheduler/policy/runs/{runId}");
|
||||
getResponse.EnsureSuccessStatusCode();
|
||||
var retrieved = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.Equal(runId, retrieved.GetProperty("run").GetProperty("runId").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MissingScopeReturnsForbidden()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
|
||||
|
||||
var response = await client.GetAsync("/api/v1/scheduler/policy/runs");
|
||||
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
}
|
||||
using System.Text.Json;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class PolicyRunEndpointTests : IClassFixture<WebApplicationFactory<Program>>
|
||||
{
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public PolicyRunEndpointTests(WebApplicationFactory<Program> factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateListGetPolicyRun()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", "policy:run");
|
||||
|
||||
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/policy/runs", new
|
||||
{
|
||||
policyId = "P-7",
|
||||
policyVersion = 4,
|
||||
mode = "incremental",
|
||||
priority = "normal",
|
||||
metadata = new { source = "cli" },
|
||||
inputs = new
|
||||
{
|
||||
sbomSet = new[] { "sbom:S-42", "sbom:S-99" },
|
||||
advisoryCursor = "2025-10-26T13:59:00+00:00",
|
||||
vexCursor = "2025-10-26T13:58:30+00:00",
|
||||
environment = new { @sealed = false, exposure = "internet" },
|
||||
captureExplain = true
|
||||
}
|
||||
});
|
||||
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
Assert.Equal(System.Net.HttpStatusCode.Created, createResponse.StatusCode);
|
||||
|
||||
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var runJson = created.GetProperty("run");
|
||||
var runId = runJson.GetProperty("runId").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(runId));
|
||||
Assert.Equal("queued", runJson.GetProperty("status").GetString());
|
||||
Assert.Equal("P-7", runJson.GetProperty("policyId").GetString());
|
||||
Assert.True(runJson.GetProperty("inputs").GetProperty("captureExplain").GetBoolean());
|
||||
|
||||
var listResponse = await client.GetAsync("/api/v1/scheduler/policy/runs?policyId=P-7");
|
||||
listResponse.EnsureSuccessStatusCode();
|
||||
var list = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var runsArray = list.GetProperty("runs");
|
||||
Assert.True(runsArray.GetArrayLength() >= 1);
|
||||
|
||||
var getResponse = await client.GetAsync($"/api/v1/scheduler/policy/runs/{runId}");
|
||||
getResponse.EnsureSuccessStatusCode();
|
||||
var retrieved = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.Equal(runId, retrieved.GetProperty("run").GetProperty("runId").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MissingScopeReturnsForbidden()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-policy");
|
||||
|
||||
var response = await client.GetAsync("/api/v1/scheduler/policy/runs");
|
||||
|
||||
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,7 @@ using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Mongo2Go;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using StellaOps.Scheduler.WebService.PolicySimulations;
|
||||
using System.Collections.Generic;
|
||||
@@ -273,41 +271,6 @@ public sealed class PolicySimulationEndpointTests : IClassFixture<WebApplication
|
||||
Assert.True(seenHeartbeat, "Heartbeat event was not observed.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MongoBackedCreateSimulationPersists()
|
||||
{
|
||||
using var runner = MongoDbRunner.Start(additionalMongodArguments: "--quiet");
|
||||
await using var factory = _factory.WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureAppConfiguration((_, configuration) =>
|
||||
{
|
||||
configuration.AddInMemoryCollection(new[]
|
||||
{
|
||||
new KeyValuePair<string, string?>("Scheduler:Storage:ConnectionString", runner.ConnectionString),
|
||||
new KeyValuePair<string, string?>("Scheduler:Storage:Database", $"scheduler_web_tests_{Guid.NewGuid():N}")
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
using var client = factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-sim-mongo");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", "policy:simulate");
|
||||
|
||||
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/policies/simulations", new
|
||||
{
|
||||
policyId = "policy-mongo",
|
||||
policyVersion = 11
|
||||
});
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
var runId = (await createResponse.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("simulation").GetProperty("runId").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(runId));
|
||||
|
||||
var fetched = await client.GetAsync($"/api/v1/scheduler/policies/simulations/{runId}");
|
||||
fetched.EnsureSuccessStatusCode();
|
||||
var payload = await fetched.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.Equal(runId, payload.GetProperty("simulation").GetProperty("runId").GetString());
|
||||
}
|
||||
|
||||
private sealed class StubPolicySimulationMetricsProvider : IPolicySimulationMetricsProvider, IPolicySimulationMetricsRecorder
|
||||
{
|
||||
public PolicySimulationMetricsResponse Response { get; set; } = new(
|
||||
|
||||
@@ -6,7 +6,6 @@ using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Storage.Postgres.Repositories;
|
||||
using StellaOps.Scheduler.WebService.PolicySimulations;
|
||||
@@ -250,7 +249,6 @@ public sealed class PolicySimulationMetricsProviderTests
|
||||
|
||||
public Task InsertAsync(
|
||||
PolicyRunJob job,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Jobs.Add(job);
|
||||
@@ -287,7 +285,6 @@ public sealed class PolicySimulationMetricsProviderTests
|
||||
IReadOnlyCollection<PolicyRunJobStatus>? statuses = null,
|
||||
DateTimeOffset? queuedAfter = null,
|
||||
int limit = 50,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
IEnumerable<PolicyRunJob> query = Jobs;
|
||||
@@ -309,14 +306,12 @@ public sealed class PolicySimulationMetricsProviderTests
|
||||
public Task<PolicyRunJob?> GetAsync(
|
||||
string tenantId,
|
||||
string jobId,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(Jobs.FirstOrDefault(job => job.Id == jobId));
|
||||
|
||||
public Task<PolicyRunJob?> GetByRunIdAsync(
|
||||
string tenantId,
|
||||
string runId,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(Jobs.FirstOrDefault(job => string.Equals(job.RunId, runId, StringComparison.Ordinal)));
|
||||
|
||||
@@ -325,14 +320,12 @@ public sealed class PolicySimulationMetricsProviderTests
|
||||
DateTimeOffset now,
|
||||
TimeSpan leaseDuration,
|
||||
int maxAttempts,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(null);
|
||||
|
||||
public Task<bool> ReplaceAsync(
|
||||
PolicyRunJob job,
|
||||
string? expectedLeaseOwner = null,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult(true);
|
||||
}
|
||||
|
||||
@@ -1,88 +1,88 @@
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class ScheduleEndpointTests : IClassFixture<WebApplicationFactory<Program>>
|
||||
{
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public ScheduleEndpointTests(WebApplicationFactory<Program> factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateListAndRetrieveSchedule()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-schedules");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
|
||||
|
||||
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
|
||||
{
|
||||
name = "Nightly",
|
||||
cronExpression = "0 2 * * *",
|
||||
timezone = "UTC",
|
||||
mode = "analysis-only",
|
||||
selection = new
|
||||
{
|
||||
scope = "all-images"
|
||||
},
|
||||
notify = new
|
||||
{
|
||||
onNewFindings = true,
|
||||
minSeverity = "medium",
|
||||
includeKev = true
|
||||
}
|
||||
});
|
||||
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(scheduleId));
|
||||
|
||||
var listResponse = await client.GetAsync("/api/v1/scheduler/schedules");
|
||||
listResponse.EnsureSuccessStatusCode();
|
||||
var listJson = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var schedules = listJson.GetProperty("schedules");
|
||||
Assert.True(schedules.GetArrayLength() >= 1);
|
||||
|
||||
var getResponse = await client.GetAsync($"/api/v1/scheduler/schedules/{scheduleId}");
|
||||
getResponse.EnsureSuccessStatusCode();
|
||||
var scheduleJson = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.Equal("Nightly", scheduleJson.GetProperty("schedule").GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PauseAndResumeSchedule()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-controls");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
|
||||
|
||||
var create = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
|
||||
{
|
||||
name = "PauseResume",
|
||||
cronExpression = "*/5 * * * *",
|
||||
timezone = "UTC",
|
||||
mode = "analysis-only",
|
||||
selection = new
|
||||
{
|
||||
scope = "all-images"
|
||||
}
|
||||
});
|
||||
|
||||
create.EnsureSuccessStatusCode();
|
||||
var created = await create.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(scheduleId));
|
||||
|
||||
var pauseResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/pause", null);
|
||||
pauseResponse.EnsureSuccessStatusCode();
|
||||
var paused = await pauseResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.False(paused.GetProperty("schedule").GetProperty("enabled").GetBoolean());
|
||||
|
||||
var resumeResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/resume", null);
|
||||
resumeResponse.EnsureSuccessStatusCode();
|
||||
var resumed = await resumeResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.True(resumed.GetProperty("schedule").GetProperty("enabled").GetBoolean());
|
||||
}
|
||||
}
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public sealed class ScheduleEndpointTests : IClassFixture<WebApplicationFactory<Program>>
|
||||
{
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public ScheduleEndpointTests(WebApplicationFactory<Program> factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateListAndRetrieveSchedule()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-schedules");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
|
||||
|
||||
var createResponse = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
|
||||
{
|
||||
name = "Nightly",
|
||||
cronExpression = "0 2 * * *",
|
||||
timezone = "UTC",
|
||||
mode = "analysis-only",
|
||||
selection = new
|
||||
{
|
||||
scope = "all-images"
|
||||
},
|
||||
notify = new
|
||||
{
|
||||
onNewFindings = true,
|
||||
minSeverity = "medium",
|
||||
includeKev = true
|
||||
}
|
||||
});
|
||||
|
||||
createResponse.EnsureSuccessStatusCode();
|
||||
var created = await createResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(scheduleId));
|
||||
|
||||
var listResponse = await client.GetAsync("/api/v1/scheduler/schedules");
|
||||
listResponse.EnsureSuccessStatusCode();
|
||||
var listJson = await listResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var schedules = listJson.GetProperty("schedules");
|
||||
Assert.True(schedules.GetArrayLength() >= 1);
|
||||
|
||||
var getResponse = await client.GetAsync($"/api/v1/scheduler/schedules/{scheduleId}");
|
||||
getResponse.EnsureSuccessStatusCode();
|
||||
var scheduleJson = await getResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.Equal("Nightly", scheduleJson.GetProperty("schedule").GetProperty("name").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PauseAndResumeSchedule()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("X-Tenant-Id", "tenant-controls");
|
||||
client.DefaultRequestHeaders.Add("X-Scopes", "scheduler.schedules.write scheduler.schedules.read");
|
||||
|
||||
var create = await client.PostAsJsonAsync("/api/v1/scheduler/schedules", new
|
||||
{
|
||||
name = "PauseResume",
|
||||
cronExpression = "*/5 * * * *",
|
||||
timezone = "UTC",
|
||||
mode = "analysis-only",
|
||||
selection = new
|
||||
{
|
||||
scope = "all-images"
|
||||
}
|
||||
});
|
||||
|
||||
create.EnsureSuccessStatusCode();
|
||||
var created = await create.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var scheduleId = created.GetProperty("schedule").GetProperty("id").GetString();
|
||||
Assert.False(string.IsNullOrEmpty(scheduleId));
|
||||
|
||||
var pauseResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/pause", null);
|
||||
pauseResponse.EnsureSuccessStatusCode();
|
||||
var paused = await pauseResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.False(paused.GetProperty("schedule").GetProperty("enabled").GetBoolean());
|
||||
|
||||
var resumeResponse = await client.PostAsync($"/api/v1/scheduler/schedules/{scheduleId}/resume", null);
|
||||
resumeResponse.EnsureSuccessStatusCode();
|
||||
var resumed = await resumeResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
Assert.True(resumed.GetProperty("schedule").GetProperty("enabled").GetBoolean());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,73 +1,73 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using StellaOps.Plugin.Hosting;
|
||||
using StellaOps.Scheduler.WebService.Hosting;
|
||||
using StellaOps.Scheduler.WebService.Options;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public class SchedulerPluginHostFactoryTests
|
||||
{
|
||||
[Fact]
|
||||
public void Build_usesDefaults_whenOptionsEmpty()
|
||||
{
|
||||
var options = new SchedulerOptions.PluginOptions();
|
||||
var contentRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(contentRoot);
|
||||
|
||||
try
|
||||
{
|
||||
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRoot);
|
||||
|
||||
var expectedBase = Path.GetFullPath(Path.Combine(contentRoot, ".."));
|
||||
var expectedPlugins = Path.Combine(expectedBase, "plugins", "scheduler");
|
||||
|
||||
Assert.Equal(expectedBase, hostOptions.BaseDirectory);
|
||||
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
|
||||
Assert.Single(hostOptions.SearchPatterns, "StellaOps.Scheduler.Plugin.*.dll");
|
||||
Assert.True(hostOptions.EnsureDirectoryExists);
|
||||
Assert.False(hostOptions.RecursiveSearch);
|
||||
Assert.Empty(hostOptions.PluginOrder);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(contentRoot, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_respectsConfiguredValues()
|
||||
{
|
||||
var options = new SchedulerOptions.PluginOptions
|
||||
{
|
||||
BaseDirectory = Path.Combine(Path.GetTempPath(), "scheduler-options", Guid.NewGuid().ToString("N")),
|
||||
Directory = Path.Combine("custom", "plugins"),
|
||||
RecursiveSearch = true,
|
||||
EnsureDirectoryExists = false
|
||||
};
|
||||
|
||||
options.SearchPatterns.Add("Custom.Plugin.*.dll");
|
||||
options.OrderedPlugins.Add("StellaOps.Scheduler.Plugin.Alpha");
|
||||
|
||||
Directory.CreateDirectory(options.BaseDirectory!);
|
||||
|
||||
try
|
||||
{
|
||||
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRootPath: Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")));
|
||||
|
||||
var expectedPlugins = Path.GetFullPath(Path.Combine(options.BaseDirectory!, options.Directory!));
|
||||
|
||||
Assert.Equal(options.BaseDirectory, hostOptions.BaseDirectory);
|
||||
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
|
||||
Assert.Single(hostOptions.SearchPatterns, "Custom.Plugin.*.dll");
|
||||
Assert.Single(hostOptions.PluginOrder, "StellaOps.Scheduler.Plugin.Alpha");
|
||||
Assert.True(hostOptions.RecursiveSearch);
|
||||
Assert.False(hostOptions.EnsureDirectoryExists);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(options.BaseDirectory!, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.IO;
|
||||
using StellaOps.Plugin.Hosting;
|
||||
using StellaOps.Scheduler.WebService.Hosting;
|
||||
using StellaOps.Scheduler.WebService.Options;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.WebService.Tests;
|
||||
|
||||
public class SchedulerPluginHostFactoryTests
|
||||
{
|
||||
[Fact]
|
||||
public void Build_usesDefaults_whenOptionsEmpty()
|
||||
{
|
||||
var options = new SchedulerOptions.PluginOptions();
|
||||
var contentRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(contentRoot);
|
||||
|
||||
try
|
||||
{
|
||||
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRoot);
|
||||
|
||||
var expectedBase = Path.GetFullPath(Path.Combine(contentRoot, ".."));
|
||||
var expectedPlugins = Path.Combine(expectedBase, "plugins", "scheduler");
|
||||
|
||||
Assert.Equal(expectedBase, hostOptions.BaseDirectory);
|
||||
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
|
||||
Assert.Single(hostOptions.SearchPatterns, "StellaOps.Scheduler.Plugin.*.dll");
|
||||
Assert.True(hostOptions.EnsureDirectoryExists);
|
||||
Assert.False(hostOptions.RecursiveSearch);
|
||||
Assert.Empty(hostOptions.PluginOrder);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(contentRoot, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_respectsConfiguredValues()
|
||||
{
|
||||
var options = new SchedulerOptions.PluginOptions
|
||||
{
|
||||
BaseDirectory = Path.Combine(Path.GetTempPath(), "scheduler-options", Guid.NewGuid().ToString("N")),
|
||||
Directory = Path.Combine("custom", "plugins"),
|
||||
RecursiveSearch = true,
|
||||
EnsureDirectoryExists = false
|
||||
};
|
||||
|
||||
options.SearchPatterns.Add("Custom.Plugin.*.dll");
|
||||
options.OrderedPlugins.Add("StellaOps.Scheduler.Plugin.Alpha");
|
||||
|
||||
Directory.CreateDirectory(options.BaseDirectory!);
|
||||
|
||||
try
|
||||
{
|
||||
var hostOptions = SchedulerPluginHostFactory.Build(options, contentRootPath: Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")));
|
||||
|
||||
var expectedPlugins = Path.GetFullPath(Path.Combine(options.BaseDirectory!, options.Directory!));
|
||||
|
||||
Assert.Equal(options.BaseDirectory, hostOptions.BaseDirectory);
|
||||
Assert.Equal(expectedPlugins, hostOptions.PluginsDirectory);
|
||||
Assert.Single(hostOptions.SearchPatterns, "Custom.Plugin.*.dll");
|
||||
Assert.Single(hostOptions.PluginOrder, "StellaOps.Scheduler.Plugin.Alpha");
|
||||
Assert.True(hostOptions.RecursiveSearch);
|
||||
Assert.False(hostOptions.EnsureDirectoryExists);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(options.BaseDirectory!, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
<UseConcelierTestInfra>false</UseConcelierTestInfra>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Mongo2Go" Version="4.1.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.0" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
global using System.Collections.Immutable;
|
||||
global using StellaOps.Scheduler.ImpactIndex;
|
||||
global using StellaOps.Scheduler.Models;
|
||||
global using StellaOps.Scheduler.Worker;
|
||||
global using Xunit;
|
||||
global using System.Collections.Immutable;
|
||||
global using StellaOps.Scheduler.ImpactIndex;
|
||||
global using StellaOps.Scheduler.Models;
|
||||
global using StellaOps.Scheduler.Worker;
|
||||
global using Xunit;
|
||||
|
||||
@@ -4,7 +4,6 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Scheduler.Queue;
|
||||
using StellaOps.Scheduler.Storage.Postgres.Repositories.Projections;
|
||||
using StellaOps.Scheduler.Storage.Postgres.Repositories;
|
||||
@@ -212,23 +211,23 @@ public sealed class PlannerBackgroundServiceTests
|
||||
|
||||
public IReadOnlyList<Run> UpdatedRuns => _updates.ToArray();
|
||||
|
||||
public Task InsertAsync(Run run, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task InsertAsync(Run run, CancellationToken cancellationToken = default)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
public Task<bool> UpdateAsync(Run run, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<bool> UpdateAsync(Run run, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_updates.Enqueue(run);
|
||||
Interlocked.Increment(ref _updateCount);
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task<Run?> GetAsync(string tenantId, string runId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<Run?> GetAsync(string tenantId, string runId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<Run?>(null);
|
||||
|
||||
public Task<IReadOnlyList<Run>> ListAsync(string tenantId, RunQueryOptions? options = null, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Run>> ListAsync(string tenantId, RunQueryOptions? options = null, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<Run>>(Array.Empty<Run>());
|
||||
|
||||
public Task<IReadOnlyList<Run>> ListByStateAsync(RunState state, int limit = 50, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Run>> ListByStateAsync(RunState state, int limit = 50, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (state != RunState.Planning)
|
||||
{
|
||||
@@ -266,25 +265,25 @@ public sealed class PlannerBackgroundServiceTests
|
||||
|
||||
private readonly Dictionary<(string TenantId, string ScheduleId), Schedule> _schedules;
|
||||
|
||||
public Task UpsertAsync(Schedule schedule, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task UpsertAsync(Schedule schedule, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_schedules[(schedule.TenantId, schedule.Id)] = schedule;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<Schedule?> GetAsync(string tenantId, string scheduleId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<Schedule?> GetAsync(string tenantId, string scheduleId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_schedules.TryGetValue((tenantId, scheduleId), out var schedule);
|
||||
return Task.FromResult(schedule);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<Schedule>> ListAsync(string tenantId, ScheduleQueryOptions? options = null, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Schedule>> ListAsync(string tenantId, ScheduleQueryOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var results = _schedules.Values.Where(schedule => schedule.TenantId == tenantId).ToArray();
|
||||
return Task.FromResult<IReadOnlyList<Schedule>>(results);
|
||||
}
|
||||
|
||||
public Task<bool> SoftDeleteAsync(string tenantId, string scheduleId, string deletedBy, DateTimeOffset deletedAt, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<bool> SoftDeleteAsync(string tenantId, string scheduleId, string deletedBy, DateTimeOffset deletedAt, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var removed = _schedules.Remove((tenantId, scheduleId));
|
||||
return Task.FromResult(removed);
|
||||
@@ -295,16 +294,16 @@ public sealed class PlannerBackgroundServiceTests
|
||||
{
|
||||
public ImpactSet? LastSnapshot { get; private set; }
|
||||
|
||||
public Task UpsertAsync(ImpactSet snapshot, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task UpsertAsync(ImpactSet snapshot, CancellationToken cancellationToken = default)
|
||||
{
|
||||
LastSnapshot = snapshot;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<ImpactSet?> GetBySnapshotIdAsync(string snapshotId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<ImpactSet?> GetBySnapshotIdAsync(string snapshotId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<ImpactSet?>(null);
|
||||
|
||||
public Task<ImpactSet?> GetLatestBySelectorAsync(Selector selector, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<ImpactSet?> GetLatestBySelectorAsync(Selector selector, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<ImpactSet?>(null);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using MongoDB.Driver;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Queue;
|
||||
@@ -187,22 +186,22 @@ public sealed class PlannerExecutionServiceTests
|
||||
_store = schedules.ToDictionary(schedule => (schedule.TenantId, schedule.Id), schedule => schedule);
|
||||
}
|
||||
|
||||
public Task UpsertAsync(Schedule schedule, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task UpsertAsync(Schedule schedule, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_store[(schedule.TenantId, schedule.Id)] = schedule;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<Schedule?> GetAsync(string tenantId, string scheduleId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<Schedule?> GetAsync(string tenantId, string scheduleId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_store.TryGetValue((tenantId, scheduleId), out var schedule);
|
||||
return Task.FromResult(schedule);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<Schedule>> ListAsync(string tenantId, ScheduleQueryOptions? options = null, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Schedule>> ListAsync(string tenantId, ScheduleQueryOptions? options = null, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<Schedule>>(_store.Values.Where(schedule => schedule.TenantId == tenantId).ToArray());
|
||||
|
||||
public Task<bool> SoftDeleteAsync(string tenantId, string scheduleId, string deletedBy, DateTimeOffset deletedAt, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<bool> SoftDeleteAsync(string tenantId, string scheduleId, string deletedBy, DateTimeOffset deletedAt, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult(_store.Remove((tenantId, scheduleId)));
|
||||
}
|
||||
|
||||
@@ -218,28 +217,28 @@ public sealed class PlannerExecutionServiceTests
|
||||
}
|
||||
}
|
||||
|
||||
public Task InsertAsync(Run run, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task InsertAsync(Run run, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_runs[(run.TenantId, run.Id)] = run;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> UpdateAsync(Run run, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<bool> UpdateAsync(Run run, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_runs[(run.TenantId, run.Id)] = run;
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task<Run?> GetAsync(string tenantId, string runId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<Run?> GetAsync(string tenantId, string runId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_runs.TryGetValue((tenantId, runId), out var run);
|
||||
return Task.FromResult(run);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<Run>> ListAsync(string tenantId, RunQueryOptions? options = null, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Run>> ListAsync(string tenantId, RunQueryOptions? options = null, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<Run>>(_runs.Values.Where(run => run.TenantId == tenantId).ToArray());
|
||||
|
||||
public Task<IReadOnlyList<Run>> ListByStateAsync(RunState state, int limit = 50, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Run>> ListByStateAsync(RunState state, int limit = 50, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<Run>>(_runs.Values.Where(run => run.State == state).Take(limit).ToArray());
|
||||
}
|
||||
|
||||
@@ -247,16 +246,16 @@ public sealed class PlannerExecutionServiceTests
|
||||
{
|
||||
public ImpactSet? LastSnapshot { get; private set; }
|
||||
|
||||
public Task UpsertAsync(ImpactSet snapshot, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task UpsertAsync(ImpactSet snapshot, CancellationToken cancellationToken = default)
|
||||
{
|
||||
LastSnapshot = snapshot;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<ImpactSet?> GetBySnapshotIdAsync(string snapshotId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<ImpactSet?> GetBySnapshotIdAsync(string snapshotId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<ImpactSet?>(null);
|
||||
|
||||
public Task<ImpactSet?> GetLatestBySelectorAsync(Selector selector, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<ImpactSet?> GetLatestBySelectorAsync(Selector selector, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<ImpactSet?>(null);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MongoDB.Driver;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Scheduler.Models;
|
||||
@@ -67,13 +66,13 @@ public sealed class PolicyRunDispatchBackgroundServiceTests
|
||||
|
||||
public int LeaseAttempts => Volatile.Read(ref _leaseAttempts);
|
||||
|
||||
public Task InsertAsync(PolicyRunJob job, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task InsertAsync(PolicyRunJob job, CancellationToken cancellationToken = default)
|
||||
=> Task.CompletedTask;
|
||||
|
||||
public Task<PolicyRunJob?> GetAsync(string tenantId, string jobId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<PolicyRunJob?> GetAsync(string tenantId, string jobId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(null);
|
||||
|
||||
public Task<PolicyRunJob?> GetByRunIdAsync(string tenantId, string runId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<PolicyRunJob?> GetByRunIdAsync(string tenantId, string runId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(null);
|
||||
|
||||
public Task<PolicyRunJob?> LeaseAsync(
|
||||
@@ -81,7 +80,6 @@ public sealed class PolicyRunDispatchBackgroundServiceTests
|
||||
DateTimeOffset now,
|
||||
TimeSpan leaseDuration,
|
||||
int maxAttempts,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Interlocked.Increment(ref _leaseAttempts);
|
||||
@@ -95,14 +93,12 @@ public sealed class PolicyRunDispatchBackgroundServiceTests
|
||||
IReadOnlyCollection<PolicyRunJobStatus>? statuses = null,
|
||||
DateTimeOffset? queuedAfter = null,
|
||||
int limit = 50,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<PolicyRunJob>>(Array.Empty<PolicyRunJob>());
|
||||
|
||||
public Task<bool> ReplaceAsync(
|
||||
PolicyRunJob job,
|
||||
string? expectedLeaseOwner = null,
|
||||
IClientSessionHandle? session = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult(true);
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Storage.Postgres.Repositories;
|
||||
using StellaOps.Scheduler.Worker.Options;
|
||||
@@ -310,13 +309,13 @@ public sealed class PolicyRunExecutionServiceTests
|
||||
public string? ExpectedLeaseOwner { get; private set; }
|
||||
public PolicyRunJob? LastJob { get; private set; }
|
||||
|
||||
public Task<PolicyRunJob?> GetAsync(string tenantId, string jobId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<PolicyRunJob?> GetAsync(string tenantId, string jobId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(null);
|
||||
|
||||
public Task<PolicyRunJob?> GetByRunIdAsync(string tenantId, string runId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<PolicyRunJob?> GetByRunIdAsync(string tenantId, string runId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(null);
|
||||
|
||||
public Task InsertAsync(PolicyRunJob job, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task InsertAsync(PolicyRunJob job, CancellationToken cancellationToken = default)
|
||||
{
|
||||
LastJob = job;
|
||||
return Task.CompletedTask;
|
||||
@@ -325,10 +324,10 @@ public sealed class PolicyRunExecutionServiceTests
|
||||
public Task<long> CountAsync(string tenantId, PolicyRunMode mode, IReadOnlyCollection<PolicyRunJobStatus> statuses, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult(0L);
|
||||
|
||||
public Task<PolicyRunJob?> LeaseAsync(string leaseOwner, DateTimeOffset now, TimeSpan leaseDuration, int maxAttempts, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<PolicyRunJob?> LeaseAsync(string leaseOwner, DateTimeOffset now, TimeSpan leaseDuration, int maxAttempts, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<PolicyRunJob?>(null);
|
||||
|
||||
public Task<bool> ReplaceAsync(PolicyRunJob job, string? expectedLeaseOwner = null, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<bool> ReplaceAsync(PolicyRunJob job, string? expectedLeaseOwner = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ReplaceCalled = true;
|
||||
ExpectedLeaseOwner = expectedLeaseOwner;
|
||||
@@ -336,7 +335,7 @@ public sealed class PolicyRunExecutionServiceTests
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<PolicyRunJob>> ListAsync(string tenantId, string? policyId = null, PolicyRunMode? mode = null, IReadOnlyCollection<PolicyRunJobStatus>? statuses = null, DateTimeOffset? queuedAfter = null, int limit = 50, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<PolicyRunJob>> ListAsync(string tenantId, string? policyId = null, PolicyRunMode? mode = null, IReadOnlyCollection<PolicyRunJobStatus>? statuses = null, DateTimeOffset? queuedAfter = null, int limit = 50, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<PolicyRunJob>>(Array.Empty<PolicyRunJob>());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,255 +1,255 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Worker;
|
||||
using StellaOps.Scheduler.Worker.Options;
|
||||
using StellaOps.Scheduler.Worker.Policy;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.Worker.Tests;
|
||||
|
||||
public sealed class PolicyRunTargetingServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_ReturnsUnchanged_ForNonIncrementalJob()
|
||||
{
|
||||
var service = CreateService();
|
||||
var job = CreateJob(mode: PolicyRunMode.Full);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Unchanged, result.Status);
|
||||
Assert.Equal(job, result.Job);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_ReturnsUnchanged_WhenSbomSetAlreadyPresent()
|
||||
{
|
||||
var service = CreateService();
|
||||
var inputs = new PolicyRunInputs(sbomSet: new[] { "sbom:S-1" });
|
||||
var job = CreateJob(inputs: inputs);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Unchanged, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_ReturnsNoWork_WhenNoCandidatesResolved()
|
||||
{
|
||||
var impact = new StubImpactTargetingService();
|
||||
var service = CreateService(impact);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.purls", "pkg:npm/leftpad");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.NoWork, result.Status);
|
||||
Assert.Equal("no_matches", result.Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_TargetsDirectSboms()
|
||||
{
|
||||
var service = CreateService();
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.sboms", "sbom:S-2, sbom:S-1, sbom:S-2");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Targeted, result.Status);
|
||||
Assert.Equal(new[] { "sbom:S-1", "sbom:S-2" }, result.Job.Inputs.SbomSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_TargetsUsingImpactIndex()
|
||||
{
|
||||
var impact = new StubImpactTargetingService
|
||||
{
|
||||
OnResolveByPurls = (keys, usageOnly, selector, _) =>
|
||||
{
|
||||
var image = new ImpactImage(
|
||||
"sha256:111",
|
||||
"registry",
|
||||
"repo",
|
||||
labels: ImmutableSortedDictionary.Create<string, string>(StringComparer.Ordinal).Add("sbomId", "sbom:S-42"));
|
||||
var impactSet = new ImpactSet(
|
||||
selector,
|
||||
new[] { image },
|
||||
usageOnly,
|
||||
DateTimeOffset.UtcNow,
|
||||
total: 1,
|
||||
snapshotId: null,
|
||||
schemaVersion: SchedulerSchemaVersions.ImpactSet);
|
||||
return ValueTask.FromResult(impactSet);
|
||||
}
|
||||
};
|
||||
|
||||
var service = CreateService(impact);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.purls", "pkg:npm/example");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Targeted, result.Status);
|
||||
Assert.Equal(new[] { "sbom:S-42" }, result.Job.Inputs.SbomSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_FallsBack_WhenLimitExceeded()
|
||||
{
|
||||
var service = CreateService(configure: options => options.MaxSboms = 1);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.sboms", "sbom:S-1,sbom:S-2");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Unchanged, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_FallbacksToDigest_WhenLabelMissing()
|
||||
{
|
||||
var impact = new StubImpactTargetingService
|
||||
{
|
||||
OnResolveByVulnerabilities = (ids, usageOnly, selector, _) =>
|
||||
{
|
||||
var image = new ImpactImage("sha256:aaa", "registry", "repo");
|
||||
var impactSet = new ImpactSet(
|
||||
selector,
|
||||
new[] { image },
|
||||
usageOnly,
|
||||
DateTimeOffset.UtcNow,
|
||||
total: 1,
|
||||
snapshotId: null,
|
||||
schemaVersion: SchedulerSchemaVersions.ImpactSet);
|
||||
return ValueTask.FromResult(impactSet);
|
||||
}
|
||||
};
|
||||
|
||||
var service = CreateService(impact);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.vulns", "CVE-2025-1234");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Targeted, result.Status);
|
||||
Assert.Equal(new[] { "sbom:sha256:aaa" }, result.Job.Inputs.SbomSet);
|
||||
}
|
||||
|
||||
private static PolicyRunTargetingService CreateService(
|
||||
IImpactTargetingService? impact = null,
|
||||
Action<SchedulerWorkerOptions.PolicyOptions.TargetingOptions>? configure = null)
|
||||
{
|
||||
impact ??= new StubImpactTargetingService();
|
||||
var options = CreateOptions(configure);
|
||||
return new PolicyRunTargetingService(
|
||||
impact,
|
||||
Microsoft.Extensions.Options.Options.Create(options),
|
||||
timeProvider: null,
|
||||
NullLogger<PolicyRunTargetingService>.Instance);
|
||||
}
|
||||
|
||||
private static SchedulerWorkerOptions CreateOptions(Action<SchedulerWorkerOptions.PolicyOptions.TargetingOptions>? configure)
|
||||
{
|
||||
var options = new SchedulerWorkerOptions
|
||||
{
|
||||
Policy =
|
||||
{
|
||||
Api =
|
||||
{
|
||||
BaseAddress = new Uri("https://policy.example.com"),
|
||||
RunsPath = "/runs",
|
||||
SimulatePath = "/simulate"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
configure?.Invoke(options.Policy.Targeting);
|
||||
return options;
|
||||
}
|
||||
|
||||
private static PolicyRunJob CreateJob(
|
||||
PolicyRunMode mode = PolicyRunMode.Incremental,
|
||||
ImmutableSortedDictionary<string, string>? metadata = null,
|
||||
PolicyRunInputs? inputs = null)
|
||||
{
|
||||
return new PolicyRunJob(
|
||||
SchemaVersion: SchedulerSchemaVersions.PolicyRunJob,
|
||||
Id: "job-1",
|
||||
TenantId: "tenant-alpha",
|
||||
PolicyId: "P-7",
|
||||
PolicyVersion: 4,
|
||||
Mode: mode,
|
||||
Priority: PolicyRunPriority.Normal,
|
||||
PriorityRank: 0,
|
||||
RunId: null,
|
||||
RequestedBy: null,
|
||||
CorrelationId: null,
|
||||
Metadata: metadata ?? ImmutableSortedDictionary<string, string>.Empty,
|
||||
Inputs: inputs ?? PolicyRunInputs.Empty,
|
||||
QueuedAt: DateTimeOffset.UtcNow,
|
||||
Status: PolicyRunJobStatus.Dispatching,
|
||||
AttemptCount: 0,
|
||||
LastAttemptAt: null,
|
||||
LastError: null,
|
||||
CreatedAt: DateTimeOffset.UtcNow,
|
||||
UpdatedAt: DateTimeOffset.UtcNow,
|
||||
AvailableAt: DateTimeOffset.UtcNow,
|
||||
SubmittedAt: null,
|
||||
CompletedAt: null,
|
||||
LeaseOwner: "lease",
|
||||
LeaseExpiresAt: DateTimeOffset.UtcNow.AddMinutes(1),
|
||||
CancellationRequested: false,
|
||||
CancellationRequestedAt: null,
|
||||
CancellationReason: null,
|
||||
CancelledAt: null);
|
||||
}
|
||||
|
||||
private sealed class StubImpactTargetingService : IImpactTargetingService
|
||||
{
|
||||
public Func<IEnumerable<string>, bool, Selector, CancellationToken, ValueTask<ImpactSet>>? OnResolveByPurls { get; set; }
|
||||
|
||||
public Func<IEnumerable<string>, bool, Selector, CancellationToken, ValueTask<ImpactSet>>? OnResolveByVulnerabilities { get; set; }
|
||||
|
||||
public ValueTask<ImpactSet> ResolveByPurlsAsync(IEnumerable<string> productKeys, bool usageOnly, Selector selector, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (OnResolveByPurls is null)
|
||||
{
|
||||
return ValueTask.FromResult(CreateEmptyImpactSet(selector, usageOnly));
|
||||
}
|
||||
|
||||
return OnResolveByPurls(productKeys, usageOnly, selector, cancellationToken);
|
||||
}
|
||||
|
||||
public ValueTask<ImpactSet> ResolveByVulnerabilitiesAsync(IEnumerable<string> vulnerabilityIds, bool usageOnly, Selector selector, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (OnResolveByVulnerabilities is null)
|
||||
{
|
||||
return ValueTask.FromResult(CreateEmptyImpactSet(selector, usageOnly));
|
||||
}
|
||||
|
||||
return OnResolveByVulnerabilities(vulnerabilityIds, usageOnly, selector, cancellationToken);
|
||||
}
|
||||
|
||||
public ValueTask<ImpactSet> ResolveAllAsync(Selector selector, bool usageOnly, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult(CreateEmptyImpactSet(selector, usageOnly));
|
||||
|
||||
private static ImpactSet CreateEmptyImpactSet(Selector selector, bool usageOnly)
|
||||
{
|
||||
return new ImpactSet(
|
||||
selector,
|
||||
ImmutableArray<ImpactImage>.Empty,
|
||||
usageOnly,
|
||||
DateTimeOffset.UtcNow,
|
||||
total: 0,
|
||||
snapshotId: null,
|
||||
schemaVersion: SchedulerSchemaVersions.ImpactSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Worker;
|
||||
using StellaOps.Scheduler.Worker.Options;
|
||||
using StellaOps.Scheduler.Worker.Policy;
|
||||
using Xunit;
|
||||
|
||||
namespace StellaOps.Scheduler.Worker.Tests;
|
||||
|
||||
public sealed class PolicyRunTargetingServiceTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_ReturnsUnchanged_ForNonIncrementalJob()
|
||||
{
|
||||
var service = CreateService();
|
||||
var job = CreateJob(mode: PolicyRunMode.Full);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Unchanged, result.Status);
|
||||
Assert.Equal(job, result.Job);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_ReturnsUnchanged_WhenSbomSetAlreadyPresent()
|
||||
{
|
||||
var service = CreateService();
|
||||
var inputs = new PolicyRunInputs(sbomSet: new[] { "sbom:S-1" });
|
||||
var job = CreateJob(inputs: inputs);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Unchanged, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_ReturnsNoWork_WhenNoCandidatesResolved()
|
||||
{
|
||||
var impact = new StubImpactTargetingService();
|
||||
var service = CreateService(impact);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.purls", "pkg:npm/leftpad");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.NoWork, result.Status);
|
||||
Assert.Equal("no_matches", result.Reason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_TargetsDirectSboms()
|
||||
{
|
||||
var service = CreateService();
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.sboms", "sbom:S-2, sbom:S-1, sbom:S-2");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Targeted, result.Status);
|
||||
Assert.Equal(new[] { "sbom:S-1", "sbom:S-2" }, result.Job.Inputs.SbomSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_TargetsUsingImpactIndex()
|
||||
{
|
||||
var impact = new StubImpactTargetingService
|
||||
{
|
||||
OnResolveByPurls = (keys, usageOnly, selector, _) =>
|
||||
{
|
||||
var image = new ImpactImage(
|
||||
"sha256:111",
|
||||
"registry",
|
||||
"repo",
|
||||
labels: ImmutableSortedDictionary.Create<string, string>(StringComparer.Ordinal).Add("sbomId", "sbom:S-42"));
|
||||
var impactSet = new ImpactSet(
|
||||
selector,
|
||||
new[] { image },
|
||||
usageOnly,
|
||||
DateTimeOffset.UtcNow,
|
||||
total: 1,
|
||||
snapshotId: null,
|
||||
schemaVersion: SchedulerSchemaVersions.ImpactSet);
|
||||
return ValueTask.FromResult(impactSet);
|
||||
}
|
||||
};
|
||||
|
||||
var service = CreateService(impact);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.purls", "pkg:npm/example");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Targeted, result.Status);
|
||||
Assert.Equal(new[] { "sbom:S-42" }, result.Job.Inputs.SbomSet);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_FallsBack_WhenLimitExceeded()
|
||||
{
|
||||
var service = CreateService(configure: options => options.MaxSboms = 1);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.sboms", "sbom:S-1,sbom:S-2");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Unchanged, result.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EnsureTargetsAsync_FallbacksToDigest_WhenLabelMissing()
|
||||
{
|
||||
var impact = new StubImpactTargetingService
|
||||
{
|
||||
OnResolveByVulnerabilities = (ids, usageOnly, selector, _) =>
|
||||
{
|
||||
var image = new ImpactImage("sha256:aaa", "registry", "repo");
|
||||
var impactSet = new ImpactSet(
|
||||
selector,
|
||||
new[] { image },
|
||||
usageOnly,
|
||||
DateTimeOffset.UtcNow,
|
||||
total: 1,
|
||||
snapshotId: null,
|
||||
schemaVersion: SchedulerSchemaVersions.ImpactSet);
|
||||
return ValueTask.FromResult(impactSet);
|
||||
}
|
||||
};
|
||||
|
||||
var service = CreateService(impact);
|
||||
var metadata = ImmutableSortedDictionary<string, string>.Empty.Add("delta.vulns", "CVE-2025-1234");
|
||||
var job = CreateJob(metadata: metadata, inputs: PolicyRunInputs.Empty);
|
||||
|
||||
var result = await service.EnsureTargetsAsync(job, CancellationToken.None);
|
||||
|
||||
Assert.Equal(PolicyRunTargetingStatus.Targeted, result.Status);
|
||||
Assert.Equal(new[] { "sbom:sha256:aaa" }, result.Job.Inputs.SbomSet);
|
||||
}
|
||||
|
||||
private static PolicyRunTargetingService CreateService(
|
||||
IImpactTargetingService? impact = null,
|
||||
Action<SchedulerWorkerOptions.PolicyOptions.TargetingOptions>? configure = null)
|
||||
{
|
||||
impact ??= new StubImpactTargetingService();
|
||||
var options = CreateOptions(configure);
|
||||
return new PolicyRunTargetingService(
|
||||
impact,
|
||||
Microsoft.Extensions.Options.Options.Create(options),
|
||||
timeProvider: null,
|
||||
NullLogger<PolicyRunTargetingService>.Instance);
|
||||
}
|
||||
|
||||
private static SchedulerWorkerOptions CreateOptions(Action<SchedulerWorkerOptions.PolicyOptions.TargetingOptions>? configure)
|
||||
{
|
||||
var options = new SchedulerWorkerOptions
|
||||
{
|
||||
Policy =
|
||||
{
|
||||
Api =
|
||||
{
|
||||
BaseAddress = new Uri("https://policy.example.com"),
|
||||
RunsPath = "/runs",
|
||||
SimulatePath = "/simulate"
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
configure?.Invoke(options.Policy.Targeting);
|
||||
return options;
|
||||
}
|
||||
|
||||
private static PolicyRunJob CreateJob(
|
||||
PolicyRunMode mode = PolicyRunMode.Incremental,
|
||||
ImmutableSortedDictionary<string, string>? metadata = null,
|
||||
PolicyRunInputs? inputs = null)
|
||||
{
|
||||
return new PolicyRunJob(
|
||||
SchemaVersion: SchedulerSchemaVersions.PolicyRunJob,
|
||||
Id: "job-1",
|
||||
TenantId: "tenant-alpha",
|
||||
PolicyId: "P-7",
|
||||
PolicyVersion: 4,
|
||||
Mode: mode,
|
||||
Priority: PolicyRunPriority.Normal,
|
||||
PriorityRank: 0,
|
||||
RunId: null,
|
||||
RequestedBy: null,
|
||||
CorrelationId: null,
|
||||
Metadata: metadata ?? ImmutableSortedDictionary<string, string>.Empty,
|
||||
Inputs: inputs ?? PolicyRunInputs.Empty,
|
||||
QueuedAt: DateTimeOffset.UtcNow,
|
||||
Status: PolicyRunJobStatus.Dispatching,
|
||||
AttemptCount: 0,
|
||||
LastAttemptAt: null,
|
||||
LastError: null,
|
||||
CreatedAt: DateTimeOffset.UtcNow,
|
||||
UpdatedAt: DateTimeOffset.UtcNow,
|
||||
AvailableAt: DateTimeOffset.UtcNow,
|
||||
SubmittedAt: null,
|
||||
CompletedAt: null,
|
||||
LeaseOwner: "lease",
|
||||
LeaseExpiresAt: DateTimeOffset.UtcNow.AddMinutes(1),
|
||||
CancellationRequested: false,
|
||||
CancellationRequestedAt: null,
|
||||
CancellationReason: null,
|
||||
CancelledAt: null);
|
||||
}
|
||||
|
||||
private sealed class StubImpactTargetingService : IImpactTargetingService
|
||||
{
|
||||
public Func<IEnumerable<string>, bool, Selector, CancellationToken, ValueTask<ImpactSet>>? OnResolveByPurls { get; set; }
|
||||
|
||||
public Func<IEnumerable<string>, bool, Selector, CancellationToken, ValueTask<ImpactSet>>? OnResolveByVulnerabilities { get; set; }
|
||||
|
||||
public ValueTask<ImpactSet> ResolveByPurlsAsync(IEnumerable<string> productKeys, bool usageOnly, Selector selector, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (OnResolveByPurls is null)
|
||||
{
|
||||
return ValueTask.FromResult(CreateEmptyImpactSet(selector, usageOnly));
|
||||
}
|
||||
|
||||
return OnResolveByPurls(productKeys, usageOnly, selector, cancellationToken);
|
||||
}
|
||||
|
||||
public ValueTask<ImpactSet> ResolveByVulnerabilitiesAsync(IEnumerable<string> vulnerabilityIds, bool usageOnly, Selector selector, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (OnResolveByVulnerabilities is null)
|
||||
{
|
||||
return ValueTask.FromResult(CreateEmptyImpactSet(selector, usageOnly));
|
||||
}
|
||||
|
||||
return OnResolveByVulnerabilities(vulnerabilityIds, usageOnly, selector, cancellationToken);
|
||||
}
|
||||
|
||||
public ValueTask<ImpactSet> ResolveAllAsync(Selector selector, bool usageOnly, CancellationToken cancellationToken = default)
|
||||
=> ValueTask.FromResult(CreateEmptyImpactSet(selector, usageOnly));
|
||||
|
||||
private static ImpactSet CreateEmptyImpactSet(Selector selector, bool usageOnly)
|
||||
{
|
||||
return new ImpactSet(
|
||||
selector,
|
||||
ImmutableArray<ImpactImage>.Empty,
|
||||
usageOnly,
|
||||
DateTimeOffset.UtcNow,
|
||||
total: 0,
|
||||
snapshotId: null,
|
||||
schemaVersion: SchedulerSchemaVersions.ImpactSet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using MongoDB.Driver;
|
||||
using StellaOps.Scheduler.Models;
|
||||
using StellaOps.Scheduler.Queue;
|
||||
using StellaOps.Scheduler.Storage.Postgres.Repositories;
|
||||
@@ -205,28 +204,28 @@ public sealed class RunnerExecutionServiceTests
|
||||
}
|
||||
}
|
||||
|
||||
public Task InsertAsync(Run run, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task InsertAsync(Run run, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_runs[(run.TenantId, run.Id)] = run;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task<bool> UpdateAsync(Run run, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<bool> UpdateAsync(Run run, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_runs[(run.TenantId, run.Id)] = run;
|
||||
return Task.FromResult(true);
|
||||
}
|
||||
|
||||
public Task<Run?> GetAsync(string tenantId, string runId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<Run?> GetAsync(string tenantId, string runId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
_runs.TryGetValue((tenantId, runId), out var run);
|
||||
return Task.FromResult(run);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<Run>> ListAsync(string tenantId, RunQueryOptions? options = null, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Run>> ListAsync(string tenantId, RunQueryOptions? options = null, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<Run>>(_runs.Values.Where(run => run.TenantId == tenantId).ToArray());
|
||||
|
||||
public Task<IReadOnlyList<Run>> ListByStateAsync(RunState state, int limit = 50, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<IReadOnlyList<Run>> ListByStateAsync(RunState state, int limit = 50, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<IReadOnlyList<Run>>(_runs.Values.Where(run => run.State == state).Take(limit).ToArray());
|
||||
|
||||
public Run? GetSnapshot(string tenantId, string runId)
|
||||
@@ -253,13 +252,13 @@ public sealed class RunnerExecutionServiceTests
|
||||
total: imageArray.Length);
|
||||
}
|
||||
|
||||
public Task UpsertAsync(ImpactSet snapshot, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task UpsertAsync(ImpactSet snapshot, CancellationToken cancellationToken = default)
|
||||
=> Task.CompletedTask;
|
||||
|
||||
public Task<ImpactSet?> GetBySnapshotIdAsync(string snapshotId, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<ImpactSet?> GetBySnapshotIdAsync(string snapshotId, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<ImpactSet?>(string.Equals(snapshotId, _snapshotId, StringComparison.Ordinal) ? _snapshot : null);
|
||||
|
||||
public Task<ImpactSet?> GetLatestBySelectorAsync(Selector selector, IClientSessionHandle? session = null, CancellationToken cancellationToken = default)
|
||||
public Task<ImpactSet?> GetLatestBySelectorAsync(Selector selector, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult<ImpactSet?>(_snapshot);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user