feat: host tls data service and route node and cluster connections
This commit is contained in:
+23
@@ -0,0 +1,23 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataScopeArtifactTests
|
||||
{
|
||||
[Fact]
|
||||
public void Empty_scope_artifact_carries_its_authoritative_revision()
|
||||
{
|
||||
var artifact = ConfigComposer.Compose(new DraftSnapshot { GenerationId = 0, ClusterId = "", DataConnectionScopeVersion = 42 });
|
||||
using var input = new MemoryStream(artifact.Blob);
|
||||
using var gzip = new GZipStream(input, CompressionMode.Decompress);
|
||||
using var json = JsonDocument.Parse(gzip);
|
||||
json.RootElement.GetProperty("DataConnectionScopeVersion").GetInt64().ShouldBe(42);
|
||||
json.RootElement.GetProperty("DataConnections").GetArrayLength().ShouldBe(0);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using Akka.Actor;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.EntityFrameworkCore.Storage;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataScopeSealingTests : ControlPlaneActorTestBase
|
||||
{
|
||||
[Fact]
|
||||
public void Failed_save_does_not_dispatch_or_consume_version_and_retry_seals_matching_artifact()
|
||||
{
|
||||
var root = new InMemoryDatabaseRoot(); var name = Guid.NewGuid().ToString("N");
|
||||
var fault = new FailFirstSave(); var factory = new Factory(name, root, fault);
|
||||
var coordinator = CreateTestProbe();
|
||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Array.Empty<IDriverProbe>()));
|
||||
actor.Tell(new StartDeployment("test", CorrelationId.NewId()));
|
||||
var failed = ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
failed.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
||||
coordinator.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken);
|
||||
using (var db = factory.CreateDbContext())
|
||||
{
|
||||
db.Deployments.Count().ShouldBe(0);
|
||||
db.DataConnectionScopeStates.Count().ShouldBe(0);
|
||||
}
|
||||
actor.Tell(new StartDeployment("test", CorrelationId.NewId()));
|
||||
var accepted = ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
accepted.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, accepted.Message);
|
||||
coordinator.ExpectMsg<DispatchDeployment>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
using var verify = factory.CreateDbContext();
|
||||
var state = verify.DataConnectionScopeStates.Single();
|
||||
state.ScopeVersion.ShouldBe(1);
|
||||
var deployment = verify.Deployments.Single();
|
||||
using var stream = new GZipStream(new MemoryStream(deployment.ArtifactBlob), CompressionMode.Decompress);
|
||||
using var json = JsonDocument.Parse(stream);
|
||||
json.RootElement.GetProperty("DataConnectionScopeVersion").GetInt64().ShouldBe(state.ScopeVersion);
|
||||
deployment.Status.ShouldBe(DeploymentStatus.Dispatching);
|
||||
}
|
||||
[Fact]
|
||||
public void Unchanged_empty_scope_reseals_same_version_and_hash()
|
||||
{
|
||||
var factory = NewInMemoryDbFactory(); var coordinator = CreateTestProbe();
|
||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, coordinator.Ref, Array.Empty<IDriverProbe>()));
|
||||
actor.Tell(new StartDeployment("test", CorrelationId.NewId()));
|
||||
var first = ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
first.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, first.Message);
|
||||
coordinator.ExpectMsg<DispatchDeployment>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
string firstHash;
|
||||
using (var db = factory.CreateDbContext())
|
||||
{
|
||||
db.DataConnectionScopeStates.Single().ScopeVersion.ShouldBe(1);
|
||||
var deployment = db.Deployments.Single(); firstHash = deployment.RevisionHash;
|
||||
deployment.Status = DeploymentStatus.Sealed; db.SaveChanges();
|
||||
}
|
||||
actor.Tell(new StartDeployment("test", CorrelationId.NewId()));
|
||||
var second = ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
second.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, second.Message);
|
||||
coordinator.ExpectMsg<DispatchDeployment>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
using var verify = factory.CreateDbContext();
|
||||
verify.DataConnectionScopeStates.Single().ScopeVersion.ShouldBe(1);
|
||||
verify.Deployments.Select(x => x.RevisionHash).ToArray().ShouldAllBe(x => x == firstHash);
|
||||
}
|
||||
private sealed class FailFirstSave : SaveChangesInterceptor
|
||||
{
|
||||
private int _failed;
|
||||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _failed, 1) == 0) throw new InvalidOperationException("injected failure");
|
||||
return base.SavingChangesAsync(eventData, result, cancellationToken);
|
||||
}
|
||||
}
|
||||
private sealed class Factory(string name, InMemoryDatabaseRoot root, IInterceptor interceptor) : IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
public OtOpcUaConfigDbContext CreateDbContext() => new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
|
||||
.UseInMemoryDatabase(name, root).AddInterceptors(interceptor).Options);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
using System.Text.Json;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataBundleLifecycleTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Missing_file_is_not_revocation_and_restarted_loader_replays_completed_bundle()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var directory = Directory.CreateTempSubdirectory("data-bundle-");
|
||||
try
|
||||
{
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node");
|
||||
await new DataConnectionScopeActivator(p, trust).SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
var credentials = Path.Combine(directory.FullName, "credentials.json"); var trustFile = Path.Combine(directory.FullName, "trust.json");
|
||||
await File.WriteAllTextAsync(credentials, JsonSerializer.Serialize(new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "bearer", false)], 1)), ct);
|
||||
await File.WriteAllTextAsync(trustFile, JsonSerializer.Serialize(new DataConnectionTrustBundle("pair", "node", 1, [new("c", 1, [])])), ct);
|
||||
var loader = new DataConnectionBundleLoader(p, trust, "pair", "node");
|
||||
var first = await loader.ApplyFilesAsync(credentials, trustFile, ct);
|
||||
first.CredentialsLoaded.ShouldBeTrue(); first.TrustLoaded.ShouldBeTrue();
|
||||
var restarted = new DataConnectionBundleLoader(p, trust, "PAIR", "NODE");
|
||||
var replay = await restarted.ApplyFilesAsync(credentials, trustFile, ct);
|
||||
replay.CredentialsLoaded.ShouldBeTrue(); replay.TrustLoaded.ShouldBeTrue();
|
||||
File.Delete(credentials);
|
||||
var absent = await restarted.ApplyFilesAsync(credentials, trustFile, ct);
|
||||
absent.CredentialsLoaded.ShouldBeFalse();
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("bearer");
|
||||
}
|
||||
finally { directory.Delete(true); }
|
||||
}
|
||||
[Fact]
|
||||
public async Task Invalid_trust_batch_is_not_partially_applied_and_transient_failure_retries()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var directory = Directory.CreateTempSubdirectory("data-bundle-");
|
||||
try
|
||||
{
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node");
|
||||
await new DataConnectionScopeActivator(p, trust).SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
var path = Path.Combine(directory.FullName, "trust.json"); var loader = new DataConnectionBundleLoader(p, trust, "pair", "node");
|
||||
await File.WriteAllTextAsync(path, JsonSerializer.Serialize(new DataConnectionTrustBundle("pair", "node", 1, [new("c", 1, []), new("unauthorized", 1, [])])), ct);
|
||||
(await loader.ApplyFilesAsync(null, path, ct)).TrustLoaded.ShouldBeFalse();
|
||||
await trust.SetAsync("c", 1, [], 1, ct); // failed batch did not commit its first entry
|
||||
await File.WriteAllTextAsync(path, JsonSerializer.Serialize(new DataConnectionTrustBundle("wrong", "node", 1, [new("c", 2, [])])), ct);
|
||||
(await loader.ApplyFilesAsync(null, path, ct)).TrustLoaded.ShouldBeFalse();
|
||||
await File.WriteAllTextAsync(path, JsonSerializer.Serialize(new DataConnectionTrustBundle("pair", "node", 1, [new("c", 2, [])])), ct);
|
||||
(await loader.ApplyFilesAsync(null, path, ct)).TrustLoaded.ShouldBeTrue();
|
||||
}
|
||||
finally { directory.Delete(true); }
|
||||
}
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P07")]
|
||||
public class GrpcDataCredentialRetirementTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Removal_persists_scope_and_stale_bundle_cannot_resurrect_after_restart()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node");
|
||||
await provisioner.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
var bundle = new DataConnectionCredentialBundle("cluster", "node", 1, [new("c", "secret:data/key", "value", false)], ScopeVersion: 1);
|
||||
await provisioner.ApplyAsync(bundle, ct);
|
||||
await provisioner.SetScopeAsync(2, new Dictionary<string, string>(), ct);
|
||||
var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => restarted.ApplyAsync(bundle, ct));
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "cluster", "node").ResolveAsync("c", ct)).ShouldBeNull();
|
||||
}
|
||||
[Fact]
|
||||
public async Task Shared_reference_is_retained_until_last_scope_is_removed()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["a"] = "secret:data/key", ["b"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("a", "secret:data/key", "secret", false)], ScopeVersion: 1), ct);
|
||||
await p.SetScopeAsync(2, new Dictionary<string, string> { ["b"] = "secret:data/key" }, ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("b", ct))!.Value.ShouldBe("secret");
|
||||
await p.SetScopeAsync(3, new Dictionary<string, string>(), ct);
|
||||
store.Rows.ContainsKey("data/key").ShouldBeFalse();
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.SetScopeAsync(2, new Dictionary<string, string>(), ct));
|
||||
}
|
||||
[Fact]
|
||||
public async Task Reintroducing_scope_does_not_reactivate_a_previously_retired_reference()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
var scope = new Dictionary<string, string> { ["c"] = "secret:data/key" };
|
||||
await p.SetScopeAsync(1, scope, ct);
|
||||
var old = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1);
|
||||
await p.ApplyAsync(old, ct);
|
||||
var staleRow = store.Rows["data/key"];
|
||||
await p.SetScopeAsync(2, new Dictionary<string, string>(), ct);
|
||||
// A stale replicated row or failed external deletion must not bypass the tombstone.
|
||||
store.Rows["data/key"] = staleRow;
|
||||
await p.SetScopeAsync(3, scope, ct);
|
||||
await p.SetScopeAsync(3, scope, ct); // unchanged applied artifact can be replayed on restart
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.SetScopeAsync(3, new Dictionary<string, string>(), ct));
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull();
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.ApplyAsync(old, ct));
|
||||
await p.ApplyAsync(new("pair", "node", 2, [new("c", "secret:data/key", "new", false)], ScopeVersion: 3), ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("new");
|
||||
}
|
||||
[Fact]
|
||||
public async Task Failed_deletion_is_retried_after_restart_with_same_scope_version()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "secret", false)], ScopeVersion: 1), ct);
|
||||
store.FailDelete = true;
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.SetScopeAsync(2, new Dictionary<string, string>(), ct));
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull();
|
||||
store.FailDelete = false;
|
||||
var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await restarted.SetScopeAsync(2, new Dictionary<string, string>(), ct);
|
||||
store.Rows.ContainsKey("data/key").ShouldBeFalse();
|
||||
}
|
||||
[Fact]
|
||||
public void A_throwing_retirement_observer_does_not_prevent_other_observers_from_draining()
|
||||
{
|
||||
var changes = new DataConnectionSecretChangeHandler(); var observed = new List<string>();
|
||||
changes.ConnectionChanged += _ => throw new InvalidOperationException("broken observer");
|
||||
changes.ConnectionChanged += observed.Add;
|
||||
Should.Throw<AggregateException>(() => changes.NotifyConnectionChanged("c"));
|
||||
observed.ShouldBe(["c"]);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Failed_scope_notification_is_retried_on_same_version()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
var calls = 0; Action<string> observer = _ => { calls++; if (calls == 1) throw new InvalidOperationException(); };
|
||||
changes.ConnectionChanged += observer;
|
||||
await Should.ThrowAsync<AggregateException>(() => p.SetScopeAsync(2, new Dictionary<string, string>(), ct));
|
||||
await p.SetScopeAsync(2, new Dictionary<string, string>(), ct);
|
||||
calls.ShouldBe(2);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Scope_generation_allows_reference_churn_without_stale_bundle_resurrection()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
var old = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1);
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(old, ct);
|
||||
for (var i = 0; i < DataConnectionSecretProvisioner.MaximumReferences + 1; i++)
|
||||
{
|
||||
var generation = 2L + i; var reference = "secret:data/churn" + i;
|
||||
await p.SetScopeAsync(generation, new Dictionary<string, string> { ["c"] = reference }, ct);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("c", reference, "value", false)], ScopeVersion: generation), ct);
|
||||
}
|
||||
var latest = 3L + DataConnectionSecretProvisioner.MaximumReferences;
|
||||
await p.SetScopeAsync(latest, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.ApplyAsync(old with { Version = 999 }, ct));
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "new", false)], ScopeVersion: latest), ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("new");
|
||||
}
|
||||
[Fact]
|
||||
public async Task Scope_removal_between_eligibility_and_observation_does_not_leak_id()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node");
|
||||
await trust.ApplyScopeAsync(1, ["c"], ct);
|
||||
using var provider = new DataConnectionSecurityProvider(new DataConnectionCredentialResolver(store, cipher, "pair", "node"), trust, changes);
|
||||
var eligible = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var resume = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
provider.AfterEligibilityForTest = async () => { eligible.SetResult(); await resume.Task; };
|
||||
var resolving = provider.ResolveAsync("c", new Uri("https://example.test"), ct).AsTask();
|
||||
await eligible.Task.WaitAsync(ct);
|
||||
await p.SetScopeAsync(2, new Dictionary<string, string>(), ct);
|
||||
resume.SetResult();
|
||||
(await resolving).ShouldBeNull();
|
||||
provider.ObservedCountForTest.ShouldBe(0);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Mixed_case_scope_and_bundle_reuse_one_durable_generation_floor_after_restart()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher();
|
||||
var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "Cluster", "Node");
|
||||
var central = ZB.MOM.WW.OtOpcUa.Configuration.Validation.DataConnectionScopeRevision.Advance(0, null,
|
||||
[new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection { Enabled = true, ClusterId = "Cluster", DataConnectionId = "Link", ConsumerNodeIds = ["Node"], SecretReference = "secret:data/key" }]);
|
||||
var same = ZB.MOM.WW.OtOpcUa.Configuration.Validation.DataConnectionScopeRevision.Advance(central.Version, central.Fingerprint,
|
||||
[new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection { Enabled = true, ClusterId = "cluster", DataConnectionId = "link", ConsumerNodeIds = ["node"], SecretReference = "secret:data/key" }]);
|
||||
same.Version.ShouldBe(central.Version);
|
||||
await p.SetScopeAsync(central.Version, new Dictionary<string, string> { ["Link"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(new("cluster", "node", 1, [new("LINK", "secret:data/key", "token", false)], ScopeVersion: 1), ct);
|
||||
var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "CLUSTER", "NODE");
|
||||
await restarted.SetScopeAsync(1, new Dictionary<string, string> { ["link"] = "secret:data/key" }, ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "cluster", "NODE").ResolveAsync("lInK", ct))!.Value.ShouldBe("token");
|
||||
await restarted.SetScopeAsync(2, new Dictionary<string, string>(), ct);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.SetScopeAsync(1, new Dictionary<string, string> { ["Link"] = "secret:data/key" }, ct));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => restarted.ApplyAsync(new("cluster", "node", 999, [new("LINK", "secret:data/other", "token", false)], ScopeVersion: 1), ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scope_rejects_duplicate_connection_ids_that_differ_only_by_case()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var p = new DataConnectionSecretProvisioner(new MemoryStore(), new TestCipher(), new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "cluster", "node");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.SetScopeAsync(1, new Dictionary<string, string> { ["Link"] = "secret:data/a", ["link"] = "secret:data/b" }, ct));
|
||||
}
|
||||
[Fact]
|
||||
public async Task Invalidator_attempts_galaxy_and_data_even_when_inner_throws()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore();
|
||||
var directory = new GalaxyAckIdentityDirectory(store, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(2));
|
||||
(await directory.RefreshAsync(ct)).ShouldBeTrue();
|
||||
const string key = "0a1b2c3d4e5f6071";
|
||||
directory.GetPresence(key).ShouldBe(GalaxyAckIdentityPresence.Absent);
|
||||
var changes = new DataConnectionSecretChangeHandler(); var called = 0;
|
||||
changes.SecretChanged += _ => called++;
|
||||
var invalidator = new SecretChangeSignallingInvalidator(new ThrowingInvalidator(), directory, changes);
|
||||
Should.Throw<AggregateException>(() => invalidator.Invalidate(new SecretName(GalaxyAckIdentitySecrets.UserSecretName(key))));
|
||||
called.ShouldBe(1);
|
||||
directory.GetPresence(key).ShouldBe(GalaxyAckIdentityPresence.Unknown);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Registration_composes_the_lightweight_handler_without_replacing_inner()
|
||||
{
|
||||
var services = new ServiceCollection(); var inner = new CountingInvalidator();
|
||||
services.AddSingleton<ISecretCacheInvalidator>(inner);
|
||||
services.AddSingleton<DataConnectionSecretChangeHandler>();
|
||||
SecretsRegistration.DecorateCacheInvalidator(services);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
var changed = 0; provider.GetRequiredService<DataConnectionSecretChangeHandler>().SecretChanged += _ => changed++;
|
||||
provider.GetRequiredService<ISecretCacheInvalidator>().Invalidate(new SecretName("data/key"));
|
||||
inner.Count.ShouldBe(1); changed.ShouldBe(1);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Composed_invalidation_retires_only_connections_that_reference_the_changed_secret()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node");
|
||||
using var security = new DataConnectionSecurityProvider(new DataConnectionCredentialResolver(store, cipher, "pair", "node"), trust, changes);
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node", "pair", security, new DataConnectionScopeActivator(p, trust), 4);
|
||||
DataConnection Definition(string id, string reference) => new() { DataConnectionId = id, ClusterId = "pair", Revision = 1, Enabled = true,
|
||||
ConsumerNodeIds = ["node"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "target", ExpectedNodeId = "remote",
|
||||
Endpoints = ["https://remote.example:8443"], SecretReference = reference, SecretScopeClusterId = "pair", AllowedOperations = DataOperations.Read };
|
||||
runtime.Apply(new DataConnectionDeploymentSnapshot(1, "rev", [Definition("a", "secret:data/a"), Definition("shared", "secret:data/a"), Definition("b", "secret:data/b")]));
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); deadline.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
while (!runtime.CurrentScopeReady) await Task.Delay(10, deadline.Token);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("a", "secret:data/a", "first", false), new("b", "secret:data/b", "second", false)], 1), ct);
|
||||
store.Rows.ContainsKey("data/a").ShouldBeTrue();
|
||||
store.Rows.ContainsKey("data/b").ShouldBeTrue();
|
||||
using var key = RSA.Create(2048); var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
await trust.SetBundleAsync([("a", 1, [ca]), ("shared", 1, [ca]), ("b", 1, [ca])], 1, ct);
|
||||
DataConnectionDeploymentLease? a = null, shared = null, b = null;
|
||||
while (!(runtime.TryAcquire("a", out a) && runtime.TryAcquire("shared", out shared) && runtime.TryAcquire("b", out b)))
|
||||
{
|
||||
a?.Dispose(); shared?.Dispose(); b?.Dispose(); a = null; shared = null; b = null;
|
||||
await Task.Delay(10, deadline.Token);
|
||||
}
|
||||
using (a!) using (shared!) using (b!)
|
||||
{
|
||||
var invalidator = new SecretChangeSignallingInvalidator(new NoopInvalidator(), null, changes);
|
||||
invalidator.Invalidate(new SecretName("otopcua/apikeys/unrelated"));
|
||||
a!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
shared!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
b!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
invalidator.Invalidate(new SecretName("data/a"));
|
||||
a.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
shared.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
b.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ThrowingInvalidator : ISecretCacheInvalidator { public void Invalidate(SecretName name) => throw new InvalidOperationException("failed"); }
|
||||
private sealed class CountingInvalidator : ISecretCacheInvalidator { public int Count; public void Invalidate(SecretName name) => Count++; }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataIngressAuthTests
|
||||
{
|
||||
[Fact]
|
||||
public void Authentication_uses_the_current_snapshot_and_original_key_material()
|
||||
{
|
||||
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var key = new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true };
|
||||
authority.Apply("cluster", "v1", [key], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var auth = new DataConnectionAuthenticator(authority,
|
||||
Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
|
||||
var context = auth.Authenticate(bearer);
|
||||
context.PrincipalId.ShouldBe("peer");
|
||||
context.ApiKeyId.ShouldBe(id);
|
||||
context.CredentialVersion.ShouldBe(DataCallerIdentity.CredentialVersionFor(key));
|
||||
auth.IsCurrent(context).ShouldBeTrue();
|
||||
authority.Apply("cluster", "v2", [], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
auth.IsCurrent(context).ShouldBeFalse();
|
||||
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate(bearer));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Missing_pepper_missing_authority_and_forged_or_expired_keys_deny()
|
||||
{
|
||||
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var auth = new DataConnectionAuthenticator(authority,
|
||||
Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
|
||||
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate(bearer));
|
||||
var expired = new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash,
|
||||
Enabled = true, ExpiresUtc = DateTime.UtcNow.AddMinutes(-1) };
|
||||
authority.Apply("cluster", "v1", [expired], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate(bearer));
|
||||
expired.ExpiresUtc = null;
|
||||
authority.Apply("cluster", "v2", [expired], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
Should.Throw<UnauthorizedAccessException>(() => auth.Authenticate("not-a-key"));
|
||||
Should.Throw<UnauthorizedAccessException>(() => new DataConnectionAuthenticator(authority,
|
||||
Options.Create(new ApiKeyOptions()), TimeProvider.System).Authenticate(bearer));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataListenerTests
|
||||
{
|
||||
[Fact(Timeout = 15000)]
|
||||
public async Task Long_lived_streams_have_a_separate_bounded_lane_from_unary_work()
|
||||
{
|
||||
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
authority.Apply("cluster", "one", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }],
|
||||
[], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var auth = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
|
||||
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, CertificatePath = "server.pem",
|
||||
AllowedHosts = ["source.local"], MaxConcurrentCalls = 1, MaxStreams = 1 };
|
||||
var streamEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var unaryEntered = false;
|
||||
var middleware = new DataConnectionAdmissionMiddleware(async http =>
|
||||
{
|
||||
if (http.Request.Path.Value!.EndsWith("/Subscribe", StringComparison.Ordinal))
|
||||
{ streamEntered.TrySetResult(); await release.Task.WaitAsync(TestContext.Current.CancellationToken); }
|
||||
else unaryEntered = true;
|
||||
}, Options.Create(options));
|
||||
DefaultHttpContext Request(string method)
|
||||
{
|
||||
var http = At(9443, DataConnectionEndpoints.ServicePrefix + method);
|
||||
http.Request.Headers.Authorization = "Bearer " + bearer;
|
||||
http.Request.Headers["x-data-target-mode"] = "Node";
|
||||
http.Request.Headers["x-data-consistency"] = "Primary";
|
||||
http.Request.Headers["x-data-cluster-id"] = "cluster";
|
||||
http.Request.Headers["x-data-node-id"] = "node";
|
||||
return http;
|
||||
}
|
||||
var stream = middleware.InvokeAsync(Request("Subscribe"), auth);
|
||||
try
|
||||
{
|
||||
await streamEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
var extraStream = Request("Subscribe");
|
||||
await middleware.InvokeAsync(extraStream, auth);
|
||||
extraStream.Response.Headers["grpc-status"].ToString().ShouldBe("8");
|
||||
await middleware.InvokeAsync(Request("Read"), auth);
|
||||
unaryEntered.ShouldBeTrue("occupied stream capacity must preserve unary read/write/browse admission");
|
||||
}
|
||||
finally { release.TrySetResult(); await stream; }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Mesh_calls_on_data_port_and_unauthenticated_data_calls_never_enter_body_parsing()
|
||||
{
|
||||
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443,
|
||||
CertificatePath = "server.pem", AllowedHosts = ["source.local"] };
|
||||
var parsed = 0;
|
||||
var middleware = new DataConnectionAdmissionMiddleware(_ => { parsed++; return Task.CompletedTask; }, Options.Create(options));
|
||||
var auth = new DataConnectionAuthenticator(new DataPlaneAuthorityState(), Options.Create(new ApiKeyOptions()), TimeProvider.System);
|
||||
var mesh = At(9443, "/mesh_transport.v1.NodeCommandService/Execute");
|
||||
await middleware.InvokeAsync(mesh, auth);
|
||||
mesh.Response.Headers["grpc-status"].ToString().ShouldBe("7");
|
||||
var data = At(9443, DataConnectionEndpoints.ServicePrefix + "Read");
|
||||
await middleware.InvokeAsync(data, auth);
|
||||
data.Response.Headers["grpc-status"].ToString().ShouldBe("16");
|
||||
parsed.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 15000)]
|
||||
public async Task Unary_lifetime_also_bounds_preparse_work_when_client_supplies_no_deadline()
|
||||
{
|
||||
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
authority.Apply("cluster", "one", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }],
|
||||
[], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var auth = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
|
||||
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443,
|
||||
CertificatePath = "server.pem", AllowedHosts = ["source.local"], UnaryTimeout = TimeSpan.FromMilliseconds(50) };
|
||||
using var cleanup = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var middleware = new DataConnectionAdmissionMiddleware(async http =>
|
||||
{ entered.TrySetResult(); await Task.Delay(Timeout.InfiniteTimeSpan, http.RequestAborted); }, Options.Create(options));
|
||||
var context = At(9443, DataConnectionEndpoints.ServicePrefix + "Read");
|
||||
context.RequestAborted = cleanup.Token;
|
||||
context.Request.Headers.Authorization = "Bearer " + bearer;
|
||||
context.Request.Headers["x-data-target-mode"] = "Node";
|
||||
context.Request.Headers["x-data-consistency"] = "Primary";
|
||||
context.Request.Headers["x-data-cluster-id"] = "cluster";
|
||||
context.Request.Headers["x-data-node-id"] = "node";
|
||||
var processing = middleware.InvokeAsync(context, auth);
|
||||
bool stopped;
|
||||
try
|
||||
{
|
||||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
stopped = await Task.WhenAny(processing, Task.Delay(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken)) == processing;
|
||||
}
|
||||
finally
|
||||
{
|
||||
await cleanup.CancelAsync();
|
||||
try { await processing; } catch (OperationCanceledException) { }
|
||||
}
|
||||
stopped.ShouldBeTrue("the server's own unary budget must cover pre-parse HTTP work");
|
||||
}
|
||||
[Fact]
|
||||
public void Disabled_surface_has_no_listener_or_method_admission()
|
||||
{
|
||||
var options = new DataConnectionOptions();
|
||||
DataConnectionOptionsValidator.Validate(options, development: false).ShouldBeEmpty();
|
||||
DataConnectionEndpoints.IsDataRequest(At(9443, "/data_connection.v1.DataConnectionService/Read"), options).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cleartext_requires_explicit_development_and_literal_loopback()
|
||||
{
|
||||
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443,
|
||||
ListenAddress = "127.0.0.1", AllowDevelopmentCleartext = true, AllowedHosts = ["localhost"] };
|
||||
DataConnectionOptionsValidator.Validate(options, development: true).ShouldBeEmpty();
|
||||
DataConnectionOptionsValidator.Validate(options, development: false).ShouldNotBeEmpty();
|
||||
options.ListenAddress = "0.0.0.0";
|
||||
DataConnectionOptionsValidator.Validate(options, development: true).ShouldNotBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exact_rpc_host_and_actual_listener_are_required()
|
||||
{
|
||||
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443,
|
||||
CertificatePath = "server.pem", AllowedHosts = ["source.local"] };
|
||||
var request = At(9443, "/data_connection.v1.DataConnectionService/Read");
|
||||
DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeTrue();
|
||||
request.Connection.LocalPort = 8080;
|
||||
request.Request.Headers["X-Forwarded-Port"] = "9443";
|
||||
DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeFalse();
|
||||
request.Connection.LocalPort = 9443;
|
||||
request.Request.Host = new HostString("other.local", 9443);
|
||||
DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeFalse();
|
||||
request.Request.Host = new HostString("source.local", 9443);
|
||||
request.Request.Path += "Anything";
|
||||
DataConnectionEndpoints.IsDataRequest(request, options).ShouldBeFalse();
|
||||
}
|
||||
|
||||
private static DefaultHttpContext At(int port, string path)
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.Connection.LocalPort = port;
|
||||
context.Request.Host = new HostString("source.local", port);
|
||||
context.Request.Scheme = "https";
|
||||
context.Request.Protocol = "HTTP/2";
|
||||
context.Request.Method = "POST";
|
||||
context.Request.Path = path;
|
||||
return context;
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
using Google.Protobuf;
|
||||
using Grpc.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Grpc;
|
||||
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataPublicationHandoffTests
|
||||
{
|
||||
[Fact]
|
||||
public void Monotonic_unary_deadline_is_rechecked_after_validation_even_without_a_timer_callback()
|
||||
{
|
||||
var binder = new CaptureBinder();
|
||||
DataConnectionGrpcBinding.BindService(binder, null!);
|
||||
var clock = new PublicationClock();
|
||||
var deadline = new DataConnectionUnaryLifetime(clock, TimeSpan.FromSeconds(1));
|
||||
var response = new W.CapabilitiesResponse { ProtocolMajor = 1 };
|
||||
using var registration = DataConnectionPublication.RegisterUnary(response, () =>
|
||||
{ clock.Advance(TimeSpan.FromSeconds(2)); return true; }, 1024, deadline);
|
||||
var context = new CaptureContext();
|
||||
Should.Throw<RpcException>(() => binder.Unary["GetCapabilities"](response, context));
|
||||
context.Handoffs.ShouldBe(0);
|
||||
}
|
||||
|
||||
private sealed class PublicationClock : TimeProvider
|
||||
{
|
||||
private long _ticks;
|
||||
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
|
||||
public override long GetTimestamp() => _ticks;
|
||||
internal void Advance(TimeSpan duration) => _ticks += duration.Ticks;
|
||||
}
|
||||
[Fact]
|
||||
public void Registered_binding_checks_revocation_after_method_return_before_any_body_handoff()
|
||||
{
|
||||
var binder = new CaptureBinder();
|
||||
DataConnectionGrpcBinding.BindService(binder, null!);
|
||||
var response = new W.CapabilitiesResponse { ProtocolMajor = 1 };
|
||||
var allowed = true;
|
||||
using var registration = DataConnectionPublication.Register(response, () => allowed, 1024);
|
||||
allowed = false;
|
||||
var context = new CaptureContext();
|
||||
Should.Throw<RpcException>(() => binder.Unary["GetCapabilities"](response, context));
|
||||
context.Handoffs.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Registered_binding_performs_exactly_one_successful_private_buffer_handoff()
|
||||
{
|
||||
var binder = new CaptureBinder();
|
||||
DataConnectionGrpcBinding.BindService(binder, null!);
|
||||
var response = new W.CapabilitiesResponse { ProtocolMajor = 1 };
|
||||
using var registration = DataConnectionPublication.Register(response, () => true, 1024);
|
||||
var context = new CaptureContext();
|
||||
binder.Unary["GetCapabilities"](response, context);
|
||||
context.Handoffs.ShouldBe(1);
|
||||
W.CapabilitiesResponse.Parser.ParseFrom(context.Payload!).ProtocolMajor.ShouldBe(1);
|
||||
Should.Throw<RpcException>(() => binder.Unary["GetCapabilities"](response, context));
|
||||
context.Handoffs.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Skipped_serializer_cleanup_and_unregistered_responses_fail_closed()
|
||||
{
|
||||
var binder = new CaptureBinder();
|
||||
DataConnectionGrpcBinding.BindService(binder, null!);
|
||||
var response = new W.CapabilitiesResponse();
|
||||
var registration = DataConnectionPublication.Register(response, () => true, 1024);
|
||||
registration.Dispose();
|
||||
var context = new CaptureContext();
|
||||
Should.Throw<RpcException>(() => binder.Unary["GetCapabilities"](response, context));
|
||||
Should.Throw<RpcException>(() => binder.Unary["GetCapabilities"](new W.CapabilitiesResponse(), context));
|
||||
context.Handoffs.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 15000)]
|
||||
public async Task Disposal_during_a_blocked_final_guard_prevents_handoff()
|
||||
{
|
||||
var binder = new CaptureBinder();
|
||||
DataConnectionGrpcBinding.BindService(binder, null!);
|
||||
var response = new W.CapabilitiesResponse { ProtocolMajor = 1 };
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var resume = new ManualResetEventSlim();
|
||||
using var registration = DataConnectionPublication.Register(response, () =>
|
||||
{
|
||||
entered.Set();
|
||||
if (!resume.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)) throw new TimeoutException();
|
||||
return true;
|
||||
}, 1024);
|
||||
var context = new CaptureContext();
|
||||
var serialization = Task.Run(() =>
|
||||
{
|
||||
try { binder.Unary["GetCapabilities"](response, context); return (Exception?)null; }
|
||||
catch (Exception error) { return error; }
|
||||
}, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
entered.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken).ShouldBeTrue();
|
||||
registration.Dispose();
|
||||
}
|
||||
finally { resume.Set(); }
|
||||
(await serialization.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeOfType<RpcException>();
|
||||
context.Handoffs.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Prepared_stream_delivery_requires_one_live_runtime_publication_guard()
|
||||
{
|
||||
var binder = new CaptureBinder();
|
||||
DataConnectionGrpcBinding.BindService(binder, null!);
|
||||
W.SubscriptionFrame Frame() => new() { SubscriptionId = "s", StreamEpoch = 1, Sequence = 1, Control = new W.Control() };
|
||||
var unbound = Frame();
|
||||
using (var prepared = new PreparedDataSubscription(unbound, unbound.ToByteArray(), 1024, 1024,
|
||||
() => true, TestContext.Current.CancellationToken))
|
||||
Should.Throw<RpcException>(() => binder.Duplex["Subscribe"](unbound, new CaptureContext()));
|
||||
var valid = Frame();
|
||||
using var delivery = new PreparedDataSubscription(valid, valid.ToByteArray(), 1024, 1024,
|
||||
() => true, TestContext.Current.CancellationToken);
|
||||
((IDataPreparedSubscriptionPublication)delivery).SetPublicationGuard(() => true);
|
||||
Should.Throw<InvalidOperationException>(() => delivery.SetPublicationGuard(() => true));
|
||||
var context = new CaptureContext();
|
||||
binder.Duplex["Subscribe"](valid, context);
|
||||
context.Handoffs.ShouldBe(1);
|
||||
}
|
||||
|
||||
private sealed class CaptureBinder : ServiceBinderBase
|
||||
{
|
||||
internal readonly Dictionary<string, Action<IMessage, SerializationContext>> Unary = [];
|
||||
internal readonly Dictionary<string, Action<IMessage, SerializationContext>> Duplex = [];
|
||||
public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method,
|
||||
UnaryServerMethod<TRequest, TResponse>? handler) =>
|
||||
Unary.Add(method.Name, (response, context) => method.ResponseMarshaller.ContextualSerializer((TResponse)(object)response, context));
|
||||
public override void AddMethod<TRequest, TResponse>(Method<TRequest, TResponse> method,
|
||||
DuplexStreamingServerMethod<TRequest, TResponse>? handler) =>
|
||||
Duplex.Add(method.Name, (response, context) => method.ResponseMarshaller.ContextualSerializer((TResponse)(object)response, context));
|
||||
}
|
||||
|
||||
private sealed class CaptureContext : SerializationContext
|
||||
{
|
||||
internal int Handoffs;
|
||||
internal byte[]? Payload;
|
||||
public override void Complete(byte[] payload) { Handoffs++; Payload = payload; }
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using Akka.Actor;
|
||||
using Akka.Hosting;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataRuntimeRegistrationTests
|
||||
{
|
||||
[Fact]
|
||||
public void Disabled_registration_requires_no_driver_or_secret_store_and_exposes_no_facade()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
var options = services.AddOtOpcUaDataConnections(new ConfigurationBuilder().Build(), new Environment(), hasDriver: false);
|
||||
options.Enabled.ShouldBeFalse();
|
||||
using var provider = services.BuildServiceProvider();
|
||||
provider.GetService<IDataConnectionFactory>().ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Enabled_surface_requires_the_actual_driver_role()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
Should.Throw<InvalidOperationException>(() => services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: false));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Startup_facade_is_available_without_constructing_a_disconnected_actor_graph()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
var factory = provider.GetRequiredService<IDataConnectionFactory>();
|
||||
Should.Throw<InvalidOperationException>(() => factory.Create(new("peer", "key", "version", null, 1),
|
||||
new(DataTargetMode.Node, "cluster", "node")));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Real_registered_graph_activates_scope_and_catalog_for_deferred_factory()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var system = ActorSystem.Create("grpc-di-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var registry = new ActorRegistry();
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton(registry);
|
||||
services.AddSingleton<IClusterRoleInfo>(new LocalRole());
|
||||
services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService<DataWriteDispatchFence>()));
|
||||
services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService<DataWriteDispatchFence>()));
|
||||
services.AddSingleton<IPermissionEvaluator>(sp => new TriePermissionEvaluator(sp.GetRequiredService<DataPlaneAuthorityState>().Tries));
|
||||
services.AddSingleton<ISecretStore>(new GrpcDataSecretProvisioningTests.MemoryStore());
|
||||
services.AddSingleton<ISecretCipher>(new GrpcDataSecretProvisioningTests.TestCipher());
|
||||
services.AddSingleton<ISecretCacheInvalidator>(new GrpcDataSecretProvisioningTests.NoopInvalidator());
|
||||
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
var factory = provider.GetRequiredService<IDataConnectionFactory>();
|
||||
var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a:4840");
|
||||
var key = new ApiKey { ApiKeyId = "key", Name = "key", Principal = "peer", SecretHash = "hash", Enabled = true };
|
||||
var catalog = provider.GetRequiredService<LocalCatalogCoordinator>();
|
||||
var role = provider.GetRequiredService<RedundancyRoleView>();
|
||||
role.PublishDataServingRole(RedundancyRole.Primary, true);
|
||||
var attempt = catalog.BeginAttempt("revision");
|
||||
catalog.InstallAuthority(attempt, new DataPlaneAuthorityProjection("cluster", [key], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>())).ShouldBeTrue();
|
||||
var context = new DataAuthenticatedContext("peer", "key", DataCallerIdentity.CredentialVersionFor(key), null,
|
||||
provider.GetRequiredService<DataPlaneAuthorityState>().Current.GenerationId);
|
||||
Should.Throw<InvalidOperationException>(() => factory.Create(context, target)); // no registered host
|
||||
var actor = system.ActorOf(Props.Create(() => new LocalActor()));
|
||||
registry.Register<DriverHostActorKey>(actor);
|
||||
await using var connection = factory.Create(context, target);
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 100, 1_000_000);
|
||||
(await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Unavailable);
|
||||
var snapshot = new DraftSnapshot { GenerationId = 0, ClusterId = "cluster",
|
||||
ClusterNodes = [new ClusterNode { ClusterId = "cluster", NodeId = "node-a:4840", Host = "node-a", ApplicationUri = "urn:node-a", CreatedBy = "test" }] };
|
||||
catalog.Stage(attempt, snapshot, "node-a:4840").ShouldBeTrue();
|
||||
catalog.Complete(attempt, true).ShouldBeTrue();
|
||||
(await connection.GetCapabilitiesAsync(budget, ct)).Readiness.ShouldBe(DataReadiness.Unavailable); // scope not yet durable
|
||||
var deployment = provider.GetRequiredService<DataConnectionDeploymentRuntime>();
|
||||
deployment.Apply(new DataConnectionDeploymentSnapshot(1, "revision", []));
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
while (!deployment.CurrentScopeReady) await Task.Delay(10, deadline.Token);
|
||||
var ready = await connection.GetCapabilitiesAsync(budget, ct);
|
||||
ready.Readiness.ShouldBe(DataReadiness.Ready);
|
||||
ready.Serving.NodeId.ShouldBe("node-a:4840");
|
||||
ready.Serving.Incarnation.ShouldBe(catalog.Serving.Incarnation);
|
||||
var composition = provider.GetRequiredService<LocalDataRuntimeComposition>();
|
||||
composition.AcquisitionCapacity.ShouldBeSameAs(provider.GetRequiredService<SubscriptionAcquisitionCapacity>());
|
||||
composition.Services.Clock.ShouldBeSameAs(provider.GetRequiredService<TimeProvider>());
|
||||
}
|
||||
finally { await system.Terminate().WaitAsync(ct); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Local_warm_standby_overrides_hot_artifact_and_withdraws_ready_import()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var services = new ServiceCollection();
|
||||
services.AddSingleton<IClusterRoleInfo>(new LocalRole());
|
||||
services.AddSingleton(sp => new DataPlaneAuthorityState(sp.GetRequiredService<DataWriteDispatchFence>()));
|
||||
services.AddSingleton(sp => new RedundancyRoleView(sp.GetRequiredService<DataWriteDispatchFence>()));
|
||||
services.AddSingleton(new WarmRedundancySettings(OpcUaRedundancyMode.Warm));
|
||||
services.AddSingleton<ISecretStore>(new GrpcDataSecretProvisioningTests.MemoryStore());
|
||||
services.AddSingleton<ISecretCipher>(new GrpcDataSecretProvisioningTests.TestCipher());
|
||||
services.AddSingleton<ISecretCacheInvalidator>(new GrpcDataSecretProvisioningTests.NoopInvalidator());
|
||||
services.AddOtOpcUaDataConnections(Configuration(), new Environment(), hasDriver: true);
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
var role = provider.GetRequiredService<RedundancyRoleView>();
|
||||
var warm = provider.GetRequiredService<DataConnectionWarmRoleView>();
|
||||
var owner = warm.RegisterOwner(); warm.Publish(owner, WarmRole.Active);
|
||||
role.PublishDataServingRole(RedundancyRole.Primary, true);
|
||||
var runtime = provider.GetRequiredService<DataConnectionDeploymentRuntime>();
|
||||
var connection = new DataConnection { DataConnectionId = "link", ClusterId = "cluster", Revision = 1, Enabled = true,
|
||||
ConsumerNodeIds = ["node-a:4840"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "remote", ExpectedNodeId = "remote:4840",
|
||||
Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster", AllowedOperations = DataOperations.Read };
|
||||
runtime.Apply(new DataConnectionDeploymentSnapshot(1, "revision", [connection], RedundancyMode.Hot));
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); deadline.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
while (!runtime.CurrentScopeReady) await Task.Delay(10, deadline.Token);
|
||||
await provider.GetRequiredService<DataConnectionSecretProvisioner>().ApplyAsync(new("cluster", "node-a:4840", 1,
|
||||
[new("link", "secret:data/key", "bearer", false)], 1), ct);
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
await provider.GetRequiredService<DataConnectionTrustPolicyStore>().SetAsync("link", 1, [ca], 1, ct);
|
||||
DataConnectionDeploymentLease? lease = null;
|
||||
while (!runtime.TryAcquire("link", out lease)) await Task.Delay(10, deadline.Token);
|
||||
lease.ShouldNotBeNull();
|
||||
role.PublishDataServingRole(RedundancyRole.Secondary, false);
|
||||
warm.Publish(owner, WarmRole.Standby);
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
Should.Throw<InvalidOperationException>(() => lease.GetCapabilitiesAsync(new DataBudget(TimeSpan.FromSeconds(1), 1, 1024), ct));
|
||||
lease.Dispose();
|
||||
}
|
||||
|
||||
private sealed class LocalActor : ReceiveActor { }
|
||||
private sealed class LocalRole : IClusterRoleInfo
|
||||
{
|
||||
public NodeId LocalNode => NodeId.Parse("node-a:4840");
|
||||
public IReadOnlySet<string> LocalRoles => new HashSet<string> { "driver", "cluster-cluster" };
|
||||
public string? ClusterRole => "cluster-cluster";
|
||||
public string? ClusterId => "cluster";
|
||||
public bool HasRole(string role) => LocalRoles.Contains(role);
|
||||
public IReadOnlyList<NodeId> MembersWithRole(string role) => [];
|
||||
public NodeId? RoleLeader(string role) => null;
|
||||
public event EventHandler<RoleLeaderChangedEventArgs>? RoleLeaderChanged { add { } remove { } }
|
||||
}
|
||||
|
||||
private static IConfiguration Configuration() => new ConfigurationBuilder().AddInMemoryCollection(
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
["DataConnections:Enabled"] = "true", ["DataConnections:ListenPort"] = "9443",
|
||||
["DataConnections:AllowedHosts:0"] = "source.local", ["DataConnections:CertificatePath"] = "server.pem"
|
||||
}).Build();
|
||||
|
||||
private sealed class Environment : IHostEnvironment
|
||||
{
|
||||
public string EnvironmentName { get; set; } = Environments.Production;
|
||||
public string ApplicationName { get; set; } = "GrpcDataTests";
|
||||
public string ContentRootPath { get; set; } = "/";
|
||||
public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider();
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataScopeActivationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Activation_persists_identical_scope_to_credentials_and_trust()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node");
|
||||
var activator = new DataConnectionScopeActivator(p, trust);
|
||||
await activator.SetScopeAsync(1, new Dictionary<string, string> { ["link"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("link", "secret:data/key", "bearer", false)], 1), ct);
|
||||
await trust.SetAsync("LINK", 1, [], 1, ct);
|
||||
await activator.SetScopeAsync(2, new Dictionary<string, string>(), ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("link", ct)).ShouldBeNull();
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => trust.SetAsync("link", 2, [], 1, ct));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => activator.SetScopeAsync(1, new Dictionary<string, string> { ["link"] = "secret:data/key" }, ct));
|
||||
}
|
||||
}
|
||||
+205
@@ -0,0 +1,205 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.Secrets.DependencyInjection;
|
||||
using ZB.MOM.WW.Secrets.Sqlite;
|
||||
using Xunit;
|
||||
|
||||
using System.Text;
|
||||
using Shouldly;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P07")]
|
||||
public class GrpcDataSecretProvisioningTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Scoped_bundle_is_encrypted_and_survives_restart_without_bundle()
|
||||
{
|
||||
var store = new MemoryStore();
|
||||
var cipher = new TestCipher();
|
||||
var changed = new DataConnectionSecretChangeHandler();
|
||||
var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changed, "consumer-cluster", "node-a");
|
||||
await provisioner.SetScopeAsync(1, new Dictionary<string, string> { ["connection"] = "secret:data/key" }, TestContext.Current.CancellationToken);
|
||||
await provisioner.ApplyAsync(new DataConnectionCredentialBundle("consumer-cluster", "node-a", 1,
|
||||
[new DataConnectionCredentialEntry("connection", "secret:data/key", "bearer-value", false)], ScopeVersion: 1), TestContext.Current.CancellationToken);
|
||||
var row = await store.GetAsync(new SecretName("data/key"), TestContext.Current.CancellationToken);
|
||||
row.ShouldNotBeNull();
|
||||
Encoding.UTF8.GetString(row.Ciphertext).ShouldNotContain("bearer-value");
|
||||
var restarted = new DataConnectionCredentialResolver(store, cipher, "consumer-cluster", "node-a");
|
||||
var resolved = await restarted.ResolveAsync("connection", TestContext.Current.CancellationToken);
|
||||
resolved.ShouldNotBeNull();
|
||||
resolved.Value.ShouldBe("bearer-value");
|
||||
resolved.Version.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Replica_and_pair_scopes_are_independent()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var a = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair-a", "a1");
|
||||
var b = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair-a", "a2");
|
||||
await a.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key-a" }, ct);
|
||||
await b.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key-b" }, ct);
|
||||
await a.ApplyAsync(new("pair-a", "a1", 1, [new("c", "secret:data/key-a", "a", false)], ScopeVersion: 1), ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair-a", "a2").ResolveAsync("c", ct)).ShouldBeNull();
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair-b", "a1").ResolveAsync("c", ct)).ShouldBeNull();
|
||||
await b.ApplyAsync(new("pair-a", "a2", 1, [new("c", "secret:data/key-b", "b", false)], ScopeVersion: 1), ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair-a", "a2").ResolveAsync("c", ct))!.Value.ShouldBe("b");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_store_write_leaves_pending_credential_unavailable()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1), ct);
|
||||
store.FailUpsertName = "data/key";
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.ApplyAsync(new("pair", "node", 2, [new("c", "secret:data/key", "new", false)], ScopeVersion: 1), ct));
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Real_sqlite_store_keeps_ciphertext_and_recovers_after_provider_restart()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var directory = Directory.CreateTempSubdirectory("data-credentials-");
|
||||
try
|
||||
{
|
||||
var keyFile = Path.Combine(directory.FullName, "master-key");
|
||||
var db = Path.Combine(directory.FullName, "secrets.db");
|
||||
await File.WriteAllTextAsync(keyFile, Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)), ct);
|
||||
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Secrets:SqlitePath"] = db, ["Secrets:MasterKey:Source"] = "File",
|
||||
["Secrets:MasterKey:FilePath"] = keyFile, ["Secrets:RunMigrationsOnStartup"] = "false",
|
||||
}).Build();
|
||||
await using (var first = new ServiceCollection().AddLogging().AddZbSecrets(config, "Secrets").BuildServiceProvider())
|
||||
{
|
||||
await first.GetRequiredService<SqliteSecretsStoreMigrator>().MigrateAsync(ct);
|
||||
var provisioner = new DataConnectionSecretProvisioner(first.GetRequiredService<ISecretStore>(), first.GetRequiredService<ISecretCipher>(),
|
||||
new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "cluster", "node");
|
||||
await provisioner.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
await provisioner.ApplyAsync(new("cluster", "node", 1, [new("c", "secret:data/key", "private-bearer-value", false)], ScopeVersion: 1), ct);
|
||||
}
|
||||
var database = await File.ReadAllBytesAsync(db, ct);
|
||||
Encoding.UTF8.GetString(database).ShouldNotContain("private-bearer-value");
|
||||
await using var second = new ServiceCollection().AddLogging().AddZbSecrets(config, "Secrets").BuildServiceProvider();
|
||||
var resolver = new DataConnectionCredentialResolver(second.GetRequiredService<ISecretStore>(), second.GetRequiredService<ISecretCipher>(), "cluster", "node");
|
||||
(await resolver.ResolveAsync("c", ct))!.Value.ShouldBe("private-bearer-value");
|
||||
}
|
||||
finally { directory.Delete(true); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Interrupted_version_can_resume_only_with_the_same_payload()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
var bundle = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "intended", false)], ScopeVersion: 1);
|
||||
store.FailUpsertName = "data/key";
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.ApplyAsync(bundle, ct));
|
||||
store.FailUpsertName = null;
|
||||
var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => restarted.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "different", false)], ScopeVersion: 1), ct));
|
||||
await restarted.ApplyAsync(bundle, ct);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("intended");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scope_and_historical_reference_capacity_fail_closed()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
var tooMany = Enumerable.Range(0, DataConnectionSecretProvisioner.MaximumReferences + 1).ToDictionary(i => "c" + i, i => "secret:data/key" + i);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.SetScopeAsync(1, tooMany, ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Replaced_secret_cannot_be_resolved_under_a_committed_version()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1), ct);
|
||||
store.Rows["data/key"] = cipher.Encrypt(new SecretName("data/key"), "replacement", SecretContentType.Text);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull();
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1), ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Completed_bundle_replay_after_restart_is_idempotent_but_changed_payload_is_rejected()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher();
|
||||
var changes = new DataConnectionSecretChangeHandler(); var notices = 0; changes.ConnectionChanged += _ => notices++;
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
var bundle = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1);
|
||||
await p.ApplyAsync(bundle, ct);
|
||||
var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node");
|
||||
await restarted.ApplyAsync(bundle, ct);
|
||||
notices.ShouldBe(1);
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("original");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => restarted.ApplyAsync(bundle with { Entries = [new("c", "secret:data/key", "different", false)] }, ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Canonical_reference_uses_physical_secret_name_for_store_and_resolution()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher();
|
||||
var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await p.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "bearer", false)], 1), ct);
|
||||
(await store.GetAsync(new SecretName("data/key"), ct)).ShouldNotBeNull();
|
||||
(await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("bearer");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pinned_secret_name_normalizes_case_so_wire_aliases_must_not_share_a_row()
|
||||
{
|
||||
new SecretName("data/Key").Value.ShouldBe(new SecretName("data/key").Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Canonical_scope_rejects_uppercase_physical_secret_aliases()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var p = new DataConnectionSecretProvisioner(new MemoryStore(), new TestCipher(), new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => p.SetScopeAsync(1, new Dictionary<string, string> { ["a"] = "secret:data/Key", ["b"] = "secret:data/key" }, ct));
|
||||
}
|
||||
|
||||
internal sealed class NoopInvalidator : ISecretCacheInvalidator { public void Invalidate(SecretName name) { } }
|
||||
internal sealed class TestCipher : ISecretCipher
|
||||
{
|
||||
public StoredSecret Encrypt(SecretName name, string plaintext, SecretContentType contentType) => new()
|
||||
{
|
||||
Name = name, ContentType = contentType,
|
||||
Ciphertext = Encoding.UTF8.GetBytes(plaintext).Select(b => (byte)(b ^ 0x5a)).ToArray(),
|
||||
Nonce = [], Tag = [], WrappedDek = [], WrapNonce = [], WrapTag = [], KekId = "test", Revision = 0,
|
||||
CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow,
|
||||
};
|
||||
public string Decrypt(StoredSecret secret) => Encoding.UTF8.GetString(secret.Ciphertext.Select(b => (byte)(b ^ 0x5a)).ToArray());
|
||||
public StoredSecret Rewrap(StoredSecret secret, IMasterKeyProvider oldKek, IMasterKeyProvider newKek) => throw new NotSupportedException();
|
||||
}
|
||||
internal sealed class MemoryStore : ISecretStore
|
||||
{
|
||||
public Dictionary<string, StoredSecret> Rows { get; } = new();
|
||||
public string? FailUpsertName { get; set; }
|
||||
public bool FailDelete { get; set; }
|
||||
public Task<StoredSecret?> GetAsync(SecretName name, CancellationToken ct) => Task.FromResult(Rows.GetValueOrDefault(name.Value));
|
||||
public Task UpsertAsync(StoredSecret row, CancellationToken ct) { if (row.Name.Value == FailUpsertName) throw new InvalidOperationException("store unavailable"); Rows[row.Name.Value] = row; return Task.CompletedTask; }
|
||||
public Task<bool> DeleteAsync(SecretName name, string? actor, CancellationToken ct) => FailDelete ? throw new InvalidOperationException("delete unavailable") : Task.FromResult(Rows.Remove(name.Value));
|
||||
public Task<IReadOnlyList<SecretMetadata>> ListAsync(bool includeDeleted, CancellationToken ct) => Task.FromResult<IReadOnlyList<SecretMetadata>>([]);
|
||||
public Task<IReadOnlyList<SecretManifestEntry>> GetManifestAsync(CancellationToken ct) => throw new NotSupportedException();
|
||||
public Task ApplyReplicatedAsync(StoredSecret row, CancellationToken ct) => throw new NotSupportedException();
|
||||
public Task<bool> ApplyRewrapAsync(StoredSecret row, byte[] expectedCurrentWrappedDek, CancellationToken ct) => throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P07")]
|
||||
public class GrpcDataSecretRotationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Rotation_retires_and_rejects_downgrade_and_wrong_node()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var changed = new List<string>(); changes.ConnectionChanged += changed.Add;
|
||||
var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node");
|
||||
await provisioner.SetScopeAsync(1, new Dictionary<string, string> { ["c"] = "secret:data/key" }, ct);
|
||||
DataConnectionCredentialBundle Bundle(long version, string node) => new("cluster", node, version, [new("c", "secret:data/key", "value" + version, false)], ScopeVersion: 1);
|
||||
await provisioner.ApplyAsync(Bundle(1, "node"), ct);
|
||||
await provisioner.ApplyAsync(Bundle(2, "node"), ct);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => provisioner.ApplyAsync(Bundle(1, "node"), ct));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => provisioner.ApplyAsync(Bundle(3, "other"), ct));
|
||||
var credential = await new DataConnectionCredentialResolver(store, cipher, "cluster", "node").ResolveAsync("c", ct);
|
||||
credential.ShouldNotBeNull(); credential.Value.ShouldBe("value2"); credential.Version.ShouldBe(2);
|
||||
changed.Count.ShouldBe(2);
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Grpc;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
|
||||
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataServiceDispatchTests
|
||||
{
|
||||
[Fact]
|
||||
public void Serving_provenance_uses_the_observed_role_instead_of_inventing_a_secondary_from_a_false_verdict()
|
||||
{
|
||||
var role = new RedundancyRoleView();
|
||||
role.DataServingRole.ShouldBe("Unknown");
|
||||
role.PublishPrimaryRole(false);
|
||||
role.DataServingRole.ShouldBe("Unknown");
|
||||
role.PublishDataServingRole(RedundancyRole.Secondary, false);
|
||||
role.DataServingRole.ShouldBe("Secondary");
|
||||
role.ShouldActAsPrimary.ShouldBeFalse();
|
||||
var generation = role.PrimaryGeneration;
|
||||
role.PublishDataServingRole(null, false);
|
||||
role.DataServingRole.ShouldBe("Unknown");
|
||||
role.PrimaryGeneration.ShouldBeGreaterThan(generation);
|
||||
role.PublishDataServingRole(RedundancyRole.Primary, true);
|
||||
role.DataServingRole.ShouldBe("Primary");
|
||||
role.ShouldActAsPrimary.ShouldBeTrue();
|
||||
}
|
||||
[Fact]
|
||||
public async Task Ingress_binds_the_trusted_caller_and_explicit_target_to_the_local_facade()
|
||||
{
|
||||
var fixture = Create();
|
||||
var failure = await Should.ThrowAsync<RpcException>(() => fixture.Service.GetCapabilities(new() { ProtocolMajor = 1 }, fixture.Context));
|
||||
failure.StatusCode.ShouldBe(StatusCode.Unavailable);
|
||||
fixture.Context.WriteOptions!.Flags.ShouldBe(WriteFlags.NoCompress);
|
||||
fixture.Factory.Caller!.PrincipalId.ShouldBe("peer");
|
||||
fixture.Factory.Target.ShouldBe(new(DataTargetMode.Node, "cluster", "node"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Revocation_after_preparse_authentication_prevents_facade_creation()
|
||||
{
|
||||
var fixture = Create();
|
||||
fixture.Authority.Apply("cluster", "revoked", [], [], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var failure = await Should.ThrowAsync<RpcException>(() => fixture.Service.GetCapabilities(new() { ProtocolMajor = 1 }, fixture.Context));
|
||||
failure.StatusCode.ShouldBe(StatusCode.Unauthenticated);
|
||||
fixture.Factory.Caller.ShouldBeNull();
|
||||
}
|
||||
|
||||
private static (DataConnectionGrpcService Service, CallContext Context, RejectingFactory Factory, DataPlaneAuthorityState Authority) Create()
|
||||
{
|
||||
var (bearer, id, hash) = ApiKeySecret.Generate("pepper");
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
authority.Apply("cluster", "v1", [new ApiKey { ApiKeyId = id, Name = "test", Principal = "peer", SecretHash = hash, Enabled = true }],
|
||||
[], new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var authenticator = new DataConnectionAuthenticator(authority, Options.Create(new ApiKeyOptions { Pepper = "pepper" }), TimeProvider.System);
|
||||
var options = new DataConnectionOptions { Enabled = true, ListenPort = 9443, AllowedHosts = ["source.local"], CertificatePath = "server.pem" };
|
||||
var context = new CallContext();
|
||||
var http = new DefaultHttpContext();
|
||||
http.Connection.LocalPort = 9443;
|
||||
http.Request.Protocol = "HTTP/2"; http.Request.Scheme = "https"; http.Request.Method = "POST";
|
||||
http.Request.Host = new HostString("source.local", 9443); http.Request.Path = context.Method;
|
||||
http.Items[typeof(DataAuthenticatedContext)] = authenticator.Authenticate(bearer);
|
||||
http.Items[typeof(DataTarget)] = new DataTarget(DataTargetMode.Node, "cluster", "node");
|
||||
context.UserState["__HttpContext"] = http;
|
||||
var factory = new RejectingFactory();
|
||||
return (new(factory, Options.Create(options), authenticator), context, factory, authority);
|
||||
}
|
||||
|
||||
private sealed class RejectingFactory : IDataConnectionFactory
|
||||
{
|
||||
public DataAuthenticatedContext? Caller;
|
||||
public DataTarget? Target;
|
||||
public IDataConnection Create(DataAuthenticatedContext context, DataTarget target)
|
||||
{ Caller = context; Target = target; throw new InvalidOperationException("Not ready."); }
|
||||
}
|
||||
|
||||
private sealed class CallContext : ServerCallContext
|
||||
{
|
||||
protected override string MethodCore => DataConnectionEndpoints.ServicePrefix + "GetCapabilities";
|
||||
protected override string HostCore => "source.local";
|
||||
protected override string PeerCore => "ipv4:127.0.0.1:0";
|
||||
protected override DateTime DeadlineCore => DateTime.MaxValue;
|
||||
protected override Metadata RequestHeadersCore => [];
|
||||
protected override CancellationToken CancellationTokenCore => TestContext.Current.CancellationToken;
|
||||
protected override Metadata ResponseTrailersCore { get; } = [];
|
||||
protected override Status StatusCore { get; set; }
|
||||
protected override WriteOptions? WriteOptionsCore { get; set; }
|
||||
protected override AuthContext AuthContextCore => new(null, new Dictionary<string, List<AuthProperty>>());
|
||||
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => throw new NotSupportedException();
|
||||
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData")]
|
||||
[Trait("Phase", "P07")]
|
||||
public class GrpcDataTrustRotationTests
|
||||
{
|
||||
[Fact]
|
||||
public void Trust_changes_fingerprint_and_name_mismatch_never_falls_back()
|
||||
{
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=localhost", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
var policy = new DataConnectionTrustPolicy(1, [certificate]);
|
||||
using var message = new HttpRequestMessage(HttpMethod.Get, "https://localhost");
|
||||
policy.Validate(message, certificate, null, SslPolicyErrors.RemoteCertificateNameMismatch).ShouldBeFalse();
|
||||
policy.Validate(message, certificate, null, SslPolicyErrors.None).ShouldBeFalse(); // CN alone is insufficient
|
||||
Should.Throw<ArgumentException>(() => new DataConnectionTrustPolicy(2, []));
|
||||
}
|
||||
[Fact]
|
||||
public async Task Trust_version_rotation_and_removal_survive_restart()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new GrpcDataSecretProvisioningTests.MemoryStore();
|
||||
var cipher = new GrpcDataSecretProvisioningTests.TestCipher();
|
||||
var changes = new DataConnectionSecretChangeHandler(); var retired = new List<string>();
|
||||
changes.ConnectionChanged += retired.Add;
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=root", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
using var oldRoot = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
using var newKey = RSA.Create(2048);
|
||||
var newRequest = new CertificateRequest("CN=new", newKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
newRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
using var newRoot = newRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
var policies = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node");
|
||||
await policies.ApplyScopeAsync(1, ["c"], ct);
|
||||
await policies.SetAsync("c", 1, [oldRoot], 1, ct);
|
||||
var old = await policies.ResolveAsync("c", ct); old.ShouldNotBeNull();
|
||||
await policies.SetAsync("c", 2, [oldRoot, newRoot], 1, ct);
|
||||
var rotated = await policies.ResolveAsync("c", ct); rotated.ShouldNotBeNull();
|
||||
rotated.Fingerprint.ShouldNotBe(old.Fingerprint);
|
||||
var restarted = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node");
|
||||
await restarted.SetAsync("c", 3, [newRoot], 1, ct);
|
||||
using var message = new HttpRequestMessage(HttpMethod.Get, "https://localhost");
|
||||
var current = await restarted.ResolveAsync("c", ct); current.ShouldNotBeNull();
|
||||
current.Validate(message, oldRoot, null, SslPolicyErrors.RemoteCertificateChainErrors).ShouldBeFalse();
|
||||
await restarted.SetAsync("c", 4, [], 1, ct);
|
||||
(await restarted.ResolveAsync("c", ct)).ShouldBeNull();
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => restarted.SetAsync("c", 2, [oldRoot], 1, ct));
|
||||
retired.Count.ShouldBe(4);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Trust_tombstone_capacity_does_not_evict_prior_versions()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var store = new GrpcDataSecretProvisioningTests.MemoryStore();
|
||||
var policies = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await policies.ApplyScopeAsync(1, Enumerable.Range(0, DataConnectionTrustPolicyStore.MaximumConnections).Select(i => "c" + i), ct);
|
||||
for (var i = 0; i < DataConnectionTrustPolicyStore.MaximumConnections; i++) await policies.SetAsync("c" + i, 1, [], 1, ct);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => policies.SetAsync("overflow", 1, [], 1, ct));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => policies.SetAsync("c0", 1, [], 1, ct));
|
||||
}
|
||||
[Fact]
|
||||
public void Validation_requires_matching_san_and_trusted_issuer()
|
||||
{
|
||||
using var caKey = RSA.Create(2048);
|
||||
var caRequest = new CertificateRequest("CN=ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true));
|
||||
using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
using var leafKey = RSA.Create(2048);
|
||||
var leafRequest = new CertificateRequest("CN=ignored", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("service.example");
|
||||
leafRequest.CertificateExtensions.Add(san.Build());
|
||||
using var leaf = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddHours(1), [1, 2, 3]);
|
||||
var policy = new DataConnectionTrustPolicy(1, [ca]);
|
||||
using var good = new HttpRequestMessage(HttpMethod.Get, "https://service.example");
|
||||
using var bad = new HttpRequestMessage(HttpMethod.Get, "https://wrong.example");
|
||||
policy.Validate(good, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors).ShouldBeTrue();
|
||||
policy.Validate(bad, leaf, null, SslPolicyErrors.None).ShouldBeFalse();
|
||||
}
|
||||
[Fact]
|
||||
public async Task Failed_trust_notification_can_resume_same_version()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var calls = 0; changes.ConnectionChanged += _ => { calls++; if (calls == 1) throw new InvalidOperationException(); };
|
||||
var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node");
|
||||
await trust.ApplyScopeAsync(1, ["c"], ct);
|
||||
await Should.ThrowAsync<AggregateException>(() => trust.SetAsync("c", 1, [], 1, ct));
|
||||
await trust.SetAsync("c", 1, [], 1, ct);
|
||||
calls.ShouldBe(2);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Scoped_trust_churn_reclaims_retired_ids_and_rejects_stale_scope()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore();
|
||||
var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await trust.ApplyScopeAsync(1, ["first"], ct);
|
||||
await trust.SetAsync("first", 1, [], 1, ct);
|
||||
for (var i = 0; i < DataConnectionTrustPolicyStore.MaximumConnections + 1; i++)
|
||||
{
|
||||
var generation = 2L + i; var id = "c" + i;
|
||||
await trust.ApplyScopeAsync(generation, [id], ct);
|
||||
await trust.SetAsync(id, 1, [], generation, ct);
|
||||
}
|
||||
var latest = 3L + DataConnectionTrustPolicyStore.MaximumConnections;
|
||||
await trust.ApplyScopeAsync(latest, ["first"], ct);
|
||||
trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => trust.SetAsync("first", 999, [], 1, ct));
|
||||
await trust.SetAsync("first", 1, [], latest, ct);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Failed_retirement_followed_by_reintroduction_cannot_restore_old_ca()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore();
|
||||
var changes = new DataConnectionSecretChangeHandler(); var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node");
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
await trust.ApplyScopeAsync(1, ["c"], ct);
|
||||
await trust.SetAsync("c", 1, [ca], 1, ct);
|
||||
Action<string> broken = _ => throw new InvalidOperationException("retirement failed");
|
||||
changes.ConnectionChanged += broken;
|
||||
await Should.ThrowAsync<AggregateException>(() => trust.ApplyScopeAsync(2, [], ct));
|
||||
changes.ConnectionChanged -= broken;
|
||||
trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node");
|
||||
await trust.ApplyScopeAsync(3, ["c"], ct);
|
||||
(await trust.ResolveAsync("c", ct)).ShouldBeNull();
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => trust.SetAsync("c", 999, [ca], 1, ct));
|
||||
await trust.SetAsync("c", 1, [ca], 3, ct);
|
||||
(await trust.ResolveAsync("c", ct)).ShouldNotBeNull();
|
||||
}
|
||||
[Fact]
|
||||
public async Task Trust_scope_identifiers_and_owner_node_are_case_insensitive_across_restart()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore();
|
||||
var cipher = new GrpcDataSecretProvisioningTests.TestCipher(); var changes = new DataConnectionSecretChangeHandler();
|
||||
var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "Cluster", "Node");
|
||||
await trust.ApplyScopeAsync(1, ["Link"], ct);
|
||||
await trust.SetAsync("link", 1, [], 1, ct);
|
||||
trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "cluster", "NODE");
|
||||
await trust.ApplyScopeAsync(1, ["LINK"], ct);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => trust.SetAsync("LINK", 1, [], 1, ct));
|
||||
await trust.ApplyScopeAsync(2, [], ct);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => trust.SetAsync("link", 999, [], 1, ct));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => trust.ApplyScopeAsync(3, ["Link", "link"], ct));
|
||||
}
|
||||
[Fact]
|
||||
public void A_trusted_server_name_with_client_auth_only_certificate_is_rejected()
|
||||
{
|
||||
using var caKey = RSA.Create(2048);
|
||||
var caRequest = new CertificateRequest("CN=ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true));
|
||||
using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
using var leafKey = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=ignored", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("service.example"); request.CertificateExtensions.Add(san.Build());
|
||||
var usages = new OidCollection { new Oid("1.3.6.1.5.5.7.3.2") };
|
||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(usages, true));
|
||||
using var leaf = request.Create(ca, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddHours(1), [4, 5, 6]);
|
||||
using var message = new HttpRequestMessage(HttpMethod.Get, "https://service.example");
|
||||
new DataConnectionTrustPolicy(1, [ca]).Validate(message, leaf, null, SslPolicyErrors.None).ShouldBeFalse();
|
||||
}
|
||||
[Fact]
|
||||
public async Task Public_trust_batch_rejects_excess_certificate_count_and_bytes_before_writing()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore();
|
||||
var policy = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node");
|
||||
await policy.ApplyScopeAsync(1, ["c"], ct);
|
||||
using var key = RSA.Create(2048);
|
||||
var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
|
||||
request.CertificateExtensions.Add(new X509Extension("1.2.3.4", new byte[16384], false));
|
||||
using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => policy.SetBundleAsync([("c", 1, Enumerable.Repeat(cert, DataConnectionTrustPolicyStore.MaximumRootCertificates + 1).ToArray())], 1, ct));
|
||||
var byteLimitCount = checked((int)(DataConnectionTrustPolicyStore.MaximumTrustBytes / cert.RawData.Length) + 1);
|
||||
byteLimitCount.ShouldBeLessThanOrEqualTo(DataConnectionTrustPolicyStore.MaximumRootCertificates);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => policy.SetBundleAsync([("c", 1, Enumerable.Repeat(cert, byteLimitCount).ToArray())], 1, ct));
|
||||
await policy.SetAsync("c", 1, [], 1, ct); // rejected batches wrote nothing
|
||||
}
|
||||
}
|
||||
+23
@@ -1,12 +1,35 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataCachedReadTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Source_invalidation_during_publication_authority_validation_is_rechecked_afterwards()
|
||||
{
|
||||
using var fixture = new LocalDataFixture();
|
||||
var invalidate = false;
|
||||
var capabilities = new DataCapabilitiesProvider("cluster", () => fixture.Serving,
|
||||
() => fixture.Catalog.IsActive, fixture.Services.SubscriptionLimits);
|
||||
var services = new LocalDataServices(() =>
|
||||
{
|
||||
if (invalidate) fixture.Hub.Invalidate(fixture.Ticket, "During publication authority validation");
|
||||
return fixture.Catalog;
|
||||
}, fixture.Hub, new DataOperationPolicy(fixture.Authority,
|
||||
new TriePermissionEvaluator(fixture.Authority.Tries, fixture.Clock), fixture.Clock), capabilities, fixture.Clock);
|
||||
fixture.Publish(7);
|
||||
await using var connection = services.Create(fixture.Context, new(DataTargetMode.Node, "cluster", "node-a"));
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using var result = results.ShouldHaveSingleItem();
|
||||
var lease = result.ResourceLease.ShouldBeAssignableTo<IDataPublicationLease>();
|
||||
invalidate = true;
|
||||
lease!.IsValid.ShouldBeFalse();
|
||||
}
|
||||
[Fact]
|
||||
public async Task Prepared_response_is_fenced_before_send_after_ingress_invalidation_or_authority_change()
|
||||
{
|
||||
|
||||
+114
-5
@@ -1,8 +1,11 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.Json;
|
||||
using Akka.Actor;
|
||||
using Akka.DependencyInjection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
@@ -33,6 +36,34 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
|
||||
private static readonly ServingIdentity BootIdentity = new("node-a", "process-1", "Primary", 0, 0);
|
||||
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 100, 1_000_000);
|
||||
|
||||
[Fact]
|
||||
public async Task Returning_to_the_same_role_cannot_revive_a_previous_publication_permit()
|
||||
{
|
||||
var authority = new DataPlaneAuthorityState();
|
||||
var serving = BootIdentity with { ServingGeneration = 1 };
|
||||
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(), authority, () => serving);
|
||||
var attempt = Prepare(coordinator, Artifact());
|
||||
coordinator.Complete(attempt, true).ShouldBeTrue();
|
||||
using var hub = HubTest.Create();
|
||||
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
|
||||
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
||||
var caps = new DataCapabilitiesProvider("cluster", () => coordinator.Serving, () => coordinator.Current is not null, limits);
|
||||
var services = new LocalDataServices(() => coordinator.Current, hub,
|
||||
new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, hub.Clock), hub.Clock), caps, hub.Clock);
|
||||
var key = authority.Current.FindUsableKey("peer-key", DateTime.UtcNow).ShouldNotBeNull();
|
||||
await using var connection = services.Create(new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key),
|
||||
DateTimeOffset.UtcNow.AddMinutes(10), authority.Current.GenerationId), new(DataTargetMode.Node, "cluster", Node.Value));
|
||||
var previous = await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
|
||||
var gate = (IDataConnectionPublicationGate)connection;
|
||||
gate.CanPublish(previous.Serving).ShouldBeTrue();
|
||||
// The consumer need not observe the intervening demotion or actor replacement.
|
||||
serving = serving with { ServingGeneration = 3 };
|
||||
gate.CanPublish(previous.Serving).ShouldBeFalse();
|
||||
var current = await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
|
||||
current.Serving.ServingGeneration.ShouldBe(3);
|
||||
gate.CanPublish(current.Serving).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_new_attempt_closes_a_completed_catalog_even_when_authority_revision_is_unchanged()
|
||||
{
|
||||
@@ -274,11 +305,13 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
|
||||
var coordinator = NewCoordinator(authority, activation);
|
||||
using var entered = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var sink = NullOpcUaAddressSpaceSink.Instance;
|
||||
var hooks = new OpcUaPublishActor.TestHooks { BeforeComposition = () => { entered.Set(); release.Wait(); } };
|
||||
var publish = Sys.ActorOf(OpcUaPublishActor.PropsForTests(sink,
|
||||
new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), hooks,
|
||||
dataPlaneAuthority: authority, catalogCoordinator: coordinator));
|
||||
var sink = new HeldFolderSink(entered, release);
|
||||
using var services = new ServiceCollection()
|
||||
.AddSingleton<IDataPlaneAuthoritySink>(authority)
|
||||
.AddSingleton(activation).AddSingleton(coordinator).BuildServiceProvider();
|
||||
var props = DataConnectionPublisherProps.Create(new ServiceProviderDependencyResolver(services), sink, NullServiceLevelPublisher.Instance, Node,
|
||||
dbFactory: null, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance), dbHealthProbe: null);
|
||||
var publish = Sys.ActorOf(props.WithDispatcher("akka.actor.default-dispatcher"));
|
||||
var acks = CreateTestProbe();
|
||||
var host = NewHost(bytes, coordinator, acks.Ref, publish: publish);
|
||||
try
|
||||
@@ -297,6 +330,52 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
|
||||
finally { release.Set(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_next_local_artifact_drains_active_import_before_fallible_staging()
|
||||
{
|
||||
var first = JsonNode.Parse(Artifact())!.AsObject();
|
||||
first["DataConnectionScopeVersion"] = 1;
|
||||
first["DataConnections"] = JsonSerializer.SerializeToNode(new[] { new DataConnection
|
||||
{
|
||||
DataConnectionId = "link", ClusterId = "cluster", Revision = 1, Enabled = true,
|
||||
ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "remote-cluster", ExpectedNodeId = "remote",
|
||||
Endpoints = ["https://remote.example:8443"], SecretReference = "secret:data/key", SecretScopeClusterId = "cluster",
|
||||
AllowedOperations = DataOperations.Read
|
||||
}});
|
||||
var valid = Encoding.UTF8.GetBytes(first.ToJsonString());
|
||||
DeploymentArtifact.ParseDataConnectionScopeVersion(valid).ShouldBe(1);
|
||||
DeploymentArtifact.ParseDataConnections(valid, Node.Value).ShouldHaveSingleItem().DataConnectionId.ShouldBe("link");
|
||||
var fetcher = new MutableFetcher(valid); var authority = new DataPlaneAuthorityState();
|
||||
var coordinator = NewCoordinator(authority, new CatalogActivation());
|
||||
await using var outbound = new DataConnectionDeploymentRuntime("node-a", "cluster", new ReadySecurity(), new ImmediateScope(), 8);
|
||||
var acks = CreateTestProbe();
|
||||
var host = Sys.ActorOf(DriverHostActor.Props(dbFactory: null, localNode: Node, ackRouter: acks.Ref,
|
||||
localRoles: new HashSet<string> { "driver" }, fetchAndCacheMode: true, artifactFetcher: fetcher,
|
||||
catalogCoordinator: coordinator, dataConnections: outbound));
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(valid), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||||
AwaitCondition(() => outbound.CurrentScopeReady, TimeSpan.FromSeconds(2), "initial scope activation never completed", TestContext.Current.CancellationToken);
|
||||
AwaitCondition(() =>
|
||||
{
|
||||
if (!outbound.TryAcquire("link", out var candidate)) return false;
|
||||
candidate!.Dispose(); return true;
|
||||
}, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
outbound.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
var invalid = first.DeepClone().AsObject();
|
||||
invalid["DataConnectionScopeVersion"] = 2;
|
||||
invalid["DataConnections"] = new JsonArray();
|
||||
invalid["RawFolders"] = new JsonObject(); // malformed local topology, before scope apply
|
||||
fetcher.Bytes = Encoding.UTF8.GetBytes(invalid.ToJsonString());
|
||||
host.Tell(new DispatchDeployment(DeploymentId.NewId(), Revision(fetcher.Bytes), CorrelationId.NewId()));
|
||||
acks.ExpectMsg<ApplyAck>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
outbound.CurrentScopeReady.ShouldBeFalse();
|
||||
outbound.TryAcquire("link", out _).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Role_transition_reuses_the_adjusted_catalog_and_does_not_freshen_the_cached_acquisition()
|
||||
{
|
||||
@@ -571,6 +650,36 @@ public sealed class GrpcDataCatalogStagingTests : RuntimeActorTestBase
|
||||
return Encoding.UTF8.GetBytes(root.ToJsonString());
|
||||
}
|
||||
|
||||
private sealed class ReadySecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new("1", "trust", "key", () => new NoNetworkHandler()));
|
||||
}
|
||||
private sealed class NoNetworkHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException("This test does not send network traffic.");
|
||||
}
|
||||
private sealed class ImmediateScope : IDataConnectionScopeActivator
|
||||
{
|
||||
public Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class HeldFolderSink(ManualResetEventSlim entered, ManualResetEventSlim release) : IOpcUaAddressSpaceSink
|
||||
{
|
||||
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
|
||||
public void WriteAlarmQuality(string alarmNodeId, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm) { }
|
||||
public void WriteAlarmCondition(string alarmNodeId, AlarmConditionSnapshot state, DateTime occurredUtc, AddressSpaceRealm realm) { }
|
||||
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false) { }
|
||||
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { entered.Set(); release.Wait(); }
|
||||
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false) { }
|
||||
public void RebuildAddressSpace() { }
|
||||
public void RaiseNodesAddedModelChange(string affectedNodeId, AddressSpaceRealm realm) { }
|
||||
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
|
||||
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes") { }
|
||||
}
|
||||
|
||||
private sealed class MutableFetcher(byte[] bytes) : IDeploymentArtifactFetcher
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
+824
@@ -0,0 +1,824 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Net;
|
||||
using Google.Protobuf;
|
||||
using Shouldly;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataConnectionClientTests
|
||||
{
|
||||
private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5));
|
||||
private static readonly ServingIdentity Serving = new("a", "boot", "Primary", 1, 1, 1);
|
||||
private static readonly DataView View = new(new("c", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x");
|
||||
private static readonly DataBudget Budget = new(TimeSpan.FromSeconds(5), 16, 65536);
|
||||
|
||||
[Fact]
|
||||
public void Security_material_does_not_render_the_presented_bearer()
|
||||
{
|
||||
var security = new DataConnectionSecurity("credential-v1", "trust-fingerprint", "sensitive-bearer-value", () => new WireHandler());
|
||||
security.ToString().ShouldNotContain("sensitive-bearer-value");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Configured_pending_byte_cap_is_enforced_before_stream_command_send()
|
||||
{
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)]));
|
||||
ack.Serving = DataProtoMapper.EncodeServing(Serving);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"),
|
||||
65536, 1, maxPendingCommandBytes: 128);
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5),
|
||||
[new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Pending_command_bytes_are_shared_across_streams()
|
||||
{
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)]));
|
||||
ack.Serving = DataProtoMapper.EncodeServing(Serving);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"),
|
||||
65536, 1, maxPendingCommandBytes: 500);
|
||||
await using var first = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
await using var second = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
await first.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => second.SendAsync(new OpenSubscription("s2", 1, "open2", TimeSpan.FromSeconds(5),
|
||||
[new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Local_stream_capacity_must_be_positive_independently_of_peer_limits()
|
||||
{
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
using var scope = manager.Acquire("link");
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(new WireHandler()), scope, 65536, 1, maxStreams: 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Negotiated_envelope_peer_must_advertise_a_positive_serving_generation()
|
||||
{
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(new WireHandler { ZeroServingGeneration = true }), manager.Acquire("link"), 65536, 1);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Lost_write_reply_is_unknown_and_is_not_resent()
|
||||
{
|
||||
var handler = new WireHandler { LoseWrite = true };
|
||||
var security = new Security(handler);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], security, manager.Acquire("link"), 65536, 1);
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
||||
var result = await connection.WriteAsync(new([new("item", "op", View, value, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken);
|
||||
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
handler.WriteCalls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Browse_rejects_a_lease_from_another_authority_generation()
|
||||
{
|
||||
var handler = new WireHandler { BadBrowseLease = true };
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.BrowseAsync(new(View, null, null, Budget), TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Read_rejects_a_response_from_another_boot()
|
||||
{
|
||||
var handler = new WireHandler { WrongReadServing = true };
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.ReadAsync(new([new("item", View, null)], Budget), TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task No_ready_primary_backs_off_before_probing_again()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var handler = new UnreadyHandler();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1, clock,
|
||||
new HashSet<string> { "a" });
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
|
||||
handler.Calls.ShouldBe(1);
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
|
||||
handler.Calls.ShouldBe(2);
|
||||
}
|
||||
private sealed class UnreadyHandler : HttpMessageHandler
|
||||
{
|
||||
public int Calls { get; private set; }
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
Calls++;
|
||||
return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2,
|
||||
Serving with { Role = "Secondary" }, DataReadiness.Ready, DataOperations.Read,
|
||||
new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Discovery_consumes_each_write_items_original_budget_independently()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var handler = new FailoverHandler("a", false, () => clock.Advance(TimeSpan.FromMilliseconds(600)));
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://a.test")], new PairSecurity(handler, handler), manager.Acquire("link"), 65536, 1, clock);
|
||||
using var first = DataValue.FromScalar(DataValueKind.Int32, 1);
|
||||
using var second = DataValue.FromScalar(DataValueKind.Int32, 2);
|
||||
var result = await connection.WriteAsync(new([new("expired", "one", View, first, 1, "boot", TimeSpan.FromMilliseconds(500)),
|
||||
new("live", "two", View, second, 1, "boot", TimeSpan.FromSeconds(3))], Budget), TestContext.Current.CancellationToken);
|
||||
result[0].Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
result[1].Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
handler.WrittenIds.ShouldBe(new[] { "live" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failover_metadata_cannot_restart_a_rejected_items_budget()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var first = new FailoverHandler("a", true);
|
||||
var second = new FailoverHandler("b", false, onMetadata: () => clock.Advance(TimeSpan.FromMilliseconds(600)));
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
|
||||
[new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"),
|
||||
65536, 2, clock, new HashSet<string> { "a", "b" });
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 1);
|
||||
var result = await connection.WriteAsync(new([new("retry", "one", View, value, 1, "boot", TimeSpan.FromMilliseconds(500))], Budget), TestContext.Current.CancellationToken);
|
||||
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||||
second.WrittenIds.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cluster_failover_retries_only_authenticated_pre_dispatch_rejection()
|
||||
{
|
||||
var first = new FailoverHandler("a", true);
|
||||
var second = new FailoverHandler("b", false);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Cluster, "c", null),
|
||||
[new Uri("https://a.test"), new Uri("https://b.test")], new PairSecurity(first, second), manager.Acquire("link"),
|
||||
65536, 2, eligibleNodeIds: new HashSet<string> { "a", "b" });
|
||||
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 1);
|
||||
using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 2);
|
||||
var result = await connection.WriteAsync(new([new("retry", "one", View, firstValue, 1, "boot", TimeSpan.FromSeconds(4)),
|
||||
new("unknown", "two", View, secondValue, 1, "boot", TimeSpan.FromSeconds(4))], Budget), TestContext.Current.CancellationToken);
|
||||
result[0].Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
||||
result[1].Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
second.WrittenIds.ShouldBe(new[] { "retry" });
|
||||
}
|
||||
private sealed class PairSecurity(FailoverHandler first, FailoverHandler second) : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => endpoint.Host == "a.test" ? first : second));
|
||||
}
|
||||
private sealed class FailoverHandler(string node, bool rejectFirst, Action? onCapabilities = null, Action? onMetadata = null) : HttpMessageHandler
|
||||
{
|
||||
public List<string> WrittenIds { get; } = [];
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
var serving = new ServingIdentity(node, "boot", "Primary", 1, 1, 1);
|
||||
IMessage message;
|
||||
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
||||
{
|
||||
onCapabilities?.Invoke();
|
||||
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, serving, DataReadiness.Ready,
|
||||
DataOperations.Read | DataOperations.Write | DataOperations.Metadata, new HashSet<DataValueKind> { DataValueKind.Int32 },
|
||||
Limits, false, 0, "c", false, true));
|
||||
}
|
||||
else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal))
|
||||
{
|
||||
onMetadata?.Invoke();
|
||||
var metadata = new DataMetadata(View, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write,
|
||||
2, null, null, false);
|
||||
var wire = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]);
|
||||
wire.Serving = DataProtoMapper.EncodeServing(serving); message = wire;
|
||||
}
|
||||
else
|
||||
{
|
||||
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
|
||||
var write = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
|
||||
WrittenIds.AddRange(write.Items.Select(x => x.CorrelationId));
|
||||
var result = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(serving) };
|
||||
foreach (var item in write.Items)
|
||||
result.Items.Add(DataProtoMapper.EncodeWriteResult(new(item.CorrelationId, new(rejectFirst
|
||||
? item.CorrelationId == "retry" ? DataWriteState.RejectedBeforeDispatch : DataWriteState.OutcomeUnknown
|
||||
: DataWriteState.DriverConfirmedSuccess, 1, null))));
|
||||
message = result;
|
||||
}
|
||||
return Frame(message);
|
||||
}
|
||||
}
|
||||
private static HttpResponseMessage Frame(IMessage message)
|
||||
{
|
||||
var payload = message.ToByteArray(); var framed = new byte[payload.Length + 5];
|
||||
BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length); payload.CopyTo(framed, 5);
|
||||
var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
|
||||
response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0");
|
||||
return response;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Reconnect_cannot_reuse_the_same_subscription_epoch()
|
||||
{
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)]));
|
||||
ack.Serving = DataProtoMapper.EncodeServing(Serving);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1);
|
||||
var open = new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget);
|
||||
await using (var first = await connection.SubscribeAsync(TestContext.Current.CancellationToken))
|
||||
{
|
||||
await first.SendAsync(open, TestContext.Current.CancellationToken);
|
||||
await using var reader = first.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
|
||||
(await reader.MoveNextAsync()).ShouldBeTrue();
|
||||
}
|
||||
await using var second = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => second.SendAsync(open, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Acknowledged_command_payload_is_not_retained_by_a_delayed_timer_continuation()
|
||||
{
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)]));
|
||||
ack.Serving = DataProtoMapper.EncodeServing(Serving);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(new StreamWireHandler([ack])), manager.Acquire("link"), 65536, 1);
|
||||
WeakReference? pendingIdentity = null;
|
||||
var timerEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var releaseTimer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
connection.PendingIdentityObserverForTests = weak => pendingIdentity = weak;
|
||||
connection.AfterTimerCancelledForTests = async () => { timerEntered.TrySetResult(); await releaseTimer.Task; };
|
||||
try
|
||||
{
|
||||
await SendOneAndDrainAsync(connection, settings);
|
||||
await timerEntered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
for (var i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); }
|
||||
pendingIdentity.ShouldNotBeNull();
|
||||
pendingIdentity.IsAlive.ShouldBeFalse();
|
||||
}
|
||||
finally { releaseTimer.TrySetResult(); }
|
||||
}
|
||||
private static async Task SendOneAndDrainAsync(GrpcDataConnection connection, DataSubscriptionSettings settings)
|
||||
{
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(20), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken);
|
||||
await using var reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
|
||||
(await reader.MoveNextAsync()).ShouldBeTrue();
|
||||
(await reader.MoveNextAsync()).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Stream_acknowledgement_is_bound_to_the_sent_copy_not_a_mutated_caller_list()
|
||||
{
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open",
|
||||
[new("item", DataItemStatus.Good, handle, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null), null)]));
|
||||
ack.Serving = DataProtoMapper.EncodeServing(Serving);
|
||||
var handler = new StreamWireHandler([ack]);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
var items = new List<DataSubscriptionItem> { new("item", View, new(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null)) };
|
||||
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), items, false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken);
|
||||
items.Clear();
|
||||
await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
|
||||
(await enumerator.MoveNextAsync()).ShouldBeTrue();
|
||||
enumerator.Current.ShouldBeOfType<DataSubscriptionAck>();
|
||||
}
|
||||
[Fact]
|
||||
public async Task Stream_rejects_reuse_of_a_removed_handle_for_a_new_item()
|
||||
{
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
W.SubscriptionFrame Ack(long sequence, string id, string clientId, DataItemHandle item)
|
||||
{
|
||||
var wire = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, sequence, id,
|
||||
[new(clientId, DataItemStatus.Good, item, settings, null)]));
|
||||
wire.Serving = DataProtoMapper.EncodeServing(Serving); return wire;
|
||||
}
|
||||
var handler = new StreamWireHandler([Ack(1, "open", "item", handle), Ack(2, "remove", "item", handle), Ack(3, "add", "other", handle)]);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken);
|
||||
await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
|
||||
(await enumerator.MoveNextAsync()).ShouldBeTrue();
|
||||
await subscription.SendAsync(new RemoveSubscriptionItems("s", 1, "remove", TimeSpan.FromSeconds(5), [handle]), TestContext.Current.CancellationToken);
|
||||
(await enumerator.MoveNextAsync()).ShouldBeTrue();
|
||||
await subscription.SendAsync(new AddSubscriptionItems("s", 1, "add", TimeSpan.FromSeconds(5), [new("other", View, settings)]), TestContext.Current.CancellationToken);
|
||||
await Should.ThrowAsync<InvalidOperationException>(async () => await enumerator.MoveNextAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Stream_rejects_a_sample_version_regression_before_yield()
|
||||
{
|
||||
var handle = new DataItemHandle("s", 1, 1, 1);
|
||||
var settings = new DataSubscriptionSettings(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), DataChangeTrigger.StatusValue, null);
|
||||
var ack = DataProtoMapper.EncodeControlOrAck(new DataSubscriptionAck("s", 1, 1, "open", [new("item", DataItemStatus.Good, handle, settings, null)]));
|
||||
ack.Serving = DataProtoMapper.EncodeServing(Serving);
|
||||
W.SubscriptionFrame ValueFrame(long seq, long version)
|
||||
{
|
||||
using var frame = new DataSubscriptionValues("s", 1, seq, false,
|
||||
[new(handle, new DataSample(DataValue.FromScalar(DataValueKind.Int32, 42), 0, null, null, Serving, version))]);
|
||||
var wire = DataProtoMapper.EncodeValues(frame, false); wire.Serving = DataProtoMapper.EncodeServing(Serving); return wire;
|
||||
}
|
||||
var handler = new StreamWireHandler([ack, ValueFrame(2, 100), ValueFrame(3, 99)]);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(5), [new("item", View, settings)], false, TimeSpan.FromMinutes(1), Budget), TestContext.Current.CancellationToken);
|
||||
await using var enumerator = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
|
||||
(await enumerator.MoveNextAsync()).ShouldBeTrue();
|
||||
(await enumerator.MoveNextAsync()).ShouldBeTrue();
|
||||
((IDisposable)enumerator.Current).Dispose();
|
||||
await Should.ThrowAsync<InvalidOperationException>(async () => await enumerator.MoveNextAsync());
|
||||
}
|
||||
private sealed class StreamWireHandler(IReadOnlyList<W.SubscriptionFrame> frames) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
||||
return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready,
|
||||
DataOperations.Subscribe, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))));
|
||||
using var stream = new MemoryStream();
|
||||
foreach (var frame in frames)
|
||||
{
|
||||
var bytes = frame.ToByteArray(); var prefix = new byte[5]; BinaryPrimitives.WriteInt32BigEndian(prefix.AsSpan(1), bytes.Length);
|
||||
stream.Write(prefix); stream.Write(bytes);
|
||||
}
|
||||
var sent = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_ = DrainRequestAsync(request.Content!, sent, cancellationToken);
|
||||
var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20,
|
||||
Content = new StreamContent(new GatedResponseStream(stream.ToArray(), sent.Task)) };
|
||||
response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0");
|
||||
return Task.FromResult(response);
|
||||
}
|
||||
private static async Task DrainRequestAsync(HttpContent content, TaskCompletionSource sent, CancellationToken ct)
|
||||
{
|
||||
try { await content.CopyToAsync(new SignalSink(sent), ct); }
|
||||
catch (Exception) { sent.TrySetCanceled(); }
|
||||
}
|
||||
}
|
||||
private sealed class SignalSink(TaskCompletionSource sent) : Stream
|
||||
{
|
||||
public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true;
|
||||
public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
public override void Flush() { }
|
||||
public override void Write(byte[] buffer, int offset, int count) { if (count > 0) sent.TrySetResult(); }
|
||||
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{ if (buffer.Length > 0) sent.TrySetResult(); return ValueTask.CompletedTask; }
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
}
|
||||
private sealed class GatedResponseStream(byte[] bytes, Task sent) : MemoryStream(bytes)
|
||||
{
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{ await sent.WaitAsync(cancellationToken); return await base.ReadAsync(buffer, cancellationToken); }
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{ await sent.WaitAsync(cancellationToken); return await base.ReadAsync(buffer, offset, count, cancellationToken); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disposal_winning_before_stream_install_keeps_raw_send_charged()
|
||||
{
|
||||
var handler = new BlockedDuplexHandler();
|
||||
var installReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var proceed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
var consumers = new HashSet<string> { "consumer" };
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(1, consumers) });
|
||||
var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1, maxStreams: 1);
|
||||
connection.BeforeStreamInstallForTests = async () =>
|
||||
{
|
||||
await handler.Started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
installReached.TrySetResult();
|
||||
await proceed.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
};
|
||||
var opening = connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
Task? closing = null;
|
||||
try
|
||||
{
|
||||
await installReached.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
closing = connection.DisposeAsync().AsTask();
|
||||
proceed.TrySetResult();
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => opening);
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(2, consumers) });
|
||||
await Should.ThrowAsync<TimeoutException>(() => closing.WaitAsync(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken));
|
||||
Should.Throw<UnauthorizedAccessException>(() => manager.Acquire("link"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
proceed.TrySetResult(); handler.Release.TrySetResult();
|
||||
try { await opening; } catch (Exception) { }
|
||||
if (closing is not null) await closing;
|
||||
await connection.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Stream_capacity_is_reserved_before_blocked_capability_discovery()
|
||||
{
|
||||
var provider = new IgnoringSecurity();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxStreams: 1);
|
||||
var first = connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.SubscribeAsync(TestContext.Current.CancellationToken));
|
||||
provider.Sends.ShouldBe(1);
|
||||
}
|
||||
finally { provider.Release.TrySetResult(); try { await first; } catch (Exception) { } }
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Duplex_disposal_waits_for_ignored_preheaders_http_send(bool startReader)
|
||||
{
|
||||
var handler = new BlockedDuplexHandler();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], new Security(handler), manager.Acquire("link"), 65536, 1);
|
||||
var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
IAsyncEnumerator<DataSubscriptionFrame>? reader = null;
|
||||
Task<bool>? moving = null;
|
||||
try
|
||||
{
|
||||
await handler.Started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
if (startReader)
|
||||
{
|
||||
reader = subscription.ReadAllAsync(TestContext.Current.CancellationToken).GetAsyncEnumerator(TestContext.Current.CancellationToken);
|
||||
moving = reader.MoveNextAsync().AsTask();
|
||||
}
|
||||
var closing = subscription.DisposeAsync().AsTask();
|
||||
await Should.ThrowAsync<TimeoutException>(() => closing.WaitAsync(TimeSpan.FromMilliseconds(500), TestContext.Current.CancellationToken));
|
||||
}
|
||||
finally
|
||||
{
|
||||
handler.Release.TrySetResult();
|
||||
if (moving is not null) { try { await moving; } catch (Exception) { } }
|
||||
if (reader is not null) await reader.DisposeAsync();
|
||||
await subscription.DisposeAsync();
|
||||
}
|
||||
}
|
||||
private sealed class BlockedDuplexHandler : HttpMessageHandler
|
||||
{
|
||||
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
||||
return Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready,
|
||||
DataOperations.Subscribe, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)));
|
||||
Started.TrySetResult(); await Release.Task;
|
||||
var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent([]) };
|
||||
response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0");
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ignored_response_body_cancellation_remains_charged_after_rotation()
|
||||
{
|
||||
var provider = new IgnoringBodySecurity();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxConcurrentUnaryCalls: 1);
|
||||
var first = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
provider.Rotate();
|
||||
await provider.Disposed.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
first.IsCompleted.ShouldBeFalse();
|
||||
var failure = await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
|
||||
failure.Message.ShouldBe("Unary capacity exhausted.");
|
||||
provider.Sends.ShouldBe(1);
|
||||
}
|
||||
finally { provider.Release.TrySetResult(); try { await first; } catch (Exception) { } }
|
||||
await WaitForReady(connection);
|
||||
provider.Sends.ShouldBe(2);
|
||||
}
|
||||
private sealed class IgnoringBodySecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
private int _version;
|
||||
public event Action<string>? Changed;
|
||||
public int Sends;
|
||||
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new(_version.ToString(), "ca", "key", () => new IgnoringBodyHandler(this)));
|
||||
public void Rotate() { _version++; Changed?.Invoke("link"); }
|
||||
}
|
||||
private sealed class IgnoringBodyHandler(IgnoringBodySecurity owner) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Increment(ref owner.Sends) > 1)
|
||||
return Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready,
|
||||
DataOperations.Read, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))));
|
||||
var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20,
|
||||
Content = new StreamContent(new IgnoringBodyStream(owner)) };
|
||||
response.Content.Headers.ContentType = new("application/grpc"); response.TrailingHeaders.Add("grpc-status", "0");
|
||||
return Task.FromResult(response);
|
||||
}
|
||||
protected override void Dispose(bool disposing) { if (disposing) owner.Disposed.TrySetResult(); base.Dispose(disposing); }
|
||||
}
|
||||
private sealed class IgnoringBodyStream(IgnoringBodySecurity owner) : Stream
|
||||
{
|
||||
public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => false;
|
||||
public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{ owner.Started.TrySetResult(); await owner.Release.Task; return 0; }
|
||||
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
||||
{ owner.Started.TrySetResult(); await owner.Release.Task; return 0; }
|
||||
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
public override void Flush() { }
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ignored_http_cancellation_remains_charged_after_channel_dispose_and_rotation()
|
||||
{
|
||||
var provider = new IgnoringSecurity();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1, maxConcurrentUnaryCalls: 1);
|
||||
var first = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
provider.Rotate();
|
||||
await provider.Disposed.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
first.IsCompleted.ShouldBeFalse();
|
||||
var failure = await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
|
||||
failure.Message.ShouldBe("Unary capacity exhausted.");
|
||||
provider.Sends.ShouldBe(1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
provider.Release.TrySetResult();
|
||||
try { await first; } catch (Exception) { }
|
||||
}
|
||||
await WaitForReady(connection);
|
||||
provider.Sends.ShouldBe(2);
|
||||
}
|
||||
private static async Task WaitForReady(GrpcDataConnection connection)
|
||||
{
|
||||
for (var attempt = 0; attempt < 100; attempt++)
|
||||
{
|
||||
try { await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken); return; }
|
||||
catch (InvalidOperationException) { await Task.Delay(50, TestContext.Current.CancellationToken); }
|
||||
}
|
||||
throw new TimeoutException("Fresh channel did not recover.");
|
||||
}
|
||||
private sealed class IgnoringSecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
private int _version;
|
||||
public event Action<string>? Changed;
|
||||
public int Sends;
|
||||
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Disposed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new(_version.ToString(), "ca", "key", () => new IgnoringHandler(this)));
|
||||
public void Rotate() { _version++; Changed?.Invoke("link"); }
|
||||
}
|
||||
private sealed class IgnoringHandler(IgnoringSecurity owner) : HttpMessageHandler
|
||||
{
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Increment(ref owner.Sends) == 1)
|
||||
{ owner.Started.TrySetResult(); await owner.Release.Task; }
|
||||
return Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready,
|
||||
DataOperations.Read, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "c", false, true)));
|
||||
}
|
||||
protected override void Dispose(bool disposing) { if (disposing) owner.Disposed.TrySetResult(); base.Dispose(disposing); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Connection_disposal_retains_scope_until_physical_channel_cleanup_finishes()
|
||||
{
|
||||
var provider = new BlockingSecurity();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
var members = new HashSet<string> { "consumer" };
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(1, members) });
|
||||
var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1);
|
||||
try
|
||||
{
|
||||
await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
|
||||
var disposal = connection.DisposeAsync().AsTask();
|
||||
await provider.Entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(2, members) });
|
||||
disposal.IsCompleted.ShouldBeFalse();
|
||||
Should.Throw<UnauthorizedAccessException>(() => manager.Acquire("link"));
|
||||
}
|
||||
finally { provider.Release.Set(); await connection.DisposeAsync(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Blocked_channel_disposal_remains_charged_during_rotation()
|
||||
{
|
||||
var provider = new BlockingSecurity();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1);
|
||||
try
|
||||
{
|
||||
await connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
|
||||
provider.Rotate();
|
||||
await provider.Entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken));
|
||||
provider.Created.ShouldBe(1);
|
||||
}
|
||||
finally { provider.Release.Set(); }
|
||||
}
|
||||
private sealed class BlockingSecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed;
|
||||
public int Created { get; private set; }
|
||||
public ManualResetEventSlim Release { get; } = new();
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => { Created++; return new BlockingHandler(this); }));
|
||||
public void Rotate() => Changed?.Invoke("link");
|
||||
}
|
||||
private sealed class BlockingHandler(BlockingSecurity owner) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(Frame(DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, Serving, DataReadiness.Ready,
|
||||
DataOperations.Read, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits, false, 0, "c", false, true))));
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing) { owner.Entered.TrySetResult(); owner.Release.Wait(); }
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rotation_during_resolution_cannot_install_stale_security()
|
||||
{
|
||||
var provider = new DelayedSecurity();
|
||||
using var manager = new DataConnectionManager("consumer", 1);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "consumer" } });
|
||||
await using var connection = new GrpcDataConnection("link", new(DataTargetMode.Node, "c", "a"),
|
||||
[new Uri("https://example.test")], provider, manager.Acquire("link"), 65536, 1);
|
||||
var pending = connection.GetCapabilitiesAsync(Budget, TestContext.Current.CancellationToken);
|
||||
await provider.Started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
provider.Rotate();
|
||||
provider.Resolved.SetResult(new("old", "old-ca", "key", () => { provider.Installed = true; throw new InvalidOperationException("Stale handler installed."); }));
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => pending);
|
||||
provider.Installed.ShouldBeFalse();
|
||||
}
|
||||
private sealed class DelayedSecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed;
|
||||
public bool Installed { get; set; }
|
||||
public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource<DataConnectionSecurity?> Resolved { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken)
|
||||
{ Started.TrySetResult(); return new(Resolved.Task); }
|
||||
public void Rotate() => Changed?.Invoke("link");
|
||||
}
|
||||
private sealed class Security(HttpMessageHandler handler) : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca1", "key", () => handler));
|
||||
}
|
||||
private sealed class WireHandler : HttpMessageHandler
|
||||
{
|
||||
public bool LoseWrite { get; init; }
|
||||
public bool WrongReadServing { get; init; }
|
||||
public bool ZeroServingGeneration { get; init; }
|
||||
public bool BadBrowseLease { get; init; }
|
||||
public int WriteCalls { get; private set; }
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
IMessage message;
|
||||
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
||||
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 2, ZeroServingGeneration ? Serving with { ServingGeneration = 0 } : Serving, DataReadiness.Ready,
|
||||
DataOperations.Read | DataOperations.Write, new HashSet<DataValueKind> { DataValueKind.Int32 }, Limits,
|
||||
false, 0, "c", false, true));
|
||||
else if (request.RequestUri.AbsolutePath.EndsWith("/Write", StringComparison.Ordinal))
|
||||
{
|
||||
WriteCalls++;
|
||||
if (LoseWrite) throw new HttpRequestException("Lost response after send.");
|
||||
message = new W.WriteResponse { Serving = DataProtoMapper.EncodeServing(Serving) };
|
||||
}
|
||||
else if (request.RequestUri.AbsolutePath.EndsWith("/Browse", StringComparison.Ordinal))
|
||||
{
|
||||
var browse = DataProtoMapper.EncodeBrowseResponse(new DataBrowseBranch(View, DataItemStatus.Good, [], true, null,
|
||||
new MetadataLease(Serving.CatalogEpoch, BadBrowseLease ? Serving.AuthorityEpoch + 1 : Serving.AuthorityEpoch, TimeSpan.FromSeconds(1))));
|
||||
browse.Serving = DataProtoMapper.EncodeServing(Serving); message = browse;
|
||||
}
|
||||
else if (request.RequestUri.AbsolutePath.EndsWith("/Read", StringComparison.Ordinal))
|
||||
message = new W.ReadResponse { Serving = DataProtoMapper.EncodeServing(WrongReadServing ? Serving with { Incarnation = "other" } : Serving) };
|
||||
else throw new InvalidOperationException("Unexpected call.");
|
||||
var payload = message.ToByteArray();
|
||||
var framed = new byte[payload.Length + 5];
|
||||
BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length);
|
||||
payload.CopyTo(framed, 5);
|
||||
var response = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
|
||||
response.Content.Headers.ContentType = new("application/grpc");
|
||||
response.TrailingHeaders.Add("grpc-status", "0");
|
||||
return Task.FromResult(response);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Only_explicit_rejection_can_be_selected_for_mutation_retry()
|
||||
{
|
||||
var outcomes = new[] {
|
||||
new WriteItemResult("rejected", new(DataWriteState.RejectedBeforeDispatch, 1, null)),
|
||||
new WriteItemResult("unknown", new(DataWriteState.OutcomeUnknown, 1, null)),
|
||||
new WriteItemResult("accepted", new(DataWriteState.AcceptedUnconfirmed, 1, null)),
|
||||
new WriteItemResult("success", new(DataWriteState.DriverConfirmedSuccess, 0, null)) };
|
||||
GrpcDataConnection.RetryableWriteIndexes(outcomes).ShouldBe(new[] { 0 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Demotion_is_negative_proof_only_for_an_entirely_rejected_batch_from_the_same_boot()
|
||||
{
|
||||
var expected = new ServingIdentity("a", "boot", "Primary", 4, 5);
|
||||
var demoted = expected with { Role = "Secondary", AuthorityEpoch = 6 };
|
||||
var rejected = new WriteItemResult("a", new(DataWriteState.RejectedBeforeDispatch, 1, null));
|
||||
var unknown = new WriteItemResult("b", new(DataWriteState.OutcomeUnknown, 1, null));
|
||||
GrpcDataConnection.AcceptWriteServing(expected, demoted, [rejected]).ShouldBeTrue();
|
||||
GrpcDataConnection.AcceptWriteServing(expected, demoted, [rejected, unknown]).ShouldBeFalse();
|
||||
GrpcDataConnection.AcceptWriteServing(expected, demoted with { Incarnation = "new" }, [rejected]).ShouldBeFalse();
|
||||
GrpcDataConnection.AcceptWriteServing(expected, demoted with { NodeId = "b" }, [rejected]).ShouldBeFalse();
|
||||
GrpcDataConnection.AcceptWriteServing(expected, demoted, []).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Channel_identity_includes_both_security_versions()
|
||||
{
|
||||
var endpoint = new Uri("https://node.example:8443");
|
||||
var first = new DataConnectionChannelIdentity("link", endpoint, "credential-1", "trust-1");
|
||||
first.ShouldNotBe(first with { CredentialVersion = "credential-2" });
|
||||
first.ShouldNotBe(first with { TrustFingerprint = "trust-2" });
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataConsumerScopeTests
|
||||
{
|
||||
private static DataConnectionScopeLease WaitForLease(DataConnectionManager manager)
|
||||
{
|
||||
DataConnectionScopeLease? lease = null;
|
||||
SpinWait.SpinUntil(() => { try { lease = manager.Acquire("link"); return true; } catch (UnauthorizedAccessException) { return false; } }, TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||||
return lease!;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Warm_standby_cannot_acquire_and_hot_secondary_cannot_write()
|
||||
{
|
||||
DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Warm, WarmRole.Standby, RedundancyRole.Secondary).ShouldBeFalse();
|
||||
DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Warm, null, null).ShouldBeFalse();
|
||||
DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Warm, WarmRole.Active, RedundancyRole.Primary).ShouldBeTrue();
|
||||
DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Hot, null, RedundancyRole.Secondary).ShouldBeTrue();
|
||||
DataConnectionRoleAdapter.MayAcquire(RedundancyMode.Hot, null, null).ShouldBeFalse();
|
||||
DataConnectionRoleAdapter.MayWrite(RedundancyRole.Secondary).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Blocked_scope_cleanup_stays_charged_and_coalesces_revisions()
|
||||
{
|
||||
using var manager = new DataConnectionManager("node-a", 1);
|
||||
var members = new HashSet<string> { "node-a" };
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(1, members) });
|
||||
using var old = manager.Acquire("link");
|
||||
using var release = new ManualResetEventSlim();
|
||||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var registration = old.CancellationToken.Register(() => { entered.TrySetResult(); release.Wait(); });
|
||||
try
|
||||
{
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(2, members) });
|
||||
await entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(3, members) });
|
||||
Should.Throw<UnauthorizedAccessException>(() => manager.Acquire("link"));
|
||||
}
|
||||
finally { release.Set(); }
|
||||
old.Dispose();
|
||||
using var replacement = WaitForLease(manager);
|
||||
replacement.Epoch.ShouldBeGreaterThan(old.Epoch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_new_connection_revision_retires_old_lifetimes_even_when_consumers_are_unchanged()
|
||||
{
|
||||
using var manager = new DataConnectionManager("node-a", 4);
|
||||
var members = new HashSet<string> { "node-a" };
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(1, members) });
|
||||
using var old = manager.Acquire("link");
|
||||
manager.ApplyScope(new Dictionary<string, DataConnectionScope> { ["link"] = new(2, members) });
|
||||
old.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
old.Dispose();
|
||||
using var replacement = WaitForLease(manager);
|
||||
replacement.Epoch.ShouldBeGreaterThan(old.Epoch);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Scope_removal_cancels_existing_lifetime_and_readdition_uses_new_epoch()
|
||||
{
|
||||
using var manager = new DataConnectionManager("node-a", 4);
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "node-a" } });
|
||||
using var first = manager.Acquire("link");
|
||||
first.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "node-b" } });
|
||||
first.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
Should.Throw<UnauthorizedAccessException>(() => manager.Acquire("link"));
|
||||
manager.ApplyScope(new Dictionary<string, IReadOnlySet<string>> { ["link"] = new HashSet<string> { "node-a" } });
|
||||
first.Dispose();
|
||||
using var next = WaitForLease(manager);
|
||||
next.Epoch.ShouldBeGreaterThan(first.Epoch);
|
||||
next.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
+481
@@ -0,0 +1,481 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataDeploymentActivationTests
|
||||
{
|
||||
private static DataConnection Definition(string id, string secret) => new()
|
||||
{
|
||||
DataConnectionId = id, ClusterId = "owner", Revision = 1, Enabled = true,
|
||||
ConsumerNodeIds = ["node-a"], TargetMode = DataTargetMode.Node,
|
||||
ExpectedClusterId = "target", ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"],
|
||||
SecretReference = secret, SecretScopeClusterId = "owner", AllowedOperations = DataOperations.Read,
|
||||
MaxMessageBytes = 65536, MaxBatchItems = 16, MaxPageItems = 16, MaxStreams = 2,
|
||||
MaxMonitoredItems = 16, MaxPendingBytes = 65536, TimeoutMilliseconds = 5000
|
||||
};
|
||||
private static DataConnectionDeploymentSnapshot Snapshot(long version, params DataConnection[] connections) =>
|
||||
new(version, $"artifact-{version}", connections);
|
||||
private static async Task EventuallyAsync(Func<bool> condition)
|
||||
{
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
if (condition()) return;
|
||||
await Task.Delay(20, TestContext.Current.CancellationToken);
|
||||
}
|
||||
throw new TimeoutException("Expected deployment state did not arrive.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Transient_security_resolution_exception_retries_without_a_change_event()
|
||||
{
|
||||
var clock = new ManualTimeProvider(); var security = new FailOnceSecurity();
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4, clock);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && security.Attempts == 1 && clock.ArmedTimers == 1);
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await EventuallyAsync(() => runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!));
|
||||
security.Attempts.ShouldBe(2);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Temporarily_missing_security_material_retries_without_a_change_event()
|
||||
{
|
||||
var clock = new ManualTimeProvider(); var security = new NullOnceSecurity();
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4, clock);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && security.Attempts == 1 && clock.ArmedTimers == 1);
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await EventuallyAsync(() => runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!));
|
||||
security.Attempts.ShouldBe(2);
|
||||
}
|
||||
private sealed class NullOnceSecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
private int _attempts;
|
||||
public int Attempts => Volatile.Read(ref _attempts);
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(Interlocked.Increment(ref _attempts) == 1
|
||||
? null : new("1", "trust", "key", () => new EmptyHandler()));
|
||||
}
|
||||
|
||||
private sealed class FailOnceSecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
private int _attempts;
|
||||
public int Attempts => Volatile.Read(ref _attempts);
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Increment(ref _attempts) == 1) throw new IOException("transient security store failure");
|
||||
return ValueTask.FromResult<DataConnectionSecurity?>(new("1", "trust", "key", () => new EmptyHandler()));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Transient_role_read_failure_during_apply_does_not_strand_the_current_scope()
|
||||
{
|
||||
var checks = 0;
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4,
|
||||
consumerMayAcquire: () => Interlocked.Increment(ref checks) > 1);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Temporarily_unavailable_role_is_retried_on_the_owned_timer()
|
||||
{
|
||||
var clock = new ManualTimeProvider(); var role = new RoleFlag();
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock, () => role.Allowed);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && clock.ArmedTimers == 1);
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
role.Allowed = true;
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await EventuallyAsync(() => runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!));
|
||||
}
|
||||
private sealed class RoleFlag { public volatile bool Allowed; }
|
||||
|
||||
[Fact]
|
||||
public async Task Transient_scope_store_failure_retries_on_one_clock_timer_without_external_signal()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var activator = new FailOnceActivator();
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => activator.Attempts == 1 && clock.ArmedTimers == 1);
|
||||
runtime.CurrentScopeReady.ShouldBeFalse();
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!));
|
||||
activator.Attempts.ShouldBe(2);
|
||||
}
|
||||
[Fact]
|
||||
public async Task Superseding_an_attempt_disarms_its_retry_and_activates_only_the_new_floor()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var activator = new FailOnceActivator();
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock);
|
||||
runtime.Apply(Snapshot(1, Definition("old", "old-ref")));
|
||||
await EventuallyAsync(() => activator.Attempts == 1 && clock.ArmedTimers == 1);
|
||||
runtime.BeginAttempt("artifact-2");
|
||||
clock.ArmedTimers.ShouldBe(0);
|
||||
runtime.Apply(Snapshot(2, Definition("new", "new-ref")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("new", out var lease) && DisposeAndTrue(lease!));
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
activator.Attempts.ShouldBe(2);
|
||||
runtime.TryAcquire("old", out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disposal_disarms_the_pending_scope_retry()
|
||||
{
|
||||
var clock = new ManualTimeProvider();
|
||||
var activator = new FailOnceActivator();
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, clock);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => activator.Attempts == 1 && clock.ArmedTimers == 1);
|
||||
await runtime.DisposeAsync();
|
||||
clock.ArmedTimers.ShouldBe(0);
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
activator.Attempts.ShouldBe(1);
|
||||
}
|
||||
|
||||
private sealed class FailOnceActivator : IDataConnectionScopeActivator
|
||||
{
|
||||
private int _attempts;
|
||||
public int Attempts => Volatile.Read(ref _attempts);
|
||||
public Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Increment(ref _attempts) == 1) throw new IOException("transient local store failure");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Beginning_a_new_artifact_attempt_immediately_denies_old_routes_and_rejects_stale_apply()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
|
||||
runtime.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
runtime.BeginAttempt("artifact-2");
|
||||
lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
runtime.CurrentScopeReady.ShouldBeFalse();
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
Should.Throw<InvalidOperationException>(() => runtime.Apply(Snapshot(1, Definition("link", "secret"))));
|
||||
}
|
||||
runtime.Apply(Snapshot(2, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var next) && DisposeAndTrue(next!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Replaying_the_accepted_artifact_attempt_keeps_live_routes()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
|
||||
runtime.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
runtime.BeginAttempt("artifact-1");
|
||||
lease!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
runtime.CurrentScopeReady.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Starting_a_new_attempt_before_first_activation_rejects_an_older_artifact()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.BeginAttempt("artifact-2");
|
||||
Should.Throw<InvalidOperationException>(() => runtime.Apply(Snapshot(1, Definition("old", "secret"))));
|
||||
runtime.CurrentScopeReady.ShouldBeFalse();
|
||||
runtime.TryAcquire("old", out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Stale_scope_completion_cannot_publish_its_old_connection()
|
||||
{
|
||||
var activator = new PausedActivator();
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
try
|
||||
{
|
||||
runtime.Apply(Snapshot(1, Definition("old", "old-ref")));
|
||||
await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
runtime.Apply(Snapshot(2, Definition("new", "new-ref")));
|
||||
runtime.CurrentScopeReady.ShouldBeFalse();
|
||||
runtime.TryAcquire("old", out _).ShouldBeFalse();
|
||||
}
|
||||
finally { activator.Release.TrySetResult(); }
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("new", out var lease) && DisposeAndTrue(lease!));
|
||||
runtime.TryAcquire("old", out _).ShouldBeFalse();
|
||||
activator.AppliedVersions.ShouldBe(new long[] { 1, 2 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Scope_removal_cancels_existing_lease_before_the_new_floor_finishes()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false, PauseSecond = true };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var value) && DisposeAndTrue(value!));
|
||||
runtime.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
try
|
||||
{
|
||||
runtime.Apply(Snapshot(2));
|
||||
lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
runtime.CurrentScopeReady.ShouldBeFalse();
|
||||
await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
}
|
||||
finally { activator.Release.TrySetResult(); }
|
||||
}
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Desired_definitions_are_copied_before_any_asynchronous_activation()
|
||||
{
|
||||
var activator = new PausedActivator();
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
var definition = Definition("link", "secret");
|
||||
try
|
||||
{
|
||||
runtime.Apply(Snapshot(1, definition));
|
||||
await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
definition.SecretReference = "changed";
|
||||
definition.ExpectedNodeId = "forged";
|
||||
definition.Endpoints.Clear();
|
||||
}
|
||||
finally { activator.Release.TrySetResult(); }
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var lease) && DisposeAndTrue(lease!));
|
||||
activator.Scopes[1]["link"].ShouldBe("secret");
|
||||
runtime.TryAcquire("link", out var current).ShouldBeTrue();
|
||||
using (current!) current!.Connection.Target.ExpectedNodeId.ShouldBe("remote");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Same_scope_version_with_different_contents_is_rejected()
|
||||
{
|
||||
var activator = new PausedActivator();
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
try
|
||||
{
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await activator.Entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
Should.Throw<InvalidOperationException>(() => runtime.Apply(Snapshot(1, Definition("link", "other-secret"))));
|
||||
}
|
||||
finally { activator.Release.TrySetResult(); }
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Consumer_redundancy_mode_is_preserved_from_the_validated_snapshot()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.Apply(new DataConnectionDeploymentSnapshot(1, "artifact-1", [Definition("link", "secret")], RedundancyMode.Hot));
|
||||
runtime.CurrentConsumerMode.ShouldBe(RedundancyMode.Hot);
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Replaying_identical_artifact_does_not_retire_a_live_connection()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
|
||||
runtime.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
lease!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
runtime.CurrentScopeReady.ShouldBeTrue();
|
||||
activator.AppliedVersions.ShouldBe(new long[] { 1 });
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Same_artifact_revision_cannot_replace_connection_definitions()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
|
||||
runtime.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
var changed = Definition("link", "secret");
|
||||
changed.Endpoints = ["https://different.example:8443"];
|
||||
Should.Throw<InvalidOperationException>(() => runtime.Apply(Snapshot(1, changed)));
|
||||
lease!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
runtime.CurrentScopeReady.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Transient_role_contention_during_one_credential_change_does_not_strand_other_connections()
|
||||
{
|
||||
var clock = new ManualTimeProvider(); var role = new RoleFlag { Allowed = true };
|
||||
var security = new MutableSecurity(); var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4, clock, () => role.Allowed);
|
||||
runtime.Apply(Snapshot(1, Definition("one", "secret-one"), Definition("two", "secret-two")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("one", out var a) && DisposeAndTrue(a!) &&
|
||||
runtime.TryAcquire("two", out var b) && DisposeAndTrue(b!));
|
||||
runtime.TryAcquire("one", out var first).ShouldBeTrue();
|
||||
runtime.TryAcquire("two", out var second).ShouldBeTrue();
|
||||
using (first!) using (second!)
|
||||
{
|
||||
role.Allowed = false;
|
||||
security.Rotate("one");
|
||||
role.Allowed = true;
|
||||
first!.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
second!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
runtime.TryAcquire("two", out var unaffected).ShouldBeTrue();
|
||||
unaffected!.Dispose();
|
||||
}
|
||||
await EventuallyAsync(() => clock.ArmedTimers > 0 || runtime.TryAcquire("one", out var value) && DisposeAndTrue(value!));
|
||||
if (clock.ArmedTimers > 0) clock.Advance(TimeSpan.FromMinutes(1));
|
||||
await EventuallyAsync(() => runtime.TryAcquire("one", out var recovered) && DisposeAndTrue(recovered!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Credential_change_drains_only_affected_connection_before_reactivation()
|
||||
{
|
||||
var security = new MutableSecurity();
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", security, activator, 4);
|
||||
runtime.Apply(Snapshot(1, Definition("one", "secret-one"), Definition("two", "secret-two")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("one", out var a) && DisposeAndTrue(a!) &&
|
||||
runtime.TryAcquire("two", out var b) && DisposeAndTrue(b!));
|
||||
runtime.TryAcquire("one", out var first).ShouldBeTrue();
|
||||
runtime.TryAcquire("two", out var second).ShouldBeTrue();
|
||||
using (first!) using (second!)
|
||||
{
|
||||
security.Rotate("one");
|
||||
first!.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
second!.CancellationToken.IsCancellationRequested.ShouldBeFalse();
|
||||
runtime.CurrentScopeReady.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
private sealed class MutableSecurity : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed;
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(new("1", "trust", "key", () => new EmptyHandler()));
|
||||
public void Rotate(string id) => Changed?.Invoke(id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Deployed_operation_and_batch_limits_apply_before_any_network_call()
|
||||
{
|
||||
var definition = Definition("link", "secret");
|
||||
definition.MaxBatchItems = 1;
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
runtime.Apply(Snapshot(1, definition));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
|
||||
runtime.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
var view = new DataView(new("target", "urn:test", "string", "x"), DataRealm.Raw, null, 0, "x");
|
||||
using var value = DataValue.FromScalar(DataValueKind.Int32, 1);
|
||||
var budget = new DataBudget(TimeSpan.FromSeconds(1), 4, 1024);
|
||||
await Should.ThrowAsync<UnauthorizedAccessException>(() => lease!.Connection.WriteAsync(new([new("a", "op", view, value, 1, "boot", TimeSpan.FromSeconds(1))], budget), TestContext.Current.CancellationToken));
|
||||
await Should.ThrowAsync<ArgumentOutOfRangeException>(() => lease!.Connection.ReadAsync(new([new("a", view, null), new("b", view, null)], budget), TestContext.Current.CancellationToken));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Warm_standby_drains_existing_routes_and_keeps_durable_scope_ready()
|
||||
{
|
||||
var active = true;
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4, consumerMayAcquire: () => active);
|
||||
runtime.Apply(Snapshot(1, Definition("link", "secret")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("link", out var candidate) && DisposeAndTrue(candidate!));
|
||||
runtime.TryAcquire("link", out var lease).ShouldBeTrue();
|
||||
using (lease!)
|
||||
{
|
||||
active = false;
|
||||
runtime.NotifyConsumerRoleChanged();
|
||||
lease!.CancellationToken.IsCancellationRequested.ShouldBeTrue();
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
runtime.CurrentScopeReady.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Missing_one_credential_does_not_hold_other_connections_or_the_scope_unready()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security("missing"), activator, 4);
|
||||
runtime.Apply(Snapshot(1, Definition("ready", "a"), Definition("missing", "b")));
|
||||
await EventuallyAsync(() => runtime.CurrentScopeReady && runtime.TryAcquire("ready", out var lease) && DisposeAndTrue(lease!));
|
||||
runtime.TryAcquire("missing", out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_scope_version_is_denied_before_any_activation()
|
||||
{
|
||||
var activator = new PausedActivator { PauseFirst = false };
|
||||
await using var runtime = new DataConnectionDeploymentRuntime("node-a", "owner", new Security(), activator, 4);
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => runtime.Apply(Snapshot(0, Definition("link", "secret"))));
|
||||
runtime.CurrentScopeReady.ShouldBeFalse();
|
||||
runtime.TryAcquire("link", out _).ShouldBeFalse();
|
||||
activator.AppliedVersions.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
private static bool DisposeAndTrue(IDisposable lease) { lease.Dispose(); return true; }
|
||||
private sealed class Security(string? missing = null) : IDataConnectionSecurityProvider
|
||||
{
|
||||
public event Action<string>? Changed { add { } remove { } }
|
||||
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<DataConnectionSecurity?>(string.Equals(connectionId, missing, StringComparison.OrdinalIgnoreCase)
|
||||
? null : new("1", "trust", "key", () => new EmptyHandler()));
|
||||
}
|
||||
private sealed class EmptyHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
throw new InvalidOperationException("This activation test must not use the network.");
|
||||
}
|
||||
private sealed class PausedActivator : IDataConnectionScopeActivator
|
||||
{
|
||||
public bool PauseFirst { get; init; } = true;
|
||||
public bool PauseSecond { get; init; }
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private readonly ConcurrentQueue<long> _versions = new();
|
||||
public long[] AppliedVersions => _versions.ToArray();
|
||||
public ConcurrentDictionary<long, IReadOnlyDictionary<string, string>> Scopes { get; } = new();
|
||||
public async Task SetScopeAsync(long version, IReadOnlyDictionary<string, string> allowlist, CancellationToken cancellationToken)
|
||||
{
|
||||
_versions.Enqueue(version);
|
||||
Scopes[version] = new Dictionary<string, string>(allowlist, StringComparer.OrdinalIgnoreCase);
|
||||
if (version == 1 && PauseFirst || version == 2 && PauseSecond)
|
||||
{
|
||||
Entered.TrySetResult();
|
||||
// Deliberately ignore cancellation to exercise stale-completion fencing.
|
||||
await Release.Task;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-2
@@ -58,6 +58,8 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
|
||||
[InlineData("host-membership-event")]
|
||||
[InlineData("incarnation")]
|
||||
[InlineData("current-key-expiry-fence")]
|
||||
[InlineData("warm-standby-fence")]
|
||||
[InlineData("warm-return-active-fence")]
|
||||
public async Task Real_catalog_policy_and_actor_revalidate_at_the_driver_invocation(string change)
|
||||
{
|
||||
var clock = new PolicyCompletionClock();
|
||||
@@ -133,7 +135,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
|
||||
var proof = new WriteRouteProof(admission,
|
||||
new(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray()),
|
||||
node.EntityKind, node.EntityId, node.Source, "driver", target.DriverReference,
|
||||
target.RouteGeneration, role.PrimaryGeneration);
|
||||
target.RouteGeneration, role.PrimaryGeneration, catalog.Serving);
|
||||
var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, 7), now);
|
||||
var registry = new WriteOperationRegistry("serving", 8, 8192, TimeSpan.FromMinutes(1), clock);
|
||||
var claim = registry.Claim("peer", "real-gate", "serving", SHA256.HashData([1, 2, 3])).Claim.ShouldNotBeNull();
|
||||
@@ -157,6 +159,8 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
|
||||
case "role": role.PublishPrimaryRole(false); role.PublishPrimaryRole(true); break;
|
||||
case "incarnation": routes.RetireDriver("driver", incarnation); routes.BeginDriverIncarnation("driver"); break;
|
||||
case "current-key-expiry-fence":
|
||||
case "warm-standby-fence":
|
||||
case "warm-return-active-fence":
|
||||
{
|
||||
using var releaseFence = new ManualResetEventSlim();
|
||||
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
@@ -171,7 +175,12 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase
|
||||
// The wrapped evaluator arms a signal for the *last* policy UTC read. It returns
|
||||
// the captured pre-expiry instant even if the test advances the clock immediately.
|
||||
await clock.AfterPolicyUtc.Task.WaitAsync(Timeout, TestContext.Current.CancellationToken);
|
||||
clock.Advance(TimeSpan.FromSeconds(2));
|
||||
if (change == "current-key-expiry-fence") clock.Advance(TimeSpan.FromSeconds(2));
|
||||
else
|
||||
{
|
||||
serving = serving with { Role = change == "warm-standby-fence" ? "Standby" : "Primary", ServingGeneration = 2 };
|
||||
role.PrimaryGeneration.ShouldBe(proof.PrimaryGeneration, "the driver's Primary verdict has not changed");
|
||||
}
|
||||
}
|
||||
finally { releaseFence.Set(); await holder.WaitAsync(Timeout, TestContext.Current.CancellationToken); }
|
||||
break;
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataEndpointSelectionTests
|
||||
{
|
||||
private static readonly DataLimits Limits = new(16, 16, 65536, 16, 4, 65536, TimeSpan.FromSeconds(5), TimeSpan.FromMinutes(1), TimeSpan.FromSeconds(5));
|
||||
private static DataCapabilities Cap(string node, string role, DataReadiness ready = DataReadiness.Ready, string cluster = "c") =>
|
||||
new(1, 1, new(node, "boot", role, 1, 1, 1), ready, DataOperations.Read, new HashSet<DataValueKind>(), Limits, false, 0, cluster);
|
||||
|
||||
[Fact]
|
||||
public void Cluster_requires_authenticated_ready_primary_and_expected_cluster()
|
||||
{
|
||||
var target = new DataTarget(DataTargetMode.Cluster, "c", null);
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("a", "Primary", DataReadiness.Unavailable), false).ShouldBeFalse();
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("a", "Primary", cluster: "other"), false).ShouldBeFalse();
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("a", "Secondary"), false).ShouldBeFalse();
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("a", "Unknown"), false).ShouldBeFalse();
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("a", "Primary"), false).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pinned_node_cannot_substitute_partner_and_secondary_requires_explicit_read_consistency()
|
||||
{
|
||||
var target = new DataTarget(DataTargetMode.Node, "c", "a", DataConsistency.ReadyReplica);
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("b", "Primary"), true).ShouldBeFalse();
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("a", "Secondary"), true).ShouldBeFalse();
|
||||
ClusterEndpointSelector.IsEligible(target, Cap("a", "Secondary"), false).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
using Akka.Actor;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataLocalCompositionTests : RuntimeActorTestBase
|
||||
{
|
||||
private sealed class PassiveActor : ReceiveActor { }
|
||||
|
||||
[Fact]
|
||||
public void One_composition_shares_the_given_process_capacity_and_rejects_mismatched_clock()
|
||||
{
|
||||
var clock = TimeProvider.System;
|
||||
var fence = new DataWriteDispatchFence(); var authority = new DataPlaneAuthorityState(fence);
|
||||
var activation = new CatalogActivation(fence); var role = new RedundancyRoleView(fence);
|
||||
var serving = new ServingIdentity("node", "boot", "Primary", 0, 0);
|
||||
var catalog = new LocalCatalogCoordinator(activation, authority, () => serving);
|
||||
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
||||
var caps = new DataCapabilitiesProvider("cluster", () => serving, () => false, limits);
|
||||
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock);
|
||||
var bounds = new DriverWriteBounds(TimeSpan.FromMilliseconds(300));
|
||||
var writes = new DataWriteRuntime(catalog, activation, authority, policy, caps, role, clock, bounds, "boot", 16, 16_384, 16_384, 4, TimeSpan.FromMinutes(1));
|
||||
using var hub = HubTest.Create(clock: clock, bytes: 1_000_000);
|
||||
var host = Sys.ActorOf(Props.Create(() => new PassiveActor()));
|
||||
var shared = new SubscriptionAcquisitionCapacity(8);
|
||||
var config = new LocalDataRuntimeLimits(8, 128, 8, 4, 1_000_000, 16, 16, 100_000, TimeSpan.FromMinutes(5), TimeSpan.FromSeconds(2));
|
||||
using var runtime = new LocalDataRuntimeComposition(catalog, hub, policy, caps, clock, writes, host, shared, config);
|
||||
runtime.AcquisitionCapacity.ShouldBeSameAs(shared);
|
||||
runtime.Services.ShouldNotBeNull();
|
||||
runtime.Services.Clock.ShouldBeSameAs(clock);
|
||||
Should.Throw<ArgumentException>(() => new LocalDataRuntimeComposition(catalog, hub, policy, caps,
|
||||
new ManualTimeProvider(), writes, host, shared, config));
|
||||
}
|
||||
}
|
||||
+19
-1
@@ -12,6 +12,23 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
public sealed class GrpcDataLocalConnectionTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Browse_lease_never_outlives_the_original_target_credential()
|
||||
{
|
||||
using var fixture = new LocalDataFixture(additionalRawNodes: 1);
|
||||
var context = fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow().AddSeconds(1) };
|
||||
await using var connection = fixture.Services.Create(context, new(DataTargetMode.Node, "cluster", "node-a"));
|
||||
var budget = LocalDataFixture.Budget with { MaxItems = 1 };
|
||||
var branch = await connection.BrowseAsync(new(fixture.Root, null, null, budget), TestContext.Current.CancellationToken);
|
||||
branch.Status.ShouldBe(DataItemStatus.Good);
|
||||
branch.Lease!.Duration.ShouldBeLessThanOrEqualTo(TimeSpan.FromSeconds(1));
|
||||
branch.Continuation.ShouldNotBeNull();
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
|
||||
var expired = await connection.BrowseAsync(new(fixture.Root, null, branch.Continuation, budget), TestContext.Current.CancellationToken);
|
||||
expired.Status.ShouldBe(DataItemStatus.Denied);
|
||||
expired.Items.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Metadata_bootstrap_resolves_address_and_never_uses_the_claimed_subject_as_authority()
|
||||
{
|
||||
@@ -110,8 +127,9 @@ internal sealed class LocalDataFixture : IDisposable
|
||||
internal LocalDataFixture(int additionalRawNodes = 0,
|
||||
Func<DataAuthenticatedContext, IDataSubscriptionService>? subscriptions = null,
|
||||
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
|
||||
bool advanceAuthority = false)
|
||||
bool advanceAuthority = false, string role = "Primary")
|
||||
{
|
||||
Serving = Serving with { Role = role };
|
||||
Hub = HubTest.Create(clock: Clock, bytes: 1_000_000);
|
||||
Hub.TryBind(Ticket).ShouldBeTrue();
|
||||
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataLocalRoleTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Cluster_and_default_node_requests_cannot_read_a_secondary()
|
||||
{
|
||||
using var fixture = new LocalDataFixture(role: "Secondary");
|
||||
fixture.Publish(7);
|
||||
foreach (var target in new[] { new DataTarget(DataTargetMode.Node, "cluster", "node-a"),
|
||||
new DataTarget(DataTargetMode.Cluster, "cluster", null) })
|
||||
{
|
||||
await using var connection = fixture.Services.Create(fixture.Context, target);
|
||||
var caps = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, TestContext.Current.CancellationToken);
|
||||
caps.Operations.ShouldBe(DataOperations.None);
|
||||
caps.Readiness.ShouldBe(DataReadiness.Unavailable);
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => connection.ReadAsync(
|
||||
new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken));
|
||||
((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Unknown")]
|
||||
[InlineData("Stopped")]
|
||||
public async Task Ready_replica_never_treats_an_arbitrary_nonprimary_role_as_a_ready_secondary(string role)
|
||||
{
|
||||
using var fixture = new LocalDataFixture(role: role);
|
||||
await using var connection = fixture.Services.Create(fixture.Context,
|
||||
new(DataTargetMode.Node, "cluster", "node-a", DataConsistency.ReadyReplica));
|
||||
var caps = await connection.GetCapabilitiesAsync(LocalDataFixture.Budget, TestContext.Current.CancellationToken);
|
||||
caps.Readiness.ShouldBe(DataReadiness.Unavailable);
|
||||
((IDataConnectionPublicationGate)connection).CanPublish(fixture.Serving).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Explicit_node_ready_replica_reads_its_own_cache()
|
||||
{
|
||||
using var fixture = new LocalDataFixture(role: "Secondary");
|
||||
fixture.Publish(7);
|
||||
await using var connection = fixture.Services.Create(fixture.Context,
|
||||
new(DataTargetMode.Node, "cluster", "node-a", DataConsistency.ReadyReplica));
|
||||
var results = await connection.ReadAsync(new([new("read", fixture.Raw, null)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
using var result = results.ShouldHaveSingleItem();
|
||||
result.Status.ShouldBe(DataItemStatus.Good);
|
||||
result.Sample!.Value.GetScalar().ShouldBe(7);
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -513,8 +513,13 @@ public sealed class GrpcDataStreamOrderingTests
|
||||
using (var first = reader.Current.ShouldBeOfType<DataSubscriptionValues>())
|
||||
first.Items.ShouldHaveSingleItem().Sample.Value.GetScalar().ShouldBe(1);
|
||||
fixture.Clock.Advance(TimeSpan.FromSeconds(2));
|
||||
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2);
|
||||
fixture.Hub.ProcessPending();
|
||||
// Arrange successful ingress; nonblocking contention deliberately invalidates a
|
||||
// source and is covered separately from frozen-snapshot/delta ordering.
|
||||
fixture.Hub.WithPartitionLockForTest(fixture.Ticket.Key, () =>
|
||||
{
|
||||
HubTest.Publish(fixture.Hub, fixture.Ticket, 2, 2);
|
||||
fixture.Hub.ProcessPending();
|
||||
});
|
||||
var frozen = 1;
|
||||
while (true)
|
||||
{
|
||||
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Feature", "GrpcData"), Trait("Category", "Unit"), Trait("Phase", "P07")]
|
||||
public sealed class GrpcDataTransportPublicationTests
|
||||
{
|
||||
[Fact(Timeout = 30000)]
|
||||
public async Task Valid_late_publication_has_one_handoff_and_allows_snapshot_end()
|
||||
{
|
||||
using var fixture = CreateFixture(out _);
|
||||
fixture.Publish(1);
|
||||
await using var connection = fixture.Connection();
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
var sink = new DelayedMarshallerSink(false);
|
||||
var writer = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
|
||||
await Open(subscription, fixture);
|
||||
try { await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
||||
finally { sink.Release.TrySetResult(); }
|
||||
await sink.SnapshotEnd.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
sink.Bound.ShouldBeTrue();
|
||||
sink.BlockedHandoffs.ShouldBe(1);
|
||||
await subscription.DisposeAsync();
|
||||
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000)]
|
||||
public async Task Ignored_cancellation_keeps_the_prepared_frame_and_work_charged_until_physical_write_finishes()
|
||||
{
|
||||
using var fixture = CreateFixture(out var capacity);
|
||||
fixture.Publish(1);
|
||||
await using var connection = fixture.Connection();
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
var sink = new DelayedMarshallerSink(false);
|
||||
var writer = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
|
||||
await Open(subscription, fixture);
|
||||
try
|
||||
{
|
||||
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
await subscription.DisposeAsync();
|
||||
capacity.ActiveOperations.ShouldBe(1);
|
||||
sink.BlockedPreparedDisposed.Task.IsCompleted.ShouldBeFalse();
|
||||
}
|
||||
finally { sink.Release.TrySetResult(); }
|
||||
await sink.BlockedPreparedDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
capacity.ActiveOperations.ShouldBe(0);
|
||||
sink.BlockedHandoffs.ShouldBe(0);
|
||||
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private static LocalDataFixture CreateFixture(out SubscriptionTransportCapacity capacity)
|
||||
{
|
||||
var demand = new DeferredSubscriptionDemand(); demand.Accept();
|
||||
var shared = new SubscriptionTransportCapacity(4, 2, 1_000_000);
|
||||
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
|
||||
LocalDataFixture? fixture = null;
|
||||
fixture = new LocalDataFixture(targetSubscriptions: (caller, target) =>
|
||||
new LocalSubscriptionService(fixture!.Services, caller, target, demand, limits, shared));
|
||||
capacity = shared;
|
||||
return fixture;
|
||||
}
|
||||
private static Task Open(IDataSubscription subscription, LocalDataFixture fixture) => subscription.SendAsync(
|
||||
new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
|
||||
[new("one", fixture.Raw, new(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null))],
|
||||
false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
|
||||
[Theory(Timeout = 30000)]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Late_transport_serialization_revalidates_source_without_a_catalog_change(bool blockEnd)
|
||||
{
|
||||
var demand = new DeferredSubscriptionDemand(); demand.Accept();
|
||||
var capacity = new SubscriptionTransportCapacity(4, 2, 1_000_000);
|
||||
var limits = new SubscriptionSessionLimits(16, 16, 100_000, TimeSpan.FromMinutes(1));
|
||||
LocalDataFixture? fixture = null;
|
||||
using (fixture = new LocalDataFixture(targetSubscriptions: (caller, target) =>
|
||||
new LocalSubscriptionService(fixture!.Services, caller, target, demand, limits, capacity)))
|
||||
{
|
||||
fixture.Publish(1);
|
||||
await using var connection = fixture.Connection();
|
||||
await using var subscription = await connection.SubscribeAsync(TestContext.Current.CancellationToken);
|
||||
var sink = new DelayedMarshallerSink(blockEnd);
|
||||
var writer = ((IDataSubscriptionTransport)subscription).RunDeliveryAsync(sink, TestContext.Current.CancellationToken);
|
||||
await subscription.SendAsync(new OpenSubscription("s", 1, "open", TimeSpan.FromSeconds(10),
|
||||
[new("one", fixture.Raw, new(TimeSpan.Zero, TimeSpan.Zero, DataChangeTrigger.StatusValue, null))],
|
||||
false, TimeSpan.FromSeconds(30), LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
||||
try
|
||||
{
|
||||
await sink.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
fixture.Hub.Invalidate(fixture.Ticket, "Late transport invalidation");
|
||||
}
|
||||
finally { sink.Release.TrySetResult(); }
|
||||
await sink.Settled.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
sink.Bound.ShouldBeTrue();
|
||||
sink.BlockedHandoffs.ShouldBe(0);
|
||||
await subscription.DisposeAsync();
|
||||
await writer.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DelayedMarshallerSink(bool blockEnd) : IDataSubscriptionDeliverySink
|
||||
{
|
||||
internal readonly TaskCompletionSource Entered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal readonly TaskCompletionSource Release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal readonly TaskCompletionSource Settled = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal readonly TaskCompletionSource SnapshotEnd = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal readonly TaskCompletionSource BlockedPreparedDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
internal bool Bound;
|
||||
internal int BlockedHandoffs;
|
||||
public ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes,
|
||||
CancellationToken cancellationToken) => ValueTask.FromResult<IDataPreparedSubscriptionDelivery>(new Prepared(frame,
|
||||
() => { if (Blocked(frame)) BlockedPreparedDisposed.TrySetResult(); }));
|
||||
private bool Blocked(DataSubscriptionFrame frame) => blockEnd
|
||||
? frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }
|
||||
: frame is DataSubscriptionValues;
|
||||
public async ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken)
|
||||
{
|
||||
var item = (Prepared)prepared;
|
||||
if (!Blocked(item.Frame))
|
||||
{
|
||||
if (item.Frame is DataSubscriptionControl { Kind: DataStreamControlKind.SnapshotEnd }) SnapshotEnd.TrySetResult();
|
||||
return;
|
||||
}
|
||||
Bound = item.Guard is not null;
|
||||
Entered.TrySetResult();
|
||||
try
|
||||
{
|
||||
await Release.Task; // Models ASP.NET starting the response before invoking its marshaller.
|
||||
if (item.Guard is null || !item.Guard()) throw new InvalidOperationException("Publication refused.");
|
||||
BlockedHandoffs++;
|
||||
}
|
||||
finally { Settled.TrySetResult(); }
|
||||
}
|
||||
private sealed class Prepared(DataSubscriptionFrame frame, Action disposed) : IDataPreparedSubscriptionPublication
|
||||
{
|
||||
internal DataSubscriptionFrame Frame { get; } = frame;
|
||||
internal Func<bool>? Guard;
|
||||
public long RetainedBytes => 1;
|
||||
public void SetPublicationGuard(Func<bool> guard) => Guard = guard;
|
||||
public void Dispose() => disposed();
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -6,6 +6,7 @@ using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
|
||||
@@ -23,6 +24,57 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||||
/// </remarks>
|
||||
public sealed class DriverHostActorPrimaryRoleSourceTests : RuntimeActorTestBase
|
||||
{
|
||||
[Fact]
|
||||
public void An_accepted_snapshot_missing_local_node_retires_observed_primary_provenance()
|
||||
{
|
||||
var view = new RedundancyRoleView();
|
||||
var host = SpawnHost(view, () => 2);
|
||||
host.Tell(Snapshot(RedundancyRole.Primary));
|
||||
AwaitAssert(() => view.DataServingRole.ShouldBe("Primary"), duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
var generation = view.PrimaryGeneration;
|
||||
host.Tell(new RedundancyStateChanged([], CorrelationId.NewId()));
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
view.DataServingRole.ShouldBe("Unknown");
|
||||
view.PrimaryGeneration.ShouldBeGreaterThan(generation);
|
||||
}, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Stopping_the_actual_role_publisher_retires_its_serving_proof()
|
||||
{
|
||||
var view = new RedundancyRoleView();
|
||||
var host = SpawnHost(view, () => 2);
|
||||
host.Tell(Snapshot(RedundancyRole.Primary));
|
||||
AwaitAssert(() => view.DataServingRole.ShouldBe("Primary"), duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
var watcher = CreateTestProbe(); watcher.Watch(host); Sys.Stop(host);
|
||||
watcher.ExpectTerminated(host, Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
view.DataServingRole.ShouldBe("Unknown");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_old_publisher_cannot_overwrite_or_retire_its_replacement()
|
||||
{
|
||||
var view = new RedundancyRoleView();
|
||||
var old = SpawnHost(view, () => 2);
|
||||
old.Tell(Snapshot(RedundancyRole.Primary));
|
||||
AwaitAssert(() => view.DataServingRole.ShouldBe("Primary"), duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
var generation = view.PrimaryGeneration;
|
||||
var current = SpawnHost(view, () => 2);
|
||||
current.Tell(Snapshot(RedundancyRole.Primary));
|
||||
AwaitAssert(() =>
|
||||
{
|
||||
view.PrimaryGeneration.ShouldBeGreaterThan(generation);
|
||||
view.DataServingRole.ShouldBe("Primary");
|
||||
}, duration: Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
old.Tell(Snapshot(RedundancyRole.Secondary));
|
||||
await old.Ask<DriverHostActor.OpenAcquisitionCountForTest>(new DriverHostActor.GetOpenAcquisitionCountForTest(),
|
||||
Timeout, TestContext.Current.CancellationToken);
|
||||
view.DataServingRole.ShouldBe("Primary");
|
||||
var watcher = CreateTestProbe(); watcher.Watch(old); Sys.Stop(old);
|
||||
watcher.ExpectTerminated(old, Timeout, cancellationToken: TestContext.Current.CancellationToken);
|
||||
view.DataServingRole.ShouldBe("Primary");
|
||||
}
|
||||
private static readonly NodeId TestNode = NodeId.Parse("driver-primary-source-test");
|
||||
private static readonly TimeSpan Timeout = PresenceBudget;
|
||||
|
||||
|
||||
@@ -8,7 +8,10 @@ using ZB.MOM.WW.OtOpcUa.Commons.Messages.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Health;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Redundancy;
|
||||
@@ -64,6 +67,98 @@ public sealed class OpcUaPublishActorWarmTests : RuntimeActorTestBase
|
||||
private static readonly string[] Promotion = ["proj:False", "queue:False", "delivery:False", "alarms:False", "refresh", "SL:250"];
|
||||
private static readonly string[] Demotion = ["SL:90", "delivery:True", "alarms:True", "proj:True", "queue:True"];
|
||||
|
||||
[Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public void Data_warm_verdict_stays_unknown_until_revisioned_snapshot_and_tracks_actual_transitions()
|
||||
{
|
||||
var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence());
|
||||
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
serviceLevel: new LoggingPublisher(_log), localNode: Self, dbLess: true,
|
||||
healthTickInterval: TimeSpan.FromMinutes(5), redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm),
|
||||
standbyProjection: new RecordingProjection(_log), dataWarmRole: view));
|
||||
view.CurrentRole.ShouldBeNull();
|
||||
actor.Tell(Snapshot(Self, revisioned: false));
|
||||
AwaitLogEndsWith("SL:90");
|
||||
view.CurrentRole.ShouldBeNull();
|
||||
actor.Tell(Snapshot(Self));
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
actor.Tell(Snapshot(Other));
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Standby), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
Watch(actor); Sys.Stop(actor); ExpectTerminated(actor, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public void A_primary_snapshot_is_not_a_warm_active_verdict_after_endpoint_failure()
|
||||
{
|
||||
var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence());
|
||||
var endpoint = new OpcUaEndpointState(); endpoint.MarkStarted();
|
||||
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
serviceLevel: new LoggingPublisher(_log), localNode: Self, dbLess: true,
|
||||
healthTickInterval: TimeSpan.FromMilliseconds(25), endpointState: endpoint,
|
||||
redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm),
|
||||
standbyProjection: new RecordingProjection(_log), dataWarmRole: view));
|
||||
actor.Tell(Snapshot(Self));
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
endpoint.MarkFailed("test failure");
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Standby), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public async Task Warm_demotion_invalidates_import_role_before_a_blocked_projection_callback()
|
||||
{
|
||||
var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence());
|
||||
using var publisher = new BlockingStandbyPublisher();
|
||||
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
serviceLevel: publisher, localNode: Self, dbLess: true, healthTickInterval: TimeSpan.FromMinutes(5),
|
||||
redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm),
|
||||
standbyProjection: new RecordingProjection(_log), dataWarmRole: view));
|
||||
try
|
||||
{
|
||||
actor.Tell(Snapshot(Self));
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
publisher.Block = true;
|
||||
actor.Tell(Snapshot(Other));
|
||||
await publisher.Entered.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||
view.CurrentRole.ShouldBe(WarmRole.Standby);
|
||||
}
|
||||
finally { publisher.Release.Set(); Watch(actor); Sys.Stop(actor); ExpectTerminated(actor, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); }
|
||||
}
|
||||
private sealed class BlockingStandbyPublisher : IServiceLevelPublisher, IDisposable
|
||||
{
|
||||
public volatile bool Block;
|
||||
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ManualResetEventSlim Release { get; } = new();
|
||||
public void Publish(byte level)
|
||||
{
|
||||
if (Block && level < 100) { Entered.TrySetResult(); Release.Wait(); }
|
||||
}
|
||||
public void Dispose() => Release.Dispose();
|
||||
}
|
||||
|
||||
[Fact, Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P07")]
|
||||
public void Superseded_warm_actor_cannot_publish_or_retire_the_new_owner()
|
||||
{
|
||||
var view = new DataConnectionWarmRoleView(new DataWriteDispatchFence());
|
||||
IActorRef NewActor() => Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
serviceLevel: new LoggingPublisher(_log), localNode: Self, dbLess: true,
|
||||
healthTickInterval: TimeSpan.FromMinutes(5), redundancy: new WarmRedundancySettings(OpcUaRedundancyMode.Warm),
|
||||
standbyProjection: new RecordingProjection(_log), dataWarmRole: view));
|
||||
var first = NewActor(); first.Tell(Snapshot(Self));
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
var oldGeneration = view.Generation;
|
||||
var second = NewActor();
|
||||
AwaitAssert(() => { view.Generation.ShouldBeGreaterThan(oldGeneration); view.CurrentRole.ShouldBeNull(); }, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
first.Tell(Snapshot(Other));
|
||||
AwaitLogEndsWith(Demotion);
|
||||
view.CurrentRole.ShouldBeNull();
|
||||
second.Tell(Snapshot(Self));
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBe(WarmRole.Active), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
Watch(first); Sys.Stop(first); ExpectTerminated(first, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
view.CurrentRole.ShouldBe(WarmRole.Active);
|
||||
Watch(second); Sys.Stop(second); ExpectTerminated(second, PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitAssert(() => view.CurrentRole.ShouldBeNull(), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Promotion_and_demotion_run_in_the_spec_order()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user