390 lines
23 KiB
C#
390 lines
23 KiB
C#
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 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.RejectedBeforeDispatch);
|
|
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)
|
|
{
|
|
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", () => fixture.Serving, () => true, limits);
|
|
return new DataWriteExecutor(context ?? fixture.Context, () => catalog ?? fixture.Catalog, policy, capabilities, route,
|
|
registry, new WriteValueBudget(16_384), fixture.Clock, new DriverWriteBounds(TimeSpan.FromMilliseconds(100)));
|
|
}
|
|
|
|
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);
|
|
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);
|
|
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);
|
|
}
|
|
}
|