using System.Security.Cryptography; namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; /// /// Bounds on age since normalized ingress into the origin cache, not sensor measurement age. /// A null endpoint is unknown. An upper bound alone certifies freshness; a lower bound alone /// can prove staleness. Original wall-clock timestamps are independent of these bounds. /// public readonly record struct DataAgeBounds(TimeSpan? Lower, TimeSpan? Upper) { public void Validate() { if (Lower < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Lower)); if (Upper < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Upper)); if (Lower is { } lower && Upper is { } upper && upper < lower) throw new ArgumentException("Upper age bound must not precede lower bound."); } public DataAgeBounds Advance(TimeSpan elapsed) { Validate(); if (elapsed < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(elapsed)); return new(Lower is { } lower ? TimeSpan.FromTicks(checked(lower.Ticks + elapsed.Ticks)) : null, Upper is { } upper ? TimeSpan.FromTicks(checked(upper.Ticks + elapsed.Ticks)) : null); } public bool IsFresh(TimeSpan maximumAge) { Validate(); if (maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maximumAge)); return Upper is { } upper && upper <= maximumAge; } public bool IsStale(TimeSpan maximumAge) { Validate(); if (maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maximumAge)); return Lower is { } lower && lower > maximumAge; } } public enum DataValueKind { Unspecified = 0, Null = 1, Boolean = 2, Int8 = 3, Int16 = 4, Int32 = 5, Int64 = 6, UInt8 = 7, UInt16 = 8, UInt32 = 9, UInt64 = 10, Float = 11, Double = 12, String = 13, Bytes = 14, Timestamp = 15, Guid = 16, Array = 17 } public enum DataItemStatus { Unspecified = 0, Good = 1, Denied = 2, NotFound = 3, Unsupported = 4, InvalidArgument = 5, Unavailable = 6, WaitingForInitialData = 7, Stale = 8, LimitExceeded = 9, InvalidContinuation = 10, TypeMismatch = 11, ResourceExhausted = 12 } public enum DataReadiness { Unspecified = 0, Ready = 1, WaitingForInitialData = 2, Unavailable = 3, Invalidated = 4 } public enum DataWriteState { Unspecified = 0, RejectedBeforeDispatch = 1, DriverConfirmedSuccess = 2, DriverConfirmedFailure = 3, AcceptedUnconfirmed = 4, OutcomeUnknown = 5 } public enum DataChangeTrigger { Unspecified = 0, Status = 1, StatusValue = 2, StatusValueTimestamp = 3 } public enum DataStreamControlKind { Unspecified = 0, SnapshotBegin = 1, SnapshotEnd = 2, CatalogInvalidated = 3, AuthorityInvalidated = 4, Heartbeat = 5, Reset = 6, Coalesced = 7 } /// /// Owned immutable value. Factory methods copy mutable inputs; Retain creates an independently /// disposable lease. Consumers must dispose every lease after asynchronous use completes. /// public sealed class DataValue : IDisposable { private readonly object? _payload; private bool _disposed; private DataValue(DataValueKind kind, object? payload, IReadOnlyList? dimensions = null) { Kind = kind; _payload = payload; Dimensions = dimensions; } public DataValueKind Kind { get; } public IReadOnlyList? Dimensions { get; } /// A conservative, allocation-free estimate of retained value storage, in bytes. public long EstimatedRetainedBytes { get { ThrowIfDisposed(); checked { const long baseline = 256; if (_payload is byte[] bytes) return baseline + 32L + bytes.LongLength; if (_payload is string text) return baseline + 32L + 2L * text.Length; if (_payload is ArrayPayload array) { long size = baseline + 128L + 8L * (Dimensions?.Count ?? 0) + 48L * array.Elements.LongLength; if (array.Kind == DataValueKind.String) foreach (var element in array.Elements) size += 2L * ((string)element).Length; return size; } return baseline + 32L; } } } public static DataValue Null() => new(DataValueKind.Null, null); public static DataValue FromBytes(byte[] bytes) => new(DataValueKind.Bytes, (byte[])bytes.Clone()); public static DataValue FromScalar(DataValueKind kind, object value) { ArgumentNullException.ThrowIfNull(value); var valid = kind switch { DataValueKind.Boolean => value is bool, DataValueKind.Int8 => value is sbyte, DataValueKind.Int16 => value is short, DataValueKind.Int32 => value is int, DataValueKind.Int64 => value is long, DataValueKind.UInt8 => value is byte, DataValueKind.UInt16 => value is ushort, DataValueKind.UInt32 => value is uint, DataValueKind.UInt64 => value is ulong, DataValueKind.Float => value is float, DataValueKind.Double => value is double, DataValueKind.String => value is string, DataValueKind.Timestamp => value is DateTimeOffset, DataValueKind.Guid => value is Guid, _ => false }; if (!valid) throw new ArgumentException("Unsupported value or kind mismatch.", nameof(value)); if (value is DateTimeOffset timestamp && timestamp.Offset != TimeSpan.Zero) throw new ArgumentException("Timestamp must be UTC.", nameof(value)); return new(kind, value); } /// Copies elements and shape; arrays contain one declared scalar kind, including empty arrays. public static DataValue FromArray(DataValueKind elementKind, IReadOnlyList elements, IReadOnlyList dimensions) { ArgumentNullException.ThrowIfNull(elements); ArgumentNullException.ThrowIfNull(dimensions); if (!IsSupportedArrayElementKind(elementKind)) { throw new ArgumentOutOfRangeException(nameof(elementKind)); } if (dimensions.Count == 0 || dimensions.Any(d => d < 0)) throw new ArgumentException("Invalid dimensions.", nameof(dimensions)); long count = 1; foreach (var dimension in dimensions) count = checked(count * dimension); if (count != elements.Count) throw new ArgumentException("Dimensions do not match element count.", nameof(dimensions)); var copy = new object[elements.Count]; for (var i = 0; i < copy.Length; i++) { using var scalar = FromScalar(elementKind, elements[i]); copy[i] = scalar._payload!; } return new(DataValueKind.Array, new ArrayPayload(elementKind, copy), Array.AsReadOnly(dimensions.ToArray())); } /// Whether the value kind is supported as an element of a typed array. public static bool IsSupportedArrayElementKind(DataValueKind kind) => kind is DataValueKind.Boolean or DataValueKind.Int8 or DataValueKind.Int16 or DataValueKind.Int32 or DataValueKind.Int64 or DataValueKind.UInt8 or DataValueKind.UInt16 or DataValueKind.UInt32 or DataValueKind.UInt64 or DataValueKind.Float or DataValueKind.Double or DataValueKind.String or DataValueKind.Timestamp or DataValueKind.Guid; public object GetScalar() { ThrowIfDisposed(); return Kind is DataValueKind.Null or DataValueKind.Bytes or DataValueKind.Array ? throw new InvalidOperationException() : _payload!; } public ReadOnlyMemory GetBytes() { ThrowIfDisposed(); return Kind == DataValueKind.Bytes ? ((byte[])_payload!).ToArray() : throw new InvalidOperationException(); } public DataValueKind ArrayElementKind { get { ThrowIfDisposed(); return (_payload as ArrayPayload)?.Kind ?? throw new InvalidOperationException(); } } public IReadOnlyList GetArray() { ThrowIfDisposed(); return _payload is ArrayPayload a ? Array.AsReadOnly((object[])a.Elements.Clone()) : throw new InvalidOperationException(); } public DataValue Retain() { ThrowIfDisposed(); return new(Kind, _payload, Dimensions); } /// Compares immutable owned values without exposing or duplicating their storage. internal bool ContentEquals(DataValue other) { ArgumentNullException.ThrowIfNull(other); ThrowIfDisposed(); other.ThrowIfDisposed(); if (Kind != other.Kind) return false; if (ReferenceEquals(_payload, other._payload)) return true; if (Kind == DataValueKind.Null) return true; if (_payload is byte[] bytes && other._payload is byte[] otherBytes) return bytes.AsSpan().SequenceEqual(otherBytes); if (_payload is ArrayPayload array && other._payload is ArrayPayload otherArray) { if (array.Kind != otherArray.Kind || Dimensions is null || other.Dimensions is null || Dimensions.Count != other.Dimensions.Count || array.Elements.Length != otherArray.Elements.Length) return false; for (var i = 0; i < Dimensions.Count; i++) if (Dimensions[i] != other.Dimensions[i]) return false; for (var i = 0; i < array.Elements.Length; i++) if (!Equals(array.Elements[i], otherArray.Elements[i])) return false; return true; } return Equals(_payload, other._payload); } /// Appends a private canonical value encoding without exposing or copying owned payload storage. internal void AppendSemanticFingerprint(IncrementalHash hash) { ArgumentNullException.ThrowIfNull(hash); ThrowIfDisposed(); DataFingerprintEncoding.AppendInt32(hash, 1); DataFingerprintEncoding.AppendInt32(hash, (int)Kind); if (Kind == DataValueKind.Null) return; if (Kind == DataValueKind.Bytes) { var bytes = (byte[])_payload!; DataFingerprintEncoding.AppendInt32(hash, bytes.Length); hash.AppendData(bytes); return; } if (_payload is ArrayPayload array) { DataFingerprintEncoding.AppendInt32(hash, (int)array.Kind); DataFingerprintEncoding.AppendInt32(hash, Dimensions!.Count); for (var i = 0; i < Dimensions.Count; i++) DataFingerprintEncoding.AppendInt32(hash, Dimensions[i]); DataFingerprintEncoding.AppendInt32(hash, array.Elements.Length); foreach (var element in array.Elements) DataFingerprintEncoding.AppendScalar(hash, array.Kind, element); return; } DataFingerprintEncoding.AppendScalar(hash, Kind, _payload!); } public void Dispose() => _disposed = true; private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); private sealed record ArrayPayload(DataValueKind Kind, object[] Elements); } /// Owns its value lease; timestamps are independent original timestamps, never synthesized. public sealed record DataSample(DataValue Value, uint StatusCode, DateTimeOffset? SourceTimestampUtc, DateTimeOffset? ServerTimestampUtc, ServingIdentity Serving, long Version) : IDisposable { public void Validate() { ArgumentNullException.ThrowIfNull(Value); ArgumentNullException.ThrowIfNull(Serving); Serving.Validate(requireEpochs: true); if (Version <= 0) { throw new ArgumentOutOfRangeException(nameof(Version)); } } public void Dispose() => Value.Dispose(); } public sealed record DataWriteOutcome(DataWriteState State, uint StatusCode, string? Diagnostic) { public bool IsConfirmedSuccess => State == DataWriteState.DriverConfirmedSuccess; public void Validate() => DataContractValidation.Required(State); } public sealed record DataItemHandle(string SubscriptionId, long StreamEpoch, ulong Handle, long ItemRevision) { public void Validate() { ArgumentException.ThrowIfNullOrWhiteSpace(SubscriptionId); if (StreamEpoch <= 0 || Handle == 0 || ItemRevision <= 0) throw new ArgumentOutOfRangeException(nameof(Handle)); } } /// Renewal is anchored at monotonic request start, not response receipt. public sealed record MetadataLease(long CatalogEpoch, long AuthorityEpoch, TimeSpan Duration) { public void Validate() { if (Duration <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(Duration)); } public long Deadline(long requestStartTimestamp, TimeSpan transportMargin, TimeProvider clock) { Validate(); ArgumentNullException.ThrowIfNull(clock); if (transportMargin < TimeSpan.Zero || transportMargin >= Duration) throw new ArgumentOutOfRangeException(nameof(transportMargin)); return checked(requestStartTimestamp + (long)((Duration - transportMargin).TotalSeconds * clock.TimestampFrequency)); } } public sealed record DataBudget(TimeSpan Timeout, int MaxItems, long MaxBytes) { public void Validate() { if (Timeout <= TimeSpan.Zero || MaxItems <= 0 || MaxBytes <= 0) throw new ArgumentOutOfRangeException(nameof(Timeout)); } } /// /// Data operation grants. The values are persisted (ConfigDb int) and carried on the wire (uint); never renumber. /// Bits 32..512 were RESERVED by phase X0 of the history/alarm plan. Every reader masks to /// (an unknown grant is no grant) and the authoring validator rejects a bit /// until the phase that implements it: H2 implements ; A2 the alarm bits. /// [Flags] public enum DataOperations { None = 0, Browse = 1, Metadata = 2, Read = 4, Write = 8, Subscribe = 16, /// H2: Raw/Processed/AtTime history reads. HistoryRead = 32, /// A2: root-scoped condition items (origin-side grant; plan §5.5). AlarmSubscribe = 64, /// A2b: remote condition Acknowledge and AddComment (CallConditionMethod; plan §5.6). AlarmAcknowledge = 128, /// A2b: remote condition Confirm. AlarmConfirm = 256, /// Reserved for the deferred shelve methods. AlarmShelve = 512, } /// The one authority for which bits this build understands. public static class DataOperationSets { /// The v1 operation set. public const DataOperations V1 = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; /// /// What tolerant readers keep; every other bit is dropped fail-closed. Grows only in the phase that implements /// a bit (H2 added ; A2a ; A2b /// the method bits and ). /// public const DataOperations Understood = V1 | DataOperations.HistoryRead | ConditionGrants; /// Bits reserved by X0 that no phase has implemented yet (H2 took out, /// A2a , A2b the Acknowledge/Confirm method bits). public const DataOperations Reserved = DataOperations.AlarmShelve; /// A2b: the remote condition-method grants (CallConditionMethod). public const DataOperations ConditionMethods = DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm; /// A2: every grant that travels only with the negotiated conditions feature (field 17): the /// root-scoped item grant and the method grants. A header-less call never sees any of them. public const DataOperations ConditionGrants = DataOperations.AlarmSubscribe | ConditionMethods; } /// /// Optional per-call protocol features negotiated through the x-otopcua-data-features request header. /// A call without the header (or with an empty effective set) gets exactly the v1 behaviour. /// [Flags] public enum DataFeatures { None = 0, History = 1, Conditions = 2 } /// /// Negotiated limits. When a peer omits the per-value element limit, the protocol default is 100,000. /// public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMessageBytes, int MaxMonitoredItems, int MaxStreams, long MaxPendingBytes, TimeSpan MaxMetadataLease, TimeSpan MaxSessionLifetime, TimeSpan WriteRetryWindow, int MaxValueElements = 100_000) { public void Validate() { if (MaxPageItems <= 0 || MaxBatchItems <= 0 || MaxMessageBytes <= 0 || MaxMonitoredItems <= 0 || MaxStreams <= 0 || MaxPendingBytes <= 0 || MaxMetadataLease <= TimeSpan.Zero || MaxSessionLifetime <= TimeSpan.Zero || WriteRetryWindow <= TimeSpan.Zero || MaxValueElements <= 0) { throw new ArgumentOutOfRangeException(nameof(DataLimits), "Limits must be positive."); } } } /// /// Remote history an origin can serve (plan §4.2, CapabilitiesResponse.history). Advertised only when the origin /// has a historian backend AND the call negotiated ; null otherwise. /// /// HistoryRead-Raw. /// HistoryRead-Processed (at least one aggregate served). /// HistoryRead-AtTime. /// The served aggregates, as stable HistoryAggregateType names. /// The backend's stored timestamp resolution (QuestDB µs = 10); 1 = 100 ns; 0 = undisclosed (no grant). /// The origin's per-node page ceiling for this caller. /// The origin's concurrent history reads admitted per principal. /// How long an untaken origin continuation lives. public sealed record DataHistoryCapabilities(bool Raw, bool Processed, bool AtTime, IReadOnlyList Aggregates, long TimestampResolutionTicks, int MaxValuesPerPage, int MaxConcurrentReads, TimeSpan ContinuationIdle) { public void Validate() { ArgumentNullException.ThrowIfNull(Aggregates); // Resolution 0 = undisclosed (the caller holds no HistoryRead grant on any export). if (TimestampResolutionTicks < 0 || MaxValuesPerPage <= 0 || MaxConcurrentReads <= 0 || ContinuationIdle <= TimeSpan.Zero || Aggregates.Any(string.IsNullOrWhiteSpace)) throw new ArgumentOutOfRangeException(nameof(MaxValuesPerPage), "History capabilities must be positive."); } } /// Per-node history metadata (Metadata.history); only on a call that negotiated history. /// The caller may HistoryRead this node (historized AND granted — never one without the other). public sealed record DataHistoryInfo(bool Historizing); public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness, DataOperations Operations, IReadOnlySet ValueKinds, DataLimits Limits, bool CompactBatches, int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false, bool WriteServingGenerationEnforced = false, bool SubscriptionFreshnessChallenges = false, bool MetadataItemLeases = false, DataHistoryCapabilities? History = null, DataConditionCapabilities? Conditions = null) { private readonly DataOperations _operations = Operations & DataOperationSets.Understood; /// Masked to on construction and on every with. public DataOperations Operations { get => _operations; init => _operations = value & DataOperationSets.Understood; } public void Validate() { ArgumentException.ThrowIfNullOrWhiteSpace(ClusterId); ArgumentNullException.ThrowIfNull(Serving); DataContractValidation.Required(Readiness); Serving.Validate(requireEpochs: Readiness == DataReadiness.Ready); if (ProtocolMajor <= 0 || ProtocolMinor < 0 || CompactCodecVersion < 0 || (CompactBatches && CompactCodecVersion == 0)) { throw new ArgumentOutOfRangeException(nameof(ProtocolMajor)); } ArgumentNullException.ThrowIfNull(Limits); Limits.Validate(); ArgumentNullException.ThrowIfNull(ValueKinds); foreach (var kind in ValueKinds) { DataContractValidation.Required(kind); } // Operations is masked by its accessor, so unknown bits from a newer peer never reach here (X0). History?.Validate(); Conditions?.Validate(); } } public sealed record DataMetadata(DataView View, string BrowseName, string NodeKind, DataValueKind ValueKind, int ValueRank, IReadOnlyList Dimensions, bool Writable, DataOperations AllowedOperations, long CatalogRevision, string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null, DataHistoryInfo? History = null) { public void Validate() { ArgumentNullException.ThrowIfNull(View); View.Validate(); DataContractValidation.Required(ValueKind); ArgumentNullException.ThrowIfNull(Dimensions); if (CatalogRevision <= 0 || Dimensions.Any(d => d < 0)) { throw new ArgumentOutOfRangeException(nameof(CatalogRevision)); } if (ValueKind == DataValueKind.Array && (ValueRank <= 0 || Dimensions.Count != ValueRank)) { throw new ArgumentException("Array rank and dimensions must agree.", nameof(ValueRank)); } if (ValueKind != DataValueKind.Array && (ValueRank != -1 || Dimensions.Count != 0)) { throw new ArgumentException("A scalar requires rank -1 and no dimensions.", nameof(ValueRank)); } if (ValueKind == DataValueKind.Array) { if (ArrayElementKind is not { } kind || !DataValue.IsSupportedArrayElementKind(kind)) { throw new ArgumentException("Arrays require a supported element kind.", nameof(ArrayElementKind)); } } else if (ArrayElementKind is not null) { throw new ArgumentException("Only arrays may specify an element kind.", nameof(ArrayElementKind)); } } } /// /// A per-item result. A metadata lease certifies only this returned item; its local /// request-start timestamp uses the connection's clock and is never serialized. /// public sealed record DataItemResult(string CorrelationId, DataItemStatus Status, T? Value, string? Diagnostic, MetadataLease? Lease = null, long? LeaseRequestStartedTimestamp = null); public sealed record DataBrowseBranch(DataView Parent, DataItemStatus Status, IReadOnlyList Items, bool Complete, string? Continuation, MetadataLease? Lease, ServingIdentity? Serving = null);