Merge Sql/AbLegacy follow-ups: one shared Sql driver JSON options definition for driver + deploy gate (#1076), AbLegacy read-plan memoisation keyed on the exact reference list (#1073)
This commit is contained in:
@@ -109,21 +109,6 @@ public static class SqlTagDeployChecks
|
||||
/// <summary>Error code for a named query the Sql driver would refuse at construction (lmxopcua#1058).</summary>
|
||||
public const string NamedQueryInvalidCode = "SqlNamedQueryInvalid";
|
||||
|
||||
/// <summary>
|
||||
/// The driver factory's config reader options (<c>SqlDriverFactoryExtensions.JsonOptions</c>, which lives in the
|
||||
/// driver assembly this one does not reference): case-insensitive, comments + trailing commas tolerated, unknown
|
||||
/// members skipped, enums by name. Keep in step — a looser reader here could pass a blob the driver refuses.
|
||||
/// </summary>
|
||||
private static readonly JsonSerializerOptions SqlConfigJson = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true,
|
||||
UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Skip,
|
||||
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1058 (#974 follow-up). The driver checks every <c>queries</c> entry with
|
||||
/// <see cref="SqlNamedQueryRules.Describe"/> under its provider when it is constructed, and ONE refused query
|
||||
@@ -145,7 +130,7 @@ public static class SqlTagDeployChecks
|
||||
{
|
||||
var merged = DriverDeviceConfigMerger.Merge(
|
||||
driver.DriverConfig, devices.Select(d => new DriverDeviceConfigMerger.DeviceRow(d.Name, d.DeviceConfig)).ToList(), []);
|
||||
dto = JsonSerializer.Deserialize<SqlDriverConfigDto>(merged, SqlConfigJson);
|
||||
dto = JsonSerializer.Deserialize<SqlDriverConfigDto>(merged, SqlDriverConfigJson.Options);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
|
||||
@@ -101,7 +101,7 @@ public sealed partial class AbLegacyDriver
|
||||
/// Plans a device pass: coalescable tags grouped per file into runs of nearby elements (a run of two or more
|
||||
/// tags becomes a block), everything else a single unit. Block shapes the device refused before stay single.
|
||||
/// </summary>
|
||||
private List<ReadUnit> PlanReadUnits(DeviceState device, List<ReadItem> items)
|
||||
private List<ReadUnit> PlanReadUnits(DeviceState device, List<ReadItem> items, bool applyRefusals = true)
|
||||
{
|
||||
if (_options.CoalesceReads == false || items.Count < 2) return [.. items.Select(i => new ReadUnit(i, null))];
|
||||
|
||||
@@ -138,7 +138,7 @@ public sealed partial class AbLegacyDriver
|
||||
}
|
||||
var count = run[^1].Parsed.WordNumber - start + 1;
|
||||
var block = new CoalescedBlock(letter, file, start, count, type, run);
|
||||
if (run.Count < 2 || device.RefusedBlocks.ContainsKey(block.Key))
|
||||
if (run.Count < 2 || (applyRefusals && device.RefusedBlocks.ContainsKey(block.Key)))
|
||||
units.AddRange(run.Select(r => new ReadUnit(r, null)));
|
||||
else
|
||||
units.Add(new ReadUnit(null, block));
|
||||
@@ -148,6 +148,132 @@ public sealed partial class AbLegacyDriver
|
||||
return units;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the device's CURRENT refused-block memory to a cached plan (#1073). The cache holds the plan as if no
|
||||
/// block were refused, because the memory grows while the plan lives; a refused block becomes its members as singles
|
||||
/// in place — exactly what <see cref="PlanReadUnits"/> emits when it already knows the refusal.
|
||||
/// </summary>
|
||||
private static List<ReadUnit> ApplyRefusedBlocks(DeviceState device, List<ReadUnit> units)
|
||||
{
|
||||
if (device.RefusedBlocks.IsEmpty) return units;
|
||||
List<ReadUnit>? expanded = null;
|
||||
for (var i = 0; i < units.Count; i++)
|
||||
{
|
||||
if (units[i].Block is { } b && device.RefusedBlocks.ContainsKey(b.Key))
|
||||
{
|
||||
expanded ??= [.. units.Take(i)];
|
||||
expanded.AddRange(b.Members.Select(m => new ReadUnit(m, null)));
|
||||
}
|
||||
else expanded?.Add(units[i]);
|
||||
}
|
||||
return expanded ?? units;
|
||||
}
|
||||
|
||||
/// <summary>The planned, device-bucketed form of one read's reference list (#1073).</summary>
|
||||
private sealed record ReadPlan((int Index, uint Status)[] Unresolved, DevicePlan[] Devices);
|
||||
|
||||
/// <summary>One device's units, planned with no block refusal applied (see <see cref="ApplyRefusedBlocks"/>).</summary>
|
||||
private sealed record DevicePlan(DeviceState Device, List<ReadUnit> Units);
|
||||
|
||||
/// <summary>Distinct reference lists cached per device-table generation; a full cache is cleared (a poll loop reads a
|
||||
/// handful of fixed shapes — a cache this large means ad-hoc reads, which must not grow it without bound).</summary>
|
||||
internal const int MaxCachedReadPlans = 64;
|
||||
|
||||
/// <summary>Plans built (cache misses) since construction — test seam.</summary>
|
||||
internal int ReadPlanBuilds => Volatile.Read(ref _readPlanBuilds);
|
||||
private int _readPlanBuilds;
|
||||
|
||||
/// <summary>Plans currently cached — test seam.</summary>
|
||||
internal int CachedReadPlanCount => _readPlans?.Plans.Count ?? 0;
|
||||
|
||||
private volatile ReadPlanCache? _readPlans;
|
||||
|
||||
/// <summary>
|
||||
/// One device-table generation's plans. Valid only while <see cref="Devices"/> is still the published table, which
|
||||
/// every initialise and teardown replaces (and nulls the field), so a config change always re-plans. The key is the
|
||||
/// EXACT ordered reference list, not an order-insensitive set: a plan carries each reference's result-array index,
|
||||
/// so a reordered list needs different indices, and a poll/subscription re-reads the same list in the same order.
|
||||
/// </summary>
|
||||
private sealed class ReadPlanCache(Dictionary<string, DeviceState> devices)
|
||||
{
|
||||
public Dictionary<string, DeviceState> Devices { get; } = devices;
|
||||
public System.Collections.Concurrent.ConcurrentDictionary<string[], ReadPlan> Plans { get; } = new(RefListComparer.Instance);
|
||||
}
|
||||
|
||||
private sealed class RefListComparer : IEqualityComparer<string[]>
|
||||
{
|
||||
public static readonly RefListComparer Instance = new();
|
||||
public bool Equals(string[]? x, string[]? y) => x is not null && y is not null && x.AsSpan().SequenceEqual(y);
|
||||
public int GetHashCode(string[] o)
|
||||
{
|
||||
var h = new HashCode();
|
||||
foreach (var r in o) h.Add(r, StringComparer.Ordinal);
|
||||
return h.ToHashCode();
|
||||
}
|
||||
}
|
||||
|
||||
private ReadPlan GetReadPlan(Dictionary<string, DeviceState> devices, IReadOnlyList<string> references)
|
||||
{
|
||||
var cache = _readPlans;
|
||||
if (cache is null || !ReferenceEquals(cache.Devices, devices))
|
||||
_readPlans = cache = new ReadPlanCache(devices);
|
||||
var key = references.ToArray();
|
||||
if (cache.Plans.TryGetValue(key, out var hit)) return hit;
|
||||
var plan = BuildReadPlan(devices, key);
|
||||
Interlocked.Increment(ref _readPlanBuilds);
|
||||
// Only a plan with no Unresolved entries is cached: an unresolved reference may resolve later (a transient
|
||||
// equipment-tag parse), and caching would pin the Bad answer.
|
||||
if (plan.Unresolved.Length == 0)
|
||||
{
|
||||
if (cache.Plans.Count >= MaxCachedReadPlans) cache.Plans.Clear();
|
||||
cache.Plans[key] = plan;
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
/// <summary>The uncached planning step: resolve, classify and bucket every reference, then plan each device's units.</summary>
|
||||
internal string DescribeReadPlanForTest(IReadOnlyList<string> references, bool cached)
|
||||
{
|
||||
var plan = cached ? GetReadPlan(_devices, references) : BuildReadPlan(_devices, [.. references]);
|
||||
var parts = plan.Unresolved.Select(u => $"!{u.Index}:{u.Status}")
|
||||
.Concat(plan.Devices.SelectMany(d => ApplyRefusedBlocks(d.Device, d.Units).Select(u =>
|
||||
u.Block is { } b ? $"B[{b.Key};{string.Join(",", b.Members.Select(m => m.Index))}]" : $"S{u.Single!.Index}")));
|
||||
return string.Join("|", parts);
|
||||
}
|
||||
|
||||
private ReadPlan BuildReadPlan(Dictionary<string, DeviceState> devices, string[] references)
|
||||
{
|
||||
var unresolved = new List<(int, uint)>();
|
||||
var buckets = new Dictionary<DeviceState, List<ReadItem>>(ReferenceEqualityComparer.Instance);
|
||||
for (var i = 0; i < references.Length; i++)
|
||||
{
|
||||
var reference = references[i];
|
||||
if (!_resolver.TryResolve(reference, out var def) || !devices.TryGetValue(def.DeviceHostAddress, out var device))
|
||||
{
|
||||
unresolved.Add((i, AbLegacyStatusMapper.BadNodeIdUnknown));
|
||||
continue;
|
||||
}
|
||||
// A tag whose data type its device's PLC family does not ship is a per-tag configuration error: answered
|
||||
// without touching the wire or the device's health (already warned once at init).
|
||||
if (_configRejected.ContainsKey(def.Name))
|
||||
{
|
||||
unresolved.Add((i, AbLegacyStatusMapper.BadConfigurationError));
|
||||
continue;
|
||||
}
|
||||
var parsed = device.ParseAddress(def);
|
||||
if (parsed is null)
|
||||
{
|
||||
WarnMalformedOnce(device, def);
|
||||
unresolved.Add((i, AbLegacyStatusMapper.BadNodeIdUnknown));
|
||||
continue;
|
||||
}
|
||||
if (!buckets.TryGetValue(device, out var list)) buckets[device] = list = [];
|
||||
list.Add(new ReadItem(i, reference, def, parsed));
|
||||
}
|
||||
return new ReadPlan([.. unresolved],
|
||||
[.. buckets.Select(kv => new DevicePlan(kv.Key, PlanReadUnits(kv.Key, kv.Value, applyRefusals: false)))]);
|
||||
}
|
||||
|
||||
/// <summary>What a block read concluded; <see cref="Fallback"/> = read the members singly instead.</summary>
|
||||
private enum BlockOutcome { Done, Fallback }
|
||||
|
||||
|
||||
@@ -279,6 +279,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
_tagsByRawPath = tags;
|
||||
_configRejected = rejected;
|
||||
_devices = devices;
|
||||
_readPlans = null; // a config change re-plans (#1073)
|
||||
_resolver.Clear(); // drop transient parses made against the previous table
|
||||
if (options.Probe.Enabled && !string.IsNullOrWhiteSpace(options.Probe.ProbeAddress))
|
||||
{
|
||||
@@ -346,6 +347,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
}
|
||||
var retired = _devices.Values.ToList();
|
||||
_devices = new Dictionary<string, DeviceState>(StringComparer.OrdinalIgnoreCase);
|
||||
_readPlans = null;
|
||||
return (retired, _lifecycleEpoch);
|
||||
}
|
||||
}
|
||||
@@ -519,35 +521,12 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
var results = new DataValueSnapshot[fullReferences.Count];
|
||||
var devices = _devices; // one snapshot of the published table for the whole call
|
||||
|
||||
var buckets = new Dictionary<DeviceState, List<ReadItem>>(ReferenceEqualityComparer.Instance);
|
||||
for (var i = 0; i < fullReferences.Count; i++)
|
||||
{
|
||||
var reference = fullReferences[i];
|
||||
if (!_resolver.TryResolve(reference, out var def) || !devices.TryGetValue(def.DeviceHostAddress, out var device))
|
||||
{
|
||||
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadNodeIdUnknown, null, now);
|
||||
continue;
|
||||
}
|
||||
// A tag whose data type its device's PLC family does not ship is a per-tag configuration error: answered
|
||||
// without touching the wire or the device's health (already warned once at init).
|
||||
if (_configRejected.ContainsKey(def.Name))
|
||||
{
|
||||
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadConfigurationError, null, now);
|
||||
continue;
|
||||
}
|
||||
var parsed = device.ParseAddress(def);
|
||||
if (parsed is null)
|
||||
{
|
||||
WarnMalformedOnce(device, def);
|
||||
results[i] = new DataValueSnapshot(null, AbLegacyStatusMapper.BadNodeIdUnknown, null, now);
|
||||
continue;
|
||||
}
|
||||
if (!buckets.TryGetValue(device, out var list)) buckets[device] = list = [];
|
||||
list.Add(new ReadItem(i, reference, def, parsed));
|
||||
}
|
||||
if (buckets.Count == 0) return results;
|
||||
var plan = GetReadPlan(devices, fullReferences);
|
||||
foreach (var (index, status) in plan.Unresolved)
|
||||
results[index] = new DataValueSnapshot(null, status, null, now);
|
||||
if (plan.Devices.Length == 0) return results;
|
||||
|
||||
var passes = buckets.ToArray();
|
||||
var passes = plan.Devices;
|
||||
var outcomes = new DeviceReadOutcome[passes.Length];
|
||||
using (var window = new SemaphoreSlim(MaxConcurrentDevices, MaxConcurrentDevices))
|
||||
{
|
||||
@@ -563,7 +542,7 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
await window.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
outcomes[d] = await ReadDevicePassAsync(passes[d].Key, passes[d].Value, results, now, cancellationToken)
|
||||
outcomes[d] = await ReadDevicePassAsync(passes[d].Device, passes[d].Units, results, now, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
@@ -623,10 +602,10 @@ public sealed partial class AbLegacyDriver : IDriver, IReadable, IWritable, ITag
|
||||
|
||||
/// <summary>Reads one device's references in order, failing fast once the device is marked down.</summary>
|
||||
private async Task<DeviceReadOutcome> ReadDevicePassAsync(
|
||||
DeviceState device, List<ReadItem> items, DataValueSnapshot[] results, DateTime now, CancellationToken ct)
|
||||
DeviceState device, List<ReadUnit> units, DataValueSnapshot[] results, DateTime now, CancellationToken ct)
|
||||
{
|
||||
var outcome = new DeviceReadOutcome();
|
||||
var work = new Queue<ReadUnit>(PlanReadUnits(device, items));
|
||||
var work = new Queue<ReadUnit>(ApplyRefusedBlocks(device, units));
|
||||
while (work.TryDequeue(out var unit))
|
||||
{
|
||||
var members = unit.Block?.Members ?? [unit.Single!];
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
|
||||
|
||||
/// <summary>
|
||||
/// The ONE definition of how a Sql <c>DriverConfig</c> blob is read (lmxopcua#1076). The driver factory deserialises
|
||||
/// <see cref="SqlDriverConfigDto"/> with <see cref="Options"/>, and the deploy gate (<c>SqlTagDeployChecks</c>, which
|
||||
/// cannot reference the driver assembly) uses the same instance, so the gate can never be looser or stricter than
|
||||
/// the driver about what the JSON means.
|
||||
/// <list type="bullet">
|
||||
/// <item>Case-insensitive property names, camelCase naming policy (so a write round-trips to the authored shape).</item>
|
||||
/// <item>Comments and trailing commas tolerated.</item>
|
||||
/// <item>Unknown members skipped — a blob authored against another schema version must not brick the driver.</item>
|
||||
/// <item>Enums read as names or ordinals, always written as names (the enum-serialization guard).</item>
|
||||
/// </list>
|
||||
/// Treat as read-only: do not mutate after first use.
|
||||
/// </summary>
|
||||
public static class SqlDriverConfigJson
|
||||
{
|
||||
/// <summary>Serializer options shared by the driver factory, the probe and the deploy gate.</summary>
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip,
|
||||
Converters = { new JsonStringEnumConverter() },
|
||||
};
|
||||
}
|
||||
@@ -47,15 +47,7 @@ public static class SqlDriverFactoryExtensions
|
||||
/// what makes a <em>write</em> round-trip to the authored shape.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip,
|
||||
Converters = { new JsonStringEnumConverter() },
|
||||
};
|
||||
internal static readonly JsonSerializerOptions JsonOptions = SqlDriverConfigJson.Options;
|
||||
|
||||
/// <summary>The serializer options, exposed so tests can assert the enum guard on a real round-trip.</summary>
|
||||
internal static JsonSerializerOptions JsonOptionsForTest => JsonOptions;
|
||||
|
||||
Reference in New Issue
Block a user