feat: define validated grpc data contracts and codecs
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,246 @@
|
||||
using Google.Protobuf;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using Wire = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
||||
|
||||
/// <summary>Explicit typed values only; limits are checked before constructing domain arrays.</summary>
|
||||
public static class TypedValueCodec
|
||||
{
|
||||
public const int DefaultMaxElements = 100_000;
|
||||
public const int DefaultMaxBytes = 4 * 1024 * 1024;
|
||||
public const int MaxDimensions = 16;
|
||||
|
||||
public static Wire.TypedValue Encode(DataValue value)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
var result = new Wire.TypedValue { Kind = (Wire.ValueKind)value.Kind };
|
||||
if (value.Kind == DataValueKind.Null)
|
||||
return result;
|
||||
if (value.Kind == DataValueKind.Bytes)
|
||||
{
|
||||
result.BytesValue = ByteString.CopyFrom(value.GetBytes().Span);
|
||||
return result;
|
||||
}
|
||||
if (value.Kind == DataValueKind.Array)
|
||||
{
|
||||
var array = new Wire.TypedArray
|
||||
{
|
||||
ElementKind = (Wire.ValueKind)value.ArrayElementKind,
|
||||
};
|
||||
array.Dimensions.AddRange(value.Dimensions!.Select(x => checked((uint)x)));
|
||||
foreach (var element in value.GetArray())
|
||||
{
|
||||
using var scalar = DataValue.FromScalar(value.ArrayElementKind, element);
|
||||
array.Elements.Add(Encode(scalar));
|
||||
}
|
||||
result.Array = array;
|
||||
return result;
|
||||
}
|
||||
var scalarValue = value.GetScalar();
|
||||
switch (value.Kind)
|
||||
{
|
||||
case DataValueKind.Boolean:
|
||||
result.Boolean = (bool)scalarValue;
|
||||
break;
|
||||
case DataValueKind.Int8:
|
||||
result.Signed = (sbyte)scalarValue;
|
||||
break;
|
||||
case DataValueKind.Int16:
|
||||
result.Signed = (short)scalarValue;
|
||||
break;
|
||||
case DataValueKind.Int32:
|
||||
result.Signed = (int)scalarValue;
|
||||
break;
|
||||
case DataValueKind.Int64:
|
||||
result.Signed = (long)scalarValue;
|
||||
break;
|
||||
case DataValueKind.UInt8:
|
||||
result.Unsigned = (byte)scalarValue;
|
||||
break;
|
||||
case DataValueKind.UInt16:
|
||||
result.Unsigned = (ushort)scalarValue;
|
||||
break;
|
||||
case DataValueKind.UInt32:
|
||||
result.Unsigned = (uint)scalarValue;
|
||||
break;
|
||||
case DataValueKind.UInt64:
|
||||
result.Unsigned = (ulong)scalarValue;
|
||||
break;
|
||||
case DataValueKind.Float:
|
||||
result.FloatValue = (float)scalarValue;
|
||||
break;
|
||||
case DataValueKind.Double:
|
||||
result.DoubleValue = (double)scalarValue;
|
||||
break;
|
||||
case DataValueKind.String:
|
||||
result.StringValue = (string)scalarValue;
|
||||
break;
|
||||
case DataValueKind.Timestamp:
|
||||
result.Timestamp = Timestamp.FromDateTimeOffset((DateTimeOffset)scalarValue);
|
||||
break;
|
||||
case DataValueKind.Guid:
|
||||
result.Guid = ((Guid)scalarValue).ToString("D");
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentException("Unsupported value kind.", nameof(value));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static DataValue Decode(
|
||||
Wire.TypedValue value,
|
||||
int maxElements = DefaultMaxElements,
|
||||
int maxBytes = DefaultMaxBytes
|
||||
)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(value);
|
||||
if (maxElements <= 0 || maxBytes <= 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(maxElements));
|
||||
if (value.CalculateSize() > maxBytes || DecodedBytes(value, maxBytes) > maxBytes)
|
||||
throw new ArgumentException("Decoded value exceeds budget.");
|
||||
return DecodeCore(value, maxElements, maxBytes);
|
||||
}
|
||||
|
||||
internal static long DecodedBytes(Wire.TypedValue value, long limit)
|
||||
{
|
||||
long size = 32;
|
||||
if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.StringValue)
|
||||
size += (long)value.StringValue.Length * sizeof(char);
|
||||
else if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.BytesValue)
|
||||
size += (long)value.BytesValue.Length * 2;
|
||||
else if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Guid)
|
||||
size += (long)value.Guid.Length * sizeof(char);
|
||||
else if (value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Array)
|
||||
{
|
||||
var array = value.Array;
|
||||
size +=
|
||||
(long)array.Dimensions.Count * sizeof(int) * 2
|
||||
+ (long)array.Elements.Count * (IntPtr.Size * 2 + 32);
|
||||
if (size > limit)
|
||||
return size;
|
||||
foreach (var item in array.Elements)
|
||||
{
|
||||
if ((DataValueKind)item.Kind == DataValueKind.Array)
|
||||
throw new ArgumentException("Nested arrays are unsupported.");
|
||||
size += DecodedBytes(item, limit - size);
|
||||
if (size > limit)
|
||||
return size;
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
internal static DateTimeOffset DecodeTimestamp(Timestamp value)
|
||||
{
|
||||
if (value.Nanos % 100 != 0)
|
||||
throw new ArgumentException("Timestamp is finer than domain tick precision.");
|
||||
return value.ToDateTimeOffset();
|
||||
}
|
||||
|
||||
private static DataValue DecodeCore(Wire.TypedValue value, int maxElements, int maxBytes)
|
||||
{
|
||||
var kind = (DataValueKind)value.Kind;
|
||||
if (
|
||||
kind == DataValueKind.Null
|
||||
&& value.PayloadCase == Wire.TypedValue.PayloadOneofCase.None
|
||||
)
|
||||
return DataValue.Null();
|
||||
if (
|
||||
kind == DataValueKind.Array
|
||||
&& value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Array
|
||||
)
|
||||
{
|
||||
var a = value.Array;
|
||||
if (
|
||||
a.Dimensions.Count == 0
|
||||
|| a.Dimensions.Count > MaxDimensions
|
||||
|| a.Elements.Count > maxElements
|
||||
|| (long)a.Elements.Count * IntPtr.Size > maxBytes
|
||||
)
|
||||
throw new ArgumentException("Array exceeds budget.");
|
||||
long count = 1;
|
||||
foreach (var d in a.Dimensions)
|
||||
{
|
||||
if (d > int.MaxValue || (d != 0 && count > maxElements / (long)d))
|
||||
throw new ArgumentException("Invalid array dimensions.");
|
||||
count *= d;
|
||||
}
|
||||
if (count != a.Elements.Count)
|
||||
throw new ArgumentException("Array shape mismatch.");
|
||||
var elementKind = (DataValueKind)a.ElementKind;
|
||||
if (
|
||||
elementKind
|
||||
is DataValueKind.Unspecified
|
||||
or DataValueKind.Null
|
||||
or DataValueKind.Array
|
||||
or DataValueKind.Bytes
|
||||
|| !System.Enum.IsDefined(elementKind)
|
||||
)
|
||||
throw new ArgumentException("Unsupported array kind.");
|
||||
var elements = new object[a.Elements.Count];
|
||||
for (int i = 0; i < elements.Length; i++)
|
||||
{
|
||||
if ((DataValueKind)a.Elements[i].Kind != elementKind)
|
||||
throw new ArgumentException("Array element kind mismatch.");
|
||||
using var item = DecodeCore(a.Elements[i], maxElements, maxBytes);
|
||||
elements[i] = item.GetScalar();
|
||||
}
|
||||
return DataValue.FromArray(
|
||||
elementKind,
|
||||
elements,
|
||||
a.Dimensions.Select(x => checked((int)x)).ToArray()
|
||||
);
|
||||
}
|
||||
object scalar = kind switch
|
||||
{
|
||||
DataValueKind.Boolean
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Boolean => value.Boolean,
|
||||
DataValueKind.Int8 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
|
||||
checked((sbyte)value.Signed),
|
||||
DataValueKind.Int16 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
|
||||
checked((short)value.Signed),
|
||||
DataValueKind.Int32 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
|
||||
checked((int)value.Signed),
|
||||
DataValueKind.Int64 when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Signed =>
|
||||
value.Signed,
|
||||
DataValueKind.UInt8
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned => checked(
|
||||
(byte)value.Unsigned
|
||||
),
|
||||
DataValueKind.UInt16
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned => checked(
|
||||
(ushort)value.Unsigned
|
||||
),
|
||||
DataValueKind.UInt32
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned => checked(
|
||||
(uint)value.Unsigned
|
||||
),
|
||||
DataValueKind.UInt64
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Unsigned =>
|
||||
value.Unsigned,
|
||||
DataValueKind.Float
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.FloatValue =>
|
||||
value.FloatValue,
|
||||
DataValueKind.Double
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.DoubleValue =>
|
||||
value.DoubleValue,
|
||||
DataValueKind.String
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.StringValue =>
|
||||
value.StringValue,
|
||||
DataValueKind.Timestamp
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Timestamp =>
|
||||
DecodeTimestamp(value.Timestamp),
|
||||
DataValueKind.Guid when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.Guid =>
|
||||
Guid.ParseExact(value.Guid, "D"),
|
||||
DataValueKind.Bytes
|
||||
when value.PayloadCase == Wire.TypedValue.PayloadOneofCase.BytesValue =>
|
||||
value.BytesValue.ToByteArray(),
|
||||
_ => throw new ArgumentException("Invalid or unsupported typed value."),
|
||||
};
|
||||
return kind == DataValueKind.Bytes
|
||||
? DataValue.FromBytes((byte[])scalar)
|
||||
: DataValue.FromScalar(kind, scalar);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.Protos;
|
||||
|
||||
/// <summary>Frozen wire contract identifiers; removed field numbers must remain reserved.</summary>
|
||||
public static class DataConnectionProtoContract
|
||||
{
|
||||
public const int ProtocolMajor = 1;
|
||||
public const int ProtocolMinor = 0;
|
||||
public const int CompactCodecVersion = 1;
|
||||
|
||||
public static void Validate()
|
||||
{
|
||||
if (
|
||||
TypedValue.KindFieldNumber != 1
|
||||
|| Sample.StatusCodeFieldNumber != 2
|
||||
|| SubscriptionFrame.CompactValuesFieldNumber != 7
|
||||
|| (int)ValueKind.Unspecified != 0
|
||||
)
|
||||
throw new InvalidOperationException("Data connection wire contract changed.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
syntax = "proto3";
|
||||
package data_connection.v1;
|
||||
option csharp_namespace = "ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1";
|
||||
import "google/protobuf/timestamp.proto";
|
||||
service DataConnectionService {
|
||||
rpc GetCapabilities(CapabilitiesRequest) returns (CapabilitiesResponse);
|
||||
rpc Browse(BrowseRequest) returns (BrowseResponse);
|
||||
rpc GetMetadata(MetadataRequest) returns (MetadataResponse);
|
||||
rpc Read(ReadRequest) returns (ReadResponse);
|
||||
rpc Write(WriteRequest) returns (WriteResponse);
|
||||
rpc Subscribe(stream SubscriptionCommand) returns (stream SubscriptionFrame);
|
||||
}
|
||||
enum ValueKind {
|
||||
VALUE_KIND_UNSPECIFIED = 0;
|
||||
VALUE_KIND_NULL = 1;
|
||||
VALUE_KIND_BOOLEAN = 2;
|
||||
VALUE_KIND_INT8 = 3;
|
||||
VALUE_KIND_INT16 = 4;
|
||||
VALUE_KIND_INT32 = 5;
|
||||
VALUE_KIND_INT64 = 6;
|
||||
VALUE_KIND_UINT8 = 7;
|
||||
VALUE_KIND_UINT16 = 8;
|
||||
VALUE_KIND_UINT32 = 9;
|
||||
VALUE_KIND_UINT64 = 10;
|
||||
VALUE_KIND_FLOAT = 11;
|
||||
VALUE_KIND_DOUBLE = 12;
|
||||
VALUE_KIND_STRING = 13;
|
||||
VALUE_KIND_BYTES = 14;
|
||||
VALUE_KIND_TIMESTAMP = 15;
|
||||
VALUE_KIND_GUID = 16;
|
||||
VALUE_KIND_ARRAY = 17;
|
||||
}
|
||||
message TypedValue {
|
||||
ValueKind kind = 1;
|
||||
oneof payload {
|
||||
bool boolean = 2;
|
||||
sint64 signed = 3;
|
||||
uint64 unsigned = 4;
|
||||
float float_value = 5;
|
||||
double double_value = 6;
|
||||
string string_value = 7;
|
||||
bytes bytes_value = 8;
|
||||
google.protobuf.Timestamp timestamp = 9;
|
||||
string guid = 10;
|
||||
TypedArray array = 11;
|
||||
}
|
||||
}
|
||||
message TypedArray {
|
||||
ValueKind element_kind = 1;
|
||||
repeated uint32 dimensions = 2;
|
||||
repeated TypedValue elements = 3;
|
||||
}
|
||||
message Address {
|
||||
string origin_cluster_id = 1;
|
||||
string namespace_uri = 2;
|
||||
string identifier_kind = 3;
|
||||
string identifier = 4;
|
||||
}
|
||||
message View {
|
||||
Address address = 1;
|
||||
int32 realm = 2;
|
||||
optional string mapping_id = 3;
|
||||
int64 mapping_revision = 4;
|
||||
string subject = 5;
|
||||
}
|
||||
message Serving {
|
||||
string node_id = 1;
|
||||
string incarnation = 2;
|
||||
string role = 3;
|
||||
int64 catalog_epoch = 4;
|
||||
int64 authority_epoch = 5;
|
||||
}
|
||||
message Sample {
|
||||
TypedValue value = 1;
|
||||
uint32 status_code = 2;
|
||||
google.protobuf.Timestamp source_timestamp = 3;
|
||||
google.protobuf.Timestamp server_timestamp = 4;
|
||||
Serving serving = 5;
|
||||
int64 version = 6;
|
||||
}
|
||||
message Budget {
|
||||
int64 timeout_ticks = 1;
|
||||
int32 max_items = 2;
|
||||
int64 max_bytes = 3;
|
||||
}
|
||||
message Limits {
|
||||
int32 max_page_items = 1;
|
||||
int32 max_batch_items = 2;
|
||||
int32 max_message_bytes = 3;
|
||||
int32 max_monitored_items = 4;
|
||||
int32 max_streams = 5;
|
||||
int64 max_pending_bytes = 6;
|
||||
int64 max_metadata_lease_ticks = 7;
|
||||
int64 max_session_lifetime_ticks = 8;
|
||||
int64 write_retry_window_ticks = 9;
|
||||
optional int32 max_value_elements = 10;
|
||||
}
|
||||
message CapabilitiesRequest {
|
||||
int32 protocol_major = 1;
|
||||
int32 protocol_minor = 2;
|
||||
}
|
||||
message CapabilitiesResponse {
|
||||
int32 protocol_major = 1;
|
||||
int32 protocol_minor = 2;
|
||||
Serving serving = 3;
|
||||
int32 readiness = 4;
|
||||
uint32 operations = 5;
|
||||
repeated ValueKind value_kinds = 6;
|
||||
Limits limits = 7;
|
||||
bool compact_batches = 8;
|
||||
int32 compact_codec_version = 9;
|
||||
string cluster_id = 10;
|
||||
}
|
||||
message Metadata {
|
||||
View view = 1;
|
||||
string browse_name = 2;
|
||||
string node_kind = 3;
|
||||
ValueKind value_kind = 4;
|
||||
int32 value_rank = 5;
|
||||
repeated int32 dimensions = 6;
|
||||
bool writable = 7;
|
||||
uint32 allowed_operations = 8;
|
||||
int64 catalog_revision = 9;
|
||||
optional string stable_source_id = 10;
|
||||
optional string engineering_units = 11;
|
||||
bool is_stale = 12;
|
||||
optional ValueKind array_element_kind = 13;
|
||||
}
|
||||
message Lease {
|
||||
int64 catalog_epoch = 1;
|
||||
int64 authority_epoch = 2;
|
||||
int64 duration_ticks = 3;
|
||||
}
|
||||
message BrowseRequest {
|
||||
View parent = 1;
|
||||
optional string filter = 2;
|
||||
optional string continuation = 3;
|
||||
Budget budget = 4;
|
||||
}
|
||||
message BrowseResponse {
|
||||
View parent = 1;
|
||||
int32 status = 2;
|
||||
repeated Metadata items = 3;
|
||||
bool complete = 4;
|
||||
optional string continuation = 5;
|
||||
Lease lease = 6;
|
||||
}
|
||||
message MetadataRequest {
|
||||
repeated View views = 1;
|
||||
Budget budget = 2;
|
||||
}
|
||||
message MetadataResult {
|
||||
string correlation_id = 1;
|
||||
int32 status = 2;
|
||||
Metadata value = 3;
|
||||
optional string diagnostic = 4;
|
||||
}
|
||||
message MetadataResponse { repeated MetadataResult items = 1; }
|
||||
message ReadItem {
|
||||
string correlation_id = 1;
|
||||
View view = 2;
|
||||
optional int64 maximum_age_ticks = 3;
|
||||
}
|
||||
message ReadRequest {
|
||||
repeated ReadItem items = 1;
|
||||
Budget budget = 2;
|
||||
}
|
||||
message ReadResult {
|
||||
string correlation_id = 1;
|
||||
int32 status = 2;
|
||||
int32 readiness = 3;
|
||||
optional int64 age_ticks = 4;
|
||||
Sample sample = 5;
|
||||
optional string diagnostic = 6;
|
||||
}
|
||||
message ReadResponse { repeated ReadResult items = 1; }
|
||||
message WriteItem {
|
||||
string correlation_id = 1;
|
||||
string operation_id = 2;
|
||||
View view = 3;
|
||||
TypedValue value = 4;
|
||||
int64 expected_catalog_revision = 5;
|
||||
string expected_serving_incarnation = 6;
|
||||
int64 remaining_budget_ticks = 7;
|
||||
}
|
||||
message WriteRequest {
|
||||
repeated WriteItem items = 1;
|
||||
Budget budget = 2;
|
||||
}
|
||||
message WriteResult {
|
||||
string correlation_id = 1;
|
||||
int32 state = 2;
|
||||
uint32 status_code = 3;
|
||||
optional string diagnostic = 4;
|
||||
}
|
||||
message WriteResponse { repeated WriteResult items = 1; }
|
||||
message Handle {
|
||||
string subscription_id = 1;
|
||||
int64 stream_epoch = 2;
|
||||
uint64 handle = 3;
|
||||
int64 item_revision = 4;
|
||||
}
|
||||
message Settings {
|
||||
int64 sampling_ticks = 1;
|
||||
int64 publishing_ticks = 2;
|
||||
int32 trigger = 3;
|
||||
optional double deadband = 4;
|
||||
}
|
||||
message SubscriptionItem {
|
||||
string client_item_id = 1;
|
||||
View view = 2;
|
||||
Settings settings = 3;
|
||||
}
|
||||
message SubscriptionCommand {
|
||||
string subscription_id = 1;
|
||||
int64 stream_epoch = 2;
|
||||
string command_id = 3;
|
||||
int64 acknowledgement_timeout_ticks = 4;
|
||||
oneof command {
|
||||
Open open = 5;
|
||||
ItemChanges add = 6;
|
||||
ItemChanges modify = 7;
|
||||
HandleChanges remove = 8;
|
||||
}
|
||||
}
|
||||
message Open {
|
||||
repeated SubscriptionItem items = 1;
|
||||
bool watch_catalog_only = 2;
|
||||
int64 session_lifetime_ticks = 3;
|
||||
Budget snapshot_budget = 4;
|
||||
}
|
||||
message ItemChanges { repeated SubscriptionItem items = 1; }
|
||||
message HandleChanges { repeated Handle items = 1; }
|
||||
message ItemAck {
|
||||
string client_item_id = 1;
|
||||
int32 status = 2;
|
||||
Handle handle = 3;
|
||||
Settings revised_settings = 4;
|
||||
optional string diagnostic = 5;
|
||||
}
|
||||
message Ack {
|
||||
string command_id = 1;
|
||||
repeated ItemAck items = 2;
|
||||
}
|
||||
message Watermark {
|
||||
int32 partition_id = 1;
|
||||
int64 version = 2;
|
||||
}
|
||||
message Control {
|
||||
int32 kind = 1;
|
||||
repeated Watermark watermarks = 2;
|
||||
int64 catalog_epoch = 3;
|
||||
int64 authority_epoch = 4;
|
||||
optional string diagnostic = 5;
|
||||
}
|
||||
message ValueUpdate {
|
||||
Handle handle = 1;
|
||||
Sample sample = 2;
|
||||
}
|
||||
message Values {
|
||||
bool is_snapshot = 1;
|
||||
repeated ValueUpdate items = 2;
|
||||
}
|
||||
// Override messages distinguish absent timestamp from an inherited default.
|
||||
message TimestampOverride { google.protobuf.Timestamp value = 1; }
|
||||
message CompactUpdate {
|
||||
uint64 handle = 1;
|
||||
int64 item_revision = 2;
|
||||
int64 version = 3;
|
||||
TypedValue value = 4;
|
||||
optional uint32 status_code = 5;
|
||||
TimestampOverride source_timestamp = 6;
|
||||
TimestampOverride server_timestamp = 7;
|
||||
}
|
||||
message CompactValues {
|
||||
bool is_snapshot = 1;
|
||||
Serving serving = 2;
|
||||
uint32 default_status_code = 3;
|
||||
google.protobuf.Timestamp default_source_timestamp = 4;
|
||||
google.protobuf.Timestamp default_server_timestamp = 5;
|
||||
repeated CompactUpdate items = 6;
|
||||
}
|
||||
message SubscriptionFrame {
|
||||
string subscription_id = 1;
|
||||
int64 stream_epoch = 2;
|
||||
int64 sequence = 3;
|
||||
oneof frame {
|
||||
Ack ack = 4;
|
||||
Control control = 5;
|
||||
Values values = 6;
|
||||
CompactValues compact_values = 7;
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@
|
||||
<Protobuf Include="Protos\deployment_artifact.proto" GrpcServices="Both"/>
|
||||
<Protobuf Include="Protos\telemetry.proto" GrpcServices="Both"/>
|
||||
<Protobuf Include="Protos\mesh_transport.proto" GrpcServices="Both"/>
|
||||
<Protobuf Include="Protos\data_connection.proto" GrpcServices="Both"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>Origin-qualified public identity; namespace indexes are never portable identities.</summary>
|
||||
public sealed record DataAddress(string OriginClusterId, string NamespaceUri, string IdentifierKind, string Identifier)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(OriginClusterId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(NamespaceUri);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(IdentifierKind);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(Identifier);
|
||||
}
|
||||
}
|
||||
public enum DataRealm { Unspecified = 0, Raw = 1, Uns = 2 }
|
||||
public enum DataTargetMode { Unspecified = 0, Node = 1, Cluster = 2 }
|
||||
public enum DataConsistency { Unspecified = 0, Primary = 1, ReadyReplica = 2 }
|
||||
|
||||
/// <summary>A request is bound to a cluster and, for node mode, an expected node.</summary>
|
||||
public sealed record DataTarget(DataTargetMode Mode, string ExpectedClusterId, string? ExpectedNodeId)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
DataContractValidation.Required(Mode);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedClusterId);
|
||||
if (Mode == DataTargetMode.Node) ArgumentException.ThrowIfNullOrWhiteSpace(ExpectedNodeId);
|
||||
if (Mode == DataTargetMode.Cluster && ExpectedNodeId is not null)
|
||||
throw new ArgumentException("Cluster targets cannot pin a node.", nameof(ExpectedNodeId));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The requested view, independent of backing-source identity. Subject is an untrusted claim until
|
||||
/// resolved against the authoritative catalog; it must not independently grant access.
|
||||
/// </summary>
|
||||
public sealed record DataView(DataAddress Address, DataRealm Realm, string? MappingId, long MappingRevision, string Subject)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(Address); Address.Validate();
|
||||
DataContractValidation.Required(Realm);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(Subject);
|
||||
if (MappingRevision < 0 || (MappingId is null && MappingRevision != 0) ||
|
||||
(MappingId is not null && (string.IsNullOrWhiteSpace(MappingId) || MappingRevision == 0)))
|
||||
throw new ArgumentException("Mapped views require an ID and positive revision.");
|
||||
}
|
||||
}
|
||||
/// <summary>Actual serving replica provenance, distinct from origin ownership.</summary>
|
||||
public sealed record ServingIdentity(string NodeId, string Incarnation, string Role, long CatalogEpoch, long AuthorityEpoch)
|
||||
{
|
||||
public void Validate(bool requireEpochs = false)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(NodeId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(Incarnation);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(Role);
|
||||
if (CatalogEpoch < 0 || AuthorityEpoch < 0 || (requireEpochs && (CatalogEpoch == 0 || AuthorityEpoch == 0)))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(CatalogEpoch));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataSourceIdentity(DataAddress Address, string StableSourceId, ServingIdentity Serving, DataTargetMode TargetMode,
|
||||
DataConsistency Consistency, string PrincipalId, string ExportScope);
|
||||
|
||||
public static class DataContractValidation
|
||||
{
|
||||
/// <summary>Reject zero and unrecognized values for a required enum decision.</summary>
|
||||
public static void Required<T>(T value) where T : struct, Enum
|
||||
{
|
||||
if (Convert.ToInt64(value) == 0 || !Enum.IsDefined(value))
|
||||
throw new ArgumentOutOfRangeException(nameof(value), value, "A defined nonzero value is required.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
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 }
|
||||
|
||||
/// <summary>
|
||||
/// Owned immutable value. Factory methods copy mutable inputs; Retain creates an independently
|
||||
/// disposable lease. Consumers must dispose every lease after asynchronous use completes.
|
||||
/// </summary>
|
||||
public sealed class DataValue : IDisposable
|
||||
{
|
||||
private readonly object? _payload;
|
||||
private bool _disposed;
|
||||
private DataValue(DataValueKind kind, object? payload, IReadOnlyList<int>? dimensions = null)
|
||||
{ Kind = kind; _payload = payload; Dimensions = dimensions; }
|
||||
public DataValueKind Kind { get; }
|
||||
public IReadOnlyList<int>? Dimensions { get; }
|
||||
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);
|
||||
}
|
||||
/// <summary>Copies elements and shape; arrays contain one declared scalar kind, including empty arrays.</summary>
|
||||
public static DataValue FromArray(DataValueKind elementKind, IReadOnlyList<object> elements, IReadOnlyList<int> 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()));
|
||||
}
|
||||
/// <summary>Whether the value kind is supported as an element of a typed array.</summary>
|
||||
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<byte> 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<object> 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); }
|
||||
public void Dispose() => _disposed = true;
|
||||
private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
private sealed record ArrayPayload(DataValueKind Kind, object[] Elements);
|
||||
}
|
||||
|
||||
/// <summary>Owns its value lease; timestamps are independent original timestamps, never synthesized.</summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
/// <summary>Renewal is anchored at monotonic request start, not response receipt.</summary>
|
||||
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)); }
|
||||
}
|
||||
[Flags] public enum DataOperations { None = 0, Browse = 1, Metadata = 2, Read = 4, Write = 8, Subscribe = 16 }
|
||||
/// <summary>
|
||||
/// Negotiated limits. When a peer omits the per-value element limit, the protocol default is 100,000.
|
||||
/// </summary>
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness,
|
||||
DataOperations Operations, IReadOnlySet<DataValueKind> ValueKinds, DataLimits Limits, bool CompactBatches,
|
||||
int CompactCodecVersion, string ClusterId)
|
||||
{
|
||||
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);
|
||||
}
|
||||
const DataOperations known = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read |
|
||||
DataOperations.Write | DataOperations.Subscribe;
|
||||
if ((Operations & ~known) != 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Operations));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataMetadata(DataView View, string BrowseName, string NodeKind, DataValueKind ValueKind, int ValueRank,
|
||||
IReadOnlyList<int> Dimensions, bool Writable, DataOperations AllowedOperations, long CatalogRevision,
|
||||
string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = 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));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataItemResult<T>(string CorrelationId, DataItemStatus Status, T? Value, string? Diagnostic);
|
||||
public sealed record DataBrowseBranch(DataView Parent, DataItemStatus Status, IReadOnlyList<DataMetadata> Items,
|
||||
bool Complete, string? Continuation, MetadataLease? Lease);
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// A caller-bound facade. Direct access needs no namespace mount; every operation applies the
|
||||
/// bound caller's authority and retains the same policy and outcomes.
|
||||
/// </summary>
|
||||
public interface IDataConnection : IDataCatalogService, IDataReadService, IDataWriteService, IDataSubscriptionService, IAsyncDisposable
|
||||
{
|
||||
DataTarget Target { get; }
|
||||
TimeProvider Clock { get; }
|
||||
Task<DataCapabilities> GetCapabilitiesAsync(DataBudget budget, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Authenticated authority established by the host, never supplied by an operation payload.
|
||||
/// CredentialVersion is a non-secret authority fingerprint, not a bearer credential. The original
|
||||
/// expiry is retained so renewal or replacement cannot extend an already admitted operation.
|
||||
/// </summary>
|
||||
public sealed record DataAuthenticatedContext(string PrincipalId, string ApiKeyId, string CredentialVersion,
|
||||
DateTimeOffset? CredentialExpiresUtc, long AuthorityEpoch)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(PrincipalId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ApiKeyId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(CredentialVersion);
|
||||
if (CredentialExpiresUtc is { Offset: var offset } && offset != TimeSpan.Zero)
|
||||
{
|
||||
throw new ArgumentException("Credential expiry must be UTC.", nameof(CredentialExpiresUtc));
|
||||
}
|
||||
if (AuthorityEpoch <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(AuthorityEpoch));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates strictly caller-bound local facades. Hosts construct context from authenticated
|
||||
/// authority, never from caller-supplied request fields, and must validate it before creation.
|
||||
/// </summary>
|
||||
public interface IDataConnectionFactory
|
||||
{
|
||||
IDataConnection Create(DataAuthenticatedContext context, DataTarget target);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
public sealed record BrowseRequest(DataView Parent, string? Filter, string? Continuation, DataBudget Budget);
|
||||
public sealed record MetadataRequest(IReadOnlyList<DataView> Views, DataBudget Budget);
|
||||
public sealed record ReadItem(string CorrelationId, DataView View, TimeSpan? MaximumAge);
|
||||
public sealed record ReadRequest(IReadOnlyList<ReadItem> Items, DataBudget Budget);
|
||||
/// <summary>Sample is owned by the recipient. Status/age/readiness are distinct from original sample quality.</summary>
|
||||
public sealed record ReadResult(string CorrelationId, DataItemStatus Status, DataReadiness Readiness,
|
||||
TimeSpan? Age, DataSample? Sample, string? Diagnostic) : IDisposable
|
||||
{
|
||||
public void Dispose() => Sample?.Dispose();
|
||||
}
|
||||
public sealed record WriteItem(string CorrelationId, string OperationId, DataView View, DataValue Value,
|
||||
long ExpectedCatalogRevision, string ExpectedServingIncarnation, TimeSpan RemainingBudget);
|
||||
/// <summary>
|
||||
/// Admission binds the stable principal and original credential separately. Before dispatch,
|
||||
/// recheck the original key's current principal and credential version against authority and its
|
||||
/// original expiry even when the epoch is unchanged. ApiKeyId and CredentialVersion are non-secret
|
||||
/// identifiers, never the bearer credential.
|
||||
/// </summary>
|
||||
public sealed record DataWriteAdmission(string PrincipalId, DataView View, long AuthorityEpoch, long CatalogRevision,
|
||||
string ServingIncarnation, string DriverIncarnation, string OperationId, long MonotonicExpiry,
|
||||
string ApiKeyId, DateTimeOffset? CredentialExpiresUtc, string CredentialVersion)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(PrincipalId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ApiKeyId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(CredentialVersion);
|
||||
ArgumentNullException.ThrowIfNull(View);
|
||||
View.Validate();
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ServingIncarnation);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(DriverIncarnation);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(OperationId);
|
||||
if (CredentialExpiresUtc is { Offset: var offset } && offset != TimeSpan.Zero)
|
||||
{
|
||||
throw new ArgumentException("Credential expiry must be UTC.", nameof(CredentialExpiresUtc));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record WriteBatch(IReadOnlyList<WriteItem> Items, DataBudget Budget);
|
||||
public sealed record WriteItemResult(string CorrelationId, DataWriteOutcome Outcome);
|
||||
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataCatalogService
|
||||
{
|
||||
Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken);
|
||||
Task<IReadOnlyList<DataItemResult<DataMetadata>>> GetMetadataAsync(MetadataRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataReadService
|
||||
{
|
||||
/// <summary>Reads cached values only, in request order; never initiates a device read.</summary>
|
||||
Task<IReadOnlyList<ReadResult>> ReadAsync(ReadRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataWriteService
|
||||
{
|
||||
/// <summary>Returns ordered item outcomes; cancellation after dispatch cannot undo a write.</summary>
|
||||
Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
public sealed record DataSubscriptionSettings(TimeSpan SamplingInterval, TimeSpan PublishingInterval,
|
||||
DataChangeTrigger Trigger, double? Deadband)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
DataContractValidation.Required(Trigger);
|
||||
if (SamplingInterval < TimeSpan.Zero || PublishingInterval < TimeSpan.Zero ||
|
||||
(Deadband is { } deadband && (!double.IsFinite(deadband) || deadband < 0)))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(Deadband));
|
||||
}
|
||||
}
|
||||
}
|
||||
public sealed record DataSubscriptionItem(string ClientItemId, DataView View, DataSubscriptionSettings Settings);
|
||||
public abstract record DataSubscriptionCommand(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout);
|
||||
public sealed record OpenSubscription(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataSubscriptionItem> Items, bool WatchCatalogOnly, TimeSpan SessionLifetime, DataBudget SnapshotBudget)
|
||||
: DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record AddSubscriptionItems(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataSubscriptionItem> Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record ModifySubscriptionItems(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataSubscriptionItem> Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record RemoveSubscriptionItems(string SubscriptionId, long StreamEpoch, string CommandId, TimeSpan AcknowledgementTimeout,
|
||||
IReadOnlyList<DataItemHandle> Items) : DataSubscriptionCommand(SubscriptionId, StreamEpoch, CommandId, AcknowledgementTimeout);
|
||||
public sealed record DataSubscriptionItemAck(string ClientItemId, DataItemStatus Status, DataItemHandle? Handle,
|
||||
DataSubscriptionSettings? RevisedSettings, string? Diagnostic);
|
||||
public abstract record DataSubscriptionFrame(string SubscriptionId, long StreamEpoch, long Sequence);
|
||||
public sealed record DataSubscriptionAck(string SubscriptionId, long StreamEpoch, long Sequence, string CommandId,
|
||||
IReadOnlyList<DataSubscriptionItemAck> Items) : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence);
|
||||
public sealed record PartitionWatermark(int PartitionId, long Version);
|
||||
public sealed record DataSubscriptionControl(string SubscriptionId, long StreamEpoch, long Sequence, DataStreamControlKind Kind,
|
||||
IReadOnlyList<PartitionWatermark> Watermarks, long CatalogEpoch, long AuthorityEpoch, string? Diagnostic)
|
||||
: DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence);
|
||||
/// <summary>Each frame owns its samples until disposed, including during asynchronous encoding.</summary>
|
||||
public sealed record DataSubscriptionValues(string SubscriptionId, long StreamEpoch, long Sequence, bool IsSnapshot,
|
||||
IReadOnlyList<DataSubscriptionValue> Items) : DataSubscriptionFrame(SubscriptionId, StreamEpoch, Sequence), IDisposable
|
||||
{
|
||||
public void Dispose() { foreach (var item in Items) item.Sample.Dispose(); }
|
||||
}
|
||||
public sealed record DataSubscriptionValue(DataItemHandle Handle, DataSample Sample);
|
||||
|
||||
/// <summary>Commands and frames are ordered per stream. Dispose cancels the stream and releases demand.</summary>
|
||||
public interface IDataSubscription : IAsyncDisposable
|
||||
{
|
||||
Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken);
|
||||
IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
/// <summary>Operations use the authenticated caller bound to the containing connection facade.</summary>
|
||||
public interface IDataSubscriptionService
|
||||
{
|
||||
/// <summary>Stream lifetime is independent of unary deadlines; cancellation ends the stream.</summary>
|
||||
Task<IDataSubscription> SubscribeAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>Additive driver capability for explicit dispatch and completion outcomes; IWritable remains supported.</summary>
|
||||
public interface IWriteOutcomeCapability
|
||||
{
|
||||
Task<IReadOnlyList<DataWriteOutcome>> WriteWithOutcomesAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken);
|
||||
}
|
||||
Reference in New Issue
Block a user