Files
Marc Schier 889572472f Convert DataValue from class to readonly struct for further GC relief (#3796)
Convert `DataValue` from a mutable reference type (`class`) to a `readonly struct` to eliminate per-allocation GC pressure on every attribute read, subscription publish, and history sample.

### Key API changes (user-visible)

| Before | After | Pattern |
|---|---|---|
| `class DataValue` | `readonly struct DataValue : INullable` | Foundation |
| `Equals(DataValue?)` / `operator ==(DataValue?, DataValue?)` | `Equals(DataValue)` / `operator ==(DataValue, DataValue)` | Value semantics |
| `IEncoder.WriteDataValue(string?, DataValue?)` | `IEncoder.WriteDataValue(string?, DataValue)` | Non-nullable wire API |
| `IDecoder.ReadDataValue(...) -> DataValue?` | `IDecoder.ReadDataValue(...) -> DataValue` | Same |
| `IDataChangeMonitoredItemQueue.PeekLast/Oldest()` | `TryPeekLastValue/Oldest(out DataValue)` | TryGet pattern |
| `IAggregateCalculator.GetProcessedValue(bool)` | `TryGetProcessedValue(bool, out DataValue)` | Same |
| `IUaPubSubDataStore.ReadPublishedDataItem(...)` | `TryReadPublishedDataItem(NodeId, uint, out DataValue)` | Same |
| `Dictionary<uint, DataValue?>` (NodeCacheContext) | `Dictionary<uint, DataValue>` | Default + IsNull |
| `IHistoryDataSource.FirstRaw/NextRaw` | `TryFirstRaw/TryNextRaw(out DataValue)` | TryGet pattern |
| `NodeState.ReadAttribute(... DataValue)` | `NodeState.ReadAttribute(... ref DataValue)` | Sync mutation via ref |
| `NodeState.ReadAttributeAsync(... DataValue)` | `NodeState.ReadAttributeAsync(...) -> ValueTask<(ServiceResult, DataValue)>` | Async return tuple |
| `obj as DataValue` (heterogeneous Dictionary<string, object>) | `obj is DataValue dv ? dv : default(DataValue)` | Safe struct cast |
| `Assert.That(dv, Is.Not.Null)` (tests) | `Assert.That(dv.IsNull, Is.False)` | Struct test pattern |
| `[Obsolete] Value` setter, all property setters | Removed; use ctor or `With*()` | Immutability |
| `[DataContract]` + `[DataMember]` | Removed; surrogate via `SerializableDataValue` + `DataValueSurrogateProvider` | Serialization |

### Wire format

Wire format is **byte-identical** to the previous class-based implementation across binary / JSON / XML encoders. Default DataValue (`.IsNull == true`) is treated as the equivalent of the old null reference (writes JSON `null`, binary `byte 0`, XML omitted element).

### Why TryGet pattern (instead of leaving `DataValue?`)

For methods that previously returned `DataValue?` to signal "no value available" (queue peek, aggregate result, data store lookup, history navigation), the conversion to `bool TryGet(out DataValue)` matches BCL conventions (`Dictionary.TryGetValue`, `Queue.TryPeek`, `Int32.TryParse`) and gives the caller an explicit "may be absent" affordance without `Nullable<DataValue>` overhead.

### Breaking changes summary

- `DataValue` is now a `readonly struct` - boxing/unboxing semantics change for callers using `object`-typed APIs.
- `IEncoder.WriteDataValue` / `IDecoder.ReadDataValue` / `ReadDataValueArray` interface signatures lose the `Nullable` wrapper.
- `IDataChangeMonitoredItemQueue.PeekLastValue` / `PeekOldestValue` -> `TryPeekLastValue` / `TryPeekOldestValue` (out parameter).
- `IAggregateCalculator.GetProcessedValue` -> `TryGetProcessedValue` (out parameter).
- `IUaPubSubDataStore.ReadPublishedDataItem` -> `TryReadPublishedDataItem` (out parameter).
- `NodeState.ReadAttribute` takes `ref DataValue`; `ReadAttributeAsync` returns `ValueTask<(ServiceResult, DataValue)>`.
- `DataValue` property setters removed (use constructor + `With*` mutators).
2026-05-23 11:38:49 +02:00

174 lines
6.6 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Opc.Ua.PubSub
{
/// <summary>
/// DataStore is a repository where Publisher applications will push data values for nodes + attributes published in data sets
/// </summary>
public class UaPubSubDataStore : IUaPubSubDataStore
{
private readonly Lock m_lock = new();
private readonly Dictionary<NodeId, Dictionary<uint, DataValue>> m_store;
/// <summary>
/// Create new instance of <see cref="UaPubSubDataStore"/>
/// </summary>
public UaPubSubDataStore()
{
m_store = [];
}
/// <summary>
/// Write a value to the DataStore.
/// The value is identified by node NodeId.
/// </summary>
/// <param name="nodeId">NodeId identifier for value that will be stored.</param>
/// <param name="value">The value to be store. The value is NOT copied.</param>
/// <param name="status">The status associated with the value.</param>
/// <param name="timestamp">The timestamp associated with the value.</param>
/// <exception cref="ArgumentException"><paramref name="nodeId"/></exception>
public void WritePublishedDataItem(
NodeId nodeId,
Variant value,
StatusCode? status = null,
DateTime? timestamp = null)
{
if (nodeId.IsNull)
{
throw new ArgumentException(null, nameof(nodeId));
}
lock (m_lock)
{
var dv = new DataValue(
value,
status ?? StatusCodes.Good,
timestamp ?? DateTimeUtc.Now);
if (!m_store.TryGetValue(nodeId, out Dictionary<uint, DataValue>? dictionary))
{
dictionary = [];
m_store.Add(nodeId, dictionary);
}
dictionary[Attributes.Value] = dv;
}
}
/// <summary>
/// Write a DataValue to the DataStore.
/// The DataValue is identified by node NodeId and Attribute.
/// </summary>
/// <param name="nodeId">NodeId identifier for DataValue that will be stored</param>
/// <param name="attributeId">Default value is <see cref="Attributes.Value"/>.</param>
/// <param name="dataValue">Default value is null. </param>
/// <exception cref="ArgumentException"><paramref name="nodeId"/></exception>
public void WritePublishedDataItem(
NodeId nodeId,
uint attributeId = Attributes.Value,
DataValue dataValue = default)
{
if (nodeId.IsNull)
{
throw new ArgumentException(null, nameof(nodeId));
}
if (attributeId == 0)
{
attributeId = Attributes.Value;
}
if (!Attributes.IsValid(attributeId))
{
throw new ArgumentException(null, nameof(attributeId));
}
lock (m_lock)
{
if (m_store.TryGetValue(nodeId, out Dictionary<uint, DataValue>? value))
{
value[attributeId] = dataValue;
}
else
{
var dictionary = new Dictionary<uint, DataValue>
{
{ attributeId, dataValue }
};
m_store.Add(nodeId, dictionary);
}
}
}
/// <summary>
/// Try to read the DataValue stored for a specific NodeId and Attribute.
/// </summary>
/// <param name="nodeId">NodeId identifier of node</param>
/// <param name="attributeId">Default value is <see cref="Attributes.Value"/></param>
/// <param name="dataValue">The stored DataValue when this method returns <c>true</c>.</param>
/// <returns><c>true</c> if a DataValue is stored for the given NodeId and Attribute; otherwise <c>false</c>.</returns>
/// <exception cref="ArgumentException"><paramref name="nodeId"/></exception>
public bool TryReadPublishedDataItem(NodeId nodeId, uint attributeId, out DataValue dataValue)
{
if (nodeId.IsNull)
{
throw new ArgumentException(null, nameof(nodeId));
}
if (attributeId == 0)
{
attributeId = Attributes.Value;
}
if (!Attributes.IsValid(attributeId))
{
throw new ArgumentException(null, nameof(attributeId));
}
lock (m_lock)
{
if (m_store.TryGetValue(nodeId, out Dictionary<uint, DataValue>? dictionary) &&
dictionary.TryGetValue(attributeId, out DataValue value))
{
dataValue = value;
return true;
}
}
dataValue = default;
return false;
}
/// <summary>
/// Updates the metadata.
/// </summary>
public void UpdateMetaData(PublishedDataSetDataType publishedDataSet)
{
}
}
}