Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway/GatewayHistorianServiceCollectionExtensions.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

133 lines
8.6 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
using ZB.MOM.WW.OtOpcUa.Runtime.Historian;
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway;
/// <summary>
/// Host-callable factories that build the gateway-backed historian seams against the single
/// <c>ServerHistorian</c> gateway: <see cref="CreateDataSource"/> for the read path (the Host's
/// <c>AddServerHistorian</c> wiring) and <see cref="CreateAlarmWriter"/> for the alarm-write path
/// (the Host's <c>AddAlarmHistorian</c> wiring). Both keep the concrete package-client dependency
/// inside this driver project — the Host references only the driver, not the package client directly.
/// </summary>
public static class GatewayHistorian
{
/// <summary>
/// Builds a <see cref="GatewayHistorianDataSource"/> over a lazily connected
/// <see cref="HistorianGatewayClientAdapter"/> mapped from the bound
/// <see cref="ServerHistorianOptions"/>. Resolves an <see cref="ILoggerFactory"/> and the data
/// source's <see cref="ILogger{TCategoryName}"/> from <paramref name="services"/>, falling back to
/// the null implementations when absent (e.g. minimal test providers). Performs no network I/O —
/// the underlying channel dials on first use.
/// </summary>
/// <param name="options">The bound <c>ServerHistorian</c> configuration.</param>
/// <param name="services">The resolving service provider (used only to locate logging services).</param>
/// <returns>The gateway-backed <see cref="IHistorianDataSource"/>.</returns>
public static IHistorianDataSource CreateDataSource(ServerHistorianOptions options, IServiceProvider services)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(services);
var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance;
var logger = services.GetService<ILogger<GatewayHistorianDataSource>>()
?? NullLogger<GatewayHistorianDataSource>.Instance;
return new GatewayHistorianDataSource(
HistorianGatewayClientAdapter.Create(options, loggerFactory),
logger,
// The raw-evaluated per-sample aggregates share the SQL backends' raw-row cap.
maxRawRows: options.MaxTimeWeightedRawRows,
// AtTime from raw reads + the shared evaluator; false = AVEVA's own interpolation (kill switch).
atTimeFromRaw: options.GatewayAtTimeFromRaw,
// A crowding re-read never makes room for more pre-window rows than the tie-cluster limit.
maxPreWindowRows: options.MaxTieClusterOverfetch,
// The server raw cap (R08:1.1): the page limit the server reads at, and the bound on every raw read.
maxRawValuesPerRead: options.EffectiveMaxRawValuesPerRead,
// How far a capped events read drains its stream past the cap before abandoning it.
eventDrainBudget: options.Gateway.EventDrainBudget,
// AVEVA's native TimeAverage / Total — on by default since historiangw#27 was live-verified (lmxopcua#694).
enableNativeTimeWeighted: options.Gateway.EnableNativeTimeWeighted,
// A slow ProbeAsync timer so the health snapshot reflects the gateway without waiting for a read.
probeInterval: options.Gateway.ProbeInterval);
}
/// <summary>
/// Builds a <see cref="GatewayAlarmHistorianWriter"/> over a lazily connected
/// <see cref="HistorianGatewayClientAdapter"/> mapped from the bound
/// <see cref="ServerHistorianOptions"/> — the <b>same single gateway</b> the read path
/// (<see cref="CreateDataSource"/>) targets. The Host's <c>AddAlarmHistorian</c> wiring supplies
/// this as the concrete <see cref="IAlarmHistorianWriter"/> the durable
/// <c>LocalDbStoreAndForwardSink</c> drain worker delegates to, sourcing the connection from the
/// <c>ServerHistorian</c> section (endpoint/key/TLS) rather than the legacy Wonderware-shaped
/// <c>AlarmHistorian</c> host/port. Resolves an <see cref="ILoggerFactory"/> and the writer's
/// <see cref="ILogger{TCategoryName}"/> from <paramref name="services"/>, falling back to the null
/// implementations when absent. Performs no network I/O — the underlying channel dials on first send.
/// </summary>
/// <remarks>
/// This deliberately constructs its <b>own</b> <see cref="HistorianGatewayClientAdapter"/> — a
/// second gRPC channel to the same gateway as the read path. Collapsing the two onto one shared
/// channel would require the container to own a singleton <see cref="IHistorianGatewayClient"/> and
/// the read-side <see cref="GatewayHistorianDataSource"/> to stop owning + disposing its client,
/// regressing the read cutover's dispose ownership (and its tests). A second channel to a co-located
/// sidecar is cheap — the gateway pools and amortizes the underlying historian sessions server-side —
/// so each path keeps its own channel with a clean, independent lifetime.
/// </remarks>
/// <param name="options">The bound <c>ServerHistorian</c> configuration (endpoint, key, TLS posture).</param>
/// <param name="services">The resolving service provider (used only to locate logging services).</param>
/// <returns>The gateway-backed <see cref="IAlarmHistorianWriter"/>.</returns>
public static IAlarmHistorianWriter CreateAlarmWriter(ServerHistorianOptions options, IServiceProvider services)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(services);
var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance;
var logger = services.GetService<ILogger<GatewayAlarmHistorianWriter>>()
?? NullLogger<GatewayAlarmHistorianWriter>.Instance;
return new GatewayAlarmHistorianWriter(
HistorianGatewayClientAdapter.Create(options, loggerFactory),
logger);
}
/// <summary>
/// Builds a <see cref="GatewayTagProvisioner"/> over a lazily connected
/// <see cref="HistorianGatewayClientAdapter"/> mapped from the bound
/// <see cref="ServerHistorianOptions"/> — the <b>same single gateway</b> the read path
/// (<see cref="CreateDataSource"/>) and alarm-write path (<see cref="CreateAlarmWriter"/>) target. The
/// Host's <c>AddHistorianProvisioning</c> wiring supplies this as the concrete
/// <see cref="IHistorianProvisioning"/> the <c>AddressSpaceApplier</c> calls (non-blocking
/// <c>EnsureTags</c>) when a deploy adds historized tags, so a brand-new historized tag exists in the
/// historian before the recorder's <c>WriteLiveValues</c> land. Resolves an <see cref="ILoggerFactory"/>
/// and the provisioner's <see cref="ILogger{TCategoryName}"/> from <paramref name="services"/>, falling
/// back to the null implementations when absent. Performs no network I/O — the underlying channel dials
/// on first <c>EnsureTags</c>.
/// </summary>
/// <remarks>
/// Like <see cref="CreateAlarmWriter"/>, this constructs its <b>own</b>
/// <see cref="HistorianGatewayClientAdapter"/> — a separate gRPC channel to the same gateway. A second
/// channel to a co-located sidecar is cheap (the gateway pools the historian sessions server-side), and
/// it keeps each path's channel lifetime clean and independent.
/// </remarks>
/// <param name="options">The bound <c>ServerHistorian</c> configuration (endpoint, key, TLS posture).</param>
/// <param name="services">The resolving service provider (used only to locate logging services).</param>
/// <returns>The gateway-backed <see cref="IHistorianProvisioning"/>.</returns>
public static IHistorianProvisioning CreateProvisioner(ServerHistorianOptions options, IServiceProvider services)
{
ArgumentNullException.ThrowIfNull(options);
ArgumentNullException.ThrowIfNull(services);
var loggerFactory = services.GetService<ILoggerFactory>() ?? NullLoggerFactory.Instance;
var logger = services.GetService<ILogger<GatewayTagProvisioner>>()
?? NullLogger<GatewayTagProvisioner>.Instance;
return new GatewayTagProvisioner(
HistorianGatewayClientAdapter.Create(options, loggerFactory),
logger,
createOnly: options.ProvisionPolicy == HistorianProvisionPolicy.CreateOnly);
}
}