using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using W = ZB.MOM.WW.OtOpcUa.Commons.Protos.DataConnection.V1; namespace ZB.MOM.WW.OtOpcUa.Commons.DataConnections; /// Receiver-owned post-parse limits; transport must separately bound decompression and parsing. public sealed record DataDecodeLimits( int MaxItems = 1000, int MaxBytes = 4 * 1024 * 1024, int MaxValueElements = 100000 ) { public void Validate() { if (MaxItems <= 0 || MaxBytes <= 0 || MaxValueElements <= 0) throw new ArgumentOutOfRangeException(nameof(MaxItems)); } } /// Maps the explicit transport envelope to owned domain values. public static class DataProtoMapper { private static void Preflight( IMessage message, int count, DataDecodeLimits? limits, IEnumerable? values = null ) { limits ??= new DataDecodeLimits(); limits.Validate(); int encoded = message.CalculateSize(); if (count < 0 || count > limits.MaxItems || encoded > limits.MaxBytes) throw new ArgumentException("Envelope exceeds receiver limits."); long decoded = (long)encoded * 2 + (long)count * 256 + 128; if (values is not null) foreach (var value in values) { decoded += TypedValueCodec.DecodedBytes(value, limits.MaxBytes - decoded); if (decoded > limits.MaxBytes) throw new ArgumentException("Decoded envelope exceeds receiver limits."); } if (decoded > limits.MaxBytes) throw new ArgumentException("Decoded envelope exceeds receiver limits."); } private static void ValidateFrame(string id, long epoch, long sequence) { ArgumentException.ThrowIfNullOrWhiteSpace(id); if (epoch <= 0 || sequence <= 0) throw new ArgumentOutOfRangeException(nameof(epoch)); } public static W.Address EncodeAddress(DataAddress x) { x.Validate(); return new() { OriginClusterId = x.OriginClusterId, NamespaceUri = x.NamespaceUri, IdentifierKind = x.IdentifierKind, Identifier = x.Identifier, }; } public static DataAddress DecodeAddress(W.Address x) { ArgumentNullException.ThrowIfNull(x); var v = new DataAddress(x.OriginClusterId, x.NamespaceUri, x.IdentifierKind, x.Identifier); v.Validate(); return v; } public static W.View EncodeView(DataView x) { x.Validate(); var v = new W.View { Address = EncodeAddress(x.Address), Realm = (int)x.Realm, MappingRevision = x.MappingRevision, Subject = x.Subject, }; if (x.MappingId is not null) v.MappingId = x.MappingId; return v; } public static DataView DecodeView(W.View x) { ArgumentNullException.ThrowIfNull(x); var v = new DataView( DecodeAddress(x.Address), (DataRealm)x.Realm, x.HasMappingId ? x.MappingId : null, x.MappingRevision, x.Subject ); v.Validate(); return v; } public static W.Serving EncodeServing(ServingIdentity x) => new() { NodeId = x.NodeId, Incarnation = x.Incarnation, Role = x.Role, CatalogEpoch = x.CatalogEpoch, AuthorityEpoch = x.AuthorityEpoch, ServingGeneration = x.ServingGeneration, }; public static ServingIdentity DecodeServing(W.Serving x) { ArgumentNullException.ThrowIfNull(x); var identity = new ServingIdentity( x.NodeId, x.Incarnation, x.Role, x.CatalogEpoch, x.AuthorityEpoch, x.ServingGeneration ); identity.Validate(); return identity; } public static W.Sample EncodeSample(DataSample x) { x.Validate(); var v = new W.Sample { Value = TypedValueCodec.Encode(x.Value), StatusCode = x.StatusCode, Serving = EncodeServing(x.Serving), Version = x.Version, }; if (x.SourceTimestampUtc is { } source) v.SourceTimestamp = Timestamp.FromDateTimeOffset(source); if (x.ServerTimestampUtc is { } server) v.ServerTimestamp = Timestamp.FromDateTimeOffset(server); return v; } public static DataSample DecodeSample( W.Sample x, int maxElements = TypedValueCodec.DefaultMaxElements, int maxBytes = TypedValueCodec.DefaultMaxBytes ) { ArgumentNullException.ThrowIfNull(x); var serving = DecodeServing(x.Serving); var source = x.SourceTimestamp is null ? (DateTimeOffset?)null : TypedValueCodec.DecodeTimestamp(x.SourceTimestamp); var server = x.ServerTimestamp is null ? (DateTimeOffset?)null : TypedValueCodec.DecodeTimestamp(x.ServerTimestamp); if (x.Version <= 0) throw new ArgumentException("Invalid sample version."); serving.Validate(requireEpochs: true); return new( TypedValueCodec.Decode(x.Value, maxElements, maxBytes), x.StatusCode, source, server, serving, x.Version ); } public static W.Budget EncodeBudget(DataBudget x) { x.Validate(); return new() { TimeoutTicks = x.Timeout.Ticks, MaxItems = x.MaxItems, MaxBytes = x.MaxBytes, }; } public static DataBudget DecodeBudget(W.Budget x) { ArgumentNullException.ThrowIfNull(x); var v = new DataBudget(TimeSpan.FromTicks(x.TimeoutTicks), x.MaxItems, x.MaxBytes); v.Validate(); return v; } public static W.Handle EncodeHandle(DataItemHandle x) { x.Validate(); return new() { SubscriptionId = x.SubscriptionId, StreamEpoch = x.StreamEpoch, Handle_ = x.Handle, ItemRevision = x.ItemRevision, }; } public static DataItemHandle DecodeHandle(W.Handle x) { ArgumentNullException.ThrowIfNull(x); var v = new DataItemHandle(x.SubscriptionId, x.StreamEpoch, x.Handle_, x.ItemRevision); v.Validate(); return v; } public static W.Settings EncodeSettings(DataSubscriptionSettings x) { x.Validate(); var v = new W.Settings { SamplingTicks = x.SamplingInterval.Ticks, PublishingTicks = x.PublishingInterval.Ticks, Trigger = (int)x.Trigger, }; if (x.Deadband is { } d) v.Deadband = d; return v; } public static DataSubscriptionSettings DecodeSettings(W.Settings x) { ArgumentNullException.ThrowIfNull(x); var trigger = (DataChangeTrigger)x.Trigger; DataContractValidation.Required(trigger); var settings = new DataSubscriptionSettings( TimeSpan.FromTicks(x.SamplingTicks), TimeSpan.FromTicks(x.PublishingTicks), trigger, x.HasDeadband ? x.Deadband : null ); settings.Validate(); return settings; } public static W.Metadata EncodeMetadata(DataMetadata x) { x.Validate(); var v = new W.Metadata { View = EncodeView(x.View), BrowseName = x.BrowseName, NodeKind = x.NodeKind, ValueKind = (W.ValueKind)x.ValueKind, ValueRank = x.ValueRank, Writable = x.Writable, AllowedOperations = (uint)x.AllowedOperations, CatalogRevision = x.CatalogRevision, IsStale = x.IsStale, }; v.Dimensions.AddRange(x.Dimensions); if (x.ArrayElementKind is { } elementKind) v.ArrayElementKind = (W.ValueKind)elementKind; if (x.StableSourceId is not null) v.StableSourceId = x.StableSourceId; if (x.EngineeringUnits is not null) v.EngineeringUnits = x.EngineeringUnits; return v; } public static DataMetadata DecodeMetadata(W.Metadata x) { ArgumentNullException.ThrowIfNull(x); if (x.Dimensions.Count > TypedValueCodec.MaxDimensions) throw new ArgumentException("Too many dimensions."); Preflight(x, 1, null); var kind = (DataValueKind)x.ValueKind; DataContractValidation.Required(kind); var metadata = new DataMetadata( DecodeView(x.View), x.BrowseName, x.NodeKind, kind, x.ValueRank, x.Dimensions.ToArray(), x.Writable, (DataOperations)x.AllowedOperations, x.CatalogRevision, x.HasStableSourceId ? x.StableSourceId : null, x.HasEngineeringUnits ? x.EngineeringUnits : null, x.IsStale, x.HasArrayElementKind ? (DataValueKind)x.ArrayElementKind : null ); metadata.Validate(); return metadata; } public static W.SubscriptionItem EncodeSubscriptionItem(DataSubscriptionItem x) => new() { ClientItemId = x.ClientItemId, View = EncodeView(x.View), Settings = EncodeSettings(x.Settings), }; public static DataSubscriptionItem DecodeSubscriptionItem(W.SubscriptionItem x) => new(x.ClientItemId, DecodeView(x.View), DecodeSettings(x.Settings)); public static W.SubscriptionCommand EncodeCommand(DataSubscriptionCommand x) { var v = new W.SubscriptionCommand { SubscriptionId = x.SubscriptionId, StreamEpoch = x.StreamEpoch, CommandId = x.CommandId, AcknowledgementTimeoutTicks = x.AcknowledgementTimeout.Ticks, }; switch (x) { case OpenSubscription o: v.Open = new W.Open { WatchCatalogOnly = o.WatchCatalogOnly, SessionLifetimeTicks = o.SessionLifetime.Ticks, SnapshotBudget = EncodeBudget(o.SnapshotBudget), }; v.Open.Items.AddRange(o.Items.Select(EncodeSubscriptionItem)); break; case AddSubscriptionItems a: v.Add = new W.ItemChanges(); v.Add.Items.AddRange(a.Items.Select(EncodeSubscriptionItem)); break; case ModifySubscriptionItems m: v.Modify = new W.ItemChanges(); v.Modify.Items.AddRange(m.Items.Select(EncodeSubscriptionItem)); break; case RemoveSubscriptionItems r: v.Remove = new W.HandleChanges(); v.Remove.Items.AddRange(r.Items.Select(EncodeHandle)); break; default: throw new ArgumentException("Unsupported command."); } return v; } public static DataSubscriptionCommand DecodeCommand( W.SubscriptionCommand x, DataDecodeLimits? limits = null ) { ArgumentNullException.ThrowIfNull(x); var count = x.CommandCase switch { W.SubscriptionCommand.CommandOneofCase.Open => x.Open.Items.Count, W.SubscriptionCommand.CommandOneofCase.Add => x.Add.Items.Count, W.SubscriptionCommand.CommandOneofCase.Modify => x.Modify.Items.Count, W.SubscriptionCommand.CommandOneofCase.Remove => x.Remove.Items.Count, _ => 0, }; Preflight(x, count, limits); ArgumentException.ThrowIfNullOrWhiteSpace(x.SubscriptionId); ArgumentException.ThrowIfNullOrWhiteSpace(x.CommandId); if (x.StreamEpoch <= 0 || x.AcknowledgementTimeoutTicks <= 0) throw new ArgumentException("Invalid command generation or timeout."); if ( x.Open is { } open && (open.SessionLifetimeTicks <= 0 || (open.WatchCatalogOnly && open.Items.Count != 0)) ) throw new ArgumentException("Invalid open subscription."); if (x.Remove is { } remove) foreach (var handle in remove.Items) if ( handle.SubscriptionId != x.SubscriptionId || handle.StreamEpoch != x.StreamEpoch ) throw new ArgumentException("Removal handle belongs to another stream."); var t = TimeSpan.FromTicks(x.AcknowledgementTimeoutTicks); return x.CommandCase switch { W.SubscriptionCommand.CommandOneofCase.Open => new OpenSubscription( x.SubscriptionId, x.StreamEpoch, x.CommandId, t, x.Open.Items.Select(DecodeSubscriptionItem).ToArray(), x.Open.WatchCatalogOnly, TimeSpan.FromTicks(x.Open.SessionLifetimeTicks), DecodeBudget(x.Open.SnapshotBudget) ), W.SubscriptionCommand.CommandOneofCase.Add => new AddSubscriptionItems( x.SubscriptionId, x.StreamEpoch, x.CommandId, t, x.Add.Items.Select(DecodeSubscriptionItem).ToArray() ), W.SubscriptionCommand.CommandOneofCase.Modify => new ModifySubscriptionItems( x.SubscriptionId, x.StreamEpoch, x.CommandId, t, x.Modify.Items.Select(DecodeSubscriptionItem).ToArray() ), W.SubscriptionCommand.CommandOneofCase.Remove => new RemoveSubscriptionItems( x.SubscriptionId, x.StreamEpoch, x.CommandId, t, x.Remove.Items.Select(DecodeHandle).ToArray() ), _ => throw new ArgumentException("Missing command."), }; } /// Decodes compact updates only for handles currently bound to this stream and revision. public static DataSubscriptionValues DecodeCompact( W.SubscriptionFrame frame, IReadOnlyDictionary handles, int maxItems, int maxBytes, ServingIdentity expectedServing, int maxElements = TypedValueCodec.DefaultMaxElements, bool subscriptionAgeReadiness = false ) { ArgumentNullException.ThrowIfNull(frame); ArgumentNullException.ThrowIfNull(handles); ArgumentNullException.ThrowIfNull(expectedServing); expectedServing.Validate(requireEpochs: true); var batch = frame.CompactValues ?? throw new ArgumentException("Compact batch required."); ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence); Preflight( frame, batch.Items.Count, new DataDecodeLimits(maxItems, maxBytes, maxElements), batch.Items.Select(i => i.Value) ); if ( maxItems <= 0 || maxBytes <= 0 || batch.Items.Count > maxItems || frame.CalculateSize() > maxBytes ) throw new ArgumentException("Frame exceeds budget."); long decodedBytes = 0; foreach (var update in batch.Items) { decodedBytes += TypedValueCodec.DecodedBytes(update.Value, maxBytes - decodedBytes); if (decodedBytes > maxBytes) throw new ArgumentException("Decoded frame exceeds budget."); } var serving = DecodeServing(batch.Serving); serving.Validate(requireEpochs: true); if (serving != expectedServing) throw new ArgumentException("Unexpected serving identity."); var items = new List(batch.Items.Count); try { foreach (var update in batch.Items) { if ( !handles.TryGetValue(update.Handle, out var handle) || handle.SubscriptionId != frame.SubscriptionId || handle.StreamEpoch != frame.StreamEpoch || handle.ItemRevision != update.ItemRevision ) throw new ArgumentException("Unknown or stale handle."); handle.Validate(); if (update.Version <= 0) throw new ArgumentException("Invalid sample version."); var source = update.SourceTimestamp is null ? batch.DefaultSourceTimestamp : update.SourceTimestamp.Value; var server = update.ServerTimestamp is null ? batch.DefaultServerTimestamp : update.ServerTimestamp.Value; var sourceTime = source is null ? (DateTimeOffset?)null : TypedValueCodec.DecodeTimestamp(source); var serverTime = server is null ? (DateTimeOffset?)null : TypedValueCodec.DecodeTimestamp(server); var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness, update.HasOriginAgeTicks, update.OriginAgeTicks, update.HasReadiness, update.Readiness); var sample = new DataSample( TypedValueCodec.Decode(update.Value, maxElements, maxBytes), update.HasStatusCode ? update.StatusCode : batch.DefaultStatusCode, sourceTime, serverTime, serving, update.Version ); items.Add(new DataSubscriptionValue(handle, sample, ageBounds, readiness)); } return new DataSubscriptionValues( frame.SubscriptionId, frame.StreamEpoch, frame.Sequence, batch.IsSnapshot, items ); } catch { foreach (var item in items) item.Sample.Dispose(); throw; } } public static W.SubscriptionFrame EncodeValues( DataSubscriptionValues frame, bool compactNegotiated, bool subscriptionAgeReadiness = false ) { var result = new W.SubscriptionFrame { SubscriptionId = frame.SubscriptionId, StreamEpoch = frame.StreamEpoch, Sequence = frame.Sequence, }; if (!compactNegotiated) { result.Values = new W.Values { IsSnapshot = frame.IsSnapshot }; foreach (var item in frame.Items) { var update = new W.ValueUpdate { Handle = EncodeHandle(item.Handle), Sample = EncodeSample(item.Sample), }; if (subscriptionAgeReadiness) { ValidateSubscriptionAgeReadiness(item); if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks; update.Readiness = (int)item.Readiness; } result.Values.Items.Add(update); } return result; } if (frame.Items.Count == 0) throw new ArgumentException("A compact batch requires provenance."); var first = frame.Items[0].Sample; result.CompactValues = new W.CompactValues { IsSnapshot = frame.IsSnapshot, Serving = EncodeServing(first.Serving), DefaultStatusCode = first.StatusCode, }; if (first.SourceTimestampUtc is { } source) result.CompactValues.DefaultSourceTimestamp = Timestamp.FromDateTimeOffset(source); if (first.ServerTimestampUtc is { } server) result.CompactValues.DefaultServerTimestamp = Timestamp.FromDateTimeOffset(server); foreach (var item in frame.Items) { item.Handle.Validate(); item.Sample.Validate(); if ( item.Handle.SubscriptionId != frame.SubscriptionId || item.Handle.StreamEpoch != frame.StreamEpoch || item.Sample.Serving != first.Serving ) throw new ArgumentException("Mixed stream or provenance in compact batch."); var update = new W.CompactUpdate { Handle = item.Handle.Handle, ItemRevision = item.Handle.ItemRevision, Version = item.Sample.Version, Value = TypedValueCodec.Encode(item.Sample.Value), }; if (subscriptionAgeReadiness) { ValidateSubscriptionAgeReadiness(item); if (item.AgeBounds.Lower is { } lower) update.OriginAgeTicks = lower.Ticks; update.Readiness = (int)item.Readiness; } if (item.Sample.StatusCode != first.StatusCode) update.StatusCode = item.Sample.StatusCode; if (item.Sample.SourceTimestampUtc != first.SourceTimestampUtc) { update.SourceTimestamp = new W.TimestampOverride(); if (item.Sample.SourceTimestampUtc is { } s) update.SourceTimestamp.Value = Timestamp.FromDateTimeOffset(s); } if (item.Sample.ServerTimestampUtc != first.ServerTimestampUtc) { update.ServerTimestamp = new W.TimestampOverride(); if (item.Sample.ServerTimestampUtc is { } s) update.ServerTimestamp.Value = Timestamp.FromDateTimeOffset(s); } result.CompactValues.Items.Add(update); } return result; } public static DataSubscriptionValues DecodeValues( W.SubscriptionFrame frame, IReadOnlyDictionary handles, int maxItems, int maxBytes, ServingIdentity expectedServing, int maxElements = TypedValueCodec.DefaultMaxElements, bool subscriptionAgeReadiness = false ) { ArgumentNullException.ThrowIfNull(expectedServing); expectedServing.Validate(requireEpochs: true); ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence); if (frame.CompactValues is not null) return DecodeCompact(frame, handles, maxItems, maxBytes, expectedServing, maxElements, subscriptionAgeReadiness); if ( frame.Values is null || maxItems <= 0 || maxBytes <= 0 || frame.Values.Items.Count > maxItems || frame.CalculateSize() > maxBytes ) throw new ArgumentException("Invalid or oversized values frame."); Preflight( frame, frame.Values.Items.Count, new DataDecodeLimits(maxItems, maxBytes, maxElements), frame.Values.Items.Select(i => i.Sample.Value) ); long decodedBytes = 0; foreach (var update in frame.Values.Items) { decodedBytes += TypedValueCodec.DecodedBytes( update.Sample.Value, maxBytes - decodedBytes ); if (decodedBytes > maxBytes) throw new ArgumentException("Decoded frame exceeds budget."); } var items = new List(frame.Values.Items.Count); try { foreach (var item in frame.Values.Items) { var handle = DecodeHandle(item.Handle); if ( handle.SubscriptionId != frame.SubscriptionId || handle.StreamEpoch != frame.StreamEpoch || !handles.TryGetValue(handle.Handle, out var expected) || expected != handle ) throw new ArgumentException("Unknown or stale handle."); if (DecodeServing(item.Sample.Serving) != expectedServing) throw new ArgumentException("Unexpected serving identity."); var (ageBounds, readiness) = DecodeSubscriptionAgeReadiness(subscriptionAgeReadiness, item.HasOriginAgeTicks, item.OriginAgeTicks, item.HasReadiness, item.Readiness); items.Add(new(handle, DecodeSample(item.Sample, maxElements, maxBytes), ageBounds, readiness)); } return new( frame.SubscriptionId, frame.StreamEpoch, frame.Sequence, frame.Values.IsSnapshot, items ); } catch { foreach (var item in items) item.Sample.Dispose(); throw; } } private static void ValidateSubscriptionAgeReadiness(DataSubscriptionValue item) { item.AgeBounds.Validate(); DataContractValidation.Required(item.Readiness); } private static (DataAgeBounds AgeBounds, DataReadiness Readiness) DecodeSubscriptionAgeReadiness( bool enabled, bool hasAge, long ageTicks, bool hasReadiness, int readinessValue) { if (!enabled) return (default, DataReadiness.Unspecified); if (!hasReadiness) throw new ArgumentException("Missing negotiated readiness."); var readiness = (DataReadiness)readinessValue; DataContractValidation.Required(readiness); if (hasAge && ageTicks < 0) throw new ArgumentException("Invalid origin-cache age."); return (new DataAgeBounds(hasAge ? TimeSpan.FromTicks(ageTicks) : null, null), readiness); } public static W.ReadRequest EncodeReadRequest(ReadRequest x) { var v = new W.ReadRequest { Budget = EncodeBudget(x.Budget) }; foreach (var item in x.Items) { var w = new W.ReadItem { CorrelationId = item.CorrelationId, View = EncodeView(item.View), }; if (item.MaximumAge is { } age) w.MaximumAgeTicks = age.Ticks; v.Items.Add(w); } return v; } public static ReadRequest DecodeReadRequest(W.ReadRequest x, DataDecodeLimits? limits = null) { Preflight(x, x.Items.Count, limits); return new( x.Items.Select(i => new ReadItem( i.CorrelationId, DecodeView(i.View), i.HasMaximumAgeTicks ? TimeSpan.FromTicks(i.MaximumAgeTicks) : null )) .ToArray(), DecodeBudget(x.Budget) ); } public static W.WriteRequest EncodeWriteRequest(WriteBatch x) { var v = new W.WriteRequest { Budget = EncodeBudget(x.Budget) }; foreach (var i in x.Items) v.Items.Add( new W.WriteItem { CorrelationId = i.CorrelationId, OperationId = i.OperationId, View = EncodeView(i.View), Value = TypedValueCodec.Encode(i.Value), ExpectedCatalogRevision = i.ExpectedCatalogRevision, ExpectedServingIncarnation = i.ExpectedServingIncarnation, RemainingBudgetTicks = i.RemainingBudget.Ticks, ExpectedServingGeneration = i.ExpectedServingGeneration ?? 0, } ); for (var index = 0; index < x.Items.Count; index++) if (x.Items[index].ExpectedServingGeneration is null) v.Items[index].ClearExpectedServingGeneration(); return v; } public static WriteBatch DecodeWriteRequest( W.WriteRequest x, int maxItems, int maxBytes, int maxElements = TypedValueCodec.DefaultMaxElements ) { Preflight( x, x.Items.Count, new DataDecodeLimits(maxItems, maxBytes, maxElements), x.Items.Select(i => i.Value) ); foreach (var item in x.Items) { ArgumentException.ThrowIfNullOrWhiteSpace(item.OperationId); ArgumentException.ThrowIfNullOrWhiteSpace(item.ExpectedServingIncarnation); if (item.ExpectedCatalogRevision <= 0 || item.RemainingBudgetTicks <= 0 || item.HasExpectedServingGeneration && item.ExpectedServingGeneration <= 0) throw new ArgumentException("Invalid write preconditions."); } var items = new List(); try { foreach (var i in x.Items) items.Add( new( i.CorrelationId, i.OperationId, DecodeView(i.View), TypedValueCodec.Decode(i.Value, maxElements, maxBytes), i.ExpectedCatalogRevision, i.ExpectedServingIncarnation, TimeSpan.FromTicks(i.RemainingBudgetTicks), i.HasExpectedServingGeneration ? i.ExpectedServingGeneration : null ) ); return new(items, DecodeBudget(x.Budget)); } catch { foreach (var i in items) i.Value.Dispose(); throw; } } public static W.BrowseRequest EncodeBrowseRequest(BrowseRequest x) { var v = new W.BrowseRequest { Parent = EncodeView(x.Parent), Budget = EncodeBudget(x.Budget), }; if (x.Filter is not null) v.Filter = x.Filter; if (x.Continuation is not null) v.Continuation = x.Continuation; return v; } public static BrowseRequest DecodeBrowseRequest( W.BrowseRequest x, DataDecodeLimits? limits = null ) { Preflight(x, 1, limits); return new( DecodeView(x.Parent), x.HasFilter ? x.Filter : null, x.HasContinuation ? x.Continuation : null, DecodeBudget(x.Budget) ); } public static W.MetadataRequest EncodeMetadataRequest(MetadataRequest x) { var v = new W.MetadataRequest { Budget = EncodeBudget(x.Budget) }; v.Views.AddRange(x.Views.Select(EncodeView)); return v; } public static MetadataRequest DecodeMetadataRequest( W.MetadataRequest x, DataDecodeLimits? limits = null ) { Preflight(x, x.Views.Count, limits); return new(x.Views.Select(DecodeView).ToArray(), DecodeBudget(x.Budget)); } public static W.BrowseResponse EncodeBrowseResponse(DataBrowseBranch x) { DataContractValidation.Required(x.Status); var v = new W.BrowseResponse { Parent = EncodeView(x.Parent), Status = (int)x.Status, Complete = x.Complete, }; v.Items.AddRange(x.Items.Select(EncodeMetadata)); if (x.Continuation is not null) v.Continuation = x.Continuation; if (x.Lease is { } l) v.Lease = new W.Lease { CatalogEpoch = l.CatalogEpoch, AuthorityEpoch = l.AuthorityEpoch, DurationTicks = l.Duration.Ticks, }; return v; } public static DataBrowseBranch DecodeBrowseResponse( W.BrowseResponse x, DataDecodeLimits? limits = null ) { Preflight(x, x.Items.Count, limits); if (x.Lease is not null) new MetadataLease( x.Lease.CatalogEpoch, x.Lease.AuthorityEpoch, TimeSpan.FromTicks(x.Lease.DurationTicks) ).Validate(); var status = (DataItemStatus)x.Status; DataContractValidation.Required(status); return new( DecodeView(x.Parent), status, x.Items.Select(DecodeMetadata).ToArray(), x.Complete, x.HasContinuation ? x.Continuation : null, x.Lease is null ? null : new MetadataLease( x.Lease.CatalogEpoch, x.Lease.AuthorityEpoch, TimeSpan.FromTicks(x.Lease.DurationTicks) ) ); } public static W.ReadResult EncodeReadResult(ReadResult x) { DataContractValidation.Required(x.Status); DataContractValidation.Required(x.Readiness); var v = new W.ReadResult { CorrelationId = x.CorrelationId, Status = (int)x.Status, Readiness = (int)x.Readiness, }; x.AgeBounds.Validate(); if (x.Age is { } age) { if (age < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(x)); v.AgeTicks = age.Ticks; } if (x.Sample is not null) v.Sample = EncodeSample(x.Sample); if (x.Diagnostic is not null) v.Diagnostic = x.Diagnostic; return v; } public static ReadResult DecodeReadResult(W.ReadResult x, DataDecodeLimits? limits = null, TimeSpan? causalRequestElapsed = null) { if (causalRequestElapsed < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(causalRequestElapsed)); limits ??= new DataDecodeLimits(); Preflight(x, 1, limits, x.Sample is null ? null : new[] { x.Sample.Value }); var status = (DataItemStatus)x.Status; var readiness = (DataReadiness)x.Readiness; DataContractValidation.Required(status); DataContractValidation.Required(readiness); if (x.HasAgeTicks && x.AgeTicks < 0) throw new ArgumentException("Invalid origin-cache age."); var bounds = x.HasAgeTicks ? new DataAgeBounds(TimeSpan.FromTicks(x.AgeTicks), causalRequestElapsed is { } elapsed ? TimeSpan.FromTicks(checked(x.AgeTicks + elapsed.Ticks)) : null) : default; return new( x.CorrelationId, status, readiness, null, x.Sample is null ? null : DecodeSample(x.Sample, limits.MaxValueElements, limits.MaxBytes), x.HasDiagnostic ? x.Diagnostic : null, AgeBounds: bounds ); } public static W.WriteResult EncodeWriteResult(WriteItemResult x) { x.Outcome.Validate(); var v = new W.WriteResult { CorrelationId = x.CorrelationId, State = (int)x.Outcome.State, StatusCode = x.Outcome.StatusCode, }; if (x.Outcome.Diagnostic is not null) v.Diagnostic = x.Outcome.Diagnostic; return v; } public static WriteItemResult DecodeWriteResult(W.WriteResult x) { var outcome = new DataWriteOutcome( (DataWriteState)x.State, x.StatusCode, x.HasDiagnostic ? x.Diagnostic : null ); outcome.Validate(); return new(x.CorrelationId, outcome); } /// Hash immutable operation semantics, excluding correlation and retry-varying budgets. public static byte[] WritePayloadHash(WriteItem item) { var wire = new W.WriteItem { OperationId = item.OperationId, View = EncodeView(item.View), Value = TypedValueCodec.Encode(item.Value), ExpectedCatalogRevision = item.ExpectedCatalogRevision, ExpectedServingIncarnation = item.ExpectedServingIncarnation, }; if (item.ExpectedServingGeneration is { } generation) wire.ExpectedServingGeneration = generation; return System.Security.Cryptography.SHA256.HashData(wire.ToByteArray()); } public static bool NegotiateCompact(DataCapabilities peer) { if (peer.ProtocolMajor != 1) throw new NotSupportedException("Incompatible protocol major."); return peer.CompactBatches && peer.CompactCodecVersion == 1; } public static W.CapabilitiesResponse EncodeCapabilities(DataCapabilities x) { x.Validate(); var l = x.Limits; var v = new W.CapabilitiesResponse { ProtocolMajor = x.ProtocolMajor, ProtocolMinor = x.ProtocolMinor, ClusterId = x.ClusterId, Serving = EncodeServing(x.Serving), Readiness = (int)x.Readiness, Operations = (uint)x.Operations, CompactBatches = x.CompactBatches, CompactCodecVersion = x.CompactCodecVersion, SubscriptionAgeReadiness = x.SubscriptionAgeReadiness, ResponseServingIdentity = x.ResponseServingIdentity, WriteServingGenerationEnforced = x.WriteServingGenerationEnforced, Limits = new W.Limits { MaxPageItems = l.MaxPageItems, MaxBatchItems = l.MaxBatchItems, MaxMessageBytes = l.MaxMessageBytes, MaxMonitoredItems = l.MaxMonitoredItems, MaxStreams = l.MaxStreams, MaxPendingBytes = l.MaxPendingBytes, MaxMetadataLeaseTicks = l.MaxMetadataLease.Ticks, MaxSessionLifetimeTicks = l.MaxSessionLifetime.Ticks, WriteRetryWindowTicks = l.WriteRetryWindow.Ticks, MaxValueElements = l.MaxValueElements, }, }; v.ValueKinds.AddRange(x.ValueKinds.Select(k => (W.ValueKind)k)); return v; } public static DataCapabilities DecodeCapabilities( W.CapabilitiesResponse x, DataDecodeLimits? limits = null ) { Preflight(x, x.ValueKinds.Count, limits); if (x.ProtocolMajor != 1) throw new NotSupportedException("Incompatible protocol major."); var r = (DataReadiness)x.Readiness; DataContractValidation.Required(r); var l = x.Limits ?? throw new ArgumentException("Missing limits."); var kinds = x .ValueKinds.Select(k => (DataValueKind)k) .Where(k => k != DataValueKind.Unspecified && System.Enum.IsDefined(k)) .ToHashSet(); var result = new DataCapabilities( x.ProtocolMajor, x.ProtocolMinor, DecodeServing(x.Serving), r, (DataOperations)( x.Operations & (uint)( DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe ) ), kinds, new DataLimits( l.MaxPageItems, l.MaxBatchItems, l.MaxMessageBytes, l.MaxMonitoredItems, l.MaxStreams, l.MaxPendingBytes, TimeSpan.FromTicks(l.MaxMetadataLeaseTicks), TimeSpan.FromTicks(l.MaxSessionLifetimeTicks), TimeSpan.FromTicks(l.WriteRetryWindowTicks), l.HasMaxValueElements ? l.MaxValueElements : TypedValueCodec.DefaultMaxElements ), x.CompactBatches, x.CompactCodecVersion, x.ClusterId, x.SubscriptionAgeReadiness, x.ResponseServingIdentity, x.WriteServingGenerationEnforced ); result.Validate(); return result; } public static W.SubscriptionFrame EncodeControlOrAck(DataSubscriptionFrame frame) { var v = new W.SubscriptionFrame { SubscriptionId = frame.SubscriptionId, StreamEpoch = frame.StreamEpoch, Sequence = frame.Sequence, }; if (frame is DataSubscriptionControl c) { DataContractValidation.Required(c.Kind); v.Control = new W.Control { Kind = (int)c.Kind, CatalogEpoch = c.CatalogEpoch, AuthorityEpoch = c.AuthorityEpoch, }; v.Control.Watermarks.AddRange( c.Watermarks.Select(w => new W.Watermark { PartitionId = w.PartitionId, Version = w.Version, }) ); if (c.Diagnostic is not null) v.Control.Diagnostic = c.Diagnostic; } else if (frame is DataSubscriptionAck a) { v.Ack = new W.Ack { CommandId = a.CommandId }; foreach (var item in a.Items) { DataContractValidation.Required(item.Status); var w = new W.ItemAck { ClientItemId = item.ClientItemId, Status = (int)item.Status, }; if (item.Handle is not null) w.Handle = EncodeHandle(item.Handle); if (item.RevisedSettings is not null) w.RevisedSettings = EncodeSettings(item.RevisedSettings); if (item.Diagnostic is not null) w.Diagnostic = item.Diagnostic; v.Ack.Items.Add(w); } } else throw new ArgumentException("Expected control or acknowledgement."); return v; } public static DataSubscriptionFrame DecodeControlOrAck( W.SubscriptionFrame frame, DataDecodeLimits? limits = null ) { ValidateFrame(frame.SubscriptionId, frame.StreamEpoch, frame.Sequence); Preflight(frame, frame.Control?.Watermarks.Count ?? frame.Ack?.Items.Count ?? 0, limits); if (frame.Control is { } c) { var kind = (DataStreamControlKind)c.Kind; DataContractValidation.Required(kind); if ( c.CatalogEpoch < 0 || c.AuthorityEpoch < 0 || c.Watermarks.Any(w => w.PartitionId < 0 || w.Version < 0) ) throw new ArgumentException("Invalid control epochs or watermarks."); return new DataSubscriptionControl( frame.SubscriptionId, frame.StreamEpoch, frame.Sequence, kind, c.Watermarks.Select(w => new PartitionWatermark(w.PartitionId, w.Version)) .ToArray(), c.CatalogEpoch, c.AuthorityEpoch, c.HasDiagnostic ? c.Diagnostic : null ); } if (frame.Ack is { } a) { ArgumentException.ThrowIfNullOrWhiteSpace(a.CommandId); var items = new List(); foreach (var item in a.Items) { if ( item.Handle is not null && ( item.Handle.SubscriptionId != frame.SubscriptionId || item.Handle.StreamEpoch != frame.StreamEpoch ) ) throw new ArgumentException( "Acknowledgement handle belongs to another stream." ); var status = (DataItemStatus)item.Status; DataContractValidation.Required(status); items.Add( new( item.ClientItemId, status, item.Handle is null ? null : DecodeHandle(item.Handle), item.RevisedSettings is null ? null : DecodeSettings(item.RevisedSettings), item.HasDiagnostic ? item.Diagnostic : null ) ); } return new DataSubscriptionAck( frame.SubscriptionId, frame.StreamEpoch, frame.Sequence, a.CommandId, items ); } throw new ArgumentException("Expected control or acknowledgement."); } public static W.MetadataResult EncodeMetadataResult(DataItemResult item) { DataContractValidation.Required(item.Status); var result = new W.MetadataResult { CorrelationId = item.CorrelationId, Status = (int)item.Status, }; if (item.Value is not null) result.Value = EncodeMetadata(item.Value); if (item.Diagnostic is not null) result.Diagnostic = item.Diagnostic; return result; } public static DataItemResult DecodeMetadataResult( W.MetadataResult item, DataDecodeLimits? limits = null ) { Preflight(item, 1, limits); var status = (DataItemStatus)item.Status; DataContractValidation.Required(status); return new( item.CorrelationId, status, item.Value is null ? null : DecodeMetadata(item.Value), item.HasDiagnostic ? item.Diagnostic : null ); } public static W.ReadResponse EncodeReadResponse(IReadOnlyList items) { var response = new W.ReadResponse(); response.Items.AddRange(items.Select(EncodeReadResult)); return response; } public static IReadOnlyList DecodeReadResponse( W.ReadResponse response, DataDecodeLimits? limits = null, TimeSpan? causalRequestElapsed = null ) { limits ??= new DataDecodeLimits(); Preflight( response, response.Items.Count, limits, response.Items.Where(i => i.Sample is not null).Select(i => i.Sample.Value) ); var result = new List(response.Items.Count); try { foreach (var item in response.Items) result.Add(DecodeReadResult(item, limits, causalRequestElapsed)); return result; } catch { foreach (var item in result) item.Dispose(); throw; } } public static W.WriteResponse EncodeWriteResponse(IReadOnlyList items) { var response = new W.WriteResponse(); response.Items.AddRange(items.Select(EncodeWriteResult)); return response; } public static IReadOnlyList DecodeWriteResponse( W.WriteResponse response, DataDecodeLimits? limits = null ) { Preflight(response, response.Items.Count, limits); return response.Items.Select(DecodeWriteResult).ToArray(); } public static W.MetadataResponse EncodeMetadataResponse( IReadOnlyList> items ) { var response = new W.MetadataResponse(); response.Items.AddRange(items.Select(EncodeMetadataResult)); return response; } public static IReadOnlyList> DecodeMetadataResponse( W.MetadataResponse response, DataDecodeLimits? limits = null ) { Preflight(response, response.Items.Count, limits); return response.Items.Select(i => DecodeMetadataResult(i, limits)).ToArray(); } }