75e6ff9af8
#960: a projected read reserves 16 KiB for a fixed-size scalar (16 KiB + 256 B/element for a fixed-length fixed-size array) instead of the whole MaxPendingBytes, so the default 1 MiB admits 64 concurrent scalar reads; String/Bytes/variable arrays keep the whole cap, and a waiting whole-cap read holds back smaller ones for 100 ms (anti-starvation). Writes reserve 16 KiB + identifiers + 3 x the value bound (what the origin's DataWriteExecutor admits the batch against). Monitored-item renewals reserve 256 KiB. Measured: 4 x 250 ms maxAge=0 reads 1016 ms / 1 in flight -> 285 ms / 4 in flight. #961: TryAcquireProjectedItem reports BadResourceUnavailable for a stream-capacity refusal; the node manager's CreateMonitoredItem override turns the item manager's ServiceResultException into that item's status (was a whole-request fault), and an authority race is re-classified outside Lock like the per-item probe.
1179 lines
82 KiB
C#
1179 lines
82 KiB
C#
using Opc.Ua;
|
||
using System.Threading.Channels;
|
||
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.Core.Authorization;
|
||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||
|
||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||
|
||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
||
public sealed partial class GrpcDataProjectedAccessTests
|
||
{
|
||
[Fact]
|
||
public void Acquisition_pins_the_exact_materialized_origin_and_disposal_fences_it()
|
||
{
|
||
using var fixture = new AccessFixture();
|
||
using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
demand.ShouldNotBeNull().OriginView.ShouldBe(fixture.Proof.OriginMetadata.View);
|
||
demand.MaximumSampleAge.ShouldBe(TimeSpan.FromSeconds(30));
|
||
access.HasLiveDemand(DataRealm.Raw, fixture.Proof.LocalIdentifier).ShouldBeTrue();
|
||
demand.Serving.ShouldBe(fixture.Proof.Lease.Serving);
|
||
demand.ProjectionGeneration.ShouldBe(fixture.Proof.Generation);
|
||
fixture.Pins.ShouldBe(1);
|
||
demand.IsValid.ShouldBeTrue();
|
||
demand.Dispose();
|
||
demand.IsValid.ShouldBeFalse();
|
||
fixture.Pins.ShouldBe(0);
|
||
access.HasLiveDemand(DataRealm.Raw, fixture.Proof.LocalIdentifier).ShouldBeFalse();
|
||
}
|
||
|
||
[Fact]
|
||
public void Changed_materialization_or_revoked_proof_cannot_be_acquired_or_stay_live()
|
||
{
|
||
using var fixture = new AccessFixture(); using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
fixture.Current = false;
|
||
demand.ShouldNotBeNull().IsValid.ShouldBeFalse();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
|
||
demand.Dispose();
|
||
fixture.Current = true;
|
||
fixture.Definition = fixture.Definition with { ProjectionGeneration = 2 };
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
|
||
}
|
||
|
||
[Fact]
|
||
public void Demand_admission_is_bounded_and_recovered_when_idle_demand_is_disposed()
|
||
{
|
||
using var fixture = new AccessFixture(); using var access = fixture.Create(maxDemands: 1);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
|
||
first.ShouldNotBeNull().Dispose();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var next).ShouldBeTrue();
|
||
next.ShouldNotBeNull().Dispose();
|
||
}
|
||
|
||
[Fact]
|
||
public void Demand_pins_sdk_incarnation_until_disposal_and_force_retirement_fences_it()
|
||
{
|
||
using var fixture = new AccessFixture(); using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
fixture.Definition.Lifetime.TryRetire().ShouldBeFalse();
|
||
fixture.Definition.Lifetime.ForceRetire();
|
||
demand.ShouldNotBeNull().IsValid.ShouldBeFalse();
|
||
demand.Dispose();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
|
||
}
|
||
|
||
[Fact]
|
||
public void Browse_demand_uses_the_original_caller_and_live_proof()
|
||
{
|
||
using var fixture = new AccessFixture(); using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Browse, out var demand).ShouldBeTrue();
|
||
demand.ShouldNotBeNull().IsValid.ShouldBeTrue();
|
||
fixture.Current = false;
|
||
demand.IsValid.ShouldBeFalse();
|
||
demand.Dispose();
|
||
}
|
||
|
||
[Fact]
|
||
public void Missing_freshness_policy_never_authorizes_terminal_read()
|
||
{
|
||
using var fixture = new AccessFixture(); fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.Zero };
|
||
using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out _).ShouldBeFalse();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Read_source_pins_sdk_incarnation_until_mapping_invalidation_retires_it()
|
||
{
|
||
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
|
||
fixture.Publish(7);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.Definition.Lifetime.TryRetire().ShouldBeFalse();
|
||
fixture.InvalidateMapping();
|
||
await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
update.SourceProof.IsValid.ShouldBeFalse();
|
||
fixture.Definition.Lifetime.TryRetire().ShouldBeTrue();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Invalidation_during_source_attachment_does_not_strand_its_pins()
|
||
{
|
||
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
|
||
fixture.BeforeBind = () => fixture.InvalidateMapping();
|
||
fixture.Publish(7);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
|
||
fixture.Definition.Lifetime.TryRetire().ShouldBeTrue();
|
||
fixture.Published.Task.IsCompleted.ShouldBeFalse();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Mapping_invalidation_never_waits_for_the_publication_lock()
|
||
{
|
||
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
|
||
fixture.Publish(7);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var field = typeof(ProjectedDataAccess).GetField("_sync", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!;
|
||
using var release = new ManualResetEventSlim();
|
||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
var token = TestContext.Current.CancellationToken;
|
||
var publication = Task.Run(() =>
|
||
{
|
||
lock (field.GetValue(access)!) { entered.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10), token).ShouldBeTrue(); }
|
||
}, token);
|
||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), token);
|
||
try { await Task.Run(() => fixture.InvalidateMapping(), token).WaitAsync(TimeSpan.FromSeconds(2), token); }
|
||
finally { release.Set(); await publication; }
|
||
await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Paused_source_retirement_does_not_queue_unowned_mapping_history()
|
||
{
|
||
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
|
||
using var release = new ManualResetEventSlim();
|
||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
access.BeforeSourceRetirementForTests = () => { entered.TrySetResult(); release.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); };
|
||
fixture.Publish(7);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.InvalidateMapping();
|
||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
try
|
||
{
|
||
for (var i = 0; i < 10000; i++) fixture.InvalidateMapping("historical-" + i);
|
||
access.PendingSourceRetirementsForTests.ShouldBe(1, "only the owned source bucket can require retirement work");
|
||
}
|
||
finally { release.Set(); await fixture.NoPins.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10")]
|
||
public async Task Cold_sdk_read_budget_is_bounded_to_the_configured_transport_limit_and_publishes()
|
||
{
|
||
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||
fixture.Publish(42);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
access.ScheduleRead(demand!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
update.Snapshot.Value.ShouldBe(42);
|
||
// #960: a scalar read reserves (and may decode) only what its declared shape can answer, within the configured limit.
|
||
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(ProjectedDataAccess.ProjectedEnvelopeBytes);
|
||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||
public async Task Variable_size_read_reserves_the_full_configured_budget_until_physical_completion()
|
||
{
|
||
// A String value has no declared bound, so its read keeps the whole per-read cap (#960 sizes only bounded shapes).
|
||
using var fixture = new AccessFixture(readOnly: true) { BlockAcquire = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||
UseValueKind(fixture, DataValueKind.String);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
|
||
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
try
|
||
{
|
||
access.ScheduleRead(first!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
first = null; // admitted work owns the lease
|
||
await fixture.AcquireEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse();
|
||
second!.IsValid.ShouldBeTrue("a rejected admission leaves ownership with the caller");
|
||
fixture.ReleaseAcquire.TrySetResult();
|
||
SpinWait.SpinUntil(() => access.ScheduleRead(second, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
second = null;
|
||
fixture.ReadBudget.ShouldNotBeNull().MaxBytes.ShouldBe(1024 * 1024);
|
||
}
|
||
finally { fixture.ReleaseAcquire.TrySetResult(); first?.Dispose(); second?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||
public async Task Scalar_reads_reserve_their_shape_bound_so_concurrent_reads_share_the_default_budget()
|
||
{
|
||
// The production default: DataConnections:MaxPendingBytes = 1 MiB. Before #960 every read reserved all of it, so only
|
||
// ONE projected read (or write) could be in flight per node. The operation-count limit (4 here) is the bound now.
|
||
using var fixture = new AccessFixture(readOnly: true) { BlockAcquire = true }; using var access = fixture.Create(maxDemands: 8, maxBytes: 1024 * 1024);
|
||
fixture.Publish(42);
|
||
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
var demands = new List<IProjectedDemandLease?>();
|
||
try
|
||
{
|
||
for (var i = 0; i < 5; i++)
|
||
{
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
demands.Add(demand);
|
||
}
|
||
var admitted = 0;
|
||
for (var i = 0; i < 4; i++)
|
||
if (access.ScheduleRead(demands[i]!, sdkBudget, fixture.Clock.GetTimestamp())) { admitted++; demands[i] = null; }
|
||
admitted.ShouldBe(4, "four scalar reads fit the 1 MiB budget at once");
|
||
access.ScheduleRead(demands[4]!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse("the operation-count limit still bounds them");
|
||
fixture.ReleaseAcquire.TrySetResult();
|
||
SpinWait.SpinUntil(() => access.ScheduleRead(demands[4]!, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
demands[4] = null;
|
||
await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
}
|
||
finally { fixture.ReleaseAcquire.TrySetResult(); foreach (var demand in demands) demand?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||
public async Task A_waiting_whole_cap_read_holds_back_smaller_reads_until_it_is_admitted()
|
||
{
|
||
// Scalar reads now share the budget; a whole-cap (String) read that waits for capacity must not be starved by them.
|
||
using var fixture = new AccessFixture(readOnly: true, streams: true) { BlockAcquire = true };
|
||
using var access = fixture.Create(maxDemands: 8, maxBytes: 1024 * 1024);
|
||
var stringMetadata = fixture.SecondProof!.Metadata with { ValueKind = DataValueKind.String };
|
||
fixture.SecondProof = fixture.SecondProof with { Metadata = stringMetadata, OriginMetadata = fixture.SecondProof.OriginMetadata with { ValueKind = DataValueKind.String } };
|
||
fixture.SecondDefinition = fixture.SecondDefinition! with { Metadata = stringMetadata };
|
||
fixture.Publish(42);
|
||
var sdkBudget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
var ct = TestContext.Current.CancellationToken;
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var third).ShouldBeTrue();
|
||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Read, out var large).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.ScheduleRead(first!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
first = null;
|
||
(await access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct)).Status.ShouldBe(ProjectedOriginReadStatus.NotAdmitted);
|
||
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse("a waiting whole-cap read holds back smaller ones");
|
||
// A waiter that gives up stops holding them back once the window lapses.
|
||
fixture.Advance(ProjectedDataAccess.ReadDrainWindow + TimeSpan.FromMilliseconds(1));
|
||
access.ScheduleRead(second!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
second = null;
|
||
// It waits again; the scalar reads in flight finish and it is admitted ahead of the third.
|
||
(await access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct)).Status.ShouldBe(ProjectedOriginReadStatus.NotAdmitted);
|
||
access.ScheduleRead(third!, sdkBudget, fixture.Clock.GetTimestamp()).ShouldBeFalse();
|
||
fixture.ReleaseAcquire.TrySetResult();
|
||
Task<ProjectedOriginRead>? read = null;
|
||
SpinWait.SpinUntil(() =>
|
||
{
|
||
var attempt = access.ReadNowAsync(large!, sdkBudget, fixture.Clock.GetTimestamp(), ct);
|
||
if (attempt.IsCompletedSuccessfully && attempt.Result.Status == ProjectedOriginReadStatus.NotAdmitted) return false;
|
||
read = attempt; return true;
|
||
}, TimeSpan.FromSeconds(5)).ShouldBeTrue("the waiting read is admitted once the scalar reads finish");
|
||
await read!.WaitAsync(TimeSpan.FromSeconds(5), ct);
|
||
SpinWait.SpinUntil(() => access.ScheduleRead(third!, sdkBudget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
third = null;
|
||
}
|
||
finally { fixture.ReleaseAcquire.TrySetResult(); first?.Dispose(); second?.Dispose(); third?.Dispose(); large?.Dispose(); }
|
||
}
|
||
|
||
private static void UseValueKind(AccessFixture fixture, DataValueKind kind)
|
||
{
|
||
var metadata = fixture.Proof.Metadata with { ValueKind = kind };
|
||
fixture.Proof = fixture.Proof with { Metadata = metadata, OriginMetadata = fixture.Proof.OriginMetadata with { ValueKind = kind } };
|
||
fixture.Definition = fixture.Definition with { Metadata = metadata };
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Read_without_subscribe_permission_preserves_origin_age_timestamps_and_source_proof()
|
||
{
|
||
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
|
||
fixture.Publish(42);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
access.ScheduleRead(demand!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
update.IsCompleteSnapshot.ShouldBeTrue();
|
||
update.Snapshot.Value.ShouldBe(42);
|
||
update.Snapshot.StatusCode.ShouldBe(0x00000400u);
|
||
update.Snapshot.SourceTimestampUtc.ShouldBeNull();
|
||
update.Snapshot.ServerTimestampUtc.ShouldNotBeNull();
|
||
update.OriginAgeBounds.Upper.ShouldNotBeNull();
|
||
update.SourceProof.IsValid.ShouldBeTrue();
|
||
update.Route.Serving.ShouldBe(fixture.Proof.Lease.Serving);
|
||
update.Route.ProjectionGeneration.ShouldBe(fixture.Proof.Generation);
|
||
fixture.Current = false;
|
||
update.SourceProof.IsValid.ShouldBeFalse();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Renewed_metadata_replaces_expired_source_without_reviving_old_publication()
|
||
{
|
||
using var fixture = new AccessFixture(readOnly: true); using var access = fixture.Create();
|
||
fixture.Publish(42);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
|
||
access.ScheduleRead(first!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
var old = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.Renew();
|
||
old.SourceProof.IsValid.ShouldBeFalse();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
|
||
access.ScheduleRead(second!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
var fresh = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fresh.SourceProof.IsValid.ShouldBeTrue();
|
||
fresh.Route.PublicationId.ShouldNotBe(old.Route.PublicationId);
|
||
old.SourceProof.IsValid.ShouldBeFalse();
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10")]
|
||
public async Task Sdk_write_budget_is_bounded_to_configured_limit_and_dispatches_once()
|
||
{
|
||
using var fixture = new AccessFixture(writable: true); using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
var result = await access.WriteAsync(demand!, 42, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
// #960: a scalar write reserves what it needs (envelope + the origin's write accounting), not the whole configured limit.
|
||
var sent = fixture.SentWrite.ShouldNotBeNull();
|
||
sent.Budget.MaxBytes.ShouldBeLessThan(ScalarWriteBytesBound);
|
||
sent.Budget.MaxBytes.ShouldBeGreaterThanOrEqualTo(OriginWriteAccounting(sent, 288));
|
||
fixture.WriteCalls.ShouldBe(1);
|
||
}
|
||
finally { demand?.Dispose(); }
|
||
}
|
||
|
||
/// <summary>#960: more than one scalar write's reservation (envelope + identifiers + 3 × 288), less than two.</summary>
|
||
private const long ScalarWriteBytesBound = 30 * 1024;
|
||
|
||
/// <summary>What the origin's DataWriteExecutor admits a one-item write batch against (3 × retained estimate + 512 + identifiers).</summary>
|
||
private static long OriginWriteAccounting(WriteBatch sent, long valueEstimate)
|
||
{
|
||
var item = sent.Items.ShouldHaveSingleItem();
|
||
return 3 * valueEstimate + 512 + 2L * ((item.CorrelationId?.Length ?? 0) + (item.OperationId?.Length ?? 0) +
|
||
(item.View.Subject?.Length ?? 0) + (item.View.MappingId?.Length ?? 0) + (item.View.Address.OriginClusterId?.Length ?? 0) +
|
||
(item.View.Address.NamespaceUri?.Length ?? 0) + (item.View.Address.IdentifierKind?.Length ?? 0) +
|
||
(item.View.Address.Identifier?.Length ?? 0) + (item.ExpectedServingIncarnation?.Length ?? 0));
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||
public async Task A_large_string_write_reserves_what_the_origin_admits_it_against()
|
||
{
|
||
// Sized below the cap, a write must still carry the budget the ORIGIN checks it against, or a long string that the
|
||
// whole-cap reservation used to carry is refused there ("Write batch exceeds its byte limit").
|
||
using var fixture = new AccessFixture(writable: true); using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||
UseValueKind(fixture, DataValueKind.String);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
var text = new string('x', 20_000);
|
||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
(await access.WriteAsync(demand!, text, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken)).State
|
||
.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
var sent = fixture.SentWrite.ShouldNotBeNull();
|
||
sent.Budget.MaxBytes.ShouldBeGreaterThanOrEqualTo(OriginWriteAccounting(sent, 288 + 2L * text.Length));
|
||
sent.Budget.MaxBytes.ShouldBeLessThan(1024 * 1024);
|
||
}
|
||
finally { demand?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10"), Trait("Issue", "960")]
|
||
public async Task Scalar_writes_are_dispatched_concurrently_within_the_default_budget()
|
||
{
|
||
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: 1024 * 1024);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue();
|
||
try
|
||
{
|
||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
var one = access.WriteAsync(first!, 42, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||
await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var two = access.WriteAsync(second!, 43, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||
SpinWait.SpinUntil(() => Volatile.Read(ref fixture.WriteCalls) == 2 || two.IsCompleted, TimeSpan.FromSeconds(5));
|
||
fixture.WriteCalls.ShouldBe(2, "a second write is dispatched while the first is in flight, not rejected for capacity");
|
||
fixture.ReleaseWrite.TrySetResult();
|
||
(await one.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
(await two.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
}
|
||
finally { fixture.ReleaseWrite.TrySetResult(); first?.Dispose(); second?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10")]
|
||
public async Task Clamped_write_rejects_oversized_value_before_dispatch()
|
||
{
|
||
using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create(maxBytes: 1024);
|
||
var metadata = fixture.Proof.Metadata with { Dimensions = [0] };
|
||
fixture.Proof = fixture.Proof with { Metadata = metadata, OriginMetadata = fixture.Proof.OriginMetadata with { Dimensions = [0] } };
|
||
fixture.Definition = fixture.Definition with { Metadata = metadata };
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
var result = await access.WriteAsync(demand!, new int[64], budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch); fixture.WriteCalls.ShouldBe(0);
|
||
}
|
||
finally { demand?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P10")]
|
||
public async Task Cancelled_clamped_write_keeps_capacity_until_the_physical_send_finishes()
|
||
{
|
||
// A budget that holds one scalar write's reservation but not two (#960), so the held one leaves no room for another.
|
||
using var fixture = new AccessFixture(writable: true) { BlockWrite = true }; using var access = fixture.Create(maxBytes: ScalarWriteBytesBound);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var second).ShouldBeTrue();
|
||
using var cancel = new CancellationTokenSource();
|
||
try
|
||
{
|
||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024);
|
||
var pending = access.WriteAsync(first!, 42, budget, fixture.Clock.GetTimestamp(), cancel.Token);
|
||
await fixture.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
cancel.Cancel();
|
||
(await pending.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
var denied = await access.WriteAsync(second!, 43, budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||
denied.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||
fixture.WriteCalls.ShouldBe(1);
|
||
fixture.ReleaseWrite.TrySetResult();
|
||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
}
|
||
finally { fixture.ReleaseWrite.TrySetResult(); first?.Dispose(); second?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Strict_write_dispatch_uses_exact_origin_and_preserves_unknown_without_publishing_value()
|
||
{
|
||
using var fixture = new AccessFixture(writable: true); using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
|
||
var result = await access.WriteAsync(demand!, 42, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
var sent = fixture.SentWrite.ShouldNotBeNull().Items.ShouldHaveSingleItem();
|
||
sent.View.ShouldBe(fixture.Proof.OriginMetadata.View);
|
||
sent.ExpectedCatalogRevision.ShouldBe(fixture.Proof.OriginMetadata.CatalogRevision);
|
||
sent.ExpectedServingIncarnation.ShouldBe(fixture.Proof.Lease.Serving.Incarnation);
|
||
sent.ExpectedServingGeneration.ShouldBe(fixture.Proof.Lease.Serving.ServingGeneration);
|
||
sent.OperationId.ShouldNotBeNullOrWhiteSpace();
|
||
fixture.Published.Task.IsCompleted.ShouldBeFalse();
|
||
demand!.Dispose();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Local_primary_generation_change_before_dispatch_rejects_write_even_after_role_returns()
|
||
{
|
||
using var fixture = new AccessFixture(writable: true) { BlockAcquire = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
var task = access.WriteAsync(demand!, 42, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken);
|
||
await fixture.AcquireEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.RoleGeneration = 2; fixture.RoleAllowed = false;
|
||
fixture.RoleGeneration = 3; fixture.RoleAllowed = true;
|
||
fixture.ReleaseAcquire.TrySetResult();
|
||
var outcome = await task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
||
fixture.SentWrite.ShouldBeNull();
|
||
}
|
||
finally { fixture.ReleaseAcquire.TrySetResult(); demand?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Compatible_distinct_views_share_stream_and_last_demand_closes_physical_owner()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true); using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(second!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.StreamOpens.ShouldBe(1);
|
||
first!.Dispose();
|
||
await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse();
|
||
second!.Dispose();
|
||
await fixture.StreamClosed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
}
|
||
finally { first?.Dispose(); second?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Refreshing_one_registration_keeps_the_shared_stream_and_other_registration_live()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue();
|
||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var healthy).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var first = await fixture.ReadUpdateAsync(); var second = await fixture.ReadUpdateAsync();
|
||
var baseline = new[] { first, second }.Single(x => x.Route.LocalIdentifier == fixture.Proof.LocalIdentifier);
|
||
baseline.IsCompleteSnapshot.ShouldBeTrue(); baseline.Snapshot.Value.ShouldBe(7);
|
||
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
|
||
await fixture.ThirdStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.StreamOpens.ShouldBe(1, "refreshing one registration must not restart its healthy cohort");
|
||
fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse();
|
||
var commands = fixture.StreamCommands.ToArray();
|
||
var initial = commands.OfType<OpenSubscription>().Single().Items.Single();
|
||
var other = commands.OfType<AddSubscriptionItems>().First().Items.Single();
|
||
var removed = commands.OfType<RemoveSubscriptionItems>().Single();
|
||
var rebound = commands.OfType<AddSubscriptionItems>().Last().Items.Single();
|
||
rebound.View.ShouldBe(initial.View);
|
||
rebound.ClientItemId.ShouldNotBe(initial.ClientItemId);
|
||
removed.Items.ShouldHaveSingleItem().ShouldBe(fixture.StreamHandles[initial.ClientItemId]);
|
||
var recovered = await fixture.ReadUpdateAsync();
|
||
recovered.Route.ShouldBe(baseline.Route);
|
||
recovered.IsCompleteSnapshot.ShouldBeTrue(); recovered.Snapshot.Value.ShouldBe(7);
|
||
baseline.SourceProof.IsValid.ShouldBeFalse("the last proven registration for this source was removed");
|
||
recovered.SourceProof.IsValid.ShouldBeTrue();
|
||
fixture.EmitValue(other.ClientItemId, 2, 42);
|
||
var update = await fixture.ReadUpdateAsync();
|
||
update.Snapshot.Value.ShouldBe(42);
|
||
healthy!.IsValid.ShouldBeTrue();
|
||
}
|
||
finally { slow?.Dispose(); healthy?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Snapshot_waiting_for_end_cannot_publish_after_its_freshness_expires()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true)
|
||
{ ScalarSnapshots = true, HoldNextSnapshotEnd = true };
|
||
fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) };
|
||
// The fake stream supplies a finite bound at this observation, before its queued frame is read.
|
||
fixture.SnapshotObservedTimestamp = fixture.Clock.GetTimestamp();
|
||
using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.SnapshotEndHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
SpinWait.SpinUntil(() => Volatile.Read(ref fixture.Pins) >= 2, TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
var id = fixture.StreamCommands.OfType<OpenSubscription>().Single().Items.Single().ClientItemId;
|
||
fixture.Advance(TimeSpan.FromSeconds(1));
|
||
fixture.ReleaseSnapshotEnd();
|
||
fixture.EmitValue(id, 2, 42);
|
||
var admitted = await fixture.ReadUpdateAsync();
|
||
admitted.Snapshot.Value.ShouldBe(42, "the expired pending snapshot must not be admitted before the fresh delta");
|
||
admitted.SourceVersion.ShouldBe(2);
|
||
}
|
||
finally { demand?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Decoder_observation_time_is_not_replaced_by_later_pump_time()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true };
|
||
fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) };
|
||
fixture.SnapshotObservedTimestamp = fixture.Clock.GetTimestamp();
|
||
fixture.Advance(TimeSpan.FromSeconds(1));
|
||
using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var id = fixture.StreamCommands.OfType<OpenSubscription>().Single().Items.Single().ClientItemId;
|
||
fixture.EmitValue(id, 2, 42);
|
||
var admitted = await fixture.ReadUpdateAsync();
|
||
admitted.Snapshot.Value.ShouldBe(42, "a delayed handoff must not extend the decoder's age bound");
|
||
admitted.SourceVersion.ShouldBe(2);
|
||
}
|
||
finally { demand?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Healthy_delta_is_published_while_another_registration_snapshot_is_open()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue();
|
||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var healthy).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.ReadUpdateAsync(); await fixture.ReadUpdateAsync();
|
||
var healthyId = fixture.StreamCommands.OfType<AddSubscriptionItems>().Single().Items.Single().ClientItemId;
|
||
fixture.HoldNextSnapshotEnd = true;
|
||
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
|
||
await fixture.SnapshotEndHeld.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.EmitValue(healthyId, 2, 42);
|
||
var live = await fixture.ReadUpdateAsync();
|
||
live.Snapshot.Value.ShouldBe(42); live.IsCompleteSnapshot.ShouldBeFalse();
|
||
fixture.ReleaseSnapshotEnd();
|
||
var recovered = await fixture.ReadUpdateAsync();
|
||
recovered.Route.LocalIdentifier.ShouldBe(fixture.Proof.LocalIdentifier); recovered.IsCompleteSnapshot.ShouldBeTrue();
|
||
}
|
||
finally { slow?.Dispose(); healthy?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Two_mappings_of_one_origin_keep_separate_local_routes_and_shared_stream()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true, aliases: true) { ScalarSnapshots = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue();
|
||
try
|
||
{
|
||
first!.OriginView.ShouldBe(second!.OriginView);
|
||
access.StartSubscription(first, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(second, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var one = await fixture.ReadUpdateAsync(); var two = await fixture.ReadUpdateAsync();
|
||
new[] { one.Route.LocalIdentifier, two.Route.LocalIdentifier }.ShouldBe(new[] { fixture.Proof.LocalIdentifier, fixture.SecondProof!.LocalIdentifier }, ignoreOrder: true);
|
||
one.Route.PublicationId.ShouldNotBe(two.Route.PublicationId);
|
||
fixture.StreamOpens.ShouldBe(1);
|
||
var other = fixture.StreamCommands.OfType<AddSubscriptionItems>().Single().Items.Single();
|
||
await access.DisposeConfiguredAsync(first);
|
||
var surviving = one.Route.LocalIdentifier == fixture.SecondProof.LocalIdentifier ? one : two;
|
||
surviving.SourceProof.IsValid.ShouldBeTrue();
|
||
fixture.EmitValue(other.ClientItemId, 2, 9);
|
||
var live = await fixture.ReadUpdateAsync(); live.Route.ShouldBe(surviving.Route); live.Snapshot.Value.ShouldBe(9);
|
||
}
|
||
finally { first?.Dispose(); second?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Withdrawing_one_cadence_keeps_the_shared_source_proof_live()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var first).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var second).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(first!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(second!, TimeSpan.FromSeconds(2)).ShouldBeTrue();
|
||
await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var baseline = await fixture.ReadUpdateAsync();
|
||
var other = fixture.StreamCommands.OfType<OpenSubscription>().Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items.Single();
|
||
// The other cadence must have actually delivered, not merely started its Open.
|
||
fixture.EmitValue(other.ClientItemId, 2, 41);
|
||
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(41);
|
||
await access.DisposeConfiguredAsync(first!);
|
||
baseline.SourceProof.IsValid.ShouldBeTrue();
|
||
fixture.EmitValue(other.ClientItemId, 3, 42);
|
||
var live = await fixture.ReadUpdateAsync();
|
||
live.Route.ShouldBe(baseline.Route); live.Snapshot.Value.ShouldBe(42); second!.IsValid.ShouldBeTrue();
|
||
}
|
||
finally { first?.Dispose(); second?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Latest_sample_cache_uses_one_global_budget_and_invalidation_releases_it()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, aliases: true); using var access = fixture.Create(maxBytes: 1100);
|
||
var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 1100);
|
||
fixture.Publish(7);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var first).ShouldBeTrue();
|
||
access.ScheduleRead(first!, budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(7);
|
||
SpinWait.SpinUntil(() => access.CachedSampleBytesForTests > 0, TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
var charge = access.CachedSampleBytesForTests;
|
||
charge.ShouldBeLessThanOrEqualTo(1100);
|
||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Read, out var second).ShouldBeTrue();
|
||
SpinWait.SpinUntil(() => access.ScheduleRead(second!, budget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(7);
|
||
// A second source cannot allocate another sample past the shared limit.
|
||
access.CachedSampleBytesForTests.ShouldBe(charge);
|
||
fixture.PublishVersion(2, 9);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var replacement).ShouldBeTrue();
|
||
SpinWait.SpinUntil(() => access.ScheduleRead(replacement!, budget, fixture.Clock.GetTimestamp()), TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(9);
|
||
SpinWait.SpinUntil(() => access.CachedSampleBytesForTests == charge, TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
fixture.InvalidateMapping();
|
||
await fixture.SourceRetired.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
SpinWait.SpinUntil(() => access.CachedSampleBytesForTests == 0, TimeSpan.FromSeconds(5)).ShouldBeTrue();
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Quiet_recovery_replays_the_newest_admitted_sample_with_its_elapsed_age()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, HoldRemoveAck = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var other).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(other!, TimeSpan.FromSeconds(2)).ShouldBeTrue();
|
||
await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.ReadUpdateAsync();
|
||
var opens = fixture.StreamCommands.OfType<OpenSubscription>().ToArray();
|
||
var slowId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(1)).Items[0].ClientItemId;
|
||
var otherId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items[0].ClientItemId;
|
||
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
|
||
await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.EmitValue(otherId, 2, 8);
|
||
var advance = await fixture.ReadUpdateAsync();
|
||
fixture.Advance(TimeSpan.FromSeconds(2));
|
||
fixture.ReleaseRemoveAck(slowId);
|
||
var recovered = await fixture.ReadUpdateAsync();
|
||
recovered.IsCompleteSnapshot.ShouldBeTrue(); recovered.Snapshot.ShouldBe(advance.Snapshot);
|
||
recovered.Route.ShouldBe(advance.Route);
|
||
advance.SourceVersion.ShouldBe(2); recovered.SourceVersion.ShouldBe(advance.SourceVersion);
|
||
recovered.OriginAgeBounds.ShouldBe(advance.OriginAgeBounds);
|
||
recovered.ReceivedTimestamp.ShouldBe(advance.ReceivedTimestamp);
|
||
recovered.OriginAgeBounds.Advance(fixture.Clock.GetElapsedTime(recovered.ReceivedTimestamp, fixture.Clock.GetTimestamp())).Upper.ShouldBe(TimeSpan.FromSeconds(2));
|
||
}
|
||
finally { slow?.Dispose(); other?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Expired_cached_sample_is_not_used_as_a_recovery_baseline()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, HoldRemoveAck = true };
|
||
fixture.Proof = fixture.Proof with { MaximumSampleAge = TimeSpan.FromMilliseconds(500) };
|
||
using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var other).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(other!, TimeSpan.FromSeconds(2)).ShouldBeTrue();
|
||
await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.ReadUpdateAsync();
|
||
var opens = fixture.StreamCommands.OfType<OpenSubscription>().ToArray();
|
||
var slowId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(1)).Items[0].ClientItemId;
|
||
var otherId = opens.Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items[0].ClientItemId;
|
||
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
|
||
await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.EmitValue(otherId, 2, 8); await fixture.ReadUpdateAsync();
|
||
fixture.Advance(TimeSpan.FromSeconds(1)); fixture.ReleaseRemoveAck(slowId);
|
||
await fixture.ThirdStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var rebound = fixture.StreamCommands.OfType<AddSubscriptionItems>().Single().Items.Single();
|
||
fixture.EmitValue(rebound.ClientItemId, 3, 9);
|
||
var recovered = await fixture.ReadUpdateAsync(); recovered.Snapshot.Value.ShouldBe(9); recovered.IsCompleteSnapshot.ShouldBeTrue();
|
||
}
|
||
finally { slow?.Dispose(); other?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Read_owned_source_survives_withdrawal_of_the_matching_subscription()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true) { ScalarSnapshots = true }; using var access = fixture.Create();
|
||
fixture.Publish(7);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var read).ShouldBeTrue();
|
||
access.ScheduleRead(read!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
var baseline = await fixture.ReadUpdateAsync();
|
||
await fixture.ConnectionDisposed.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var subscription).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(subscription!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var id = fixture.StreamCommands.OfType<OpenSubscription>().Single().Items.Single().ClientItemId;
|
||
fixture.EmitValue(id, 2, 8);
|
||
var live = await fixture.ReadUpdateAsync(); live.Route.ShouldBe(baseline.Route);
|
||
await access.DisposeConfiguredAsync(subscription!);
|
||
baseline.SourceProof.IsValid.ShouldBeTrue();
|
||
}
|
||
finally { subscription?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Recovery_waits_for_a_current_complete_baseline_after_another_cadence_advances()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { ScalarSnapshots = true, HoldRemoveAck = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var other).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(other!, TimeSpan.FromSeconds(2)).ShouldBeTrue();
|
||
await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
await fixture.ReadUpdateAsync();
|
||
var slowId = fixture.StreamCommands.OfType<OpenSubscription>().Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(1)).Items.Single().ClientItemId;
|
||
var otherId = fixture.StreamCommands.OfType<OpenSubscription>().Single(x => x.Items[0].Settings.PublishingInterval == TimeSpan.FromSeconds(2)).Items.Single().ClientItemId;
|
||
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
|
||
await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.EmitValue(otherId, 2, 8);
|
||
var advance = await fixture.ReadUpdateAsync(); advance.Snapshot.Value.ShouldBe(8);
|
||
fixture.ReleaseRemoveAck(slowId);
|
||
await fixture.ThirdStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var rebound = fixture.StreamCommands.OfType<AddSubscriptionItems>().Single().Items.Single();
|
||
var recovery = await fixture.ReadUpdateAsync();
|
||
recovery.Snapshot.Value.ShouldBe(8); recovery.IsCompleteSnapshot.ShouldBeTrue();
|
||
fixture.EmitValue(rebound.ClientItemId, 3, 9);
|
||
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(9);
|
||
}
|
||
finally { slow?.Dispose(); other?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000), Trait("Phase", "P11")]
|
||
public async Task Withdrawal_during_refresh_does_not_reassociate_the_registration()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true) { HoldRemoveAck = true }; using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var slow).ShouldBeTrue();
|
||
access.TryAcquire(fixture.SecondNodeId, fixture.Caller, DataOperations.Subscribe, out var healthy).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(slow!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
access.StartSubscription(healthy!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.TwoStreamItems.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
var other = fixture.StreamCommands.OfType<AddSubscriptionItems>().Single().Items.Single();
|
||
access.RequestFreshSnapshot(slow!).ShouldBeTrue();
|
||
await fixture.ItemRemoved.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
slow!.Dispose();
|
||
fixture.EmitValue(other.ClientItemId, 2, 42);
|
||
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(42);
|
||
fixture.ReleaseRemoveAck();
|
||
fixture.EmitValue(other.ClientItemId, 3, 43);
|
||
(await fixture.ReadUpdateAsync()).Snapshot.Value.ShouldBe(43);
|
||
fixture.StreamCommands.OfType<AddSubscriptionItems>().Count().ShouldBe(1);
|
||
fixture.StreamOpens.ShouldBe(1); healthy!.IsValid.ShouldBeTrue();
|
||
slow.IsValid.ShouldBeFalse();
|
||
}
|
||
finally { slow?.Dispose(); healthy?.Dispose(); }
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Subscribe_only_demand_can_request_a_fresh_snapshot_without_read_permission()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, subscribeOnly: true); using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
await fixture.FirstStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
access.RequestFreshSnapshot(demand!).ShouldBeTrue();
|
||
await fixture.SecondTotalStreamItem.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
fixture.StreamOpens.ShouldBe(1);
|
||
fixture.StreamClosed.Task.IsCompleted.ShouldBeFalse();
|
||
demand!.IsValid.ShouldBeTrue();
|
||
}
|
||
finally { demand?.Dispose(); }
|
||
}
|
||
|
||
[Fact]
|
||
public void Array_metadata_admission_uses_structural_dimensions_not_list_identity()
|
||
{
|
||
using var fixture = new AccessFixture(array: true); using var access = fixture.Create();
|
||
fixture.Definition = fixture.Definition with { Metadata = fixture.Definition.Metadata with { Dimensions = new[] { 3 } } };
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var demand).ShouldBeTrue();
|
||
demand.ShouldNotBeNull().Dispose();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Array_write_preserves_owned_shape_and_value()
|
||
{
|
||
using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create();
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var demand).ShouldBeTrue();
|
||
var input = new[] { 8, 9, 10 };
|
||
var result = await access.WriteAsync(demand!, input, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
input[0] = 99;
|
||
fixture.CapturedArray.ShouldBe(new object[] { 8, 9, 10 });
|
||
demand!.Dispose();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Array_read_and_write_preserve_owned_one_dimensional_values()
|
||
{
|
||
using var fixture = new AccessFixture(writable: true, array: true); using var access = fixture.Create();
|
||
var original = new[] { 2, 4, 6 }; fixture.ReadElements = original;
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Read, out var read).ShouldBeTrue();
|
||
access.ScheduleRead(read!, LocalDataFixture.Budget, fixture.Clock.GetTimestamp()).ShouldBeTrue();
|
||
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
original[0] = 99;
|
||
update.Snapshot.Value.ShouldBeOfType<int[]>().ShouldBe(new[] { 2, 4, 6 });
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Write, out var write).ShouldBeTrue();
|
||
var written = new[] { 8, 9, 10 };
|
||
var result = await access.WriteAsync(write!, written, LocalDataFixture.Budget, fixture.Clock.GetTimestamp(), TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||
written[0] = 100;
|
||
fixture.CapturedArray.ShouldBe(new object[] { 8, 9, 10 });
|
||
write!.Dispose();
|
||
}
|
||
|
||
[Fact(Timeout = 30000)]
|
||
public async Task Array_subscription_snapshot_is_published_as_an_owned_typed_array()
|
||
{
|
||
using var fixture = new AccessFixture(streams: true, array: true); using var access = fixture.Create();
|
||
fixture.ReadElements = [2, 4, 6];
|
||
access.TryAcquire(fixture.NodeId, fixture.Caller, DataOperations.Subscribe, out var demand).ShouldBeTrue();
|
||
try
|
||
{
|
||
access.StartSubscription(demand!, TimeSpan.FromSeconds(1)).ShouldBeTrue();
|
||
var update = await fixture.Published.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
update.IsCompleteSnapshot.ShouldBeTrue();
|
||
update.Snapshot.Value.ShouldBeOfType<int[]>().ShouldBe(new[] { 2, 4, 6 });
|
||
}
|
||
finally { demand?.Dispose(); }
|
||
}
|
||
|
||
private sealed class AccessFixture : IFederatedProjectionCatalog, IProjectedNodeLookup, IGrpcDataAdapterConnectionSource, IProjectedValuePublisher, IDisposable
|
||
{
|
||
private readonly LocalDataFixture _local = new(servingGeneration: 1);
|
||
private readonly DataOperationPolicy _policy;
|
||
internal readonly NodeId NodeId = new("projected", 2);
|
||
internal readonly NodeId SecondNodeId = new("projected-two", 2);
|
||
internal ProjectedNodeProof? SecondProof;
|
||
internal ProjectedVariableDefinition? SecondDefinition;
|
||
internal int StreamOpens;
|
||
internal readonly TaskCompletionSource FirstStreamItem = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource SecondStreamOpened = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource TwoStreamItems = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource ItemRemoved = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource ThirdStreamItem = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource SecondTotalStreamItem = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly Channel<ProjectedValueUpdate> Updates = Channel.CreateUnbounded<ProjectedValueUpdate>();
|
||
internal bool ScalarSnapshots, HoldRemoveAck, HoldNextSnapshotEnd;
|
||
internal long? SnapshotObservedTimestamp;
|
||
internal readonly TaskCompletionSource SnapshotEndHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal async Task<ProjectedValueUpdate> ReadUpdateAsync() => await Updates.Reader.ReadAsync(TestContext.Current.CancellationToken).AsTask().WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
||
internal readonly System.Collections.Concurrent.ConcurrentQueue<DataSubscriptionCommand> StreamCommands = new();
|
||
internal readonly System.Collections.Concurrent.ConcurrentDictionary<string, DataItemHandle> StreamHandles = new();
|
||
private readonly System.Collections.Concurrent.ConcurrentQueue<TestStream> _streamsByOwner = new();
|
||
internal bool BlockStreamDispose;
|
||
internal bool HoldSecondOpen;
|
||
internal readonly TaskCompletionSource SecondOpenEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource ReleaseSecondOpen = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource StreamDisposeEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource ReleaseStreamDispose = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal void EndFirstStream() => _streamsByOwner.First().End();
|
||
internal void EndAllStreams() { foreach (var stream in _streamsByOwner.ToArray()) stream.End(); }
|
||
private int _totalStreamItems;
|
||
internal void EmitValue(string id, long version, int value) => _streamsByOwner.Single(x => x.HasItem(id)).EmitValue(id, version, value);
|
||
internal void ReleaseRemoveAck(string? id = null) => (id is null ? _streamsByOwner.Single() : _streamsByOwner.Single(x => x.HasItem(id))).ReleaseRemoveAck();
|
||
internal void ReleaseSnapshotEnd() => _streamsByOwner.Single().ReleaseSnapshotEnd();
|
||
internal readonly TaskCompletionSource StreamClosed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
private readonly bool _streams;
|
||
private readonly bool _array;
|
||
internal int[] ReadElements = [2, 4, 6];
|
||
internal object[]? CapturedArray;
|
||
internal readonly RoleCarryingUserIdentity Caller;
|
||
internal ProjectedNodeProof Proof;
|
||
internal ProjectedVariableDefinition Definition;
|
||
internal bool Current = true;
|
||
internal int Pins;
|
||
internal TaskCompletionSource<ProjectedValueUpdate> Published = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal void Renew()
|
||
{
|
||
var lease = new MetadataAuthorityLease(_local.Serving, new(1, 1, TimeSpan.FromSeconds(15)), _local.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, _local.Clock);
|
||
Proof = Proof with { Lease = lease };
|
||
Definition = Definition with { AuthorityIsCurrent = () => Current };
|
||
Published = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
}
|
||
internal void Publish(int value) => _local.Publish(value);
|
||
internal void Advance(TimeSpan elapsed) => _local.Clock.Advance(elapsed);
|
||
internal void PublishVersion(long version, int value) => _local.Hub.WithPartitionLockForTest(_local.Ticket.Key, () => { HubTest.Publish(_local.Hub, _local.Ticket, version, value); _local.Hub.ProcessPending(); });
|
||
internal WriteBatch? SentWrite;
|
||
internal int WriteCalls;
|
||
internal DataBudget? ReadBudget;
|
||
internal bool BlockAcquire, BlockWrite, BlockReadReturn, RoleAllowed = true;
|
||
internal readonly TaskCompletionSource ReadResultHeld = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource ReleaseReadResult = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource WriteEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource ReleaseWrite = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal long RoleGeneration = 1;
|
||
internal readonly TaskCompletionSource AcquireEntered = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource ReleaseAcquire = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal AccessFixture(bool readOnly = false, bool writable = false, bool streams = false, bool subscribeOnly = false, bool array = false, bool aliases = false)
|
||
{
|
||
_streams = streams; _array = array;
|
||
var authority = _local.Authority;
|
||
if (writable)
|
||
{
|
||
authority = new DataPlaneAuthorityState();
|
||
var key = new ApiKey { ApiKeyId = "peer-key", Name = "peer-key", Principal = "peer", SecretHash = "hash", Enabled = true };
|
||
authority.Apply("cluster", "first", [key], [new NodeAcl { NodeAclId = "write", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = NodePermissions.Operator }],
|
||
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
|
||
}
|
||
_policy = new(authority, new TriePermissionEvaluator(authority.Tries, _local.Clock), _local.Clock);
|
||
Caller = new(new AnonymousIdentityToken(), [], _local.Context.PrincipalId, _local.Context.ApiKeyId, _local.Context.CredentialVersion, _local.Context.CredentialExpiresUtc);
|
||
var origin = _local.Raw;
|
||
var mapped = origin with { MappingId = "mapping", MappingRevision = 1, Subject = "Plant/branch/Speed" };
|
||
var serving = _local.Serving;
|
||
var operations = subscribeOnly ? DataOperations.Subscribe : readOnly ? DataOperations.Read : DataOperations.Browse | DataOperations.Read | DataOperations.Subscribe | (writable ? DataOperations.Write : DataOperations.None);
|
||
var subject = new MappedNamespaceSubject(mapped, new() { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw, Segments = ["Plant", "branch", "Speed"] }, ["folder"], serving, operations, writable);
|
||
var metadata = new DataMetadata(mapped, "Speed", "Variable", DataValueKind.Int32, -1, [], writable, operations, 1, null, null, false, Serving: serving);
|
||
if (array) metadata = metadata with { ValueKind = DataValueKind.Array, ValueRank = 1, Dimensions = [3], ArrayElementKind = DataValueKind.Int32 };
|
||
var lease = new MetadataAuthorityLease(serving, new(1, 1, TimeSpan.FromSeconds(15)), _local.Clock.GetTimestamp(), TimeSpan.FromSeconds(15), TimeSpan.Zero, _local.Clock);
|
||
Proof = new(ProjectedDataIds.Identifier("mapping", origin.Address), metadata, subject, new([subject], 1, _local.Activation.CaptureAuthority()), lease, 1, metadata with { View = origin }, TimeSpan.FromSeconds(30));
|
||
Definition = new(DataRealm.Raw, Proof.LocalIdentifier, new NodeId("parent", 2), metadata, 1, () => Current);
|
||
if (streams)
|
||
{
|
||
var secondOrigin = aliases ? origin : origin with { Address = origin.Address with { Identifier = origin.Address.Identifier + "2" }, Subject = origin.Subject + "2" };
|
||
var secondView = mapped with { Address = secondOrigin.Address, Subject = mapped.Subject + "2", MappingId = aliases ? "mapping-two" : "mapping" };
|
||
var secondSubject = subject with { View = secondView, Scope = subject.Scope with { Segments = ["Plant", "branch", "Speed2"] } };
|
||
var secondMetadata = metadata with { View = secondView, BrowseName = "Speed2" };
|
||
SecondProof = new(ProjectedDataIds.Identifier(aliases ? "mapping-two" : "mapping", secondOrigin.Address), secondMetadata, secondSubject, new([secondSubject], 1, _local.Activation.CaptureAuthority()), lease, 1, secondMetadata with { View = secondOrigin }, TimeSpan.FromSeconds(30));
|
||
SecondDefinition = new(DataRealm.Raw, SecondProof.LocalIdentifier, new NodeId("parent", 2), secondMetadata, 1, () => Current);
|
||
}
|
||
}
|
||
internal ProjectedDataAccess Create(int maxDemands = 4, long maxBytes = 2000000) => new(this, this, this, _ => "link", _policy, this, _local.Clock, new(maxDemands, 4, maxBytes, 2), () => (RoleAllowed, RoleGeneration));
|
||
public TimeProvider Clock => _local.Clock;
|
||
public event Action<string, long>? Invalidated;
|
||
internal readonly TaskCompletionSource ConnectionDisposed = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource NoPins = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal readonly TaskCompletionSource SourceRetired = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
internal void InvalidateMapping(string mapping = "mapping") { if (mapping == "mapping") Current = false; Invalidated?.Invoke(mapping, 2); }
|
||
public bool TryResolveProjected(DataRealm realm, string id, out ProjectedNodeProof? proof) { proof = Current && realm == DataRealm.Raw ? id == Proof.LocalIdentifier ? Proof : id == SecondProof?.LocalIdentifier ? SecondProof : null : null; return proof is not null; }
|
||
public bool TryPinProjected(DataRealm realm, string id, out IDisposable? pin) { if (!Current || id != Proof.LocalIdentifier && id != SecondProof?.LocalIdentifier) { pin = null; return false; } Pins++; pin = new Pin(this); return true; }
|
||
private sealed class Pin(AccessFixture owner) : IDisposable { private int _done; public void Dispose() { if (Interlocked.Exchange(ref _done, 1) == 0 && Interlocked.Decrement(ref owner.Pins) == 0) owner.NoPins.TrySetResult(); } }
|
||
public ProjectedParentSnapshot TryGetParent(ProjectedBrowseRequest request) => throw new NotSupportedException();
|
||
public Task<IProjectedPreparedPage> PreparePageAsync(ProjectedBrowseRequest request, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||
public bool TryResolve(NodeId nodeId, out ProjectedVariableDefinition? definition) { definition = nodeId == NodeId ? Definition : nodeId == SecondNodeId ? SecondDefinition : null; return definition is not null; }
|
||
public bool TryGetNodeId(string namespaceUri, string identifier, out NodeId? nodeId) { nodeId = NodeId; return true; }
|
||
public async ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
|
||
{
|
||
AcquireEntered.TrySetResult();
|
||
if (BlockAcquire) await ReleaseAcquire.Task.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken);
|
||
return new ConnectionLease(new TestConnection(_local.Connection(), this), this);
|
||
}
|
||
private sealed class TestConnection(IDataConnection inner, AccessFixture owner) : IDataConnection
|
||
{
|
||
public DataTarget Target => inner.Target;
|
||
public TimeProvider Clock => inner.Clock;
|
||
public Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken) => inner.GetCapabilitiesAsync(budget, cancellationToken);
|
||
public Task<DataBrowseBranch> BrowseAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.BrowseRequest request, CancellationToken cancellationToken) => inner.BrowseAsync(request, cancellationToken);
|
||
public Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken) => inner.GetMetadataAsync(request, cancellationToken);
|
||
public async Task<IReadOnlyList<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult>> ReadAsync(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadRequest request, CancellationToken cancellationToken)
|
||
{
|
||
owner.ReadBudget = request.Budget;
|
||
IReadOnlyList<ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.ReadResult> result;
|
||
if (!owner._array) result = await inner.ReadAsync(request, cancellationToken);
|
||
else
|
||
{
|
||
var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast<object>().ToArray(), [owner.ReadElements.Length]);
|
||
var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), owner.Proof.Lease.Serving, 1);
|
||
result = [new(request.Items[0].CorrelationId, DataItemStatus.Good, DataReadiness.Ready, TimeSpan.Zero, sample, null, AgeBounds: new(TimeSpan.Zero, TimeSpan.Zero))];
|
||
}
|
||
try
|
||
{
|
||
if (owner.BlockReadReturn)
|
||
{
|
||
owner.ReadResultHeld.TrySetResult();
|
||
await owner.ReleaseReadResult.Task.WaitAsync(cancellationToken);
|
||
}
|
||
return result;
|
||
}
|
||
catch { foreach (var item in result) item.Dispose(); throw; }
|
||
}
|
||
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
|
||
{
|
||
owner.SentWrite = request; Interlocked.Increment(ref owner.WriteCalls);
|
||
if (request.Items[0].Value.Kind == DataValueKind.Array) owner.CapturedArray = request.Items[0].Value.GetArray().ToArray();
|
||
owner.WriteEntered.TrySetResult();
|
||
if (owner.BlockWrite) await owner.ReleaseWrite.Task; // Simulates a transport that cannot be canceled after dispatch.
|
||
return [new(request.Items[0].CorrelationId, new(DataWriteState.OutcomeUnknown, StatusCodes.Bad.Code, null))];
|
||
}
|
||
public Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken)
|
||
{
|
||
if (!owner._streams) return inner.SubscribeAsync(cancellationToken);
|
||
var number = Interlocked.Increment(ref owner.StreamOpens);
|
||
if (number == 2) owner.SecondStreamOpened.TrySetResult();
|
||
var stream = new TestStream(owner, owner.Proof.Lease.Serving, number); owner._streamsByOwner.Enqueue(stream);
|
||
return Task.FromResult<IDataSubscription>(stream);
|
||
}
|
||
public ValueTask DisposeAsync() => inner.DisposeAsync();
|
||
}
|
||
private sealed class TestStream(AccessFixture owner, ServingIdentity serving, int number) : IDataSubscription, IDataSubscriptionProvenance
|
||
{
|
||
private readonly Channel<DataSubscriptionFrame> _frames = Channel.CreateUnbounded<DataSubscriptionFrame>();
|
||
private readonly object _gate = new();
|
||
private string? _subscriptionId;
|
||
private long _epoch;
|
||
private DataSubscriptionAck? _heldRemoveAck;
|
||
private bool _snapshotEndHeld;
|
||
private long _sequence; private ulong _handle; private int _items;
|
||
private readonly Dictionary<DataItemHandle, string> _ids = new();
|
||
public ServingIdentity Serving => serving;
|
||
public async Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken)
|
||
{
|
||
if (number == 2 && owner.HoldSecondOpen && command is OpenSubscription)
|
||
{
|
||
owner.SecondOpenEntered.TrySetResult();
|
||
await owner.ReleaseSecondOpen.Task.WaitAsync(cancellationToken);
|
||
}
|
||
lock (_gate)
|
||
{
|
||
owner.StreamCommands.Enqueue(command); _subscriptionId = command.SubscriptionId; _epoch = command.StreamEpoch;
|
||
IReadOnlyList<DataSubscriptionItem> items = command switch { OpenSubscription open => open.Items, AddSubscriptionItems add => add.Items, _ => [] };
|
||
var acks = items.Select(item => new DataSubscriptionItemAck(item.ClientItemId, DataItemStatus.Good,
|
||
new DataItemHandle(command.SubscriptionId, command.StreamEpoch, ++_handle, 1), item.Settings, null)).ToArray();
|
||
foreach (var ack in acks) if (ack.Handle is not null) { _ids[ack.Handle] = ack.ClientItemId; owner.StreamHandles[ack.ClientItemId] = ack.Handle; }
|
||
if (command is RemoveSubscriptionItems remove)
|
||
acks = remove.Items.Select(handle => new DataSubscriptionItemAck(_ids[handle], DataItemStatus.Good, handle, null, null)).ToArray();
|
||
if (command is RemoveSubscriptionItems && owner.HoldRemoveAck)
|
||
_heldRemoveAck = new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, 0, command.CommandId, acks);
|
||
else _frames.Writer.TryWrite(new DataSubscriptionAck(command.SubscriptionId, command.StreamEpoch, ++_sequence, command.CommandId, acks));
|
||
if (items.Count > 0)
|
||
{
|
||
_items += items.Count; owner.FirstStreamItem.TrySetResult(); if (_items >= 2) owner.TwoStreamItems.TrySetResult();
|
||
var total = Interlocked.Add(ref owner._totalStreamItems, items.Count);
|
||
if (total >= 2) owner.SecondTotalStreamItem.TrySetResult(); if (total >= 3) owner.ThirdStreamItem.TrySetResult();
|
||
_frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotBegin, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
|
||
if (owner._array && acks.Length > 0)
|
||
{
|
||
var value = ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromArray(DataValueKind.Int32, owner.ReadElements.Cast<object>().ToArray(), [owner.ReadElements.Length]);
|
||
var sample = new DataSample(value, 0, null, owner.Clock.GetUtcNow(), serving, 1);
|
||
_frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true,
|
||
[new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]));
|
||
}
|
||
if (owner.ScalarSnapshots && acks.Length > 0)
|
||
{
|
||
var sample = new DataSample(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, 7), 0, null, owner.Clock.GetUtcNow(), serving, 1);
|
||
_frames.Writer.TryWrite(new DataSubscriptionValues(command.SubscriptionId, command.StreamEpoch, ++_sequence, true,
|
||
[new DataSubscriptionValue(acks[0].Handle!, sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready,
|
||
FreshnessObservedTimestamp: owner.SnapshotObservedTimestamp)]));
|
||
}
|
||
if (owner.HoldNextSnapshotEnd)
|
||
{
|
||
owner.HoldNextSnapshotEnd = false; _snapshotEndHeld = true; owner.SnapshotEndHeld.TrySetResult();
|
||
}
|
||
else _frames.Writer.TryWrite(new DataSubscriptionControl(command.SubscriptionId, command.StreamEpoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
|
||
}
|
||
if (command is RemoveSubscriptionItems) owner.ItemRemoved.TrySetResult();
|
||
}
|
||
}
|
||
internal void ReleaseSnapshotEnd()
|
||
{
|
||
lock (_gate)
|
||
{
|
||
if (!_snapshotEndHeld) throw new InvalidOperationException("No snapshot end is held.");
|
||
_snapshotEndHeld = false;
|
||
_frames.Writer.TryWrite(new DataSubscriptionControl(_subscriptionId!, _epoch, ++_sequence, DataStreamControlKind.SnapshotEnd, [], serving.CatalogEpoch, serving.AuthorityEpoch, null));
|
||
}
|
||
}
|
||
internal bool HasItem(string id) { lock (_gate) return _ids.Values.Contains(id); }
|
||
internal void ReleaseRemoveAck()
|
||
{
|
||
lock (_gate)
|
||
{
|
||
var ack = _heldRemoveAck ?? throw new InvalidOperationException("No removal acknowledgement is held.");
|
||
_heldRemoveAck = null;
|
||
_frames.Writer.TryWrite(new DataSubscriptionAck(ack.SubscriptionId, ack.StreamEpoch, ++_sequence, ack.CommandId, ack.Items));
|
||
}
|
||
}
|
||
internal void EmitValue(string id, long version, int value)
|
||
{
|
||
lock (_gate)
|
||
{
|
||
var sample = new DataSample(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(DataValueKind.Int32, value), 0, null, owner.Clock.GetUtcNow(), serving, version);
|
||
_frames.Writer.TryWrite(new DataSubscriptionValues(_subscriptionId!, _epoch, ++_sequence, false,
|
||
[new DataSubscriptionValue(owner.StreamHandles[id], sample, new(TimeSpan.Zero, TimeSpan.Zero), DataReadiness.Ready)]));
|
||
}
|
||
}
|
||
public IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken) => _frames.Reader.ReadAllAsync(cancellationToken);
|
||
internal void End() => _frames.Writer.TryComplete();
|
||
public async ValueTask DisposeAsync()
|
||
{
|
||
_frames.Writer.TryComplete(); owner.StreamClosed.TrySetResult();
|
||
if (owner.BlockStreamDispose) { owner.StreamDisposeEntered.TrySetResult(); await owner.ReleaseStreamDispose.Task; }
|
||
}
|
||
}
|
||
private sealed class ConnectionLease(IDataConnection connection, AccessFixture owner) : IGrpcDataAdapterConnectionLease
|
||
{
|
||
public IDataConnection Connection => connection;
|
||
public CancellationToken CancellationToken => CancellationToken.None;
|
||
public async ValueTask DisposeAsync() { await connection.DisposeAsync(); owner.ConnectionDisposed.TrySetResult(); }
|
||
}
|
||
internal Action? BeforeBind;
|
||
public bool TryBind(ProjectedValueRoute route) { BeforeBind?.Invoke(); return true; }
|
||
public bool TryPublish(IReadOnlyList<ProjectedValueUpdate> updates) { Published.TrySetResult(updates[0]); Updates.Writer.TryWrite(updates[0]); return true; }
|
||
public void Retire(ProjectedValueRoute route) { SourceRetired.TrySetResult(); }
|
||
public void Dispose() => _local.Dispose();
|
||
}
|
||
}
|