using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Runtime.CompilerServices; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Origin-local cached data ports; every facade retains its authenticated caller. public sealed partial class LocalDataServices : IDataConnectionFactory { private readonly Func _catalog; private readonly PartitionedSampleHub _hub; private readonly DataOperationPolicy _policy; private readonly DataCapabilitiesProvider _capabilities; private readonly Func? _writes; private readonly Func? _subscriptions; private readonly Func? _targetSubscriptions; private readonly bool _subscriptionFreshnessChallenges; private readonly byte[] _continuationKey = RandomNumberGenerator.GetBytes(32); private readonly ConditionalWeakTable _callers = new(); private sealed record Continuation(DataView Parent, string? Filter, int Offset, string Principal, string KeyId, string CredentialVersion, ServingIdentity Serving, long Started, long DurationTicks); public LocalDataServices(Func catalog, PartitionedSampleHub hub, DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, Func? writes = null, Func? subscriptions = null, Func? targetSubscriptions = null, bool subscriptionFreshnessChallenges = false, IOriginHistoryPort? history = null) { _history = history; _historySessions = new OriginHistorySessions(clock ?? TimeProvider.System); _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _hub = hub ?? throw new ArgumentNullException(nameof(hub)); _policy = policy ?? throw new ArgumentNullException(nameof(policy)); _capabilities = capabilities ?? throw new ArgumentNullException(nameof(capabilities)); Clock = clock ?? throw new ArgumentNullException(nameof(clock)); if (!ReferenceEquals(hub.Clock, clock)) throw new ArgumentException("Hub and facade must use one clock.", nameof(clock)); _writes = writes; _subscriptions = subscriptions; _targetSubscriptions = targetSubscriptions; _subscriptionFreshnessChallenges = subscriptionFreshnessChallenges; } public TimeProvider Clock { get; } /// Diagnostics sink (history wiring faults); defaults to no logging. public Microsoft.Extensions.Logging.ILogger Logger { get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; // Grow site (plan ยง4.3): HistoryRead is implemented only while this origin can serve history (a historian backend); // A2a AlarmSubscribe only while it can serve conditions (hub + snapshot port + condition-key secret). private DataOperations Implemented(DataTarget target) => DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | (_writes is null ? DataOperations.None : DataOperations.Write) | (HistoryServing is null ? DataOperations.None : DataOperations.HistoryRead) // A2b: the method bits ride the same servability plus the node manager's method port. | (ConditionsServable ? DataOperations.AlarmSubscribe : DataOperations.None) | (ConditionMethodsServable ? DataOperationSets.ConditionMethods : DataOperations.None) | (_targetSubscriptions is not null || _subscriptions is not null && target.Mode == DataTargetMode.Node ? DataOperations.Subscribe : DataOperations.None); private DataCallerIdentity Caller(DataAuthenticatedContext context) => _callers.GetValue(context, static value => new(value.PrincipalId, value.ApiKeyId, value.CredentialVersion, value.CredentialExpiresUtc)); internal bool CanPublish(DataAuthenticatedContext context, ServingIdentity expectedServing, DataTarget? target = null) { var catalog = _catalog(); return catalog is not null && Ready(catalog) && catalog.Serving == expectedServing && context.AuthorityEpoch == catalog.AuthorityEpoch && (target is null || RoleAllows(target, catalog.Serving)) && _policy.IsCallerUsable(Caller(context)); } private static bool RoleAllows(DataTarget target, ServingIdentity serving) => string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) || target.Mode == DataTargetMode.Node && target.Consistency == DataConsistency.ReadyReplica && string.Equals(serving.Role, "Secondary", StringComparison.OrdinalIgnoreCase); internal void RequireTargetRole(DataTarget target) { if (!RoleAllows(target, _capabilities.Serving)) throw new InvalidOperationException("The requested target cannot serve the required consistency."); } internal bool CanPublishCapabilities(DataAuthenticatedContext context, DataTarget target, DataCapabilities expected) { var catalog = _catalog(); if (!_policy.IsCallerUsable(Caller(context)) || context.AuthorityEpoch != _policy.AuthorityEpoch || _capabilities.Serving != expected.Serving) return false; var ready = catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch && RoleAllows(target, catalog.Serving); var operations = ready ? catalog!.ExportOperations(context.PrincipalId) & Implemented(target) : DataOperations.None; if (!string.Equals(expected.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) operations &= ~(DataOperations.Write | DataOperationSets.ConditionMethods); return expected.Readiness == (ready ? DataReadiness.Ready : DataReadiness.Unavailable) && expected.Operations == operations && _capabilities.Serving == expected.Serving && _policy.IsCallerUsable(Caller(context)) && context.AuthorityEpoch == _policy.AuthorityEpoch; } private sealed class PublicationReadLease(CachedSourceRead read, Func gate) : IDataPublicationLease { private int _disposed; public bool IsValid => gate() && Volatile.Read(ref _disposed) == 0 && read.IsValid; public void Dispose() { if (Interlocked.Exchange(ref _disposed, 1) == 0) read.Dispose(); } } public IDataConnection Create(DataAuthenticatedContext context, DataTarget target) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(target); context.Validate(); target.Validate(); var serving = _capabilities.Serving; if (!string.Equals(target.ExpectedClusterId, _capabilities.ClusterId, StringComparison.OrdinalIgnoreCase) || (target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, serving.NodeId, StringComparison.OrdinalIgnoreCase))) throw new ArgumentException("Target does not identify this data service.", nameof(target)); if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException("Authenticated caller is no longer usable."); return new LocalDataConnection(this, context, target); } private bool Ready(LocalExportCatalog catalog) => catalog.IsActive && _capabilities.IsReady && catalog.Serving == _capabilities.Serving && catalog.AuthorityEpoch == _policy.AuthorityEpoch; private bool Allowed(LocalExportCatalog catalog, DataAuthenticatedContext context, LocalDataNode node, DataOperations operation) { if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context)) || (node.Metadata.AllowedOperations & operation) != operation || !catalog.AllowsExport(context.PrincipalId, node, operation)) return false; var required = operation switch { DataOperations.Browse => OpcUaOperation.Browse, DataOperations.Read => OpcUaOperation.Read, DataOperations.Write => OpcUaOperation.WriteOperate, DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems, DataOperations.Metadata => OpcUaOperation.Browse, // H2: the origin ACL HistoryRead on the view is checked on every ingress, ACL flag on or off. DataOperations.HistoryRead => OpcUaOperation.HistoryRead, _ => throw new ArgumentOutOfRangeException(nameof(operation)) }; var allowed = _policy.AuthorizeLocal(Caller(context), required, node.Scope); if (!allowed && operation == DataOperations.Metadata) allowed = _policy.AuthorizeLocal(Caller(context), OpcUaOperation.Read, node.Scope); return allowed && Ready(catalog); } internal DataItemStatus AuthorizeSubscription(DataAuthenticatedContext context, DataTarget target, DataView view, out SubscriptionAuthorizedView? authorized) { authorized = null; view.Validate(); target.Validate(); var catalog = _catalog(); if (catalog is null || !Ready(catalog)) return DataItemStatus.Unavailable; if (!RoleAllows(target, catalog.Serving)) return DataItemStatus.Unavailable; if (context.AuthorityEpoch != catalog.AuthorityEpoch) return DataItemStatus.Denied; if (!string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) || target.Mode == DataTargetMode.Node && !string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase)) return DataItemStatus.Unavailable; if (!_policy.IsCallerUsable(Caller(context))) return DataItemStatus.Denied; if (!catalog.TryResolve(view, out var node)) return catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound; if (!Allowed(catalog, context, node, DataOperations.Subscribe)) return DataItemStatus.Denied; var source = node.Source; if (!node.Supported || source is null) return DataItemStatus.Unsupported; if (!node.SourceEnabled) return DataItemStatus.Unavailable; var serving = catalog.Serving; var consistency = string.Equals(serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) ? DataConsistency.Primary : DataConsistency.ReadyReplica; authorized = new(node.Metadata.View, source, serving, node.Metadata, context.PrincipalId, catalog.SubscriptionExportScope(context.PrincipalId, node), target, consistency, () => { var current = _catalog(); return current is not null && current.Serving == serving && current.TryResolve(view, out var now) && now.Source == source && Allowed(current, context, now, DataOperations.Subscribe); }); return DataItemStatus.Good; } internal PartitionedSampleHub SubscriptionHub => _hub; internal DataLimits SubscriptionLimits => _capabilities.Limits; internal int SubscriptionItemLimit(DataAuthenticatedContext context) { var catalog = _catalog(); return catalog is null ? 0 : Limits(catalog, context).MaxMonitoredItems; } internal int SubscriptionStreamLimit(DataAuthenticatedContext context) { var catalog = _catalog(); return catalog is null ? 0 : Limits(catalog, context).MaxStreams; } internal bool CanUseSubscription(DataAuthenticatedContext context, DataTarget target, ServingIdentity? expected = null) { var catalog = _catalog(); return catalog is not null && Ready(catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch && RoleAllows(target, catalog.Serving) && (expected is null || catalog.Serving == expected) && _policy.IsCallerUsable(Caller(context)) && string.Equals(target.ExpectedClusterId, catalog.ClusterId, StringComparison.OrdinalIgnoreCase) && (target.Mode != DataTargetMode.Node || string.Equals(target.ExpectedNodeId, catalog.Serving.NodeId, StringComparison.OrdinalIgnoreCase)); } internal ServingIdentity? SubscriptionServing(DataAuthenticatedContext context, DataTarget target) { var catalog = _catalog(); return catalog is not null && CanUseSubscription(context, target, catalog.Serving) ? catalog.Serving : null; } private DataLimits Limits(LocalExportCatalog catalog, DataAuthenticatedContext context) => catalog.LimitsFor(context.PrincipalId, _capabilities.Limits); private void CheckBudget(DataBudget budget, int count, int limit, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(budget); cancellationToken.ThrowIfCancellationRequested(); budget.Validate(); if (count < 0 || count > Math.Min(budget.MaxItems, limit) || count > budget.MaxBytes / 256) throw new ArgumentOutOfRangeException(nameof(count), "Request exceeds the admitted item/byte budget."); } private bool Expired(long start, DataBudget budget) => Clock.GetElapsedTime(start) >= budget.Timeout; private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, DataTarget target, LocalDataNode node) { var operations = DataOperations.None; var implemented = Implemented(target); // once per node (H2 review: no per-operation rebuild of the history view) foreach (var operation in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Write, DataOperations.Subscribe, DataOperations.HistoryRead }) if ((node.Supported || operation == DataOperations.Browse) && (node.SourceEnabled || operation is DataOperations.Browse or DataOperations.Metadata) && (implemented & operation) != 0 && (node.Metadata.AllowedOperations & operation) != 0 && (operation != DataOperations.Write || node.Metadata.Writable && string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)) && Allowed(catalog, context, node, operation) && (operation != DataOperations.HistoryRead || IsHistorized(node))) operations |= operation; // H2: historizing = this caller may HistoryRead it (historized AND granted), so it never separates denied from unhistorized. var history = node.Source is not null && (implemented & DataOperations.HistoryRead) != 0 ? new DataHistoryInfo(operations.HasFlag(DataOperations.HistoryRead)) : null; return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write), Serving = catalog.Serving, History = history }; } internal Task GetCapabilitiesAsync(DataAuthenticatedContext context, DataTarget target, DataBudget budget, CancellationToken cancellationToken) { CheckBudget(budget, 0, 0, cancellationToken); var catalog = _catalog(); if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException(); var capabilities = _capabilities.Get(catalog is null ? DataOperations.None : catalog.ExportOperations(context.PrincipalId) & Implemented(target), catalog is null ? _capabilities.Limits : Limits(catalog, context)); if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) capabilities = capabilities with { Readiness = DataReadiness.Unavailable, Operations = DataOperations.None }; // H2: the transport strips History (and the bit) from a call that did not negotiate history. capabilities = capabilities with { History = HistoryCapabilitiesFor(catalog, context) }; // A2: likewise Conditions (and the AlarmSubscribe bit) from a call that did not negotiate conditions. capabilities = capabilities with { Conditions = ConditionCapabilitiesFor(catalog, context) }; return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, SubscriptionAgeReadiness = true, ResponseServingIdentity = true, SubscriptionFreshnessChallenges = _subscriptionFreshnessChallenges, MetadataItemLeases = true, ProtocolMinor = Math.Max(5, capabilities.ProtocolMinor) }); } internal Task>> GetMetadataAsync(DataAuthenticatedContext context, DataTarget target, MetadataRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Views); var catalog = _catalog(); CheckBudget(request.Budget, request.Views.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken); if (catalog is null) return Task.FromResult>>(request.Views.Select((_, i) => new DataItemResult(i.ToString(System.Globalization.CultureInfo.InvariantCulture), DataItemStatus.Unavailable, null, null)).ToArray()); var start = Clock.GetTimestamp(); var results = new List>(request.Views.Count); long bytes = 0; for (var i = 0; i < request.Views.Count; i++) { cancellationToken.ThrowIfCancellationRequested(); var view = request.Views[i]; view.Validate(); var status = !Ready(catalog) || Expired(start, request.Budget) ? DataItemStatus.Unavailable : !_policy.IsCallerUsable(Caller(context)) ? DataItemStatus.Denied : !catalog.TryResolveAddress(view, out _) ? catalog.ContainsAddress(view) ? DataItemStatus.Denied : DataItemStatus.NotFound : DataItemStatus.Good; DataMetadata? metadata = null; MetadataLease? itemLease = null; if (status == DataItemStatus.Good && catalog.TryResolveAddress(view, out var node)) { if (!Allowed(catalog, context, node, DataOperations.Metadata)) status = DataItemStatus.Denied; else if (!node.Supported) status = DataItemStatus.Unsupported; else { metadata = Metadata(catalog, context, target, node); bytes = checked(bytes + MetadataBytes(metadata) + 64); if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes)) { status = DataItemStatus.LimitExceeded; metadata = null; } else if (context.AuthorityEpoch == catalog.AuthorityEpoch && RoleAllows(target, catalog.Serving) && ReferenceEquals(_catalog(), catalog) && Allowed(catalog, context, node, DataOperations.Metadata)) { var duration = Limits(catalog, context).MaxMetadataLease; if (context.CredentialExpiresUtc is { } expiry) { var remaining = expiry - Clock.GetUtcNow(); if (remaining < duration) duration = remaining; } if (duration > TimeSpan.Zero && Ready(catalog) && ReferenceEquals(_catalog(), catalog) && context.AuthorityEpoch == catalog.AuthorityEpoch && _policy.IsCallerUsable(Caller(context))) itemLease = new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, duration); } } } results.Add(new(i.ToString(System.Globalization.CultureInfo.InvariantCulture), status, metadata, null, itemLease, itemLease is null ? null : start)); } if (!Ready(catalog) || !ReferenceEquals(_catalog(), catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving) || !_policy.IsCallerUsable(Caller(context))) return Task.FromResult>>(results.Select(x => x with { Status = !Ready(catalog) || !RoleAllows(target, catalog.Serving) ? DataItemStatus.Unavailable : DataItemStatus.Denied, Value = null, Lease = null, LeaseRequestStartedTimestamp = null }).ToArray()); return Task.FromResult>>(results); } internal Task> ReadAsync(DataAuthenticatedContext context, DataTarget target, ReadRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); var catalog = _catalog(); CheckBudget(request.Budget, request.Items.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken); if (catalog is null) return Task.FromResult>(request.Items.Select(item => new ReadResult(item.CorrelationId, DataItemStatus.Unavailable, DataReadiness.Unavailable, null, null, null)).ToArray()); var start = Clock.GetTimestamp(); var results = new List(request.Items.Count); long bytes = 0; try { foreach (var item in request.Items) { cancellationToken.ThrowIfCancellationRequested(); item.View.Validate(); if (item.MaximumAge is { } maximumAge && maximumAge < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(item.MaximumAge)); ReadResult Empty(DataItemStatus status, DataReadiness readiness = DataReadiness.Unavailable) => new(item.CorrelationId, status, readiness, null, null, null); if (!Ready(catalog) || Expired(start, request.Budget)) { results.Add(Empty(DataItemStatus.Unavailable)); continue; } if (!_policy.IsCallerUsable(Caller(context))) { results.Add(Empty(DataItemStatus.Denied)); continue; } if (!catalog.TryResolve(item.View, out var node)) { results.Add(Empty(catalog.ContainsAddress(item.View) ? DataItemStatus.Denied : DataItemStatus.NotFound)); continue; } if (!Allowed(catalog, context, node, DataOperations.Read)) { results.Add(Empty(DataItemStatus.Denied)); continue; } if (!node.Supported) { results.Add(Empty(DataItemStatus.Unsupported)); continue; } if (!node.SourceEnabled) { results.Add(Empty(DataItemStatus.Unavailable)); continue; } if (node.Source is not { } key) { results.Add(Empty(DataItemStatus.Unsupported)); continue; } if (!_hub.TryGetCurrentTicket(key, out var ticket)) { results.Add(Empty(DataItemStatus.WaitingForInitialData, DataReadiness.WaitingForInitialData)); continue; } var read = _hub.Read(ticket); if (read.Sample is not { } sample || read.Readiness != DataReadiness.Ready) { results.Add(new(item.CorrelationId, read.Status, read.Readiness, null, null, null)); read.Dispose(); continue; } if (sample.Serving.NodeId != key.ServingNodeId || sample.Serving.Incarnation != key.ServingIncarnation || !_hub.TryGetCurrentTicket(key, out var current) || current != ticket) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; } if (!ValueMatches(node.Metadata, sample.Value)) { read.Dispose(); results.Add(Empty(DataItemStatus.TypeMismatch)); continue; } bytes = checked(bytes + sample.Value.EstimatedRetainedBytes + 256); if (bytes > Math.Min(request.Budget.MaxBytes, _capabilities.Limits.MaxMessageBytes)) { read.Dispose(); results.Add(Empty(DataItemStatus.LimitExceeded)); continue; } var observedAt = Clock.GetTimestamp(); var age = Clock.GetElapsedTime(read.ReceivedTimestamp, observedAt); if (age < TimeSpan.Zero) { read.Dispose(); results.Add(Empty(DataItemStatus.Unavailable)); continue; } // Catalog/authority headers describe current serving. Cache ingress age, value version // and original timestamps remain unchanged, including provisional boot acquisitions. var exposed = sample with { Value = sample.Value.Retain(), Serving = catalog.Serving }; exposed.Validate(); if (!Allowed(catalog, context, node, DataOperations.Read) || !_hub.TryGetCurrentTicket(key, out current) || current != ticket) { exposed.Dispose(); read.Dispose(); results.Add(Empty(DataItemStatus.Denied)); continue; } var publication = new PublicationReadLease(read, () => CanPublish(context, exposed.Serving, target) && !Expired(start, request.Budget)); results.Add(new(item.CorrelationId, item.MaximumAge is { } max && age > max ? DataItemStatus.Stale : DataItemStatus.Good, DataReadiness.Ready, age, exposed, null, publication, new DataAgeBounds(age, age), observedAt)); } if (!Ready(catalog) || !_policy.IsCallerUsable(Caller(context))) for (var i = 0; i < results.Count; i++) { var result = results[i]; result.Dispose(); results[i] = new(result.CorrelationId, Ready(catalog) ? DataItemStatus.Denied : DataItemStatus.Unavailable, DataReadiness.Unavailable, null, null, null); } return Task.FromResult>(results); } catch { foreach (var result in results) result.Dispose(); throw; } } internal Task BrowseAsync(DataAuthenticatedContext context, DataTarget target, BrowseRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); request.Parent.Validate(); var catalog = _catalog(); var limits = catalog is null ? _capabilities.Limits : Limits(catalog, context); CheckBudget(request.Budget, 0, limits.MaxPageItems, cancellationToken); DataBrowseBranch Empty(DataItemStatus status) => new(request.Parent, status, [], true, null, null); if (catalog is null || !Ready(catalog)) return Task.FromResult(Empty(DataItemStatus.Unavailable)); if (!catalog.TryResolve(request.Parent, out var parent) || !Allowed(catalog, context, parent, DataOperations.Browse)) return Task.FromResult(Empty(DataItemStatus.Denied)); var start = Clock.GetTimestamp(); var offset = 0; if (request.Continuation is not null) { var continuation = DecodeContinuation(request.Continuation); if (continuation is null || continuation.Parent != request.Parent || continuation.Filter != request.Filter || continuation.Principal != context.PrincipalId || continuation.KeyId != context.ApiKeyId || continuation.CredentialVersion != context.CredentialVersion || continuation.Serving != catalog.Serving || Clock.GetElapsedTime(continuation.Started).Ticks >= continuation.DurationTicks) return Task.FromResult(Empty(DataItemStatus.InvalidContinuation)); offset = continuation.Offset; } var children = catalog.Children(parent); if (offset < 0 || offset > children.Count) return Task.FromResult(Empty(DataItemStatus.InvalidContinuation)); var page = new List(); long bytes = 256; var maximum = Math.Min(request.Budget.MaxItems, limits.MaxPageItems); var scanned = 0; while (offset < children.Count && page.Count < maximum && scanned < maximum) { cancellationToken.ThrowIfCancellationRequested(); if (Expired(start, request.Budget)) return Task.FromResult(Empty(DataItemStatus.Unavailable)); var child = children[offset++]; // #917: an unsupported value node (an alarm-bearing tag, or a data type v1 cannot carry) is never listed. Every // consumer build applies a browse page all-or-nothing and cannot materialise one, so listing it made the whole // folder unbrowsable on the consumer (BadNoCommunication). It stays addressable (GetMetadata/Read/Subscribe on it // answer Unsupported). An export rooted at it still compiles but grants nothing. A skipped node is not counted // against the scan bound (it costs one check; the budget timeout above still bounds the call), so the skip never // yields an empty Complete=false page. if (child.Source is not null && !child.Supported) continue; scanned++; if ((request.Filter is { Length: > 0 } filter && !child.Metadata.BrowseName.Contains(filter, StringComparison.Ordinal)) || !Allowed(catalog, context, child, DataOperations.Browse)) continue; var metadata = Metadata(catalog, context, target, child); var size = MetadataBytes(metadata); if (bytes + size > Math.Min(request.Budget.MaxBytes, limits.MaxMessageBytes)) { offset--; if (page.Count == 0) return Task.FromResult(Empty(DataItemStatus.LimitExceeded)); break; } bytes += size; page.Add(metadata); } if (!Allowed(catalog, context, parent, DataOperations.Browse)) return Task.FromResult(Empty(DataItemStatus.Denied)); var leaseDuration = limits.MaxMetadataLease; if (context.CredentialExpiresUtc is { } expiry) { var remaining = expiry - Clock.GetUtcNow(); if (remaining <= TimeSpan.Zero) return Task.FromResult(Empty(DataItemStatus.Denied)); if (remaining < leaseDuration) leaseDuration = remaining; } var complete = offset == children.Count; var token = complete ? null : EncodeContinuation(new(request.Parent, request.Filter, offset, context.PrincipalId, context.ApiKeyId, context.CredentialVersion, catalog.Serving, start, leaseDuration.Ticks)); return Task.FromResult(new DataBrowseBranch(request.Parent, DataItemStatus.Good, page, complete, token, new MetadataLease(catalog.Serving.CatalogEpoch, catalog.Serving.AuthorityEpoch, leaseDuration), catalog.Serving)); } internal async Task> WriteAsync(DataAuthenticatedContext context, WriteBatch request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); var catalog = _catalog(); CheckBudget(request.Budget, request.Items.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, cancellationToken); var results = new WriteItemResult[request.Items.Count]; var allowed = new List(); var indexes = new List(); for (var i = 0; i < request.Items.Count; i++) { var item = request.Items[i]; if (_writes is not null && catalog is not null && Ready(catalog) && string.Equals(_capabilities.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase) && catalog.TryResolve(item.View, out var node) && node.SourceEnabled && node.Supported && node.Metadata.Writable && Allowed(catalog, context, node, DataOperations.Write) && (item.ExpectedServingGeneration is null || item.ExpectedServingGeneration > 0 && item.ExpectedServingGeneration == catalog.Serving.ServingGeneration)) { allowed.Add(item); indexes.Add(i); } else results[i] = new(item.CorrelationId, new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Write unavailable or denied before dispatch.")); } if (allowed.Count > 0) { var outcomes = await _writes!(context).WriteAsync(new(allowed, request.Budget), cancellationToken).ConfigureAwait(false); if (outcomes.Count != allowed.Count) throw new InvalidOperationException("Write delegate returned an invalid result count."); for (var i = 0; i < outcomes.Count; i++) results[indexes[i]] = outcomes[i]; } return results; } internal Task SubscribeAsync(DataAuthenticatedContext context, DataTarget target, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var catalog = _catalog(); if ((_targetSubscriptions is null && (_subscriptions is null || target.Mode != DataTargetMode.Node)) || catalog is null || !Ready(catalog) || !_policy.IsCallerUsable(Caller(context))) throw new InvalidOperationException("Subscriptions are unavailable."); return (_targetSubscriptions?.Invoke(context, target) ?? _subscriptions!(context)).SubscribeAsync(cancellationToken); } private static bool ValueMatches(DataMetadata metadata, DataValue value) => value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind && (value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind && metadata.Dimensions.Count == value.Dimensions!.Count && metadata.Dimensions.Zip(value.Dimensions).All(x => x.First == 0 || x.First == x.Second)); private static long MetadataBytes(DataMetadata metadata) => checked(512L + 2L * (metadata.BrowseName.Length + metadata.NodeKind.Length + metadata.View.Address.Identifier.Length + metadata.View.Address.NamespaceUri.Length + metadata.View.Subject.Length + (metadata.EngineeringUnits?.Length ?? 0)) + 8L * metadata.Dimensions.Count); private string EncodeContinuation(Continuation value) { var payload = JsonSerializer.SerializeToUtf8Bytes(value); return Convert.ToBase64String(payload) + "." + Convert.ToBase64String(HMACSHA256.HashData(_continuationKey, payload)); } private Continuation? DecodeContinuation(string token) { if (token.Length > 16_384) return null; var parts = token.Split('.'); if (parts.Length != 2) return null; try { var payload = Convert.FromBase64String(parts[0]); var signature = Convert.FromBase64String(parts[1]); if (!CryptographicOperations.FixedTimeEquals(HMACSHA256.HashData(_continuationKey, payload), signature)) return null; return JsonSerializer.Deserialize(payload); } catch (Exception ex) when (ex is FormatException or JsonException) { return null; } } }