Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessValueCache.cs
T
Joseph Doherty f61c816acf perf(worker): event hot-path allocation + flush cuts (WRK-06/11/12, IPC-15)
WRK-06: MxStatusProxyConverter caches the four resolved FieldInfo per status
type in a static ConcurrentDictionary (the GetField metadata scan ran 4x per
status per event on the STA path). GetValue+Convert.ToInt32 still run per event
(late-bound RCW). Exceptions byte-identical: missing-field message unchanged
(ResolveField, not cached on throw via GetOrAdd); null-value message unchanged.

WRK-11: MxAccessEventQueue.Enqueue takes ownership of the passed MxEvent -
stamps WorkerSequence/WorkerTimestamp on it in place and enqueues it, no
Clone(). Audited all 3 callers (base/alarm event sinks, provider-mode handler):
each builds a fresh event per Enqueue, none reuse it. MxAccessValueCache.Set now
deep-copies its retained Value/SourceTimestamp/Statuses so the cache snapshot
never aliases the queue-owned (later serialized) event. Net: alarm/other events
clone nothing (was full clone); data-change clones payload-only.

WRK-12: WorkerFrameWriter coalesces the flush across a drained batch - each
frame is written but not flushed individually; one FlushAsync after the batch,
then all written frames complete. Preserves the written+flushed completion
contract; a burst of N events costs 1 flush, not N. On write failure the whole
in-flight batch + queue fail so no caller hangs.

IPC-15 (doc): the multi-event WorkerEnvelope body remains unimplemented (wire
still carries one event per worker_event frame); gateway.md Performance section
now distinguishes the shipped flush-coalescing from that deferred proto change.

net48-safe (no init/records; readonly struct cache entry). Worker builds x86
only - verification on windev. Tests added: converter cache-reuse, queue
ownership-transfer, value-cache snapshot independence, writer batch-flush-once.

Claude-Session: https://claude.ai/code/session_01DMXXvNuPekkkrTEyPNxEkW
2026-07-09 15:59:45 -04:00

