bcd4a9aa29
The late-write observer released the physical slot on its own continuation of the driver task, while RunRichWriteAsync replied and told WriteCompleted on another. A next write to the same target (queued, or sent right after the reply) could reach TryReserve before the release and be rejected with 'Outstanding driver write capacity exhausted' although nothing was outstanding. LateWriteReservation.Observe now returns a task that completes after the slot is released; the actor awaits it (when the physical write has finished) before replying and freeing the tag. The flaky unit test waited on the lifetime counter, which is disposed just before the release - it now awaits the settled task. Repro: 200 sequential same-target actor writes failed 3/3 runs (no load); 0 failures in 15 runs at load avg ~468. Unit signal: lifetime-wait 22-39 / 2M false 'slot busy', settled-wait 0/2M.
596 lines
36 KiB
C#
596 lines
36 KiB
C#
using System.Buffers.Binary;
|
|
using System.Net;
|
|
using Google.Protobuf;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
|
using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
|
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.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", "P05")]
|
|
public sealed class GrpcDataWriteAdmissionTests
|
|
{
|
|
[Fact]
|
|
public async Task Authority_publication_is_ordered_with_dispatch_and_notifications_run_outside_the_fence()
|
|
{
|
|
var fence = new DataWriteDispatchFence();
|
|
var authority = new DataPlaneAuthorityState(fence);
|
|
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var notificationCanEnter = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
authority.Changed += snapshot =>
|
|
{
|
|
// A different thread must acquire the dispatch fence while this callback runs. A reentrant
|
|
// acquisition on the notification thread would not detect holding the fence across callbacks.
|
|
var enteredFence = new ManualResetEventSlim();
|
|
_ = Task.Run(() => { using (fence.Enter()) enteredFence.Set(); }, TestContext.Current.CancellationToken);
|
|
notificationCanEnter.TrySetResult(enteredFence.Wait(TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken));
|
|
};
|
|
|
|
using var release = new ManualResetEventSlim();
|
|
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var owner = Task.Run(() =>
|
|
{
|
|
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
|
}, TestContext.Current.CancellationToken);
|
|
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
var apply = Task.Run(() =>
|
|
{
|
|
entered.TrySetResult();
|
|
authority.Apply("cluster", "revision-1", Array.Empty<ApiKey>(), Array.Empty<NodeAcl>(),
|
|
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
|
}, TestContext.Current.CancellationToken);
|
|
try
|
|
{
|
|
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
// Publication, not merely its Changed event, is ordered against the dispatch commit.
|
|
(await Task.WhenAny(apply, Task.Delay(150, TestContext.Current.CancellationToken))).ShouldNotBe(apply);
|
|
authority.Current.HasArtifact.ShouldBeFalse();
|
|
}
|
|
finally { release.Set(); }
|
|
|
|
await owner.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
await apply.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
(await notificationCanEnter.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeTrue("Changed must run outside the dispatch fence");
|
|
authority.Current.HasArtifact.ShouldBeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task A_catalog_invalidation_cannot_publish_inside_a_dispatch_commit()
|
|
{
|
|
var fence = new DataWriteDispatchFence();
|
|
var catalog = new CatalogActivation(fence);
|
|
var epoch = catalog.Begin("first");
|
|
catalog.AuthorityInstalled(epoch, 1).ShouldBeTrue();
|
|
catalog.Complete(epoch, true).ShouldBeTrue();
|
|
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
using var release = new ManualResetEventSlim();
|
|
var held = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var owner = Task.Run(() =>
|
|
{
|
|
using (fence.Enter()) { held.TrySetResult(); release.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
|
}, TestContext.Current.CancellationToken);
|
|
await held.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
var invalidate = Task.Run(() => { started.TrySetResult(); return catalog.Begin("second"); }, TestContext.Current.CancellationToken);
|
|
try
|
|
{
|
|
await started.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
(await Task.WhenAny(invalidate, Task.Delay(150, TestContext.Current.CancellationToken))).ShouldNotBe(invalidate);
|
|
catalog.Current.IsReady.ShouldBeTrue();
|
|
}
|
|
finally { release.Set(); }
|
|
|
|
await owner.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
(await invalidate.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldBeGreaterThan(epoch);
|
|
catalog.Current.IsReady.ShouldBeFalse();
|
|
}
|
|
|
|
[Fact]
|
|
public void Demotion_and_repromotion_advance_the_primary_generation_even_when_the_final_verdict_matches()
|
|
{
|
|
var role = new RedundancyRoleView(new DataWriteDispatchFence());
|
|
role.PublishPrimaryRole(true);
|
|
var before = role.PrimaryGeneration;
|
|
role.PublishPrimaryRole(false);
|
|
var demoted = role.PrimaryGeneration;
|
|
role.PublishPrimaryRole(true);
|
|
|
|
demoted.ShouldBeGreaterThan(before);
|
|
role.PrimaryGeneration.ShouldBeGreaterThan(demoted);
|
|
role.ShouldActAsPrimary.ShouldBeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public void First_primary_publication_establishes_a_generation_without_heartbeat_churn()
|
|
{
|
|
var role = new RedundancyRoleView(new DataWriteDispatchFence());
|
|
role.ShouldActAsPrimary.ShouldBeTrue(); // the legacy seed is preserved
|
|
role.PrimaryGeneration.ShouldBe(0);
|
|
role.PublishPrimaryRole(true);
|
|
var established = role.PrimaryGeneration;
|
|
established.ShouldBeGreaterThan(0);
|
|
role.PublishPrimaryRole(true);
|
|
role.PrimaryGeneration.ShouldBe(established);
|
|
}
|
|
|
|
[Fact]
|
|
public void Route_proof_is_invalidated_by_remap_and_does_not_revive_when_the_original_route_returns()
|
|
{
|
|
var state = new WriteRouteState(new DataWriteDispatchFence());
|
|
var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag");
|
|
var original = state.Publish(view, "driver", "plant/tag", "incarnation-1");
|
|
state.IsCurrent(view, original).ShouldBeTrue();
|
|
state.Publish(view, "other-driver", "plant/other", "incarnation-2");
|
|
state.IsCurrent(view, original).ShouldBeFalse();
|
|
var restored = state.Publish(view, "driver", "plant/tag", "incarnation-1");
|
|
state.IsCurrent(view, original).ShouldBeFalse();
|
|
state.IsCurrent(view, restored).ShouldBeTrue();
|
|
restored.RouteGeneration.ShouldBeGreaterThan(original.RouteGeneration);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Executor_keeps_partial_batch_results_in_input_order_and_does_not_dispatch_a_type_mismatch()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var first = DataValue.FromScalar(DataValueKind.Int32, 1);
|
|
using var wrong = DataValue.FromScalar(DataValueKind.String, "wrong type");
|
|
using var last = DataValue.FromScalar(DataValueKind.Int32, 2);
|
|
var remaining = TimeSpan.FromSeconds(5);
|
|
var results = await executor.WriteAsync(new([
|
|
new("a", "ok", fixture.Raw, first, 1, fixture.Serving.Incarnation, remaining),
|
|
new("b", "bad-type", fixture.Raw, wrong, 1, fixture.Serving.Incarnation, remaining),
|
|
new("c", "failed", fixture.Raw, last, 1, fixture.Serving.Incarnation, remaining)],
|
|
LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
|
|
results.Select(x => x.CorrelationId).ShouldBe(["a", "b", "c"]);
|
|
results.Select(x => x.Outcome.State).ShouldBe([DataWriteState.DriverConfirmedSuccess,
|
|
DataWriteState.RejectedBeforeDispatch, DataWriteState.DriverConfirmedFailure]);
|
|
route.Dispatched.Order().ShouldBe(["failed", "ok"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Batch_preflight_time_counts_against_the_write_deadline()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var item = new WriteItem("one", "slow-preflight", fixture.Raw, value, 1, fixture.Serving.Incarnation, TimeSpan.FromSeconds(5));
|
|
var items = new DelayedPreflightItems(item, fixture.Clock);
|
|
var result = await executor.WriteAsync(new(items, LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
|
route.Dispatched.ShouldBeEmpty("batch preflight consumed the remaining dispatch budget");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Slow_route_resolution_cannot_extend_the_original_write_deadline()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new DelayedResolutionRoute(fixture.Raw, fixture.Clock);
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var result = await executor.WriteAsync(new([new("one", "slow-route", fixture.Raw, value, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
|
route.Dispatched.ShouldBeEmpty("the route delay exhausted the remaining physical dispatch budget");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Executor_rejects_a_stale_generation_before_route_or_registry_claim()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), fixture.Serving.ServingGeneration + 1);
|
|
var stale = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
stale.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
|
route.Dispatched.ShouldBeEmpty();
|
|
var valid = await executor.WriteAsync(new([item with { ExpectedServingGeneration = null }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
valid.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Duplicate_operation_cannot_change_generation_presence()
|
|
{
|
|
using var fixture = new LocalDataFixture(servingGeneration: 1);
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), 1);
|
|
var first = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
var changed = await executor.WriteAsync(new([item with { CorrelationId = "two", ExpectedServingGeneration = null }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
changed.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
|
route.Dispatched.ShouldBe(["same-operation"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Same_operation_after_role_aba_returns_unknown_instead_of_retryable_rejection()
|
|
{
|
|
using var fixture = new LocalDataFixture(servingGeneration: 1);
|
|
var serving = fixture.Serving;
|
|
var catalog = fixture.Catalog;
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var executor = CreateExecutor(fixture, route, catalogSource: () => catalog, servingSource: () => serving);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, serving.Incarnation, TimeSpan.FromSeconds(5), 1);
|
|
var first = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
serving = serving with { ServingGeneration = 3 };
|
|
catalog = catalog.WithServingRole(serving);
|
|
var afterAba = await executor.WriteAsync(new([item with { ExpectedServingGeneration = 3 }], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
afterAba.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
|
route.Dispatched.ShouldBe(["same-operation"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Legacy_client_does_not_fail_over_a_real_executor_conflict_after_role_aba()
|
|
{
|
|
using var fixture = new LocalDataFixture(servingGeneration: 1);
|
|
var serving = fixture.Serving;
|
|
var catalog = fixture.Catalog;
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var executor = CreateExecutor(fixture, route, catalogSource: () => catalog, servingSource: () => serving);
|
|
var first = new ExecutorWireHandler(() => serving, fixture.Raw, executor);
|
|
var second = new ExecutorWireHandler(() => serving with { NodeId = "node-b" }, fixture.Raw, null);
|
|
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, "cluster", null),
|
|
[new Uri("https://a.test"), new Uri("https://b.test")], new ExecutorWireSecurity(first, second), manager.Acquire("link"),
|
|
1_000_000, 2, eligibleNodeIds: new HashSet<string> { "node-a", "node-b" });
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var item = new WriteItem("one", "same-operation", fixture.Raw, value, 1, serving.Incarnation, TimeSpan.FromSeconds(5));
|
|
var original = await connection.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
original.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
serving = serving with { ServingGeneration = 3 };
|
|
catalog = catalog.WithServingRole(serving);
|
|
var repeated = await connection.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
repeated.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
|
route.Dispatched.ShouldBe(["same-operation"]);
|
|
first.Writes.ShouldBe(2); second.Writes.ShouldBe(0);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Strict_write_rejects_a_different_view_shape_before_dispatch()
|
|
{
|
|
using var fixture = new LocalDataFixture(servingGeneration: 1);
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var item = new WriteItem("one", "operation", fixture.Raw with { Subject = "forged" }, value, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5), 1);
|
|
var result = await executor.WriteAsync(new([item], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
|
route.Dispatched.ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Executor_joins_concurrent_duplicate_with_a_different_remaining_budget()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new RecordingRoute(fixture.Raw) { Hold = true };
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
using var duplicateValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var first = executor.WriteAsync(new([new("first", "same-operation", fixture.Raw, firstValue, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
var duplicate = executor.WriteAsync(new([new("duplicate", "same-operation", fixture.Raw, duplicateValue, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(4))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
route.Release.TrySetResult();
|
|
|
|
var firstResult = await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
var duplicateResult = await duplicate.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
firstResult.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
duplicateResult.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
route.Dispatched.ShouldBe(["same-operation"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Equivalent_origin_cluster_spelling_uses_the_catalog_resolved_view_for_duplicate_identity()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new RecordingRoute(fixture.Raw) { Hold = true };
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var first = executor.WriteAsync(new([new("first", "canonical-view", fixture.Raw, firstValue, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
var equivalent = fixture.Raw with { Address = fixture.Raw.Address with { OriginClusterId = "CLUSTER" } };
|
|
var second = executor.WriteAsync(new([new("second", "canonical-view", equivalent, secondValue, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
route.Release.TrySetResult();
|
|
|
|
(await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))
|
|
.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
(await second.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken))
|
|
.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
route.Dispatched.ShouldBe(["canonical-view"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Ordinally_distinct_authorized_views_with_unpaired_surrogates_cannot_share_an_operation()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var existing = fixture.Catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
|
|
var first = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Driver/Device/\ud800" },
|
|
Subject = "Plant/Driver/Device/\ud800" };
|
|
var second = fixture.Raw with { Address = fixture.Raw.Address with { Identifier = "Plant/Driver/Device/\ud801" },
|
|
Subject = "Plant/Driver/Device/\ud801" };
|
|
LocalDataNode MakeNode(string id, DataView view, string leaf) => existing with
|
|
{
|
|
EntityId = id,
|
|
Metadata = existing.Metadata with { View = view, BrowseName = leaf },
|
|
Scope = new NodeScope { ClusterId = "cluster", Kind = NodeHierarchyKind.Raw,
|
|
Segments = ["Plant", "Driver", "Device", leaf] },
|
|
};
|
|
var nodes = fixture.Catalog.Nodes.Concat([MakeNode("surrogate-a", first, "\ud800"), MakeNode("surrogate-b", second, "\ud801")]);
|
|
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
|
|
var catalog = new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), nodes,
|
|
[new() { DataExportId = "raw-export", ClusterId = "cluster", Enabled = true, Realm = DataRealm.Raw,
|
|
RootKind = "RawFolder", RootEntityId = "folder", PrincipalId = "peer", AllowedOperations = operations }]);
|
|
var route = new RecordingRoute(first, second);
|
|
var executor = CreateExecutor(fixture, route, catalog: catalog);
|
|
using var firstValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
using var secondValue = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var one = await executor.WriteAsync(new([new("one", "same-id", first, firstValue, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
var two = await executor.WriteAsync(new([new("two", "same-id", second, secondValue, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
|
|
one.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
two.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
|
route.Dispatched.ShouldBe(["same-id"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Canceling_one_waiter_does_not_cancel_the_shared_dispatched_write()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new RecordingRoute(fixture.Raw) { Hold = true };
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
using var canceledWaiter = new CancellationTokenSource();
|
|
var batch = new WriteBatch([new("first", "shared", fixture.Raw, value, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget);
|
|
var first = executor.WriteAsync(batch, canceledWaiter.Token);
|
|
await route.Entered.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
|
|
var second = executor.WriteAsync(batch, TestContext.Current.CancellationToken);
|
|
canceledWaiter.Cancel();
|
|
route.Release.TrySetResult();
|
|
try { await first.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken); }
|
|
catch (OperationCanceledException) { }
|
|
|
|
(await second.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken)).ShouldHaveSingleItem().Outcome.State
|
|
.ShouldBe(DataWriteState.DriverConfirmedSuccess);
|
|
route.Dispatched.ShouldBe(["shared"]);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Executor_does_not_refine_an_unknown_after_the_observation_window_ends()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new ExpiredObservationRoute(fixture.Raw, fixture.Clock);
|
|
var executor = CreateExecutor(fixture, route);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var batch = new WriteBatch([new("first", "late-result", fixture.Raw, value, 1,
|
|
fixture.Serving.Incarnation, TimeSpan.FromSeconds(5))], LocalDataFixture.Budget);
|
|
var first = await executor.WriteAsync(batch, TestContext.Current.CancellationToken);
|
|
var duplicate = await executor.WriteAsync(batch, TestContext.Current.CancellationToken);
|
|
|
|
first.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
|
duplicate.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
|
route.Dispatches.ShouldBe(1);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("expired")]
|
|
[InlineData("principal")]
|
|
[InlineData("version")]
|
|
[InlineData("budget")]
|
|
public async Task Executor_rejects_unusable_original_credentials_and_insufficient_budget_before_any_route_call(string reason)
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var route = new RecordingRoute(fixture.Raw);
|
|
var context = reason switch
|
|
{
|
|
"expired" => fixture.Context with { CredentialExpiresUtc = fixture.Clock.GetUtcNow() },
|
|
"principal" => fixture.Context with { PrincipalId = "different-principal" },
|
|
"version" => fixture.Context with { CredentialVersion = "replaced-key-version" },
|
|
_ => fixture.Context,
|
|
};
|
|
var executor = CreateExecutor(fixture, route, context);
|
|
using var value = DataValue.FromScalar(DataValueKind.Int32, 42);
|
|
var remaining = reason == "budget" ? TimeSpan.FromMilliseconds(1) : TimeSpan.FromSeconds(5);
|
|
var result = await executor.WriteAsync(new([new("one", "operation", fixture.Raw, value, 1,
|
|
fixture.Serving.Incarnation, remaining)], LocalDataFixture.Budget), TestContext.Current.CancellationToken);
|
|
|
|
result.ShouldHaveSingleItem().Outcome.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
|
|
route.Dispatched.ShouldBeEmpty();
|
|
}
|
|
|
|
private static DataWriteExecutor CreateExecutor(LocalDataFixture fixture, IDataWriteRoute route,
|
|
DataAuthenticatedContext? context = null, LocalExportCatalog? catalog = null,
|
|
Func<LocalExportCatalog>? catalogSource = null, Func<ServingIdentity>? servingSource = null)
|
|
{
|
|
var 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.WriteOperate }],
|
|
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new(["raw", "Plant"])] });
|
|
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, fixture.Clock), fixture.Clock);
|
|
var registry = new WriteOperationRegistry(fixture.Serving.Incarnation, 16, 16_384, TimeSpan.FromMinutes(1), fixture.Clock);
|
|
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
|
|
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
|
var capabilities = new DataCapabilitiesProvider("cluster", servingSource ?? (() => fixture.Serving), () => true, limits);
|
|
return new DataWriteExecutor(context ?? fixture.Context, catalogSource ?? (() => catalog ?? fixture.Catalog), policy, capabilities, route,
|
|
registry, new WriteValueBudget(16_384), fixture.Clock, new DriverWriteBounds(TimeSpan.FromMilliseconds(100)));
|
|
}
|
|
|
|
private sealed class ExecutorWireSecurity(ExecutorWireHandler first, ExecutorWireHandler second) : IDataConnectionSecurityProvider
|
|
{
|
|
public event Action<string>? Changed { add { } remove { } }
|
|
public ValueTask<DataConnectionSecurity?> ResolveAsync(string connectionId, Uri endpoint, CancellationToken cancellationToken) =>
|
|
ValueTask.FromResult<DataConnectionSecurity?>(new("v1", "ca", "key", () => endpoint.Host == "a.test" ? first : second));
|
|
}
|
|
private sealed class ExecutorWireHandler(Func<ServingIdentity> current, DataView view, DataWriteExecutor? executor) : HttpMessageHandler
|
|
{
|
|
public int Writes { get; private set; }
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
var serving = current();
|
|
IMessage message;
|
|
if (request.RequestUri!.AbsolutePath.EndsWith("/GetCapabilities", StringComparison.Ordinal))
|
|
{
|
|
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
|
|
message = DataProtoMapper.EncodeCapabilities(new DataCapabilities(1, 3, serving, DataReadiness.Ready,
|
|
DataOperations.Read | DataOperations.Metadata | DataOperations.Write, new HashSet<DataValueKind> { DataValueKind.Int32 },
|
|
limits, false, 0, "cluster", false, true, true));
|
|
}
|
|
else if (request.RequestUri.AbsolutePath.EndsWith("/GetMetadata", StringComparison.Ordinal))
|
|
{
|
|
var metadata = new DataMetadata(view, "x", "tag", DataValueKind.Int32, -1, [], true, DataOperations.Write, 1, null, null, false);
|
|
var response = DataProtoMapper.EncodeMetadataResponse([new("0", DataItemStatus.Good, metadata, null)]);
|
|
response.Serving = DataProtoMapper.EncodeServing(serving); message = response;
|
|
}
|
|
else
|
|
{
|
|
Writes++;
|
|
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
|
|
var wire = W.WriteRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
|
|
var batch = DataProtoMapper.DecodeWriteRequest(wire, 100, 1_000_000);
|
|
try
|
|
{
|
|
var outcomes = executor is null ? batch.Items.Select(x => new WriteItemResult(x.CorrelationId,
|
|
new(DataWriteState.DriverConfirmedSuccess, 0, null))).ToArray() :
|
|
await executor.WriteAsync(batch, cancellationToken);
|
|
var response = DataProtoMapper.EncodeWriteResponse(outcomes);
|
|
response.Serving = DataProtoMapper.EncodeServing(serving); message = response;
|
|
}
|
|
finally { foreach (var item in batch.Items) item.Value.Dispose(); }
|
|
}
|
|
var payload = message.ToByteArray();
|
|
var framed = new byte[payload.Length + 5];
|
|
BinaryPrimitives.WriteInt32BigEndian(framed.AsSpan(1, 4), payload.Length);
|
|
payload.CopyTo(framed, 5);
|
|
var http = new HttpResponseMessage(HttpStatusCode.OK) { Version = HttpVersion.Version20, Content = new ByteArrayContent(framed) };
|
|
http.Content.Headers.ContentType = new("application/grpc");
|
|
http.TrailingHeaders.Add("grpc-status", "0");
|
|
return http;
|
|
}
|
|
}
|
|
|
|
private sealed class DelayedPreflightItems(WriteItem item, ManualTimeProvider clock) : IReadOnlyList<WriteItem>
|
|
{
|
|
private int _advanced;
|
|
public int Count => 1;
|
|
public WriteItem this[int index] => index == 0 ? item : throw new ArgumentOutOfRangeException(nameof(index));
|
|
public IEnumerator<WriteItem> GetEnumerator()
|
|
{
|
|
if (Interlocked.Exchange(ref _advanced, 1) == 0) clock.Advance(TimeSpan.FromSeconds(4));
|
|
yield return item;
|
|
}
|
|
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
|
|
}
|
|
|
|
private sealed class DelayedResolutionRoute(DataView view, ManualTimeProvider clock) : IDataWriteRoute
|
|
{
|
|
private readonly RecordingRoute _inner = new(view);
|
|
public string[] Dispatched => _inner.Dispatched;
|
|
public bool TryResolve(DataView requested, out WriteRouteTarget? target)
|
|
{
|
|
clock.Advance(TimeSpan.FromSeconds(4));
|
|
return _inner.TryResolve(requested, out target);
|
|
}
|
|
public Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken cancellationToken) =>
|
|
_inner.DispatchAsync(ticket, claim, cancellationToken);
|
|
}
|
|
|
|
private sealed class RecordingRoute(DataView view, DataView? alternate = null) : IDataWriteRoute
|
|
{
|
|
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _dispatched = new();
|
|
private readonly LateWriteObserver _observer = new(16, TimeSpan.FromMinutes(1));
|
|
public bool Hold { get; init; }
|
|
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public string[] Dispatched => _dispatched.ToArray();
|
|
public bool TryResolve(DataView requested, out WriteRouteTarget? target)
|
|
{
|
|
target = requested == view || requested == alternate
|
|
? new("driver", "Plant/Driver/Device/Speed", "driver-incarnation", 1, 1) : null;
|
|
return target is not null;
|
|
}
|
|
|
|
public async Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
|
|
{
|
|
var operation = ticket.Proof.Admission.OperationId;
|
|
_observer.TryReserve(out var reservation).ShouldBeTrue();
|
|
var physical = new TaskCompletionSource<DataWriteOutcome>(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var settled = reservation.ShouldNotBeNull().Observe(physical.Task, claim, ticket);
|
|
_dispatched.Enqueue(operation);
|
|
claim.TryMarkDispatched().ShouldBeTrue();
|
|
Entered.TrySetResult();
|
|
if (Hold) await Release.Task;
|
|
var outcome = operation == "failed"
|
|
? new DataWriteOutcome(DataWriteState.DriverConfirmedFailure, 0x80000000u, "device rejected")
|
|
: new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
|
|
physical.TrySetResult(outcome);
|
|
// As the driver host does (#964): the slot is back before the outcome is returned.
|
|
await settled;
|
|
return outcome;
|
|
}
|
|
}
|
|
|
|
private sealed class ExpiredObservationRoute(DataView view, ManualTimeProvider clock) : IDataWriteRoute
|
|
{
|
|
public int Dispatches { get; private set; }
|
|
public bool TryResolve(DataView requested, out WriteRouteTarget? target)
|
|
{
|
|
target = requested == view ? new("driver", "Plant/Driver/Device/Speed", "driver-incarnation", 1, 1) : null;
|
|
return target is not null;
|
|
}
|
|
|
|
public Task<DataWriteOutcome> DispatchAsync(WriteAdmissionTicket ticket, WriteClaim claim, CancellationToken ct)
|
|
{
|
|
Dispatches++;
|
|
claim.TryMarkDispatched().ShouldBeTrue();
|
|
var observer = new LateWriteObserver(1, TimeSpan.FromMilliseconds(100), new StepPastRetentionClock(clock));
|
|
observer.TryReserve(out var reservation).ShouldBeTrue();
|
|
var confirmed = new DataWriteOutcome(DataWriteState.DriverConfirmedSuccess, 0, null);
|
|
// The completed physical task lets Observe settle the expired result synchronously, before the
|
|
// host route returns the same definitive outcome to the executor.
|
|
reservation.ShouldNotBeNull().Observe(Task.FromResult(confirmed), claim, ticket);
|
|
return Task.FromResult(confirmed);
|
|
}
|
|
}
|
|
|
|
private sealed class StepPastRetentionClock(ManualTimeProvider clock) : TimeProvider
|
|
{
|
|
private int _reads;
|
|
public override long TimestampFrequency => clock.TimestampFrequency;
|
|
public override DateTimeOffset GetUtcNow() => clock.GetUtcNow();
|
|
public override long GetTimestamp()
|
|
{
|
|
if (Interlocked.Increment(ref _reads) == 2) clock.Advance(TimeSpan.FromSeconds(1));
|
|
return clock.GetTimestamp();
|
|
}
|
|
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) =>
|
|
clock.CreateTimer(callback, state, dueTime, period);
|
|
}
|
|
}
|