fix(abcip): #983 packed structure reads, non-blocking lease release, allocation trims, docs (P-24)
Structure reads of a known size pack into one MSP; browse/template lease release no longer blocks a thread-pool thread up to 2 s; scheduler packs with running totals; CipReply empty extended-status array shared. AbCip.md documents P-2/P-13/P-16/P-22/P-23/P-24.
This commit is contained in:
@@ -39,7 +39,7 @@ public sealed record CipReply(byte Service, byte GeneralStatus, ushort[] Extende
|
||||
r.U8(); // reserved
|
||||
var general = r.U8();
|
||||
var extWords = r.U8();
|
||||
var ext = new ushort[extWords];
|
||||
var ext = extWords == 0 ? [] : new ushort[extWords];
|
||||
for (var i = 0; i < extWords; i++) ext[i] = r.U16();
|
||||
var data = raw[r.Position..];
|
||||
return new CipReply(service, general, ext, data);
|
||||
|
||||
@@ -19,6 +19,13 @@ public static class MultipleServicePacket
|
||||
return w.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Exact byte size of an MSP carrying <paramref name="count"/> requests totalling <paramref name="totalRequestBytes"/>:
|
||||
/// the running-total form of <see cref="BuildSize(IReadOnlyList{int})"/>, so a packer need not keep a list.</summary>
|
||||
/// <param name="count">The number of embedded requests.</param>
|
||||
/// <param name="totalRequestBytes">The summed byte size of the embedded requests.</param>
|
||||
/// <returns>The total packet size in bytes.</returns>
|
||||
public static int BuildSize(int count, int totalRequestBytes) => HeaderSize + 2 + 2 * count + totalRequestBytes;
|
||||
|
||||
/// <summary>Exact byte size of an MSP carrying requests of the given sizes.</summary>
|
||||
/// <param name="requestSizes">The byte size of each embedded request.</param>
|
||||
/// <returns>The total packet size in bytes.</returns>
|
||||
|
||||
@@ -207,29 +207,28 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var sizes = new List<int>();
|
||||
var replySizes = new List<int>();
|
||||
var replyBudget = _channel.MaxRequestBytes; // connections are symmetric: one size bounds both directions
|
||||
// Running totals, not lists: the packer used to rebuild two Lists per pump pass and re-sum them for every
|
||||
// candidate (quadratic under the queue lock, P-24).
|
||||
var requestBytes = 0;
|
||||
var replyBytes = 0;
|
||||
var maxRequestBytes = _channel.MaxRequestBytes;
|
||||
var replyBudget = maxRequestBytes; // connections are symmetric: one size bounds both directions
|
||||
while (_queue.First is { } n)
|
||||
{
|
||||
if (batch.Count > 0)
|
||||
{
|
||||
if (!_allowPacking || n.Value.Exclusive) break;
|
||||
sizes.Add(n.Value.Request.Length);
|
||||
replySizes.Add(n.Value.ExpectedReplyBytes);
|
||||
if (MultipleServicePacket.BuildSize(sizes) > _channel.MaxRequestBytes
|
||||
|| ReplyEnvelopeSize(replySizes) > replyBudget)
|
||||
var count = batch.Count + 1;
|
||||
if (MultipleServicePacket.BuildSize(count, requestBytes + n.Value.Request.Length) > maxRequestBytes
|
||||
|| ReplyEnvelopeSize(count, replyBytes + n.Value.ExpectedReplyBytes) > replyBudget)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// The first request always goes, even when it alone exceeds the limit: it is sent
|
||||
// bare, and callers that must fit (LogixTagClient) fragment before they get here.
|
||||
sizes.Add(n.Value.Request.Length);
|
||||
replySizes.Add(n.Value.ExpectedReplyBytes);
|
||||
}
|
||||
// The first request always goes, even when it alone exceeds the limit: it is sent
|
||||
// bare, and callers that must fit (LogixTagClient) fragment before they get here.
|
||||
requestBytes += n.Value.Request.Length;
|
||||
replyBytes += n.Value.ExpectedReplyBytes;
|
||||
batch.Add(n.Value);
|
||||
_queue.RemoveFirst();
|
||||
if (n.Value.Exclusive) break;
|
||||
@@ -248,6 +247,13 @@ public sealed class RequestScheduler : IAsyncDisposable
|
||||
return total;
|
||||
}
|
||||
|
||||
/// <summary>Running-total form of <see cref="ReplyEnvelopeSize(IReadOnlyList{int})"/>.</summary>
|
||||
/// <param name="count">The number of embedded replies.</param>
|
||||
/// <param name="totalReplyBytes">The summed expected size of the embedded replies.</param>
|
||||
/// <returns>The total size of the MSP reply in bytes.</returns>
|
||||
internal static int ReplyEnvelopeSize(int count, int totalReplyBytes) =>
|
||||
ReplyHeaderBytes + 2 + 2 * count + totalReplyBytes;
|
||||
|
||||
private async Task PumpAsync()
|
||||
{
|
||||
while (true)
|
||||
|
||||
@@ -158,18 +158,28 @@ internal sealed class NativeAbCipTagEnumeratorFactory : IAbCipTagEnumeratorFacto
|
||||
/// <summary>Bounded lease release shared by the native enumerator and template reader.</summary>
|
||||
internal static class NativeLease
|
||||
{
|
||||
/// <summary>Upper bound on waiting for the lease release (and its Forward Close).</summary>
|
||||
private static readonly TimeSpan DisposeWait = TimeSpan.FromSeconds(2);
|
||||
|
||||
/// <summary>Releases, waiting at most 2 s; never throws, whatever the release delegate does.</summary>
|
||||
/// <summary>
|
||||
/// Starts the lease release and returns WITHOUT waiting for its Forward Close; never throws, whatever the
|
||||
/// release delegate does (P-24: this used to block a thread-pool thread for up to 2 s per browse / template
|
||||
/// read, from an async iterator's <c>finally</c>). Nothing is lost by not waiting: the pool's release does its
|
||||
/// bookkeeping synchronously (ref-count drop, closing-chain registration) before its first await, so an
|
||||
/// acquire made the next instant still opens only after this close — the same guarantee
|
||||
/// <see cref="ConnectionLease.ReleaseInBackground"/> gives the tag runtimes.
|
||||
/// </summary>
|
||||
/// <param name="release">The delegate that releases the lease.</param>
|
||||
/// <param name="logger">The logger used to report a failed release.</param>
|
||||
public static void ReleaseBounded(Func<ValueTask> release, ILogger logger)
|
||||
{
|
||||
try { release().AsTask().Wait(DisposeWait); }
|
||||
Task teardown;
|
||||
try { teardown = release().AsTask(); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Releasing the native AbCip device lease failed.");
|
||||
return;
|
||||
}
|
||||
_ = teardown.ContinueWith(
|
||||
t => logger.LogWarning(t.Exception, "Releasing the native AbCip device lease failed."),
|
||||
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
|
||||
TaskScheduler.Default);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,7 +207,7 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
|
||||
var path = Path();
|
||||
try
|
||||
{
|
||||
var (type, handle, data) = await client.ReadAsync(path, _wireElements, cancellationToken, ExpectedElementBytes(_p.AuthoredType)).ConfigureAwait(false);
|
||||
var (type, handle, data) = await client.ReadAsync(path, _wireElements, cancellationToken, ReplyBytesPerElementHint()).ConfigureAwait(false);
|
||||
if (_isBoolArray && SettleWholeBoolArrayCount(type))
|
||||
{
|
||||
// The reply showed the OTHER layout than the one this read was sized for: discard it and ask again
|
||||
@@ -256,6 +256,21 @@ internal sealed class NativeAbCipTagRuntime : IAbCipTagRuntime
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reply bytes per element the scheduler budgets this read at. A scalar's width is static; a Structure (or an
|
||||
/// unknown authored type, e.g. the probe) has none, which used to send EVERY such read alone — N UDT parents cost
|
||||
/// N round trips per poll instead of ~N/20 (P-24). Once one read has returned, its size is the hint. An
|
||||
/// under-estimate (the UDT grew in an online edit) is safe: the controller answers Partial and the client's
|
||||
/// fragment loop completes the read.
|
||||
/// </summary>
|
||||
/// <returns>Bytes per element, or 0 when nothing is known (the read is then sent alone).</returns>
|
||||
private int ReplyBytesPerElementHint()
|
||||
{
|
||||
var known = ExpectedElementBytes(_p.AuthoredType);
|
||||
if (known > 0 || _data.Length == 0) return known;
|
||||
return (_data.Length + _wireElements - 1) / _wireElements;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-sizes a whole BOOL-array read to the layout the reply TYPE showed: 0xD3 means packed DWORDs (count =
|
||||
/// ceil(n / 32)), 0xC1 means one byte per element (count = n, e.g. ab_server). Any other type is no evidence.
|
||||
|
||||
Reference in New Issue
Block a user