Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.AbLegacy/AbLegacyDriverFactoryExtensions.cs
T
Joseph Doherty d32d89c340 fix(drivers): stop silently discarding driver config edits (§8.3, #516)
Five drivers ignored the config handed to them on reinitialize, serving the
options their constructor captured — and the deployment sealed green anyway.
Fixed on both halves, as chosen.

Seam (load-bearing): DriverSpawnPlanner routes a changed DriverConfig to
ToStop + ToSpawn instead of an in-place delta, making the factory the single
parse authority. This REVERSES the deliberate decision documented at
DriverSpawnPlan.cs:49-50 ("a pure DriverConfig change stays an in-place delta
— no reconnect"). That reasoning was correct about the resilience pipeline and
wrong about the driver. The accepted price is a reconnect per config edit.

Per-driver, and this split was not anticipated:
- Re-parse in place — Modbus, AbLegacy, OpcUaClient. ParseOptions extracted
  from each factory, called from InitializeAsync behind a HasConfigBody guard
  so "{}" still keeps the constructor options.
- Respawn-only, deliberately NOT re-parsed — Sql and FOCAS. Each builds more
  than options from config (Sql's dialect + resolved connection string,
  FOCAS's client-factory backend, both injected at construction), so adopting
  new options alone would run a NEW tag set against an OLD connection. Half a
  re-parse is worse than none. SqlDriver's doc-comment asserted the opposite
  premise — "config parsing belongs to the factory, which builds a fresh
  instance" — which was false when written and is true only now.

Two green seals removed from ApplyChildDelta: it overwrote the cached Spec
synchronously BEFORE the child dequeued the message, so the host believed the
new config was live and the next reconcile computed no delta, sealing the
drift permanently; and it Tell'd with no Receive<ApplyResult> registered, so a
failed reinit — including Galaxy's deliberate NotSupportedException —
dead-lettered.

Exposed (not created) by the change: a factory throw is a CONFIG error, and
SpawnChild catches it and silently substitutes a stub. Only a brand-new driver
could reach that before; an ordinary config edit can now. Raised Warning ->
Error with an actionable message. It still does not fail the deployment —
doing so would let one malformed driver block a fleet deploy, so that is a
follow-up rather than a drive-by.

Tests: every pre-existing reinit test in these suites passes "{}", the exact
input a guarded re-parser treats as "keep constructor options" — blind to this
defect by construction. New tests pass CHANGED json; the Modbus one was
verified falsifiable by deleting the re-parse (goes red). Two tests asserted
the old behaviour and were rewritten, including the positive control in
DriverHostActorUnreadableArtifactTests, whose observable moved from
UnsubscribeAsync to ShutdownAsync now that teardown happens by stopping the
child rather than emptying its desired set.

Remaining full-suite failures are pre-existing and environmental, verified
identical on the pre-change tree: Host.IntegrationTests (3) and
Driver.AbLegacy.IntegrationTests (4, docker fixture-gated).
2026-07-27 19:32:46 -04:00

208 lines
9.6 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Hosting;
using ZB.MOM.WW.OtOpcUa.Driver.AbLegacy.PlcFamilies;
namespace ZB.MOM.WW.OtOpcUa.Driver.AbLegacy;
/// <summary>
/// Static factory registration helper for <see cref="AbLegacyDriver"/>. Server's Program.cs
/// calls <see cref="Register"/> once at startup; the bootstrapper then
/// materialises AB Legacy DriverInstance rows from the central config DB into live
/// driver instances. Mirrors <c>GalaxyProxyDriverFactoryExtensions</c>.
/// </summary>
public static class AbLegacyDriverFactoryExtensions
{
public const string DriverTypeName = "AbLegacy";
/// <summary>
/// Register the AbLegacy factory with the driver registry. The optional
/// <paramref name="loggerFactory"/> is captured at registration time and used to
/// construct an <see cref="ILogger{AbLegacyDriver}"/> per driver instance — without it,
/// the driver runs with the null logger (existing tests and standalone callers stay
/// unchanged). Mirrors the Modbus driver registration pattern.
/// </summary>
/// <param name="registry">The driver factory registry to register with.</param>
/// <param name="loggerFactory">Optional logger factory for driver instances.</param>
public static void Register(DriverFactoryRegistry registry, ILoggerFactory? loggerFactory = null)
{
ArgumentNullException.ThrowIfNull(registry);
registry.Register(DriverTypeName, (id, json) => CreateInstance(id, json, loggerFactory));
}
/// <summary>
/// Creates an instance of the AB Legacy driver from configuration.
/// </summary>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
/// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
/// <returns>A configured <see cref="AbLegacyDriver"/> instance.</returns>
internal static AbLegacyDriver CreateInstance(string driverInstanceId, string driverConfigJson)
=> CreateInstance(driverInstanceId, driverConfigJson, loggerFactory: null);
/// <summary>
/// Creates an instance of the AB Legacy driver with optional logger.
/// </summary>
/// <param name="driverInstanceId">The unique identifier for this driver instance.</param>
/// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
/// <param name="loggerFactory">Optional logger factory for the driver instance.</param>
/// <returns>A configured <see cref="AbLegacyDriver"/> instance.</returns>
internal static AbLegacyDriver CreateInstance(string driverInstanceId, string driverConfigJson, ILoggerFactory? loggerFactory)
{
return new AbLegacyDriver(
ParseOptions(driverInstanceId, driverConfigJson), driverInstanceId,
tagFactory: null,
logger: loggerFactory?.CreateLogger<AbLegacyDriver>());
}
/// <summary>
/// Parses an AB Legacy <c>DriverConfig</c> JSON document into typed options. Extracted so
/// <see cref="AbLegacyDriver.InitializeAsync"/> can re-parse a CHANGED config on reinitialize
/// (Gitea #516) instead of serving the options it was constructed with — which silently discarded
/// every operator edit while the deployment still sealed green.
/// </summary>
/// <param name="driverInstanceId">The unique driver instance identifier.</param>
/// <param name="driverConfigJson">The driver configuration as a JSON string.</param>
/// <returns>The parsed <see cref="AbLegacyDriverOptions"/>.</returns>
internal static AbLegacyDriverOptions ParseOptions(string driverInstanceId, string driverConfigJson)
{
ArgumentException.ThrowIfNullOrWhiteSpace(driverInstanceId);
ArgumentException.ThrowIfNullOrWhiteSpace(driverConfigJson);
var dto = JsonSerializer.Deserialize<AbLegacyDriverConfigDto>(driverConfigJson, JsonOptions)
?? throw new InvalidOperationException(
$"AB Legacy driver config for '{driverInstanceId}' deserialised to null");
var options = new AbLegacyDriverOptions
{
Devices = dto.Devices is { Count: > 0 }
? [.. dto.Devices.Select(d => new AbLegacyDeviceOptions(
HostAddress: d.HostAddress ?? throw new InvalidOperationException(
$"AB Legacy config for '{driverInstanceId}' has a device missing HostAddress"),
PlcFamily: ParseEnum<AbLegacyPlcFamily>(d.PlcFamily, driverInstanceId, "PlcFamily",
fallback: AbLegacyPlcFamily.Slc500),
DeviceName: d.DeviceName))]
: [],
// v3: the deploy artifact (Wave C) populates rawTags with the cluster's authored raw AbLegacy
// tags (RawPath + TagConfig blob + WriteIdempotent + owning DeviceName). The driver maps each
// RawTagEntry's TagConfig blob through AbLegacyTagDefinitionFactory at Initialize and routes it
// to its device by DeviceName; the legacy pre-declared DTO tag path is retired.
RawTags = dto.RawTags is { Count: > 0 } ? [.. dto.RawTags] : [],
Probe = new AbLegacyProbeOptions
{
Enabled = dto.Probe?.Enabled ?? true,
Interval = TimeSpan.FromMilliseconds(dto.Probe?.IntervalMs ?? 5_000),
Timeout = PositiveTimeoutOrDefault(dto.Probe?.TimeoutMs, 2_000),
ProbeAddress = dto.Probe?.ProbeAddress ?? "S:0",
},
Timeout = PositiveTimeoutOrDefault(dto.TimeoutMs, 2_000),
};
return options;
}
/// <summary>
/// Maps an operator-supplied timeout (ms) to a positive <see cref="TimeSpan"/>, substituting
/// <paramref name="defaultMs"/> for a null / zero / negative value. libplctag's managed
/// <c>Tag.Timeout</c> setter throws <see cref="ArgumentOutOfRangeException"/> for a
/// non-positive value, which would otherwise fault tag creation on every read/write; clamping
/// here keeps a misconfigured <c>TimeoutMs: 0</c> running on the default bound instead. (Driver
/// timeout hardening, sibling of the S7 R2-01 read-leg fix.)
/// </summary>
/// <param name="ms">The operator-supplied timeout in milliseconds, or null.</param>
/// <param name="defaultMs">The default applied when <paramref name="ms"/> is null or non-positive.</param>
/// <returns>A strictly positive timeout.</returns>
private static TimeSpan PositiveTimeoutOrDefault(int? ms, int defaultMs) =>
TimeSpan.FromMilliseconds(ms is int v and > 0 ? v : defaultMs);
private static T ParseEnum<T>(string? raw, string driverInstanceId, string field,
string? tagName = null, T? fallback = null) where T : struct, Enum
{
if (string.IsNullOrWhiteSpace(raw))
{
if (fallback.HasValue) return fallback.Value;
throw new InvalidOperationException(
$"AB Legacy {(tagName is null ? "config" : $"tag '{tagName}'")} in '{driverInstanceId}' missing {field}");
}
return Enum.TryParse<T>(raw, ignoreCase: true, out var v)
? v
: throw new InvalidOperationException(
$"AB Legacy {(tagName is null ? "config" : $"tag '{tagName}'")} has unknown {field} '{raw}'. " +
$"Expected one of {string.Join(", ", Enum.GetNames<T>())}");
}
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
};
internal sealed class AbLegacyDriverConfigDto
{
/// <summary>
/// Gets or sets the timeout in milliseconds for operations.
/// </summary>
public int? TimeoutMs { get; init; }
/// <summary>
/// Gets or sets the list of devices to connect to.
/// </summary>
public List<AbLegacyDeviceDto>? Devices { get; init; }
/// <summary>
/// Gets or sets the authored raw tags (RawPath + TagConfig blob + WriteIdempotent + owning
/// DeviceName) the deploy artifact delivers. The driver maps each through
/// <see cref="AbLegacyTagDefinitionFactory.FromTagConfig"/> at Initialize.
/// </summary>
public List<RawTagEntry>? RawTags { get; init; }
/// <summary>
/// Gets or sets the probe configuration.
/// </summary>
public AbLegacyProbeDto? Probe { get; init; }
}
internal sealed class AbLegacyDeviceDto
{
/// <summary>
/// Gets or sets the host address of the device.
/// </summary>
public string? HostAddress { get; init; }
/// <summary>
/// Gets or sets the PLC family.
/// </summary>
public string? PlcFamily { get; init; }
/// <summary>
/// Gets or sets the device name.
/// </summary>
public string? DeviceName { get; init; }
}
internal sealed class AbLegacyProbeDto
{
/// <summary>
/// Gets or sets whether probing is enabled.
/// </summary>
public bool? Enabled { get; init; }
/// <summary>
/// Gets or sets the probe interval in milliseconds.
/// </summary>
public int? IntervalMs { get; init; }
/// <summary>
/// Gets or sets the probe timeout in milliseconds.
/// </summary>
public int? TimeoutMs { get; init; }
/// <summary>
/// Gets or sets the probe address.
/// </summary>
public string? ProbeAddress { get; init; }
}
}