From e7cacd2ac93e4c5e36572e8b5f8e10bed43d4e7a Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 23 Nov 2026 20:42:51 -0500 Subject: [PATCH] feat(grpc-data): H2 origin HistoryRead ingress, header gating, LocalDataConnection history Service: HistoryRead rpc; history (field 16, Metadata.history, bit 32) emitted only on a call whose header requested history AND whose origin can serve it, otherwise stripped to the v1 shape; un-negotiated HistoryRead is FAILED_PRECONDITION. Origin: Implemented(target) grows by HistoryRead when a historian backend is configured; per-item gate catalog -> export grant + origin ACL HistoryRead -> tagname, every refusal the same BadHistoryOperationUnsupported; per-principal admission (BadTooManyOperations), per-page ceiling, response-byte chunking with single-use chunk tokens; one session per (principal, credential, HTTP/2 connection) cleared on close; wiring faults BadInternalError + error log; caller cancel never a backend outcome. DataOperationPolicy maps HistoryRead. --- .../Authorization/DataOperationPolicy.cs | 2 + .../DataConnectionRegistration.cs | 4 +- .../Grpc/DataConnectionGrpcService.cs | 91 +++++- .../DataConnections/LocalDataConnection.cs | 31 +- .../LocalDataRuntimeComposition.cs | 6 +- .../LocalDataServices.History.cs | 302 ++++++++++++++++++ .../DataConnections/LocalDataServices.cs | 25 +- .../LocalExportCatalog.Compilation.cs | 4 +- .../DataConnections/LocalExportCatalog.cs | 21 +- .../DataConnections/OriginHistorySessions.cs | 166 ++++++++++ 10 files changed, 636 insertions(+), 16 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs index 5b365877c..7ef34cb44 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/DataOperationPolicy.cs @@ -85,6 +85,8 @@ public sealed class DataOperationPolicy OpcUaOperation.Read => DataOperations.Read, OpcUaOperation.WriteOperate or OpcUaOperation.WriteTune or OpcUaOperation.WriteConfigure => DataOperations.Write, OpcUaOperation.CreateMonitoredItems or OpcUaOperation.TransferSubscriptions => DataOperations.Subscribe, + // H2: a mapped HistoryRead needs the mapping's own HistoryRead bit (opened deliberately; H3 projects it). + OpcUaOperation.HistoryRead => DataOperations.HistoryRead, _ => DataOperations.None, }; return required != DataOperations.None && (subject.AllowedOperations & required) == required diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index a99b7f078..a61e184f3 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -152,7 +152,9 @@ public static class DataConnectionRegistration sp.GetRequiredService(), sp.GetRequiredService(), host, sp.GetRequiredService(), new(4096, options.Hub.MaxTrackedSources, options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes, - 128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5))); + 128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)), + // H2: remote history over the node manager's history port, resolved once the SDK server is up. + new DeferredOriginHistoryPort(sp.GetRequiredService()), LoggerFor(sp)); }); services.AddSingleton(sp => new DeferredFactory(() => sp.GetRequiredService().Services)); services.AddSingleton(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs index 442748f08..a14db50f9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Grpc/DataConnectionGrpcService.cs @@ -17,10 +17,41 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO private readonly DataConnectionOptions _options = options.Value; /// - /// The optional features this server honours on a call that requests them. X0 reserves the negotiation and - /// supports nothing, so every call's effective set is empty and every RPC keeps its v1 behaviour. + /// The optional features this server honours on a call that requests them (H2: history). A feature is effective on + /// a call only when the header asked for it, this server supports it AND the origin can serve it (history: the + /// connection's capabilities carry ). A header-less call keeps v1 shapes exactly. /// - internal static DataFeatures SupportedFeatures => DataFeatures.None; + internal static DataFeatures SupportedFeatures => DataFeatures.History; + + /// + /// Whether this call negotiated history against . Refines the recorded effective set: an + /// origin that cannot serve history drops it, so the call stays v1-shaped. + /// + internal static bool HistoryNegotiated(ServerCallContext context, DataCapabilities caps) + { + var features = CallFeatures(context); + var negotiated = (features.Effective & DataFeatures.History) != 0 && caps.History is not null; + if (!negotiated && (features.Effective & DataFeatures.History) != 0) + context.UserState[typeof(DataCallFeatures)] = features with { Effective = features.Effective & ~DataFeatures.History }; + return negotiated; + } + + /// The v1 shape of a capabilities response: no history field and no HistoryRead bit. + internal static void StripHistory(W.CapabilitiesResponse response) + { + response.History = null; + response.Operations &= ~(uint)DataOperations.HistoryRead; + } + + /// The v1 shape of a metadata item: no history info and no HistoryRead bit. + internal static void StripHistory(W.Metadata? metadata) + { + if (metadata is null) return; + metadata.History = null; + metadata.AllowedOperations &= ~(uint)DataOperations.HistoryRead; + } + + private static RpcException NotNegotiated() => new(new Status(StatusCode.FailedPrecondition, "feature not negotiated")); /// The feature set recorded for this call by (v1 when absent). internal static DataCallFeatures CallFeatures(ServerCallContext context) => @@ -47,6 +78,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO var capabilities = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false); var response = DataProtoMapper.EncodeCapabilities(capabilities with { ProtocolMinor = Math.Max(3, capabilities.ProtocolMinor), ResponseServingIdentity = true, SubscriptionAgeReadiness = true }); + if (!HistoryNegotiated(context, capabilities)) StripHistory(response); CheckSize(response); var current = await connection.GetCapabilitiesAsync(budget, token).ConfigureAwait(false); if (!authenticator.IsCurrent(caller) || current.Serving != capabilities.Serving @@ -65,6 +97,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO var decoded = DataProtoMapper.DecodeBrowseRequest(request, DecodeLimits(caps)); var result = await connection.BrowseAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false); var response = DataProtoMapper.EncodeBrowseResponse(result); + if (!HistoryNegotiated(context, caps)) foreach (var item in response.Items) StripHistory(item); response.Serving = DataProtoMapper.EncodeServing(caps.Serving); CheckSize(response); Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving)); @@ -78,6 +111,7 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO var decoded = DataProtoMapper.DecodeMetadataRequest(request, DecodeLimits(caps)); var result = await connection.GetMetadataAsync(decoded with { Budget = Clamp(decoded.Budget) }, token).ConfigureAwait(false); var response = DataProtoMapper.EncodeMetadataResponse(result); + if (!HistoryNegotiated(context, caps)) foreach (var item in response.Items) StripHistory(item.Value); response.Serving = DataProtoMapper.EncodeServing(caps.Serving); CheckSize(response); Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving)); @@ -132,6 +166,57 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO finally { foreach (var item in decoded.Items) item.Value.Dispose(); } }); + /// + /// H2 remote history. Order: the call negotiated history (header) and the origin can serve it, else + /// FAILED_PRECONDITION; then readiness and the HistoryRead operation (as every v1 RPC); then the origin facade applies, + /// per item, the export grant, the origin ACL and the tagname lookup — answering every refusal identically. + /// + public override Task HistoryRead(W.HistoryReadRequest request, ServerCallContext context) => + Execute(context, async (connection, caller, token) => + { + if ((CallFeatures(context).Effective & DataFeatures.History) == 0 + || connection is not (IDataHistoryTransport or IDataHistoryService)) throw NotNegotiated(); + var discovered = await connection.GetCapabilitiesAsync(DiscoveryBudget, token).ConfigureAwait(false); + if (!HistoryNegotiated(context, discovered)) throw NotNegotiated(); + var caps = await Ready(connection, DataOperations.HistoryRead, token).ConfigureAwait(false); + var (decoded, release) = DataHistoryProtoMapper.DecodeRequest(request, DecodeLimits(caps)); + var channel = Channel(context); + IReadOnlyList results; + if (release) + { + var tokens = decoded.Items.Where(x => x.Continuation is not null).Select(x => x.Continuation!).ToArray(); + if (connection is IDataHistoryTransport releasing) await releasing.ReleaseForTransportAsync(tokens, channel, token).ConfigureAwait(false); + else await ((IDataHistoryService)connection).ReleaseAsync(tokens, token).ConfigureAwait(false); + results = decoded.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, 0, [], null)).ToArray(); + } + else + { + var bounded = decoded with { Budget = Clamp(decoded.Budget) }; + results = connection is IDataHistoryTransport transport + ? await transport.ReadForTransportAsync(bounded, channel, token).ConfigureAwait(false) + : await ((IDataHistoryService)connection).ReadAsync(bounded, token).ConfigureAwait(false); + } + foreach (var result in results) context.GetHttpContext().Response.RegisterForDispose(result); + if (results.Count != decoded.Items.Count) throw Unavailable(); + var response = DataHistoryProtoMapper.EncodeResponse(results); + response.Serving = DataProtoMapper.EncodeServing(caps.Serving); + CheckSize(response); + Register(context, response, () => !token.IsCancellationRequested && CanPublish(connection, caller, caps.Serving)); + return response; + }); + + /// + /// The transport channel of this call: its HTTP/2 connection. Origin continuations are partitioned by it and cleared + /// when Kestrel reports the connection closed (idle expiry is the backstop where the feature is absent). + /// + private static DataHistoryChannel Channel(ServerCallContext context) + { + var http = context.GetHttpContext(); + var closed = http.Features.Get()?.ConnectionClosed + ?? CancellationToken.None; + return new DataHistoryChannel("http:" + (http.Connection.Id ?? "unknown"), closed); + } + private DataBudget DiscoveryBudget => new(_options.UnaryTimeout, 1, _options.MaxMessageBytes); private DataBudget Clamp(DataBudget budget) => budget with { Timeout = budget.Timeout <= _options.UnaryTimeout ? budget.Timeout : _options.UnaryTimeout, diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs index 1dfe4e5c2..e4433f8e7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataConnection.cs @@ -3,7 +3,8 @@ using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// Strictly caller-bound local data facade; it creates no namespace projection. -public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate +public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublicationGate, IDataConnectionDiscoveryGate, + IDataHistoryService, IDataHistoryTransport { private readonly LocalDataServices _services; private readonly DataAuthenticatedContext _context; @@ -28,5 +29,31 @@ public sealed class LocalDataConnection : IDataConnection, IDataConnectionPublic { Check(); return _services.WriteAsync(_context, request, cancellationToken); } public Task SubscribeAsync(CancellationToken cancellationToken) { Check(); return _services.SubscribeAsync(_context, Target, cancellationToken); } - public ValueTask DisposeAsync() { Interlocked.Exchange(ref _disposed, 1); return ValueTask.CompletedTask; } + /// + /// Direct runtime-consumer history (H2): this facade is the channel, so its origin continuations live only as long as + /// the facade and are cleared on . Answers are never chunked. + /// + public Task> ReadAsync(DataHistoryReadRequest request, CancellationToken cancellationToken) + { Check(); return _services.ReadHistoryAsync(_context, Target, request, OwnChannel, chunked: false, cancellationToken); } + public Task ReleaseAsync(IReadOnlyList continuations, CancellationToken cancellationToken) + { Check(); return _services.ReleaseHistoryAsync(_context, continuations, OwnChannel, cancellationToken); } + /// + public Task> ReadForTransportAsync(DataHistoryReadRequest request, DataHistoryChannel channel, + CancellationToken cancellationToken) + { Check(); return _services.ReadHistoryAsync(_context, Target, request, channel, chunked: true, cancellationToken); } + /// + public Task ReleaseForTransportAsync(IReadOnlyList continuations, DataHistoryChannel channel, CancellationToken cancellationToken) + { Check(); return _services.ReleaseHistoryAsync(_context, continuations, channel, cancellationToken); } + private readonly CancellationTokenSource _closed = new(); + private DataHistoryChannel? _channel; + private DataHistoryChannel OwnChannel => _channel ??= new("facade:" + Guid.NewGuid().ToString("N"), _closed.Token); + public ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + try { _closed.Cancel(); } catch (AggregateException) { } + _closed.Dispose(); + } + return ValueTask.CompletedTask; + } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs index 4276f279d..e3b37b9b1 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataRuntimeComposition.cs @@ -17,7 +17,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable private int _disposed; public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub, DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes, - IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits) + IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits, + ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null) { ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub); ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities); @@ -36,7 +37,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable services = new LocalDataServices(() => catalog.Current, hub, policy, capabilities, clock, writes: context => writes.ForCaller(context, () => host), targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity), - subscriptionFreshnessChallenges: true); + subscriptionFreshnessChallenges: true, history: history) + { Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance }; Services = services; } public LocalDataServices Services { get; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs new file mode 100644 index 000000000..01c1ad0da --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.History.cs @@ -0,0 +1,302 @@ +using System.Diagnostics.Metrics; +using System.Globalization; +using System.Text; +using ZB.MOM.WW.OtOpcUa.Commons.DataConnections; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// H2 origin ingress for remote HistoryRead (plan §3.2, §6). The order per item is: the caller and catalog are ready +/// for this target (ReadyReplica allowed), the export grants HistoryRead on the view, the origin ACL grants +/// HistoryRead on the view (always, whatever Security:Acl:Enabled says), and only then the historian +/// tagname is looked up. A refusal at ANY of those steps — unknown view, folder, not exported, denied, not historized — +/// is the same answer with no backend call, so a peer cannot tell denied from unhistorized. +/// +public sealed partial class LocalDataServices +{ + /// The single answer for every per-item refusal (denied ≡ unhistorized ≡ unknown). + internal const uint Refused = 0x80720000u; // Bad_HistoryOperationUnsupported + internal const uint BadTooManyOperations = 0x80100000u; + internal const uint BadInternalError = 0x80020000u; + internal const uint BadContinuationPointInvalid = 0x804A0000u; + private const int ResponseMarginBytes = 64 * 1024; + + private static readonly Meter HistoryMeter = new("ZB.MOM.WW.OtOpcUa.DataConnections.History"); + private static readonly Counter HistoryReads = HistoryMeter.CreateCounter("otopcua.dataconn.history.reads"); + + private readonly IOriginHistoryPort? _history; + private readonly OriginHistorySessions _historySessions; + + /// What this origin can serve remotely; null without a historian backend (then nothing is advertised). + internal OriginHistoryServing? HistoryServing + { + get + { + try { return _history?.Serving; } + catch (Exception) { return null; } + } + } + + /// Live history sessions (diagnostics/tests). + internal int HistorySessionCount => _historySessions.Count; + + private bool IsHistorized(LocalDataNode node) => + _history is not null && node.Source is not null && node.Metadata.View.Address.IdentifierKind == "string" + && _history.IsHistorized(Realm(node), node.Metadata.View.Address.Identifier); + + private static AddressSpaceRealm Realm(LocalDataNode node) => + node.Metadata.View.Realm == DataRealm.Raw ? AddressSpaceRealm.Raw : AddressSpaceRealm.Uns; + + /// The caller's history capabilities, when HistoryRead is among its operations. + internal DataHistoryCapabilities? HistoryCapabilitiesFor(LocalExportCatalog? catalog, DataAuthenticatedContext context, DataOperations operations) + { + if ((operations & DataOperations.HistoryRead) == 0 || catalog?.HistoryLimitsFor(context.PrincipalId) is not { } limits + || HistoryServing is not { } serving) return null; + return new DataHistoryCapabilities(true, serving.Aggregates.Count > 0, true, serving.Aggregates, serving.TimestampResolutionTicks, + limits.ValuesPerPage, limits.ConcurrentReads, PeerHistoryIdle); + } + + /// The origin continuation idle expiry advertised to peers (the H1 store default). + internal static readonly TimeSpan PeerHistoryIdle = TimeSpan.FromSeconds(60); + + /// + /// The serving identity a peer continuation binds: process incarnation + serving generation + role, so an origin + /// restart, a failover or a role change on a still-open channel invalidates its tokens (H1 review note). + /// + private string ServingIncarnation() + { + var serving = _catalog()?.Serving ?? throw new InvalidOperationException("No serving catalog."); + return string.Create(CultureInfo.InvariantCulture, $"{serving.Incarnation}/{serving.ServingGeneration}/{serving.Role}"); + } + + internal async Task> ReadHistoryAsync(DataAuthenticatedContext context, DataTarget target, + DataHistoryReadRequest request, DataHistoryChannel channel, bool chunked, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items); + ArgumentNullException.ThrowIfNull(request.Details); ArgumentNullException.ThrowIfNull(channel); + var catalog = _catalog(); + CheckBudget(request.Budget, request.Items.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems, + cancellationToken); + foreach (var item in request.Items) { ArgumentNullException.ThrowIfNull(item); item.View.Validate(); } + ValidateDetails(request); + DataHistoryReadResult[] All(uint status) => + request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray(); + if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving)) + throw new InvalidOperationException("History is unavailable for this target."); + if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException(); + if (_history is null || HistoryServing is null || catalog.HistoryLimitsFor(context.PrincipalId) is not { } limits) + return Record(request, All(Refused)); + if (!_historySessions.TryAdmit(context.PrincipalId, limits.ConcurrentReads)) return Record(request, All(BadTooManyOperations)); + try + { + var session = _historySessions.Get(context, channel, Math.Max(1, limits.ConcurrentReads * Math.Max(1, Limits(catalog, context).MaxBatchItems))); + var details = Clamp(request.Details, limits.ValuesPerPage); + var detailsKey = DetailsKey(details); + var incarnation = ServingIncarnation(); + var results = new DataHistoryReadResult?[request.Items.Count]; + var nodes = new LocalDataNode?[request.Items.Count]; + var portIndexes = new List(); + var portItems = new List(); + for (var i = 0; i < request.Items.Count; i++) + { + var item = request.Items[i]; + if (!Gate(catalog, context, item.View, out var node)) { results[i] = new(item.CorrelationId, Refused, [], null); continue; } + nodes[i] = node; + if (session.TakeChunk(item.Continuation) is { } chunk) + { + // A chunk token resumes the transport's remainder; it is bound to the view, details and serving identity. + results[i] = chunk.View == node.Metadata.View && chunk.DetailsKey == detailsKey && chunk.Incarnation == incarnation + ? new(item.CorrelationId, chunk.StatusCode, chunk.Remaining, chunk.Continuation, chunk.Diagnostic) + : Invalid(item, chunk); + continue; + } + portIndexes.Add(i); + portItems.Add(new OriginHistoryItem(Realm(node), node.Metadata.View.Address.Identifier, BindingTag(node.Metadata.View), + item.AggregateId, item.Continuation)); + } + if (portItems.Count > 0) + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(request.Budget.Timeout); + IReadOnlyList outcomes; + try + { + outcomes = await _history.ReadAsync(session.Cursors, context.PrincipalId, ServingIncarnation, details, portItems, deadline.Token) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // The budget expired before the port answered: every in-flight node is BadTimeout, as the port itself answers. + outcomes = portItems.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray(); + } + cancellationToken.ThrowIfCancellationRequested(); // a caller cancel is never a backend outcome + for (var k = 0; k < portIndexes.Count; k++) + { + var index = portIndexes[k]; + results[index] = ToResult(request.Items[index], nodes[index]!, outcomes[k], details); + } + } + // Authority may have moved while the backend answered: re-check every served item before handing anything back. + for (var i = 0; i < results.Length; i++) + if (nodes[i] is { } node && results[i]!.StatusCode != Refused + && (!Ready(catalog) || !Allowed(catalog, context, node, DataOperations.HistoryRead) || !IsHistorized(node))) + { + results[i]!.Dispose(); + results[i] = new(request.Items[i].CorrelationId, Refused, [], null); + } + var final = results.Select(x => x!).ToArray(); + if (chunked) final = Chunk(final, nodes, session, detailsKey, incarnation, Math.Min(limits.ResponseBytes, _capabilities.Limits.MaxMessageBytes)); + return Record(request, final); + } + finally { _historySessions.Leave(context.PrincipalId); } + } + + internal Task ReleaseHistoryAsync(DataAuthenticatedContext context, IReadOnlyList continuations, DataHistoryChannel channel, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(continuations); ArgumentNullException.ThrowIfNull(channel); + cancellationToken.ThrowIfCancellationRequested(); + if (_catalog() is not { } catalog || catalog.HistoryLimitsFor(context.PrincipalId) is not { } limits) return Task.CompletedTask; + var session = _historySessions.Get(context, channel, Math.Max(1, limits.ConcurrentReads * Math.Max(1, Limits(catalog, context).MaxBatchItems))); + foreach (var token in continuations) session.Release(token); + return Task.CompletedTask; + } + + /// The per-item ingress gate (order: catalog/view, export grant + origin ACL, historized). One answer for every refusal. + private bool Gate(LocalExportCatalog catalog, DataAuthenticatedContext context, DataView view, out LocalDataNode node) + { + if (!catalog.TryResolve(view, out node) || node.Source is null || !node.Supported) return false; + if (!Allowed(catalog, context, node, DataOperations.HistoryRead)) return false; + return IsHistorized(node); + } + + private static DataHistoryReadResult Invalid(DataHistoryReadItem item, OriginHistorySession.Chunk chunk) + { + foreach (var sample in chunk.Remaining) sample.Dispose(); + return new(item.CorrelationId, BadContinuationPointInvalid, [], null); + } + + private static string BindingTag(DataView view) => + "peer:" + (view.Realm == DataRealm.Raw ? "raw:" : "uns:") + view.Address.NamespaceUri; + + /// Raw pages at the export's per-page ceiling: 0 (all) or more than it is served as pages of the ceiling. + private static DataHistoryDetails Clamp(DataHistoryDetails details, int valuesPerPage) => details is DataHistoryRawDetails raw + && (raw.NumValuesPerNode == 0 || raw.NumValuesPerNode > (uint)valuesPerPage) + ? raw with { NumValuesPerNode = (uint)valuesPerPage } : details; + + private static void ValidateDetails(DataHistoryReadRequest request) + { + switch (request.Details) + { + case DataHistoryProcessedDetails processed when processed.ProcessingInterval < TimeSpan.Zero: + throw new ArgumentOutOfRangeException(nameof(request), "Negative processing interval."); + case DataHistoryAtTimeDetails atTime when atTime.RequestedTimesUtc is null: + throw new ArgumentException("Missing requested times.", nameof(request)); + case DataHistoryRawDetails or DataHistoryProcessedDetails or DataHistoryAtTimeDetails: + return; + default: + throw new ArgumentException("Unsupported history details.", nameof(request)); + } + } + + private static string DetailsKey(DataHistoryDetails details) => details switch + { + DataHistoryRawDetails r => string.Create(CultureInfo.InvariantCulture, + $"raw|{r.StartUtc?.UtcTicks}|{r.EndUtc?.UtcTicks}|{r.NumValuesPerNode}|{r.ReturnBounds}"), + DataHistoryProcessedDetails p => string.Create(CultureInfo.InvariantCulture, + $"processed|{p.StartUtc?.UtcTicks}|{p.EndUtc?.UtcTicks}|{p.ProcessingInterval.Ticks}|{p.Configuration}"), + DataHistoryAtTimeDetails a => "attime|" + a.UseSimpleBounds + "|" + + string.Join(',', a.RequestedTimesUtc.Select(t => t.UtcTicks.ToString(CultureInfo.InvariantCulture))), + _ => throw new ArgumentException("Unsupported history details."), + }; + + /// Maps a port outcome; Raw/AtTime values whose kind disagrees with the catalog are BadTypeMismatch, never coerced. + private DataHistoryReadResult ToResult(DataHistoryReadItem item, LocalDataNode node, OriginHistoryOutcome outcome, DataHistoryDetails details) + { + if (outcome.WiringFault) + { + // A miswired continuation scope is a SERVER fault: distinct from denied/unsupported, logged, never retried as "no history". + Logger.LogWiringFault(node.Metadata.View.Address.Identifier); + return new(item.CorrelationId, BadInternalError, [], null, "Origin history continuation wiring fault."); + } + var checkKind = details is not DataHistoryProcessedDetails; + var samples = new List(outcome.Samples.Count); + foreach (var sample in outcome.Samples) + { + DataValue value; + var status = sample.StatusCode; + try { value = OwnedDataSample.Copy(sample.Value); } + catch (ArgumentException) { value = DataValue.Null(); status = DataHistoryProtoMapper.BadTypeMismatch; } + if (checkKind && !DataHistoryProtoMapper.KindMatches(node.Metadata, value)) + { + value.Dispose(); value = DataValue.Null(); status = DataHistoryProtoMapper.BadTypeMismatch; + } + samples.Add(new DataHistorySample(value, status, OwnedDataSample.Timestamp(sample.SourceTimestampUtc), + OwnedDataSample.Timestamp(sample.ServerTimestampUtc))); + } + return new(item.CorrelationId, outcome.StatusCode, samples, outcome.Continuation); + } + + /// + /// Splits the response under the byte cap: a result that does not fit keeps what fits, stores the rest as a single-use + /// chunk remainder, and answers ChunkContinues with the chunk token; the final chunk carries the real status and + /// page continuation. A remainder the session cannot hold is BadTooManyOperations (never a silent truncation). + /// + private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, OriginHistorySession session, + string detailsKey, string incarnation, int capBytes) + { + long budget = Math.Max(16 * 1024, capBytes - ResponseMarginBytes); + long used = 0; + var anySample = false; + for (var i = 0; i < results.Length; i++) + { + var result = results[i]; + used += 128 + 2L * (result.CorrelationId.Length + (result.Diagnostic?.Length ?? 0)); + var fit = 0; + foreach (var sample in result.Samples) + { + var size = SampleBytes(sample); + if (used + size > budget && (anySample || fit > 0)) break; + used += size; fit++; anySample = true; + } + if (fit == result.Samples.Count) continue; + var node = nodes[i]!; + var remaining = result.Samples.Skip(fit).ToArray(); + var token = session.SaveChunk(new OriginHistorySession.Chunk(node.Metadata.View, detailsKey, incarnation, remaining, + result.StatusCode, result.Continuation, result.Diagnostic, 0)); + if (token is null) + { + result.Dispose(); + results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history session is full."); + continue; + } + results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), token, null, ChunkContinues: true); + } + return results; + } + + private static long SampleBytes(DataHistorySample sample) => Math.Max(48, sample.Value.EstimatedRetainedBytes - 192); + + private static DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results) + { + var variant = request.Details switch + { + DataHistoryRawDetails => "raw", DataHistoryProcessedDetails => "processed", DataHistoryAtTimeDetails => "attime", _ => "unknown", + }; + foreach (var result in results) + HistoryReads.Add(1, new KeyValuePair("variant", variant), + new KeyValuePair("status_class", (result.StatusCode >> 30) switch { 0 => "good", 1 => "uncertain", _ => "bad" })); + return results; + } +} + +/// History log helpers (kept out of the hot path). +internal static class LocalDataServicesHistoryLog +{ + public static void LogWiringFault(this Microsoft.Extensions.Logging.ILogger logger, string identifier) => + Microsoft.Extensions.Logging.LoggerExtensions.LogError(logger, + "Remote HistoryRead continuation scope is miswired for {Identifier}; answered BadInternalError", identifier); +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs index 806e999a5..2dbbf0742 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalDataServices.cs @@ -5,11 +5,12 @@ 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 class LocalDataServices : IDataConnectionFactory +public sealed partial class LocalDataServices : IDataConnectionFactory { private readonly Func _catalog; private readonly PartitionedSampleHub _hub; @@ -29,8 +30,10 @@ public sealed class LocalDataServices : IDataConnectionFactory Func? writes = null, Func? subscriptions = null, Func? targetSubscriptions = null, - bool subscriptionFreshnessChallenges = false) + 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)); @@ -44,8 +47,12 @@ public sealed class LocalDataServices : IDataConnectionFactory } 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). 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) | (_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 => @@ -119,6 +126,8 @@ public sealed class LocalDataServices : IDataConnectionFactory 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); @@ -198,14 +207,20 @@ public sealed class LocalDataServices : IDataConnectionFactory private DataMetadata Metadata(LocalExportCatalog catalog, DataAuthenticatedContext context, DataTarget target, LocalDataNode node) { var operations = DataOperations.None; - foreach (var operation in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Write, DataOperations.Subscribe }) + foreach (var operation in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Write, + DataOperations.Subscribe, DataOperations.HistoryRead }) if ((node.Supported || operation == DataOperations.Browse) + && (operation != DataOperations.HistoryRead || IsHistorized(node)) && (node.SourceEnabled || operation is DataOperations.Browse or DataOperations.Metadata) && (Implemented(target) & 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)) operations |= operation; - return node.Metadata with { AllowedOperations = operations, Writable = node.Metadata.Writable && operations.HasFlag(DataOperations.Write), Serving = catalog.Serving }; + // 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(target) & 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) @@ -217,6 +232,8 @@ public sealed class LocalDataServices : IDataConnectionFactory 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, capabilities.Operations) }; return Task.FromResult(capabilities with { WriteServingGenerationEnforced = true, SubscriptionAgeReadiness = true, ResponseServingIdentity = true, SubscriptionFreshnessChallenges = _subscriptionFreshnessChallenges, MetadataItemLeases = true, ProtocolMinor = Math.Max(5, capabilities.ProtocolMinor) }); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs index 63a50792e..e04f05ec5 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.Compilation.cs @@ -68,7 +68,9 @@ public sealed partial class LocalExportCatalog var views = new Dictionary<(DataRealm Realm, string Kind, string Id), DataView>(); var rawViewsByPath = new Dictionary(StringComparer.Ordinal); const DataOperations navigation = DataOperations.Browse | DataOperations.Metadata; - const DataOperations data = navigation | DataOperations.Read | DataOperations.Subscribe; + // H2: every value node MAY offer HistoryRead; whether it does for a caller is decided live (export grant, origin + // ACL, a registered historian tagname) and the bit never reaches a call that did not negotiate history. + const DataOperations data = navigation | DataOperations.Read | DataOperations.Subscribe | DataOperations.HistoryRead; NodeScope Scope(NodeAclScopeKind kind, string id, DataRealm realm) { diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs index f54e00b1f..a15f08bde 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/LocalExportCatalog.cs @@ -18,7 +18,8 @@ public sealed partial class LocalExportCatalog private readonly ExportRule[] _exports; private readonly IDataMappedCatalogAuthority _activation; private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm, - DataOperations Operations, int Batch, int Page, int Items, int Streams); + DataOperations Operations, int Batch, int Page, int Items, int Streams, + int HistoryReads = 4, int HistoryValuesPerPage = 10_000, int HistoryResponseBytes = 4 * 1024 * 1024); public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation, IEnumerable nodes, IEnumerable exports, int maximumNodes = 100_000) @@ -87,11 +88,13 @@ public sealed partial class LocalExportCatalog && x.Metadata.View.Realm == export.Realm).ToArray(); if ((!wholeRealm && roots.Length != 1) || string.IsNullOrWhiteSpace(export.PrincipalId) || export.AllowedOperations == DataOperations.None || export.MaxBatchItems <= 0 || export.MaxPageItems <= 0 - || export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0) + || export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0 || export.MaxConcurrentHistoryReads <= 0 + || export.MaxHistoryValuesPerPage <= 0 || export.MaxHistoryResponseBytes <= 0) throw new ArgumentException("Export has no valid origin root or policy.", nameof(exports)); rules.Add(new(export.DataExportId, export.PrincipalId, export.Realm, wholeRealm ? null : roots[0].Metadata.View, wholeRealm, // X0: an export bit this build does not implement grants nothing (a None-after-mask rule is kept and inert). - export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams)); + export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams, + export.MaxConcurrentHistoryReads, export.MaxHistoryValuesPerPage, export.MaxHistoryResponseBytes)); if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None) dropped[export.DataExportId] = unknown; } @@ -195,6 +198,18 @@ public sealed partial class LocalExportCatalog }; } + /// + /// H2: the principal's remote-history limits — the minimum over every export rule that grants it HistoryRead (an + /// export without the bit cannot lower them); null when no rule grants HistoryRead. + /// + internal (int ConcurrentReads, int ValuesPerPage, int ResponseBytes)? HistoryLimitsFor(string principal) + { + var rules = _exports.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase) + && (x.Operations & DataOperations.HistoryRead) != 0).ToArray(); + return rules.Length == 0 ? null + : (rules.Min(x => x.HistoryReads), rules.Min(x => x.HistoryValuesPerPage), rules.Min(x => x.HistoryResponseBytes)); + } + internal DataOperations ExportOperations(string principal) => _exports .Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase)) .Aggregate(DataOperations.None, (operations, rule) => operations | rule.Operations); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs new file mode 100644 index 000000000..20b9880f6 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/OriginHistorySessions.cs @@ -0,0 +1,166 @@ +using System.Security.Cryptography; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; + +/// +/// The ORIGIN's remote-history session of one (authenticated principal, credential, transport channel): the H1 page +/// cursor store plus the transport's chunk remainders (plan §3.2). A peer never reaches another session's tokens; the +/// session is cleared when its channel closes, and idle expiry is the backstop. +/// +internal sealed class OriginHistorySession +{ + private readonly Lock _gate = new(); + private readonly Dictionary _chunks = new(); + private readonly TimeProvider _clock; + + internal OriginHistorySession(string principal, string channelId, int capacity, TimeProvider clock) + { + _clock = clock; + Capacity = capacity; + Cursors = new OriginHistoryCursors(principal, channelId, capacity, null, clock); + } + + /// The H1 page-continuation store of this session. + public OriginHistoryCursors Cursors { get; } + + /// The most live records of each kind. + public int Capacity { get; } + + /// Live chunk remainders. + public int ChunkCount + { + get { lock (_gate) { Sweep(_clock.GetTimestamp()); return _chunks.Count; } } + } + + /// A stored remainder of one node's answer: what is left, and the final status/continuation it ends with. + internal sealed record Chunk(DataView View, string DetailsKey, string Incarnation, IReadOnlyList Remaining, + uint StatusCode, byte[]? Continuation, string? Diagnostic, long SavedAt); + + /// Stores a remainder; null when the session is full (the caller answers BadTooManyOperations, never truncates). + public byte[]? SaveChunk(Chunk chunk) + { + var token = RandomNumberGenerator.GetBytes(16); + lock (_gate) + { + Sweep(_clock.GetTimestamp()); + if (_chunks.Count >= Capacity) return null; + _chunks[new Guid(token)] = chunk with { SavedAt = _clock.GetTimestamp() }; + } + return token; + } + + /// Takes (single-use) a remainder; null when the token is not a live chunk token. + public Chunk? TakeChunk(byte[]? token) + { + if (token is not { Length: 16 }) return null; + lock (_gate) + { + Sweep(_clock.GetTimestamp()); + return _chunks.Remove(new Guid(token), out var chunk) ? chunk : null; + } + } + + /// Releases a chunk or a page token (idempotent). + public void Release(byte[]? token) + { + if (TakeChunk(token) is { } chunk) { foreach (var sample in chunk.Remaining) sample.Dispose(); return; } + Cursors.Release(token); + } + + /// Drops everything (the channel closed or the session was evicted). + public void Clear() + { + Cursors.Clear(); + Chunk[] dropped; + lock (_gate) { dropped = _chunks.Values.ToArray(); _chunks.Clear(); } + foreach (var chunk in dropped) foreach (var sample in chunk.Remaining) sample.Dispose(); + } + + private void Sweep(long now) + { + foreach (var (id, chunk) in _chunks.ToArray()) + if (_clock.GetElapsedTime(chunk.SavedAt, now) >= Cursors.IdleExpiry) + { + _chunks.Remove(id); + foreach (var sample in chunk.Remaining) sample.Dispose(); + } + } +} + +/// +/// Every live of this origin, keyed by (principal, credential, channel), bounded, +/// plus the per-principal history admission counter (MaxConcurrentHistoryReads). +/// +internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions = 4096) +{ + private readonly Lock _gate = new(); + private readonly Dictionary _sessions = new(StringComparer.Ordinal); + private readonly Dictionary _inFlight = new(StringComparer.OrdinalIgnoreCase); + + /// The session of one channel, created on first use and cleared when fires. + public OriginHistorySession Get(DataAuthenticatedContext caller, DataHistoryChannel channel, int capacity) + { + var key = string.Join('\0', caller.PrincipalId.ToUpperInvariant(), caller.ApiKeyId, caller.CredentialVersion, channel.ChannelId); + OriginHistorySession? evicted = null; + OriginHistorySession session; + var created = false; + lock (_gate) + { + if (_sessions.TryGetValue(key, out var existing) && existing.Session.Capacity == capacity) + { + _sessions[key] = (existing.Session, clock.GetTimestamp()); + return existing.Session; + } + if (_sessions.Remove(key, out var resized)) evicted = resized.Session; + else if (_sessions.Count >= maxSessions) + { + var oldest = _sessions.MinBy(x => x.Value.Used); + _sessions.Remove(oldest.Key); + evicted = oldest.Value.Session; + } + session = new OriginHistorySession(caller.PrincipalId, channel.ChannelId, capacity, clock); + _sessions[key] = (session, clock.GetTimestamp()); + created = true; + } + evicted?.Clear(); + if (created && channel.Closed.CanBeCanceled) + channel.Closed.Register(() => Close(key, session)); + return session; + } + + /// Live sessions (diagnostics/tests). + public int Count { get { lock (_gate) return _sessions.Count; } } + + /// Admits one history request of ; false past . + public bool TryAdmit(string principal, int limit) + { + lock (_gate) + { + var current = _inFlight.GetValueOrDefault(principal); + if (current >= limit) return false; + _inFlight[principal] = current + 1; + return true; + } + } + + /// Ends one admitted request. + public void Leave(string principal) + { + lock (_gate) + { + if (_inFlight.TryGetValue(principal, out var current) && current > 1) _inFlight[principal] = current - 1; + else _inFlight.Remove(principal); + } + } + + private void Close(string key, OriginHistorySession session) + { + lock (_gate) + { + if (_sessions.TryGetValue(key, out var current) && ReferenceEquals(current.Session, session)) _sessions.Remove(key); + } + session.Clear(); + } +}