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.
This commit is contained in:
Joseph Doherty
2026-11-23 20:42:51 -05:00
parent b6895c19d4
commit e7cacd2ac9
10 changed files with 636 additions and 16 deletions
@@ -17,10 +17,41 @@ public sealed class DataConnectionGrpcService(IDataConnectionFactory factory, IO
private readonly DataConnectionOptions _options = options.Value;
/// <summary>
/// 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 <see cref="DataCapabilities.History"/>). A header-less call keeps v1 shapes exactly.
/// </summary>
internal static DataFeatures SupportedFeatures => DataFeatures.None;
internal static DataFeatures SupportedFeatures => DataFeatures.History;
/// <summary>
/// Whether this call negotiated history against <paramref name="caps"/>. Refines the recorded effective set: an
/// origin that cannot serve history drops it, so the call stays v1-shaped.
/// </summary>
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;
}
/// <summary>The v1 shape of a capabilities response: no history field and no HistoryRead bit.</summary>
internal static void StripHistory(W.CapabilitiesResponse response)
{
response.History = null;
response.Operations &= ~(uint)DataOperations.HistoryRead;
}
/// <summary>The v1 shape of a metadata item: no history info and no HistoryRead bit.</summary>
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"));
/// <summary>The feature set recorded for this call by <see cref="NegotiateFeatures"/> (v1 when absent).</summary>
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(); }
});
/// <summary>
/// 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.
/// </summary>
public override Task<W.HistoryReadResponse> 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<DataHistoryReadResult> 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;
});
/// <summary>
/// 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).
/// </summary>
private static DataHistoryChannel Channel(ServerCallContext context)
{
var http = context.GetHttpContext();
var closed = http.Features.Get<Microsoft.AspNetCore.Connections.Features.IConnectionLifetimeFeature>()?.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,