221 lines
8.7 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Worker.MxAccess;
/// <summary>
/// Per-session cache of the most recent <c>OnDataChange</c> payload for
/// each (server handle, item handle) pair. Written by the MXAccess event
/// sink as new OnDataChange callbacks arrive; read by the ReadBulk command
/// executor so it can satisfy a "current value" request from a tag that is
/// already advised without modifying the existing subscription.
/// </summary>
/// <remarks>
/// Both writers and readers run on the worker's STA thread (COM dispatches
/// events on the apartment thread; commands also execute on the STA), so
/// no internal locking is required. The class is still nominally
/// thread-safe via a single sync root in case tests drive it from a
/// non-STA thread.
/// </remarks>
public sealed class MxAccessValueCache
{
private readonly Dictionary<long, CachedValue> entries = new();
private readonly object syncRoot = new();
/// <summary>Records a fresh OnDataChange payload for the given handle pair.</summary>
/// <param name="serverHandle">MXAccess server handle.</param>
/// <param name="itemHandle">MXAccess item handle.</param>
/// <param name="mxEvent">The protobuf MxEvent created by the event mapper.</param>
public void Set(
int serverHandle,
int itemHandle,
MxEvent mxEvent)
{
if (mxEvent is null)
{
throw new ArgumentNullException(nameof(mxEvent));
}
// WRK-11: the event sink no longer clones before enqueue, so the passed
// mxEvent is the very instance handed to the outbound queue. Deep-copy
// the value/timestamp/statuses payload we retain here so the cache's
// snapshot stays independent of the enqueued (and later serialized)
// event — the two must never share mutable protobuf sub-messages.
// Value is always set for OnDataChange; SourceTimestamp may be unset when
// the source timestamp could not be parsed, so both are cloned only when
// present. The null-forgiving result matches CachedValue's non-null-
// annotated parameters, which already accepted a runtime-null value or
// timestamp before WRK-11 (the ternary keeps the compiler's null-state
// from poisoning to maybe-null, which a plain null check would do).
MxValue cachedValue = mxEvent.Value is null ? null! : mxEvent.Value.Clone();
Timestamp cachedTimestamp = mxEvent.SourceTimestamp is null ? null! : mxEvent.SourceTimestamp.Clone();
long key = CreateItemKey(serverHandle, itemHandle);
lock (syncRoot)
{
ulong nextVersion = entries.TryGetValue(key, out CachedValue existing)
? existing.Version + 1
: 1UL;
entries[key] = new CachedValue(
nextVersion,
cachedValue,
mxEvent.Quality,
cachedTimestamp,
mxEvent.Statuses.Clone());
}
}
/// <summary>Tries to read the most recent cached value for the handle pair.</summary>
/// <param name="serverHandle">MXAccess server handle.</param>
/// <param name="itemHandle">MXAccess item handle.</param>
/// <param name="value">The cached value if found.</param>
/// <returns><see langword="true"/> if a cached value exists for the handle pair; otherwise <see langword="false"/>.</returns>
public bool TryGet(
int serverHandle,
int itemHandle,
out CachedValue value)
{
long key = CreateItemKey(serverHandle, itemHandle);
lock (syncRoot)
{
return entries.TryGetValue(key, out value);
}
}
/// <summary>
/// Removes the cache slot for a handle pair. The session calls this
/// when an item is unregistered so stale values are not served to a
/// subsequent ReadBulk after a tag is removed and re-added.
/// </summary>
/// <param name="serverHandle">MXAccess server handle.</param>
/// <param name="itemHandle">MXAccess item handle.</param>
public void Remove(
int serverHandle,
int itemHandle)
{
long key = CreateItemKey(serverHandle, itemHandle);
lock (syncRoot)
{
entries.Remove(key);
}
}
/// <summary>
/// Waits until the cache entry's version exceeds <paramref name="sinceVersion"/>
/// or the deadline elapses, calling <paramref name="pumpStep"/> on every poll
/// iteration so the worker's STA can dispatch the inbound MXAccess message.
/// </summary>
/// <param name="serverHandle">MXAccess server handle.</param>
/// <param name="itemHandle">MXAccess item handle.</param>
/// <param name="sinceVersion">Version snapshot captured before the wait.</param>
/// <param name="deadlineUtc">Absolute UTC deadline.</param>
/// <param name="pumpStep">Action that pumps any pending Windows messages.</param>
/// <param name="value">The cached value if the update was received before the deadline.</param>
/// <param name="pollIntervalMs">How long to sleep between pump cycles. Default 5 ms.</param>
/// <returns><see langword="true"/> if an update newer than <paramref name="sinceVersion"/> arrived before the deadline; otherwise <see langword="false"/>.</returns>
public bool TryWaitForUpdate(
int serverHandle,
int itemHandle,
ulong sinceVersion,
DateTime deadlineUtc,
Action pumpStep,
out CachedValue value,
int pollIntervalMs = 5)
{
if (pumpStep is null)
{
throw new ArgumentNullException(nameof(pumpStep));
}
while (true)
{
pumpStep();
if (TryGet(serverHandle, itemHandle, out value) && value.Version > sinceVersion)
{
return true;
}
if (DateTime.UtcNow >= deadlineUtc)
{
return false;
}
Thread.Sleep(pollIntervalMs);
}
}
/// <summary>Returns the current version for a handle pair, or 0 if no entry exists.</summary>
/// <param name="serverHandle">MXAccess server handle.</param>
/// <param name="itemHandle">MXAccess item handle.</param>
/// <returns>The current cache entry version, or 0 if no entry exists.</returns>
public ulong CurrentVersion(
int serverHandle,
int itemHandle)
{
return TryGet(serverHandle, itemHandle, out CachedValue existing)
? existing.Version
: 0UL;
}
private static long CreateItemKey(
int serverHandle,
int itemHandle)
{
return ((long)serverHandle << 32) | (uint)itemHandle;
}
/// <summary>
/// Snapshot of the most recent OnDataChange payload for a handle pair.
/// <see cref="Version"/> increments by one on every <see cref="Set"/>
/// call so the bulk read executor can detect "a new value arrived
/// since I started waiting".
/// </summary>
/// <remarks>
/// Plain readonly struct (not a record) so this compiles under the
/// worker's net48 target, which lacks <c>IsExternalInit</c>.
/// </remarks>
public readonly struct CachedValue
{
/// <summary>Initializes a new cached value snapshot.</summary>
/// <param name="version">Version counter incremented on each update.</param>
/// <param name="value">The MXAccess value.</param>
/// <param name="quality">The MXAccess quality code.</param>
/// <param name="sourceTimestamp">The source timestamp of the value.</param>
/// <param name="statuses">The MXAccess status codes.</param>
public CachedValue(
ulong version,
MxValue value,
int quality,
Timestamp sourceTimestamp,
RepeatedField<MxStatusProxy> statuses)
{
Version = version;
Value = value;
Quality = quality;
SourceTimestamp = sourceTimestamp;
Statuses = statuses;
}
/// <summary>Monotonic per-handle version counter.</summary>
public ulong Version { get; }
/// <summary>The cached MxValue payload.</summary>
public MxValue Value { get; }
/// <summary>Quality code from the OnDataChange event.</summary>
public int Quality { get; }
/// <summary>Source timestamp from the OnDataChange event.</summary>
public Timestamp SourceTimestamp { get; }
/// <summary>MxStatusProxy entries from the OnDataChange event.</summary>
public RepeatedField<MxStatusProxy> Statuses { get; }
}
}