Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Historian/AddHistorianProvisioningTests.cs
T
Joseph Doherty 6c4d29902e
v2-ci / unit-tests (push) Has been cancelled
fix(historian): read-only historian bindings + ProvisionTags policy; provision OPC UA type names (#899, #898)
#899 — EnsureTags is an upsert, so binding a node to an existing AVEVA tag via
historianTagname re-typed/re-described it on every add and host start.
- TagConfig `historianReadOnly: true` (TagConfigIntent -> RawTagPlan.HistorianReadOnly):
  HistoryRead from an existing historian tag that OtOpcUa never provisions and never
  records into (AddressSpaceApplier.IsOwnedHistorizedValue gates both the EnsureTags
  hook and the recorder feed). Node-inert: surgical, not mirrored on UNS refs, in the
  RawTagPlan equality/hash. A non-bool value is the deploy error HistorianReadOnlyInvalid.
  AdminUI: CSV column HistorianReadOnly (strict), TagHistorizeConfig reads via the
  runtime parse.
- ServerHistorian:ProvisionTags = CreateOrUpdate (default, unchanged) | CreateOnly
  (Gateway only: TagExistsAsync first, existing tags left alone, failed lookup not
  sent) | Off. Unknown value / CreateOnly on a SQL backend fail host start.
- Default for an explicit historianTagname stays OWNED: overrides pin owned history
  across renames, a read-only default would silently stop provisioning + recording.

#898 — the hook parsed Tag.DataType (an OPC UA name) as DriverDataType, so historized
Float/Double/Byte/SByte tags were never provisioned. New shared
HistorianDataTypeNames.TryResolve: Float->Float32, Double->Float64, Byte/SByte->Int16
(lossless, provisioned as Int2); unmapped names logged at Information. Gateway now skips
Int64/UInt64 (HistorianGateway cannot create Int8/UInt8: lossless-cast-or-reject).

UPGRADE: the first host start after this provisions (upserts) every existing historized
Float/Double/Byte/SByte tag. Mark foreign-tag bindings historianReadOnly, or set
ServerHistorian:ProvisionTags=CreateOnly/Off, before upgrading (docs/Historian.md).

Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
2026-11-13 01:16:24 -05:00

236 lines
11 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime;
using ZB.MOM.WW.OtOpcUa.Runtime.Historian;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Historian;
/// <summary>
/// Verifies the config-gated <c>AddHistorianProvisioning</c> registration AND that a registered
/// provisioner is actually reached by the address-space applier on a historized-tag deploy. This is the
/// wiring the HistorianGateway-integration review found missing: PR #423 shipped
/// <c>GatewayTagProvisioner</c> + unit tests but never registered it in DI nor passed it into the applier,
/// so <c>EnsureTags</c> was dormant (every deploy used the no-op <see cref="NullHistorianProvisioning"/>).
/// <para>
/// When the <c>ServerHistorian</c> section is absent or disabled the <see cref="NullHistorianProvisioning"/>
/// default seeded by <c>AddOtOpcUaRuntime</c> survives (the factory is never invoked); when it is enabled
/// the factory's returned <see cref="IHistorianProvisioning"/> wins (last-registration-wins over the
/// <c>TryAddSingleton</c> Null default) and — constructed into the applier the way
/// <c>WithOtOpcUaRuntimeActors</c> does — its <see cref="IHistorianProvisioning.EnsureTagsAsync"/> fires
/// for an added historized tag.
/// </para>
/// </summary>
public sealed class AddHistorianProvisioningTests
{
/// <summary>Capturing <see cref="IHistorianProvisioning"/> double — records the requests it was handed and
/// signals a <see cref="TaskCompletionSource"/> when invoked so the fire-and-forget applier dispatch can be
/// awaited deterministically.</summary>
private sealed class CapturingProvisioner : IHistorianProvisioning
{
private readonly TaskCompletionSource _called = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>The requests the applier handed to <see cref="EnsureTagsAsync"/>.</summary>
public List<HistorianTagProvisionRequest> Seen { get; } = new();
/// <summary>Completes once <see cref="EnsureTagsAsync"/> has been invoked.</summary>
public Task Called => _called.Task;
/// <inheritdoc />
public Task<HistorianProvisionResult> EnsureTagsAsync(
IReadOnlyList<HistorianTagProvisionRequest> requests, CancellationToken ct)
{
Seen.AddRange(requests);
_called.TrySetResult();
return Task.FromResult(new HistorianProvisionResult(requests.Count, requests.Count, 0, 0));
}
}
private static IConfiguration ConfigFrom(Dictionary<string, string?> values)
=> new ConfigurationBuilder().AddInMemoryCollection(values).Build();
private static IConfiguration EnabledConfig() => ConfigFrom(new Dictionary<string, string?>
{
["ServerHistorian:Enabled"] = "true",
["ServerHistorian:Endpoint"] = "https://historian.example.com:5222",
["ServerHistorian:ApiKey"] = "histgw_x_y",
});
[Fact]
public void Section_absent_keeps_null_provisioning_and_factory_not_invoked()
{
var factoryInvoked = false;
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
services.AddHistorianProvisioning(ConfigFrom(new Dictionary<string, string?>()), (_, _) =>
{
factoryInvoked = true;
return new CapturingProvisioner();
});
using var provider = services.BuildServiceProvider();
provider.GetRequiredService<IHistorianProvisioning>().ShouldBeSameAs(NullHistorianProvisioning.Instance);
factoryInvoked.ShouldBeFalse();
}
[Fact]
public void Section_disabled_keeps_null_provisioning_and_factory_not_invoked()
{
var factoryInvoked = false;
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
var config = ConfigFrom(new Dictionary<string, string?> { ["ServerHistorian:Enabled"] = "false" });
services.AddHistorianProvisioning(config, (_, _) =>
{
factoryInvoked = true;
return new CapturingProvisioner();
});
using var provider = services.BuildServiceProvider();
provider.GetRequiredService<IHistorianProvisioning>().ShouldBeSameAs(NullHistorianProvisioning.Instance);
factoryInvoked.ShouldBeFalse();
}
[Fact]
public void Section_enabled_registers_factory_provisioner_over_the_null_default()
{
var prov = new CapturingProvisioner();
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
services.AddHistorianProvisioning(EnabledConfig(), (_, _) => prov);
using var provider = services.BuildServiceProvider();
var resolved = provider.GetRequiredService<IHistorianProvisioning>();
resolved.ShouldBeSameAs(prov);
resolved.ShouldNotBeSameAs(NullHistorianProvisioning.Instance);
}
/// <summary>lmxopcua#899: ServerHistorian:ProvisionTags=Off keeps the no-op even with the section enabled; the
/// other policies register the backend's provisioner (control).</summary>
[Theory]
[InlineData("Off", false)]
[InlineData("off", false)]
[InlineData("CreateOnly", true)]
[InlineData("CreateOrUpdate", true)]
public void ProvisionTags_Off_keeps_null_provisioning(string policy, bool registered)
{
var factoryInvoked = false;
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
var config = ConfigFrom(new Dictionary<string, string?>
{
["ServerHistorian:Enabled"] = "true",
["ServerHistorian:Endpoint"] = "https://historian.example.com:5222",
["ServerHistorian:ApiKey"] = "histgw_x_y",
["ServerHistorian:ProvisionTags"] = policy,
});
services.AddHistorianProvisioning(config, (_, _) =>
{
factoryInvoked = true;
return new CapturingProvisioner();
});
using var provider = services.BuildServiceProvider();
var resolved = provider.GetRequiredService<IHistorianProvisioning>();
(resolved is NullHistorianProvisioning).ShouldBe(!registered);
factoryInvoked.ShouldBe(registered);
}
[Fact]
public void Section_enabled_passes_bound_options_to_factory()
{
ServerHistorianOptions? seen = null;
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
var config = ConfigFrom(new Dictionary<string, string?>
{
["ServerHistorian:Enabled"] = "true",
["ServerHistorian:Endpoint"] = "https://historian.example.com:5222",
["ServerHistorian:ApiKey"] = "histgw_x_y",
["ServerHistorian:UseTls"] = "true",
["ServerHistorian:CaCertificatePath"] = "/etc/ssl/gateway-ca.pem",
});
services.AddHistorianProvisioning(config, (opts, _) =>
{
seen = opts;
return new CapturingProvisioner();
});
using var provider = services.BuildServiceProvider();
_ = provider.GetRequiredService<IHistorianProvisioning>();
seen.ShouldNotBeNull();
seen.Endpoint.ShouldBe("https://historian.example.com:5222");
seen.ApiKey.ShouldBe("histgw_x_y");
seen.UseTls.ShouldBeTrue();
seen.CaCertificatePath.ShouldBe("/etc/ssl/gateway-ca.pem");
}
/// <summary>
/// The end-to-end wiring proof the dormant-provisioner bug needed: register the provisioner via
/// <c>AddHistorianProvisioning</c>, resolve it, construct the <see cref="AddressSpaceApplier"/> EXACTLY
/// as <c>WithOtOpcUaRuntimeActors</c> does (<c>provisioning: resolver.GetService&lt;IHistorianProvisioning&gt;()</c>),
/// then apply a plan that adds a historized tag and assert the gateway-backed
/// <see cref="IHistorianProvisioning.EnsureTagsAsync"/> actually fires (with the resolved historian name).
/// </summary>
[Fact]
public async Task Registered_provisioner_is_invoked_by_the_applier_on_a_historized_deploy()
{
var prov = new CapturingProvisioner();
var services = new ServiceCollection();
services.AddOtOpcUaRuntime();
services.AddHistorianProvisioning(EnabledConfig(), (_, _) => prov);
using var provider = services.BuildServiceProvider();
// Mirror the production construction in WithOtOpcUaRuntimeActors: resolve the provisioner and pass it in.
var resolved = provider.GetService<IHistorianProvisioning>();
var applier = new AddressSpaceApplier(
NullOpcUaAddressSpaceSink.Instance, NullLogger<AddressSpaceApplier>.Instance, provisioning: resolved);
applier.Apply(PlanWithAddedTags(
HistorizedTag(displayName: "Temp", historianName: "Pump1.Temp", dataType: "Float32"),
NonHistorizedTag(displayName: "Run", dataType: "Boolean")));
await prov.Called.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
prov.Seen.Count.ShouldBe(1);
prov.Seen[0].TagName.ShouldBe("Pump1.Temp");
prov.Seen[0].DataType.ShouldBe(DriverDataType.Float32);
}
// v3 Batch 4: historized value tags are RAW tags (the applier provisions from AddedRawTags). NodeId plays
// the RawPath role (== mux ref + historian default).
private static RawTagPlan HistorizedTag(string displayName, string? historianName, string dataType, string fullName = "ref")
=> new("tag-" + displayName, NodeId: fullName, ParentNodeId: null, DriverInstanceId: "drv", Name: displayName,
DataType: dataType, Writable: false, Alarm: null, ReferencingEquipmentPaths: Array.Empty<string>(),
IsHistorized: true, HistorianTagname: historianName);
private static RawTagPlan NonHistorizedTag(string displayName, string dataType)
=> new("tag-" + displayName, NodeId: "ref", ParentNodeId: null, DriverInstanceId: "drv", Name: displayName,
DataType: dataType, Writable: false, Alarm: null, ReferencingEquipmentPaths: Array.Empty<string>(),
IsHistorized: false, HistorianTagname: null);
private static AddressSpacePlan PlanWithAddedTags(params RawTagPlan[] tags) => new(
AddedEquipment: Array.Empty<EquipmentNode>(),
RemovedEquipment: Array.Empty<EquipmentNode>(),
ChangedEquipment: Array.Empty<AddressSpacePlan.EquipmentDelta>(),
AddedDrivers: Array.Empty<DriverInstancePlan>(),
RemovedDrivers: Array.Empty<DriverInstancePlan>(),
ChangedDrivers: Array.Empty<AddressSpacePlan.DriverDelta>(),
AddedAlarms: Array.Empty<ScriptedAlarmPlan>(),
RemovedAlarms: Array.Empty<ScriptedAlarmPlan>(),
ChangedAlarms: Array.Empty<AddressSpacePlan.AlarmDelta>())
{
AddedRawTags = tags,
};
}