feat: add bounded shared grpc subscriptions and delivery scheduling

This commit is contained in:
Joseph Doherty
2026-11-16 07:31:57 -05:00
parent 92e6430e06
commit b710bf9f74
51 changed files with 9182 additions and 184 deletions
@@ -415,7 +415,8 @@ public static class DataProtoMapper
int maxItems,
int maxBytes,
ServingIdentity expectedServing,
int maxElements = TypedValueCodec.DefaultMaxElements
int maxElements = TypedValueCodec.DefaultMaxElements,
bool subscriptionAgeReadiness = false
)
{
ArgumentNullException.ThrowIfNull(frame);
@@ -475,6 +476,8 @@ public static class DataProtoMapper
var serverTime = server is null
? (DateTimeOffset?)null
: TypedValueCodec.DecodeTimestamp(server);
var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness,
update.HasOriginAgeTicks, update.OriginAgeTicks, update.HasReadiness, update.Readiness);
var sample = new DataSample(
TypedValueCodec.Decode(update.Value, maxElements, maxBytes),
update.HasStatusCode ? update.StatusCode : batch.DefaultStatusCode,
@@ -483,7 +486,7 @@ public static class DataProtoMapper
serving,
update.Version
);
items.Add(new DataSubscriptionValue(handle, sample));
items.Add(new DataSubscriptionValue(handle, sample, ageBounds, readiness));
}
return new DataSubscriptionValues(
frame.SubscriptionId,
@@ -503,7 +506,8 @@ public static class DataProtoMapper
public static W.SubscriptionFrame EncodeValues(
DataSubscriptionValues frame,
bool compactNegotiated
bool compactNegotiated,
bool subscriptionAgeReadiness = false
)
{
var result = new W.SubscriptionFrame
@@ -516,13 +520,20 @@ public static class DataProtoMapper
{
result.Values = new W.Values { IsSnapshot = frame.IsSnapshot };
foreach (var item in frame.Items)
result.Values.Items.Add(
new W.ValueUpdate
{
Handle = EncodeHandle(item.Handle),
Sample = EncodeSample(item.Sample),
}
);
{
var update = new W.ValueUpdate
{
Handle = EncodeHandle(item.Handle),
Sample = EncodeSample(item.Sample),
};
if (subscriptionAgeReadiness)
{
ValidateSubscriptionAgeReadiness(item);
if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks;
update.Readiness = (int)item.Readiness;
}
result.Values.Items.Add(update);
}
return result;
}
if (frame.Items.Count == 0)
@@ -555,6 +566,12 @@ public static class DataProtoMapper
Version = item.Sample.Version,
Value = TypedValueCodec.Encode(item.Sample.Value),
};
if (subscriptionAgeReadiness)
{
ValidateSubscriptionAgeReadiness(item);
if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks;
update.Readiness = (int)item.Readiness;
}
if (item.Sample.StatusCode != first.StatusCode)
update.StatusCode = item.Sample.StatusCode;
if (item.Sample.SourceTimestampUtc != first.SourceTimestampUtc)
@@ -580,14 +597,15 @@ public static class DataProtoMapper
int maxItems,
int maxBytes,
ServingIdentity expectedServing,
int maxElements = TypedValueCodec.DefaultMaxElements
int maxElements = TypedValueCodec.DefaultMaxElements,
bool subscriptionAgeReadiness = false
)
{
ArgumentNullException.ThrowIfNull(expectedServing);
expectedServing.Validate(requireEpochs: true);
ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence);
if (frame.CompactValues is not null)
return DecodeCompact(frame, handles, maxItems, maxBytes, expectedServing, maxElements);
return DecodeCompact(frame, handles, maxItems, maxBytes, expectedServing, maxElements, subscriptionAgeReadiness);
if (
frame.Values is null
|| maxItems <= 0
@@ -627,7 +645,9 @@ public static class DataProtoMapper
throw new ArgumentException("Unknown or stale handle.");
if (DecodeServing(item.Sample.Serving) != expectedServing)
throw new ArgumentException("Unexpected serving identity.");
items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes)));
var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness,
item.HasOriginAgeTicks, item.OriginAgeTicks, item.HasReadiness, item.Readiness);
items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes), ageBounds, readiness));
}
return new(
frame.SubscriptionId,
@@ -645,6 +665,23 @@ public static class DataProtoMapper
}
}
private static void ValidateSubscriptionAgeReadiness(DataSubscriptionValue item)
{
item.AgeBounds.Validate();
DataContractValidation.Required(item.Readiness);
}
private static (DataAgeBounds AgeBounds, DataReadiness Readiness) DecodeSubscriptionAgeReadiness(
bool enabled, bool hasAge, long ageTicks, bool hasReadiness, int readinessValue)
{
if (!enabled) return (default, DataReadiness.Unspecified);
if (!hasReadiness) throw new ArgumentException("Missing negotiated readiness.");
var readiness = (DataReadiness)readinessValue;
DataContractValidation.Required(readiness);
if (hasAge && ageTicks < 0) throw new ArgumentException("Invalid origin-cache age.");
return (new DataAgeBounds(hasAge ? TimeSpan.FromTicks(ageTicks) : null, null), readiness);
}
public static W.ReadRequest EncodeReadRequest(ReadRequest x)
{
var v = new W.ReadRequest { Budget = EncodeBudget(x.Budget) };
@@ -846,8 +883,12 @@ public static class DataProtoMapper
Status = (int)x.Status,
Readiness = (int)x.Readiness,
};
x.AgeBounds.Validate();
if (x.Age is { } age)
{
if (age < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(x));
v.AgeTicks = age.Ticks;
}
if (x.Sample is not null)
v.Sample = EncodeSample(x.Sample);
if (x.Diagnostic is not null)
@@ -855,23 +896,31 @@ public static class DataProtoMapper
return v;
}
public static ReadResult DecodeReadResult(W.ReadResult x, DataDecodeLimits? limits = null)
public static ReadResult DecodeReadResult(W.ReadResult x, DataDecodeLimits? limits = null,
TimeSpan? causalRequestElapsed = null)
{
if (causalRequestElapsed < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(causalRequestElapsed));
limits ??= new DataDecodeLimits();
Preflight(x, 1, limits, x.Sample is null ? null : new[] { x.Sample.Value });
var status = (DataItemStatus)x.Status;
var readiness = (DataReadiness)x.Readiness;
DataContractValidation.Required(status);
DataContractValidation.Required(readiness);
if (x.HasAgeTicks && x.AgeTicks < 0) throw new ArgumentException("Invalid origin-cache age.");
var bounds = x.HasAgeTicks
? new DataAgeBounds(TimeSpan.FromTicks(x.AgeTicks), causalRequestElapsed is { } elapsed
? TimeSpan.FromTicks(checked(x.AgeTicks + elapsed.Ticks)) : null)
: default;
return new(
x.CorrelationId,
status,
readiness,
x.HasAgeTicks ? TimeSpan.FromTicks(x.AgeTicks) : null,
null,
x.Sample is null
? null
: DecodeSample(x.Sample, limits.MaxValueElements, limits.MaxBytes),
x.HasDiagnostic ? x.Diagnostic : null
x.HasDiagnostic ? x.Diagnostic : null,
AgeBounds: bounds
);
}
@@ -935,6 +984,7 @@ public static class DataProtoMapper
Operations = (uint)x.Operations,
CompactBatches = x.CompactBatches,
CompactCodecVersion = x.CompactCodecVersion,
SubscriptionAgeReadiness = x.SubscriptionAgeReadiness,
Limits = new W.Limits
{
MaxPageItems = l.MaxPageItems,
@@ -998,7 +1048,8 @@ public static class DataProtoMapper
),
x.CompactBatches,
x.CompactCodecVersion,
x.ClusterId
x.ClusterId,
x.SubscriptionAgeReadiness
);
result.Validate();
return result;
@@ -1164,7 +1215,8 @@ public static class DataProtoMapper
public static IReadOnlyList<ReadResult> DecodeReadResponse(
W.ReadResponse response,
DataDecodeLimits? limits = null
DataDecodeLimits? limits = null,
TimeSpan? causalRequestElapsed = null
)
{
limits ??= new DataDecodeLimits();
@@ -1178,7 +1230,7 @@ public static class DataProtoMapper
try
{
foreach (var item in response.Items)
result.Add(DecodeReadResult(item, limits));
result.Add(DecodeReadResult(item, limits, causalRequestElapsed));
return result;
}
catch
@@ -6,7 +6,7 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.Protos;
public static class DataConnectionProtoContract
{
public const int ProtocolMajor = 1;
public const int ProtocolMinor = 0;
public const int ProtocolMinor = 1;
public const int CompactCodecVersion = 1;
public static void Validate()
@@ -110,6 +110,7 @@ message CapabilitiesResponse {
bool compact_batches = 8;
int32 compact_codec_version = 9;
string cluster_id = 10;
bool subscription_age_readiness = 11;
}
message Metadata {
View view = 1;
@@ -256,6 +257,9 @@ message Control {
message ValueUpdate {
Handle handle = 1;
Sample sample = 2;
// Age since normalized origin-cache ingress, not sensor measurement age.
optional int64 origin_age_ticks = 3;
optional int32 readiness = 4;
}
message Values {
bool is_snapshot = 1;
@@ -271,6 +275,9 @@ message CompactUpdate {
optional uint32 status_code = 5;
TimestampOverride source_timestamp = 6;
TimestampOverride server_timestamp = 7;
// Age since normalized origin-cache ingress, not sensor measurement age.
optional int64 origin_age_ticks = 8;
optional int32 readiness = 9;
}
message CompactValues {
bool is_snapshot = 1;
@@ -2,6 +2,44 @@ using System.Security.Cryptography;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
/// <summary>
/// Bounds on age since normalized ingress into the origin cache, not sensor measurement age.
/// A null endpoint is unknown. An upper bound alone certifies freshness; a lower bound alone
/// can prove staleness. Original wall-clock timestamps are independent of these bounds.
/// </summary>
public readonly record struct DataAgeBounds(TimeSpan? Lower, TimeSpan? Upper)
{
public void Validate()
{
if (Lower < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Lower));
if (Upper < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Upper));
if (Lower is { } lower && Upper is { } upper && upper < lower)
throw new ArgumentException("Upper age bound must not precede lower bound.");
}
public DataAgeBounds Advance(TimeSpan elapsed)
{
Validate();
if (elapsed < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(elapsed));
return new(Lower is { } lower ? TimeSpan.FromTicks(checked(lower.Ticks + elapsed.Ticks)) : null,
Upper is { } upper ? TimeSpan.FromTicks(checked(upper.Ticks + elapsed.Ticks)) : null);
}
public bool IsFresh(TimeSpan maximumAge)
{
Validate();
if (maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maximumAge));
return Upper is { } upper && upper <= maximumAge;
}
public bool IsStale(TimeSpan maximumAge)
{
Validate();
if (maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maximumAge));
return Lower is { } lower && lower > maximumAge;
}
}
public enum DataValueKind { Unspecified = 0, Null = 1, Boolean = 2, Int8 = 3, Int16 = 4, Int32 = 5, Int64 = 6, UInt8 = 7, UInt16 = 8, UInt32 = 9, UInt64 = 10, Float = 11, Double = 12, String = 13, Bytes = 14, Timestamp = 15, Guid = 16, Array = 17 }
public enum DataItemStatus { Unspecified = 0, Good = 1, Denied = 2, NotFound = 3, Unsupported = 4, InvalidArgument = 5, Unavailable = 6, WaitingForInitialData = 7, Stale = 8, LimitExceeded = 9, InvalidContinuation = 10, TypeMismatch = 11, ResourceExhausted = 12 }
public enum DataReadiness { Unspecified = 0, Ready = 1, WaitingForInitialData = 2, Unavailable = 3, Invalidated = 4 }
@@ -92,6 +130,26 @@ public sealed class DataValue : IDisposable
public DataValueKind ArrayElementKind { get { ThrowIfDisposed(); return (_payload as ArrayPayload)?.Kind ?? throw new InvalidOperationException(); } }
public IReadOnlyList<object> GetArray() { ThrowIfDisposed(); return _payload is ArrayPayload a ? Array.AsReadOnly((object[])a.Elements.Clone()) : throw new InvalidOperationException(); }
public DataValue Retain() { ThrowIfDisposed(); return new(Kind, _payload, Dimensions); }
/// <summary>Compares immutable owned values without exposing or duplicating their storage.</summary>
internal bool ContentEquals(DataValue other)
{
ArgumentNullException.ThrowIfNull(other);
ThrowIfDisposed(); other.ThrowIfDisposed();
if (Kind != other.Kind) return false;
if (ReferenceEquals(_payload, other._payload)) return true;
if (Kind == DataValueKind.Null) return true;
if (_payload is byte[] bytes && other._payload is byte[] otherBytes)
return bytes.AsSpan().SequenceEqual(otherBytes);
if (_payload is ArrayPayload array && other._payload is ArrayPayload otherArray)
{
if (array.Kind != otherArray.Kind || Dimensions is null || other.Dimensions is null ||
Dimensions.Count != other.Dimensions.Count || array.Elements.Length != otherArray.Elements.Length) return false;
for (var i = 0; i < Dimensions.Count; i++) if (Dimensions[i] != other.Dimensions[i]) return false;
for (var i = 0; i < array.Elements.Length; i++) if (!Equals(array.Elements[i], otherArray.Elements[i])) return false;
return true;
}
return Equals(_payload, other._payload);
}
/// <summary>Appends a private canonical value encoding without exposing or copying owned payload storage.</summary>
internal void AppendSemanticFingerprint(IncrementalHash hash)
{
@@ -188,7 +246,7 @@ public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMess
}
public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness,
DataOperations Operations, IReadOnlySet<DataValueKind> ValueKinds, DataLimits Limits, bool CompactBatches,
int CompactCodecVersion, string ClusterId)
int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false)
{
public void Validate()
{
@@ -12,7 +12,8 @@ public sealed record ReadItem(string CorrelationId, DataView View, TimeSpan? Max
public sealed record ReadRequest(IReadOnlyList<ReadItem> Items, DataBudget Budget);
/// <summary>Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality.</summary>
public sealed record ReadResult(string CorrelationId, DataItemStatus Status, DataReadiness Readiness,
TimeSpan? Age, DataSample? Sample, string? Diagnostic, IDisposable? ResourceLease = null) : IDisposable
TimeSpan? Age, DataSample? Sample, string? Diagnostic, IDisposable? ResourceLease = null,
DataAgeBounds AgeBounds = default) : IDisposable
{
public void Dispose()
{
@@ -105,11 +106,24 @@ public sealed record DataSubscriptionControl(string SubscriptionId, long StreamE
: DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence);
/// <summary>Each frame owns its samples until disposed, including during asynchronous encoding.</summary>
public sealed record DataSubscriptionValues(string SubscriptionId, long StreamEpoch, long Sequence, bool IsSnapshot,
IReadOnlyList<DataSubscriptionValue> Items) : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence), IDisposable
IReadOnlyList<DataSubscriptionValue> Items, IDisposable? ResourceLease = null)
: DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence), IDisposable
{
public void Dispose() { foreach (var item in Items) item.Sample.Dispose(); }
private int _disposed;
// A record clone would alias independently disposable samples and resource ownership.
private DataSubscriptionValues(DataSubscriptionValues original) : base(original) =>
throw new InvalidOperationException("Owned subscription frames cannot be copied.");
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
try { foreach (var item in Items) item.Sample.Dispose(); }
finally { ResourceLease?.Dispose(); }
}
}
public sealed record DataSubscriptionValue(DataItemHandle Handle, DataSample Sample);
/// <summary>Age bounds describe normalized origin-cache ingress age, independent of wall timestamps.</summary>
public sealed record DataSubscriptionValue(DataItemHandle Handle, DataSample Sample,
DataAgeBounds AgeBounds = default, DataReadiness Readiness = DataReadiness.Unspecified);
/// <summary>Commands and frames are ordered per stream. Dispose cancels the stream and releases demand.</summary>
public interface IDataSubscription : IAsyncDisposable
@@ -117,6 +131,27 @@ public interface IDataSubscription : IAsyncDisposable
Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken);
IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken);
}
/// <summary>One lifetime-scoped delivery mode, separate from direct enumeration.</summary>
public interface IDataSubscriptionTransport : IDataSubscription
{
Task RunDeliveryAsync(IDataSubscriptionDeliverySink sink, CancellationToken cancellationToken);
}
/// <summary>Transport-owned preparation and actual acceptance boundary for a serialized stream.</summary>
public interface IDataSubscriptionDeliverySink
{
/// <summary>Prepare without emitting. Allocations must stay within the already reserved byte budget.</summary>
ValueTask<IDataPreparedSubscriptionDelivery> PrepareAsync(DataSubscriptionFrame frame, long reservedBytes, CancellationToken cancellationToken);
/// <summary>Complete only when the transport accepts the prepared delivery.</summary>
ValueTask WriteAsync(IDataPreparedSubscriptionDelivery prepared, CancellationToken cancellationToken);
}
/// <summary>Prepared transport-owned bytes retained through completion of the underlying operation.</summary>
public interface IDataPreparedSubscriptionDelivery : IDisposable
{
long RetainedBytes { get; }
}
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
public interface IDataSubscriptionService
{
@@ -0,0 +1,30 @@
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// <summary>
/// Optional physical acquisition capability. Successful establishment acknowledges the current
/// revision and supported nominal cadence; it does not guarantee actual device timing.
/// Unsupported drivers must not claim this capability.
/// </summary>
public interface IAcknowledgedAcquisitionSource
{
/// <summary>
/// Installs the complete reference set and callback. The callback may run before this task
/// completes. It delivers fresh acquisition results, not replayed cache values. The caller
/// must fence revisions and synchronously copy mutable values into bounded owned storage
/// before returning; the producer retains ownership until then. Failed or superseded
/// establishment must release any returned physical subscription handle.
/// </summary>
Task<AcquisitionSubscriptionResult> SubscribeAcquisitionAsync(AcquisitionSubscriptionRequest request,
Action<AcquisitionBatch> onAcquired, CancellationToken cancellationToken);
}
/// <summary>Complete physical interest and revision fence for one producer incarnation.</summary>
public sealed record AcquisitionSubscriptionRequest(IReadOnlyList<string> FullReferences,
TimeSpan RequestedSamplingInterval, long DesiredRevision, long ProducerIncarnation);
/// <summary>The installed physical handle, supported nominal cadence, and acknowledged fence.</summary>
public sealed record AcquisitionSubscriptionResult(ISubscriptionHandle Handle, TimeSpan NominalSamplingInterval,
long DesiredRevision, long ProducerIncarnation);
/// <summary>Fresh device acquisition results under a specific desired revision and producer incarnation.</summary>
public sealed record AcquisitionBatch(long DesiredRevision, long ProducerIncarnation, IReadOnlyList<DataChangeItem> Items);
@@ -105,7 +105,7 @@ public sealed class PollGroupEngine : IAsyncDisposable
/// own elapsed time is NOT subtracted, so the failure branch is a fixed DELAY (cycle =
/// poll + backoff), deliberately unlike the fixed-rate success branch.</para>
/// <para>The <c>interval</c> feeding that schedule is the per-subscription interval
/// <i>already clamped</i> to <paramref name="minInterval"/> in <see cref="Subscribe"/>, so
/// <i>already clamped</i> to <paramref name="minInterval"/> in <see cref="Subscribe(IReadOnlyList{string}, TimeSpan)"/>, so
/// the first failure's wait equals the clamped interval (shift 0 → 1×) and the floor is
/// honoured for free. One asymmetry worth knowing: <c>ComputeDelay</c> saturates at the cap
/// unconditionally, so a <paramref name="backoffCap"/> set SMALLER than the clamped
@@ -154,20 +154,39 @@ public sealed class PollGroupEngine : IAsyncDisposable
/// <param name="publishingInterval">The desired polling interval; will be clamped to the configured minimum.</param>
/// <returns>A handle identifying the new subscription, for later use with <see cref="Unsubscribe"/>.</returns>
public ISubscriptionHandle Subscribe(IReadOnlyList<string> fullReferences, TimeSpan publishingInterval)
=> SubscribeCore(fullReferences, publishingInterval, null);
/// <summary>Starts a subscription with a synchronous callback for each completed physical read.</summary>
/// <remarks>The callback must copy mutable data before returning and must not mutate producer-owned
/// data. Teardown uses the engine's bounded drain; consumers must fence late callbacks when a
/// reader ignores cancellation or a callback blocks beyond that bound.</remarks>
/// <param name="fullReferences">The list of tag references to poll.</param>
/// <param name="publishingInterval">The desired polling interval, clamped to the configured minimum.</param>
/// <param name="onAcquired">Receives every result in reader order before change filtering. Values are borrowed until the callback returns.</param>
/// <returns>A handle identifying the subscription.</returns>
public ISubscriptionHandle Subscribe(IReadOnlyList<string> fullReferences, TimeSpan publishingInterval,
Action<IReadOnlyList<DataChangeItem>> onAcquired)
{
ArgumentNullException.ThrowIfNull(onAcquired);
return SubscribeCore(fullReferences, publishingInterval, onAcquired);
}
private ISubscriptionHandle SubscribeCore(IReadOnlyList<string> fullReferences, TimeSpan publishingInterval,
Action<IReadOnlyList<DataChangeItem>>? onAcquired)
{
ArgumentNullException.ThrowIfNull(fullReferences);
var id = Interlocked.Increment(ref _nextId);
var cts = new CancellationTokenSource();
var interval = publishingInterval < _minInterval ? _minInterval : publishingInterval;
var handle = new PollSubscriptionHandle(id);
var state = new SubscriptionState(handle, [.. fullReferences], interval, cts);
var state = new SubscriptionState(handle, [.. fullReferences], interval, cts, onAcquired);
_subscriptions[id] = state;
state.LoopTask = Task.Run(() => PollLoopAsync(state, cts.Token));
return handle;
}
/// <summary>
/// Cancel the background loop for a handle returned by <see cref="Subscribe"/>, BLOCKING the
/// Cancel the background loop for a handle returned by <see cref="Subscribe(IReadOnlyList{string}, TimeSpan)"/>, BLOCKING the
/// calling thread until the in-flight poll drains. Retained for compatibility; prefer
/// <see cref="UnsubscribeAsync"/> on any path that runs inside an actor mailbox turn or a
/// request pipeline, where blocking a thread for up to 5 s is never acceptable.
@@ -183,8 +202,9 @@ public sealed class PollGroupEngine : IAsyncDisposable
/// <summary>
/// Non-blocking counterpart of <see cref="Unsubscribe"/>: identical teardown semantics (the
/// loop is cancelled and awaited before the CTS is disposed, so no callback can fire after
/// this completes) but it awaits the loop task instead of blocking a thread on it.
/// loop is cancelled and awaited up to the drain timeout before the CTS is disposed) but it
/// awaits the loop task instead of blocking a thread on it. A reader or callback that does
/// not finish within that bound can outlive this call, so consumers must fence late callbacks.
/// </summary>
/// <param name="handle">The subscription handle to cancel.</param>
/// <returns><c>true</c> when the handle was known to the engine and has been torn down.</returns>
@@ -391,6 +411,19 @@ public sealed class PollGroupEngine : IAsyncDisposable
$"Reader contract violation: expected {state.TagReferences.Count} snapshots but received {snapshots.Count}. " +
"The reader delegate must return one snapshot per input reference in input order.");
// Do not publish a read that completed after teardown was requested. The callback is
// installed in the state before the loop starts and runs inline, while reader values are
// still owned by the producer. A broken consumer must not suppress legacy changes.
ct.ThrowIfCancellationRequested();
if (state.OnAcquired is not null)
{
var acquired = new DataChangeItem[state.TagReferences.Count];
for (var i = 0; i < acquired.Length; i++)
acquired[i] = new DataChangeItem(state.TagReferences[i], snapshots[i]);
try { state.OnAcquired(acquired); }
catch (Exception ex) when (!IsFatal(ex)) { ReportError(ex); }
}
// Collected lazily: nothing is allocated for a cycle with no changes, and nothing at all
// when no batch callback is wired.
List<DataChangeItem>? changed = null;
@@ -461,7 +494,8 @@ public sealed class PollGroupEngine : IAsyncDisposable
PollSubscriptionHandle Handle,
IReadOnlyList<string> TagReferences,
TimeSpan Interval,
CancellationTokenSource Cts)
CancellationTokenSource Cts,
Action<IReadOnlyList<DataChangeItem>>? OnAcquired)
{
/// <summary>Gets the cache of last-seen values per tag reference.</summary>
public ConcurrentDictionary<string, DataValueSnapshot> LastValues { get; }
@@ -469,7 +503,7 @@ public sealed class PollGroupEngine : IAsyncDisposable
/// <summary>
/// The background poll-loop task. Assigned immediately after creation in
/// <see cref="Subscribe"/>; awaited during <see cref="Unsubscribe"/> /
/// <see cref="Subscribe(IReadOnlyList{string}, TimeSpan)"/>; awaited during <see cref="Unsubscribe"/> /
/// <see cref="DisposeAsync"/> so disposal is deterministic and no
/// <c>_onChange</c> callback can fire after the caller tears down the subscription.
/// </summary>