11 Commits

Author SHA1 Message Date
Joseph Doherty be60d0b8d9 test: HistorianSession end-to-end round-trip (write+read+status+ping on one session, env-gated)
Claude-Session: https://claude.ai/code/session_012SDSQ3AcaXqPcBtDESBRii
2026-06-25 03:09:18 -04:00
Joseph Doherty 15da8516ba feat: HistorianClient.OpenSessionAsync(kind) — open a reusable HistorianSession 2026-06-25 03:07:02 -04:00
Joseph Doherty d2b00fcda5 fix: idempotent HistorianSession.DisposeAsync + upfront cancellation check 2026-06-25 03:05:10 -04:00
Joseph Doherty ad2c02eb42 feat: HistorianSession primitive — reusable authenticated session over the …OnSession seams 2026-06-25 02:59:36 -04:00
Joseph Doherty d42019f481 feat(grpc): HistorianSessionKind + …OnSession seams (read/status/tag-write) 2026-06-25 02:52:32 -04:00
Joseph Doherty a0b5d35e48 docs: write-spike results — write-reuse GREEN, ONE-KIND pool confirmed 2026-06-25 02:11:10 -04:00
Joseph Doherty 9909921e87 test(grpc): write-reuse + read-on-write-session probe (one-vs-two-kind decider) 2026-06-25 02:08:23 -04:00
Joseph Doherty f8db01fd7f feat(grpc): add RunWriteOnSession seam for write-reuse spike 2026-06-25 02:04:52 -04:00
Joseph Doherty 3849f17746 docs: handshake-reuse spike results + verdict (GREEN, idle timeout ~20-25s) 2026-06-25 01:19:50 -04:00
Joseph Doherty 899f9ccf6b test(grpc): env-gated handshake-reuse spike (validity + latency + idle sweep) 2026-06-25 01:10:19 -04:00
Joseph Doherty 96f10372de feat(grpc): add RunRawQueryOnSession seam for handshake-reuse spike 2026-06-25 01:06:03 -04:00
10 changed files with 860 additions and 31 deletions
@@ -0,0 +1,126 @@
# Handshake / session-reuse spike — live results
> **Question:** does the 2023 R2 historian honor REUSING one authenticated session
> (channel + `OpenConnection` client handle) across multiple operations, instead of
> the per-operation Create+handshake the SDK does today? This is the precondition for
> "handshake amortization" (HistorianGateway `pending.md` A1).
>
> **Verdict: GREEN — reuse works and the win is large — but the server idle-expires a
> session in ~20–25 s, so a reuse pool must keep sessions warm.**
**Date:** 2026-06-25
**Branch:** `spike/handshake-reuse`
**Server:** live 2023 R2 (`wonder-sql-vd03`), RemoteGrpc transport, read-only test tag.
**Harness:** `tests/AVEVA.Historian.Client.Tests/HandshakeReuseSpikeTests.cs` driving the new
internal seam `HistorianGrpcReadOrchestrator.RunRawQueryOnSession(connection, clientHandle, …)`
(runs a raw query against an externally-supplied, already-authenticated connection + handle —
no Create, no handshake).
---
## 1. Reuse validity — GREEN
`ReusedSession_RunsManyReads_AllSucceed` **passed**: one `HistorianGrpcChannelFactory.Create`
+ one `HistorianGrpcHandshake.OpenSession`, then **5 consecutive `RunRawQueryOnSession` reads on
the same `ClientHandle`** — all returned rows.
```
open-session (handshake) = 325 ms
reused-read[0] = 96 ms, rows=8
reused-read[1] = 101 ms, rows=8
reused-read[2] = 179 ms, rows=8
reused-read[3] = 92 ms, rows=8
reused-read[4] = 95 ms, rows=8
```
The server accepts the same client handle across back-to-back `StartQuery`/`GetNextQueryResultBuffer`/
`EndQuery` cycles. Per-query handles are opened/closed each op; the **session** handle is the reused
artifact.
## 2. Win magnitude — large (~4.7×)
`ReusedSession_VsPerCallPath_LogsLatencyDelta` (logged, not asserted):
```
per-call (5 ops) = 2626 ms # fresh Create + full handshake + query, ×5
amortized (5 ops) = 561 ms # one handshake + 5 reused reads
saving over 5 ops = 2065 ms
```
The handshake (`GetInterfaceVersion` → `ValidateClientCredential` NTLM token loop →
`OpenConnection`, ~325 ms) dominates per-call cost. Amortized, a read is ~110 ms vs ~525 ms
per-call. **Amortization is clearly worth the refactor for any burst of activity.**
## 3. Expiry — idle timeout ~20–25 s (NOT an absolute TTL)
`ReusedSession_IdleSweep_SurfacesExpiryTier` rethrows at the first idle gap the server rejects.
Coarse sweep `[0, 30]`: `idle 0s → OK`, `idle 30s → BROKE`.
Fine sweep `[0,5,10,15,20,25,30]`:
```
idle 0s -> OK (rows=8)
idle 5s -> OK
idle 10s -> OK
idle 15s -> OK
idle 20s -> OK # session age here ≈ 50 s cumulative, still alive
idle 25s -> BROKE (InvalidOperationException: gRPC StartQuery (raw) failed, errorLen=5)
```
**Key inference — it's an idle timeout, not a fixed session lifetime.** The reads at gaps of
5/10/15/20 s kept succeeding even though the cumulative session age reached ~50 s by the 20 s-gap
read. The session only died after a **≥25 s idle gap**. So a session survives indefinitely as long
as operations are spaced under ~20 s apart; a quiet gap of ≥25 s invalidates it.
Expired-session failure mode on the wire: `StartQuery` returns `BSuccess=false` with a 5-byte error
buffer, surfaced by the SDK as `InvalidOperationException: gRPC StartQuery (raw) failed
(errorLen=5)`.
---
## 4. Implications for Phase 1 (the full amortization refactor)
A reuse pool is viable and high-value, with two requirements driven by §3:
1. **Keep sessions warm.** Ping each pooled session well under the ~20 s idle floor (e.g. a
~10–15 s keepalive — a cheap handle-using op such as `GetSystemParameter`) so a steady-state
session never crosses the idle timeout. Without a keepalive, amortization only helps within a
<~20 s activity burst.
2. **Reactive re-auth on expiry.** Treat `StartQuery failed (errorLen=5)` (and the equivalent on
other handle ops) as an expired-session signal: evict the session and re-handshake on next use
(one handshake penalty). In HistorianGateway this maps onto the existing
`IHistorianConnectionPool.ReportFaulted` eviction seam.
**Concurrency note (unchanged guidance):** lease a session exclusively per-op from a bounded pool —
this validity test only exercised *sequential* reuse, so concurrent use of one handle (esp.
streaming cursors) remains unproven and should be avoided by exclusive leasing.
**Gate decision:** GREEN → HistorianGateway A1 Phase 1 (HistorianSession primitive + orchestrator
acquire/execute split + re-vendor + leased-session pool with keepalive) is warranted and earns its
own design + plan.
---
## 5. Write-spike addendum (Phase 1 Stage 0) — 2026-06-25
Extends the harness to the write path via the `RunWriteOnSession` seam on
`HistorianGrpcHistoricalWriteOrchestrator`. Read + bounded writes to `HISTORIAN_WRITE_SANDBOX_TAG`
only.
```
reused-write[0] = 377 ms, ok=True
reused-write[1] = 76 ms, ok=True # 2nd write reuses the same 0x401 session — no handshake
read-on-0x401 -> OK (rows=3) # a WRITE-enabled session ALSO serves reads
```
**Findings:**
- **Write-session reuse — GREEN.** Two historical writes on one reused `0x401` (write-enabled)
session both succeed; the 2nd skips the Create+handshake.
- **One-kind pool — CONFIRMED.** A `0x401` session served a `StartQuery` read (`session.ClientHandle`)
successfully. So a single **write-enabled** session serves both reads and writes — the gateway pool
needs **one session kind**, not two. (`0x401` "unlocks write capability" and is a superset of the
`0x402` read-only mode, as the vendored comment hinted.)
**Decision for Phase 1 Stage 3:** the gateway always opens `WriteEnabled` sessions; the
`HistorianSessionPool` is a **single warm pool** (no per-kind keying). `HistorianSessionKind` still
exists upstream for API clarity, but the gateway uses only `WriteEnabled`.
@@ -47,6 +47,24 @@ internal sealed class HistorianGrpcHistoricalWriteOrchestrator
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(
connection, _options, cancellationToken,
connectionMode: HistorianWcfAuthChainHelper.NativeIntegratedWriteEnabledConnectionMode);
return RunWriteOnSession(connection, session, tag, values, cancellationToken);
}
// Spike/Phase-1 seam (A1): run the historical write against an EXTERNALLY-supplied, already-
// authenticated write-enabled (0x401) connection + session — NO Create()/handshake here. Run()
// delegates so the per-call path and the reuse path share one write implementation (DRY).
internal bool RunWriteOnSession(
HistorianGrpcConnection connection,
HistorianGrpcHandshake.Session session,
string tag,
IReadOnlyList<HistorianHistoricalValue> values,
CancellationToken cancellationToken)
{
if (values.Count == 0)
{
return true;
}
string handle = session.StringHandle;
DateTime Deadline() => DateTime.UtcNow.Add(_options.RequestTimeout);
@@ -102,12 +102,45 @@ internal sealed class HistorianGrpcReadOrchestrator
}
}
// Spike/Phase-1 seam (pending.md A1): run a raw query against an EXTERNALLY-supplied, already-
// authenticated connection + client handle — i.e. NO Create()/handshake here. RunRawChain delegates
// to this so the per-call path and the reuse path share one query implementation (DRY). The handshake
// reuse-probe test drives this directly to measure whether the server honors a reused session.
internal List<HistorianSample> RunRawQueryOnSession(
HistorianGrpcConnection connection,
uint clientHandle,
string tag,
DateTime startUtc,
DateTime endUtc,
int maxValues,
CancellationToken cancellationToken)
{
HistorianDataQueryRequest request = HistorianWcfReadOrchestrator.BuildDataQueryRequest(tag, startUtc, endUtc, maxValues);
return RunQuery(connection, clientHandle, request, maxValues, cancellationToken);
}
private List<HistorianSample> RunRawChain(string tag, DateTime startUtc, DateTime endUtc, int maxValues, CancellationToken cancellationToken)
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
uint clientHandle = OpenAuthenticatedConnection(connection, cancellationToken);
HistorianDataQueryRequest request = HistorianWcfReadOrchestrator.BuildDataQueryRequest(tag, startUtc, endUtc, maxValues);
return RunQuery(connection, clientHandle, request, maxValues, cancellationToken);
return RunRawQueryOnSession(connection, clientHandle, tag, startUtc, endUtc, maxValues, cancellationToken);
}
// Spike/Phase-1 seam (pending.md A1): run an aggregate query against an EXTERNALLY-supplied,
// already-authenticated connection + client handle — i.e. NO Create()/handshake here.
// RunAggregateChain delegates to this so the per-call path and the reuse path share one query
// implementation (DRY).
internal List<HistorianAggregateSample> RunAggregateQueryOnSession(
HistorianGrpcConnection connection,
uint clientHandle,
string tag,
DateTime startUtc,
DateTime endUtc,
RetrievalMode mode,
TimeSpan interval,
CancellationToken ct)
{
return RunAggregateQuery(connection, clientHandle, tag, startUtc, endUtc, mode, interval, ct);
}
private List<HistorianAggregateSample> RunAggregateChain(
@@ -115,23 +148,29 @@ internal sealed class HistorianGrpcReadOrchestrator
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
uint clientHandle = OpenAuthenticatedConnection(connection, cancellationToken);
return RunAggregateQuery(connection, clientHandle, tag, startUtc, endUtc, mode, interval, cancellationToken);
return RunAggregateQueryOnSession(connection, clientHandle, tag, startUtc, endUtc, mode, interval, cancellationToken);
}
private List<HistorianSample> RunAtTimeChain(string tag, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken)
// Spike/Phase-1 seam (pending.md A1): run an at-time query against an EXTERNALLY-supplied,
// already-authenticated connection + client handle — i.e. NO Create()/handshake here.
// RunAtTimeChain delegates to this so the per-call path and the reuse path share one
// implementation (DRY).
internal List<HistorianSample> RunAtTimeOnSession(
HistorianGrpcConnection connection,
uint clientHandle,
string tag,
IReadOnlyList<DateTime> timestampsUtc,
CancellationToken ct)
{
if (timestampsUtc.Count == 0)
{
return [];
}
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
uint clientHandle = OpenAuthenticatedConnection(connection, cancellationToken);
List<HistorianSample> results = new(timestampsUtc.Count);
foreach (DateTime ts in timestampsUtc)
{
cancellationToken.ThrowIfCancellationRequested();
ct.ThrowIfCancellationRequested();
DateTime tsUtc = ts.ToUniversalTime();
List<HistorianAggregateSample> aggregates = RunAggregateQuery(
connection,
@@ -141,7 +180,7 @@ internal sealed class HistorianGrpcReadOrchestrator
tsUtc + TimeSpan.FromTicks(1),
RetrievalMode.Interpolated,
TimeSpan.FromTicks(2),
cancellationToken);
ct);
if (aggregates.Count == 0)
{
@@ -163,6 +202,18 @@ internal sealed class HistorianGrpcReadOrchestrator
return results;
}
private List<HistorianSample> RunAtTimeChain(string tag, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken)
{
if (timestampsUtc.Count == 0)
{
return [];
}
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
uint clientHandle = OpenAuthenticatedConnection(connection, cancellationToken);
return RunAtTimeOnSession(connection, clientHandle, tag, timestampsUtc, cancellationToken);
}
private uint OpenAuthenticatedConnection(HistorianGrpcConnection connection, CancellationToken cancellationToken)
=> HistorianGrpcHandshake.OpenAuthenticatedConnection(connection, _options, cancellationToken);
@@ -28,7 +28,19 @@ internal static class HistorianGrpcStatusClient
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(options);
uint clientHandle = HistorianGrpcHandshake.OpenAuthenticatedConnection(connection, options, cancellationToken);
return GetSystemParameterOnSession(connection, clientHandle, options, parameterName, cancellationToken);
}
// Spike/Phase-1 seam (pending.md A1): run GetSystemParameter against an EXTERNALLY-supplied,
// already-authenticated connection + client handle — NO Create()/handshake here. GetSystemParameter
// delegates so the per-call path and the reuse path share one RPC implementation (DRY).
internal static string? GetSystemParameterOnSession(
HistorianGrpcConnection connection,
uint clientHandle,
HistorianClientOptions options,
string parameterName,
CancellationToken cancellationToken)
{
var statusClient = new GrpcStatus.StatusService.StatusServiceClient(connection.Channel);
GrpcStatus.GetSystemParameterResponse response = statusClient.GetSystemParameter(
new GrpcStatus.GetSystemParameterRequest { UiHandle = clientHandle, StrParameterName = parameterName },
@@ -82,23 +94,7 @@ internal static class HistorianGrpcStatusClient
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(options);
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, options, cancellationToken);
var statusClient = new GrpcStatus.StatusService.StatusServiceClient(connection.Channel);
GrpcStatus.GetHistorianConsoleStatusResponse response = statusClient.GetHistorianConsoleStatus(
new GrpcStatus.GetHistorianConsoleStatusRequest { StrHandle = session.StringHandle },
connection.Metadata,
DateTime.UtcNow.Add(options.RequestTimeout),
cancellationToken);
if (response.Status?.BSuccess ?? false)
{
// Measured: server reachable, storage console reporting normally → not-storing baseline.
return NotStoring(errorOccurred: false, error: null);
}
byte[] err = response.Status?.BtError?.ToByteArray() ?? [];
string detail = err.Length == 0 ? "GetHistorianConsoleStatus returned failure." : Convert.ToHexString(err);
return NotStoring(errorOccurred: true, error: $"GetHistorianConsoleStatus failed: {detail}");
return GetStoreForwardStatusOnSession(connection, session.StringHandle, options, NotStoring, cancellationToken);
}
catch (OperationCanceledException)
{
@@ -111,6 +107,36 @@ internal static class HistorianGrpcStatusClient
}
}
// Spike/Phase-1 seam (pending.md A1): run GetHistorianConsoleStatus against an EXTERNALLY-supplied,
// already-authenticated connection + string handle — NO Create()/handshake here. GetStoreForwardStatus
// delegates so the per-call path and the reuse path share one RPC implementation (DRY). The
// unreachable/auth-failure try/catch (which must also cover the handshake) stays with the per-call
// method; this seam runs only the RPC + result mapping against the supplied session.
internal static HistorianStoreForwardStatus GetStoreForwardStatusOnSession(
HistorianGrpcConnection connection,
string stringHandle,
HistorianClientOptions options,
Func<bool, string?, HistorianStoreForwardStatus> notStoring,
CancellationToken cancellationToken)
{
var statusClient = new GrpcStatus.StatusService.StatusServiceClient(connection.Channel);
GrpcStatus.GetHistorianConsoleStatusResponse response = statusClient.GetHistorianConsoleStatus(
new GrpcStatus.GetHistorianConsoleStatusRequest { StrHandle = stringHandle },
connection.Metadata,
DateTime.UtcNow.Add(options.RequestTimeout),
cancellationToken);
if (response.Status?.BSuccess ?? false)
{
// Measured: server reachable, storage console reporting normally → not-storing baseline.
return notStoring(false, null);
}
byte[] err = response.Status?.BtError?.ToByteArray() ?? [];
string detail = err.Length == 0 ? "GetHistorianConsoleStatus returned failure." : Convert.ToHexString(err);
return notStoring(true, $"GetHistorianConsoleStatus failed: {detail}");
}
/// <summary>
/// Returns a <em>measured</em> connection status over the 2023 R2 gRPC transport (plan #5). Mirrors
/// <see cref="Wcf.HistorianWcfStatusClient"/>'s synthesize-from-handshake approach: it opens an
@@ -135,11 +161,7 @@ internal static class HistorianGrpcStatusClient
// A successful OpenConnection yields a non-empty storage-session GUID — proof the server and
// its storage session are reachable, the gRPC analog of the WCF handshake probe.
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, options, cancellationToken);
connected = session.StorageSessionId != Guid.Empty;
if (!connected)
{
error = "OpenConnection returned an empty storage-session handle.";
}
(connected, error) = EvaluateConnectionStatusOnSession(connection, session);
}
catch (OperationCanceledException)
{
@@ -162,6 +184,21 @@ internal static class HistorianGrpcStatusClient
ConnectionKind: HistorianConnectionKind.Process);
}
// Spike/Phase-1 seam (pending.md A1): evaluate connection status against an EXTERNALLY-supplied,
// already-authenticated connection + session — NO Create()/handshake here. GetConnectionStatus
// delegates so the per-call path and the reuse path share one evaluation (DRY). Unlike the other
// status seams there is no follow-on RPC: connectivity is derived entirely from the handshake's own
// storage-session GUID (a successful OpenConnection yields a non-empty GUID). The unreachable/auth
// try/catch (which must also cover the handshake) stays with the per-call method.
internal static (bool Connected, string? Error) EvaluateConnectionStatusOnSession(
HistorianGrpcConnection connection,
HistorianGrpcHandshake.Session session)
{
bool connected = session.StorageSessionId != Guid.Empty;
string? error = connected ? null : "OpenConnection returned an empty storage-session handle.";
return (connected, error);
}
/// <summary>
/// Reads the Historian server's system time-zone name (roadmap item R1.3,
/// <c>StatusService.GetSystemTimeZoneName</c>). Unlike the 2020 WCF surface — where the native
@@ -56,7 +56,18 @@ internal sealed class HistorianGrpcTagWriteOrchestrator
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, _options, cancellationToken, WriteEnabledConnectionMode);
return EnsureTagOnSession(connection, session, definition, cancellationToken);
}
// Spike/Phase-1 seam (pending.md A1): run EnsureTags against an EXTERNALLY-supplied, already-
// authenticated write-enabled (0x401) connection + session — NO Create()/handshake here. EnsureTag
// delegates so the per-call path and the reuse path share one op implementation (DRY).
internal bool EnsureTagOnSession(
HistorianGrpcConnection connection,
HistorianGrpcHandshake.Session session,
HistorianTagDefinition definition,
CancellationToken cancellationToken)
{
byte[] payload = HistorianTagWriteProtocol.SerializeAnalogCTagMetadata(
tagName: definition.TagName,
description: definition.Description,
@@ -97,7 +108,18 @@ internal sealed class HistorianGrpcTagWriteOrchestrator
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, _options, cancellationToken, WriteEnabledConnectionMode);
return DeleteTagOnSession(connection, session, tagName, cancellationToken);
}
// Spike/Phase-1 seam (pending.md A1): run DeleteTags against an EXTERNALLY-supplied, already-
// authenticated write-enabled (0x401) connection + session — NO Create()/handshake here. DeleteTag
// delegates so the per-call path and the reuse path share one op implementation (DRY).
internal bool DeleteTagOnSession(
HistorianGrpcConnection connection,
HistorianGrpcHandshake.Session session,
string tagName,
CancellationToken cancellationToken)
{
// DeleteTags takes the transient uint client handle (not the string handle), per the WCF wire capture.
byte[] tagNames = HistorianTagWriteProtocol.SerializeDeleteTagNames([tagName]);
var historyClient = new GrpcHistory.HistoryService.HistoryServiceClient(connection.Channel);
@@ -131,7 +153,20 @@ internal sealed class HistorianGrpcTagWriteOrchestrator
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, _options, cancellationToken, WriteEnabledConnectionMode);
return AddTagExtendedPropertiesOnSession(connection, session, tagName, properties, cancellationToken);
}
// Spike/Phase-1 seam (pending.md A1): run AddTagExtendedProperties against an EXTERNALLY-supplied,
// already-authenticated write-enabled (0x401) connection + session — NO Create()/handshake here.
// AddTagExtendedProperties delegates so the per-call path and the reuse path share one op
// implementation (DRY).
internal bool AddTagExtendedPropertiesOnSession(
HistorianGrpcConnection connection,
HistorianGrpcHandshake.Session session,
string tagName,
IReadOnlyList<HistorianTagExtendedProperty> properties,
CancellationToken cancellationToken)
{
byte[] inBuff = HistorianTagExtendedPropertyProtocol.SerializeAddRequest(tagName, properties);
var historyClient = new GrpcHistory.HistoryService.HistoryServiceClient(connection.Channel);
GrpcHistory.AddTagExtendedPropertiesResponse response = historyClient.AddTagExtendedProperties(
@@ -275,7 +310,18 @@ internal sealed class HistorianGrpcTagWriteOrchestrator
{
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(_options);
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, _options, cancellationToken, WriteEnabledConnectionMode);
return RenameTagsOnSession(connection, session, pairs, cancellationToken);
}
// Spike/Phase-1 seam (pending.md A1): run StartJob (rename) against an EXTERNALLY-supplied, already-
// authenticated write-enabled (0x401) connection + session — NO Create()/handshake here. RenameTags
// delegates so the per-call path and the reuse path share one op implementation (DRY).
internal HistorianTagRenameResult RenameTagsOnSession(
HistorianGrpcConnection connection,
HistorianGrpcHandshake.Session session,
IReadOnlyList<(string OldName, string NewName)> pairs,
CancellationToken cancellationToken)
{
byte[] jobBuffer = HistorianTagRenameProtocol.SerializeRenameJob(pairs);
var historyClient = new GrpcHistory.HistoryService.HistoryServiceClient(connection.Channel);
GrpcHistory.StartJobResponse response = historyClient.StartJob(
@@ -347,6 +347,41 @@ public sealed class HistorianClient : IAsyncDisposable
: new HistorianWcfTagWriteOrchestrator(_options).RenameTagsAsync(pairs, cancellationToken);
}
/// <summary>
/// Opens a reusable authenticated <see cref="HistorianSession"/> over the 2023 R2 gRPC transport.
/// The caller owns the session and must dispose it. Reusing the session across ops amortizes the auth
/// handshake; the server idle-expires it in ~20-25s, so keep it warm (HistorianSession.PingAsync) or
/// re-open. RemoteGrpc only.
/// </summary>
public async Task<HistorianSession> OpenSessionAsync(HistorianSessionKind kind, CancellationToken cancellationToken = default)
{
if (_options.Transport != HistorianTransport.RemoteGrpc)
{
throw new ProtocolEvidenceMissingException(
"HistorianSession is only supported over the 2023 R2 RemoteGrpc transport.");
}
return await Task.Run(() =>
{
uint mode = kind == HistorianSessionKind.WriteEnabled
? HistorianWcfAuthChainHelper.NativeIntegratedWriteEnabledConnectionMode
: HistorianWcfAuthChainHelper.NativeIntegratedReadOnlyConnectionMode;
Grpc.HistorianGrpcConnection connection = Grpc.HistorianGrpcChannelFactory.Create(_options);
try
{
Grpc.HistorianGrpcHandshake.Session session =
Grpc.HistorianGrpcHandshake.OpenSession(connection, _options, cancellationToken, connectionMode: mode);
return new HistorianSession(connection, session, _options, kind);
}
catch
{
connection.Dispose(); // don't leak the channel if the handshake fails
throw;
}
}, cancellationToken).ConfigureAwait(false);
}
public ValueTask DisposeAsync()
{
return ValueTask.CompletedTask;
@@ -0,0 +1,192 @@
using System.Runtime.CompilerServices;
using AVEVA.Historian.Client.Grpc;
using AVEVA.Historian.Client.Models;
namespace AVEVA.Historian.Client;
/// <summary>A live, reusable authenticated Historian session: holds one gRPC connection + one
/// OpenConnection handle and runs ops on them WITHOUT re-handshaking. Reuse across ops amortizes the
/// auth handshake. Idle-expires server-side in ~20-25s — callers keep it warm (PingAsync) or re-open.
/// Reads/historical-write/tag-write/status only; events are NOT exposed (separate channel+auth).</summary>
public sealed class HistorianSession : IAsyncDisposable
{
private readonly HistorianGrpcConnection _connection;
private readonly HistorianGrpcHandshake.Session _session;
private readonly HistorianClientOptions _options;
private int _disposed;
/// <summary>Whether this session was opened read-only or write-enabled (the Open2 connection mode).</summary>
public HistorianSessionKind Kind { get; }
internal HistorianSession(
HistorianGrpcConnection connection,
HistorianGrpcHandshake.Session session,
HistorianClientOptions options,
HistorianSessionKind kind)
{
_connection = connection;
_session = session;
_options = options;
Kind = kind;
}
// --- reads (mirror the orchestrators' async-enumerable wrapping; call the …OnSession seams,
// which take the transient uint client handle) ---
/// <summary>Raw values for <paramref name="tag"/> in [<paramref name="startUtc"/>,
/// <paramref name="endUtc"/>], capped at <paramref name="maxValues"/>, on the held session.</summary>
public async IAsyncEnumerable<HistorianSample> ReadRawAsync(
string tag,
DateTime startUtc,
DateTime endUtc,
int maxValues,
[EnumeratorCancellation] CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var orch = new HistorianGrpcReadOrchestrator(_options);
IReadOnlyList<HistorianSample> rows = await Task.Run(
() => orch.RunRawQueryOnSession(_connection, _session.ClientHandle, tag, startUtc, endUtc, maxValues, ct), ct)
.ConfigureAwait(false);
foreach (HistorianSample sample in rows)
{
ct.ThrowIfCancellationRequested();
yield return sample;
}
}
/// <summary>Aggregate values for <paramref name="tag"/> over [<paramref name="startUtc"/>,
/// <paramref name="endUtc"/>] in <paramref name="interval"/> buckets, using the supplied
/// retrieval <paramref name="mode"/>, on the held session.</summary>
public async IAsyncEnumerable<HistorianAggregateSample> ReadAggregateAsync(
string tag,
DateTime startUtc,
DateTime endUtc,
RetrievalMode mode,
TimeSpan interval,
[EnumeratorCancellation] CancellationToken ct = default)
{
ct.ThrowIfCancellationRequested();
var orch = new HistorianGrpcReadOrchestrator(_options);
IReadOnlyList<HistorianAggregateSample> rows = await Task.Run(
() => orch.RunAggregateQueryOnSession(_connection, _session.ClientHandle, tag, startUtc, endUtc, mode, interval, ct), ct)
.ConfigureAwait(false);
foreach (HistorianAggregateSample sample in rows)
{
ct.ThrowIfCancellationRequested();
yield return sample;
}
}
/// <summary>Interpolated values for <paramref name="tag"/> at each of the supplied
/// <paramref name="timestampsUtc"/>, on the held session.</summary>
public Task<IReadOnlyList<HistorianSample>> ReadAtTimeAsync(
string tag,
IReadOnlyList<DateTime> timestampsUtc,
CancellationToken ct = default)
{
var orch = new HistorianGrpcReadOrchestrator(_options);
return Task.Run<IReadOnlyList<HistorianSample>>(
() => orch.RunAtTimeOnSession(_connection, _session.ClientHandle, tag, timestampsUtc, ct), ct);
}
// --- writes (the …OnSession seams take the full Session, since the historical write keys on the
// string handle + tag GUID and the tag-config ops mix string/uint handles) ---
/// <summary>Writes historical/backfill values for <paramref name="tag"/> on the held (write-enabled) session.</summary>
public Task<bool> AddHistoricalValuesAsync(
string tag,
IReadOnlyList<HistorianHistoricalValue> values,
CancellationToken ct = default)
{
var orch = new HistorianGrpcHistoricalWriteOrchestrator(_options);
return Task.Run(() => orch.RunWriteOnSession(_connection, _session, tag, values, ct), ct);
}
/// <summary>Ensures the tag described by <paramref name="definition"/> exists on the held (write-enabled) session.</summary>
public Task<bool> EnsureTagAsync(HistorianTagDefinition definition, CancellationToken ct = default)
{
var orch = new HistorianGrpcTagWriteOrchestrator(_options);
return Task.Run(() => orch.EnsureTagOnSession(_connection, _session, definition, ct), ct);
}
/// <summary>Deletes <paramref name="tagName"/> on the held (write-enabled) session.</summary>
public Task<bool> DeleteTagAsync(string tagName, CancellationToken ct = default)
{
var orch = new HistorianGrpcTagWriteOrchestrator(_options);
return Task.Run(() => orch.DeleteTagOnSession(_connection, _session, tagName, ct), ct);
}
/// <summary>Renames the supplied (old,new) tag-name <paramref name="pairs"/> on the held (write-enabled) session.</summary>
public Task<HistorianTagRenameResult> RenameTagsAsync(
IReadOnlyList<(string OldName, string NewName)> pairs,
CancellationToken ct = default)
{
var orch = new HistorianGrpcTagWriteOrchestrator(_options);
return Task.Run(() => orch.RenameTagsOnSession(_connection, _session, pairs, ct), ct);
}
/// <summary>Adds extended <paramref name="properties"/> to <paramref name="tagName"/> on the held (write-enabled) session.</summary>
public Task<bool> AddTagExtendedPropertiesAsync(
string tagName,
IReadOnlyList<HistorianTagExtendedProperty> properties,
CancellationToken ct = default)
{
var orch = new HistorianGrpcTagWriteOrchestrator(_options);
return Task.Run(() => orch.AddTagExtendedPropertiesOnSession(_connection, _session, tagName, properties, ct), ct);
}
// --- status + keepalive (the status seams are static; handle shape differs per op) ---
/// <summary>Reads the named system parameter (e.g. "HistorianVersion") on the held session.</summary>
public Task<string?> GetSystemParameterAsync(string parameterName, CancellationToken ct = default)
=> Task.Run(() => HistorianGrpcStatusClient.GetSystemParameterOnSession(
_connection, _session.ClientHandle, _options, parameterName, ct), ct);
/// <summary>Reports connection status derived from the held session's storage handle (no follow-on RPC).</summary>
public Task<HistorianConnectionStatus> GetConnectionStatusAsync(CancellationToken ct = default)
=> Task.Run(() =>
{
(bool connected, string? error) = HistorianGrpcStatusClient.EvaluateConnectionStatusOnSession(_connection, _session);
return new HistorianConnectionStatus(
ServerName: _options.Host,
Pending: false,
ErrorOccurred: !connected,
Error: error,
ConnectedToServer: connected,
ConnectedToServerStorage: connected,
ConnectedToStoreForward: false,
ConnectionKind: HistorianConnectionKind.Process);
}, ct);
/// <summary>Reports a measured store-forward status (GetHistorianConsoleStatus) on the held session.</summary>
public Task<HistorianStoreForwardStatus> GetStoreForwardStatusAsync(CancellationToken ct = default)
=> Task.Run(() =>
{
HistorianStoreForwardStatus NotStoring(bool errorOccurred, string? error) => new(
ServerName: _options.Host,
Pending: false,
ErrorOccurred: errorOccurred,
Error: error,
DataStored: false,
Storing: false,
ConnectionKind: HistorianConnectionKind.Process);
return HistorianGrpcStatusClient.GetStoreForwardStatusOnSession(
_connection, _session.StringHandle, _options, NotStoring, ct);
}, ct);
/// <summary>Keeps the session warm against the server's ~20-25s idle expiry by issuing a cheap
/// system-parameter read. Call periodically (or before a latency-sensitive op) to avoid re-handshaking.</summary>
public Task PingAsync(CancellationToken ct = default) => GetSystemParameterAsync("HistorianVersion", ct);
/// <summary>Disposes the underlying gRPC connection (closes the channel). The server-side session
/// also idle-expires on its own; this releases the local channel resources immediately.</summary>
public ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
_connection.Dispose();
}
return ValueTask.CompletedTask;
}
}
@@ -0,0 +1,5 @@
namespace AVEVA.Historian.Client;
/// <summary>Connection mode for an authenticated session. WriteEnabled (0x401) is a superset that
/// also serves reads (live-verified 2026-06-25); ReadOnly (0x402) is read-only.</summary>
public enum HistorianSessionKind { ReadOnly, WriteEnabled }
@@ -0,0 +1,231 @@
using System.Diagnostics;
using AVEVA.Historian.Client.Grpc;
using AVEVA.Historian.Client.Models;
using AVEVA.Historian.Client.Wcf;
using Xunit.Abstractions;
namespace AVEVA.Historian.Client.Tests;
/// <summary>
/// SPIKE (pending.md A1): does the 2023 R2 historian honor REUSING one authenticated session across
/// many operations — the precondition for handshake amortization? Env-gated exactly like
/// <see cref="HistorianGrpcIntegrationTests"/> (silent skip without HISTORIAN_GRPC_HOST +
/// HISTORIAN_TEST_TAG + HISTORIAN_USER). READ-ONLY — no writes, safe against live data. Reuse
/// validity is ASSERTED; latency numbers are LOGGED only (no flaky perf gates).
/// </summary>
public sealed class HandshakeReuseSpikeTests
{
private const int ReuseOps = 5;
private readonly ITestOutputHelper _output;
public HandshakeReuseSpikeTests(ITestOutputHelper output) => _output = output;
// (1) REUSE VALIDITY: one session, N reads on the same clientHandle. If the server rejects handle
// reuse, read #2+ throws -> RED finding. All succeed -> GREEN finding.
[Fact]
public void ReusedSession_RunsManyReads_AllSucceed()
{
if (!TryGetEnv(out string host, out string tag)) return;
HistorianClientOptions options = BuildOptions(host);
(DateTime startUtc, DateTime endUtc) = LastSevenDays();
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(options);
var swHandshake = Stopwatch.StartNew();
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, options, CancellationToken.None);
swHandshake.Stop();
_output.WriteLine($"open-session (handshake) = {swHandshake.ElapsedMilliseconds} ms");
var orchestrator = new HistorianGrpcReadOrchestrator(options);
for (int i = 0; i < ReuseOps; i++)
{
var sw = Stopwatch.StartNew();
List<HistorianSample> rows = orchestrator.RunRawQueryOnSession(
connection, session.ClientHandle, tag, startUtc, endUtc, maxValues: 8, CancellationToken.None);
sw.Stop();
_output.WriteLine($"reused-read[{i}] = {sw.ElapsedMilliseconds} ms, rows={rows.Count}");
Assert.NotEmpty(rows);
Assert.All(rows, r => Assert.Equal(tag, r.TagName));
}
}
// (2) WIN MAGNITUDE: full per-call path (fresh Create+handshake+query) vs amortized (one handshake,
// N reused reads). Logged only — quantifies whether amortization is worth the refactor.
[Fact]
public async Task ReusedSession_VsPerCallPath_LogsLatencyDelta()
{
if (!TryGetEnv(out string host, out string tag)) return;
HistorianClientOptions options = BuildOptions(host);
(DateTime startUtc, DateTime endUtc) = LastSevenDays();
HistorianClient client = new(options);
var swPerCall = Stopwatch.StartNew();
for (int i = 0; i < ReuseOps; i++)
{
await foreach (HistorianSample _ in client.ReadRawAsync(tag, startUtc, endUtc, 8, CancellationToken.None)) { }
}
swPerCall.Stop();
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(options);
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, options, CancellationToken.None);
var orchestrator = new HistorianGrpcReadOrchestrator(options);
var swAmortized = Stopwatch.StartNew();
for (int i = 0; i < ReuseOps; i++)
{
orchestrator.RunRawQueryOnSession(connection, session.ClientHandle, tag, startUtc, endUtc, 8, CancellationToken.None);
}
swAmortized.Stop();
_output.WriteLine($"per-call ({ReuseOps} ops) = {swPerCall.ElapsedMilliseconds} ms");
_output.WriteLine($"amortized ({ReuseOps} ops) = {swAmortized.ElapsedMilliseconds} ms");
_output.WriteLine($"saving over {ReuseOps} ops = {swPerCall.ElapsedMilliseconds - swAmortized.ElapsedMilliseconds} ms");
}
// (3) EXPIRY SWEEP: reuse after idle gaps. Default bounded [0s, 30s]; longer tiers opt-in via
// HISTORIAN_REUSE_IDLE_SECONDS="0,30,120,600". Rethrows at the tier where reuse first breaks.
[Fact]
public void ReusedSession_IdleSweep_SurfacesExpiryTier()
{
if (!TryGetEnv(out string host, out string tag)) return;
HistorianClientOptions options = BuildOptions(host);
(DateTime startUtc, DateTime endUtc) = LastSevenDays();
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(options);
HistorianGrpcHandshake.Session session = HistorianGrpcHandshake.OpenSession(connection, options, CancellationToken.None);
var orchestrator = new HistorianGrpcReadOrchestrator(options);
foreach (int delaySec in ParseIdleSweep())
{
if (delaySec > 0) Thread.Sleep(TimeSpan.FromSeconds(delaySec));
try
{
List<HistorianSample> rows = orchestrator.RunRawQueryOnSession(
connection, session.ClientHandle, tag, startUtc, endUtc, 8, CancellationToken.None);
_output.WriteLine($"idle {delaySec,4}s -> OK (rows={rows.Count})");
}
catch (Exception ex)
{
_output.WriteLine($"idle {delaySec,4}s -> BROKE ({ex.GetType().Name})");
throw;
}
}
}
// (A) WRITE REUSE VALIDITY: one externally-opened 0x401 (write-enabled) session, N writes on it via
// RunWriteOnSession — NO Create()/handshake per write. If the server rejects reusing a write session,
// write #2 throws -> RED finding. Both succeed -> GREEN (write-reuse is sound). Bounded writes to the
// sandbox tag ONLY; latency LOGGED, success ASSERTED.
[Fact]
public void WriteEnabledSession_RunsTwoWrites_AllSucceed()
{
if (!TryGetWriteEnv(out string host, out string sandboxTag)) return;
HistorianClientOptions options = BuildOptions(host);
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(options);
HistorianGrpcHandshake.Session session = OpenWriteSession(options, connection);
var writer = new HistorianGrpcHistoricalWriteOrchestrator(options);
for (int i = 0; i < 2; i++)
{
var sw = Stopwatch.StartNew();
bool ok = writer.RunWriteOnSession(connection, session, sandboxTag,
new[] { new HistorianHistoricalValue(DateTime.UtcNow.AddSeconds(-i), 1.0 + i, OpcQuality: 192) },
CancellationToken.None);
sw.Stop();
_output.WriteLine($"reused-write[{i}] = {sw.ElapsedMilliseconds} ms, ok={ok}");
Assert.True(ok);
}
}
// (B) READ-ON-WRITE-SESSION PROBE: can a 0x401 (write-enabled) session ALSO serve a raw read? Decides
// the pool shape — ONE-KIND (a single write-enabled session serves both reads and writes) vs TWO-KIND
// (separate read 0x402 / write 0x401 sessions). The kind is LOGGED, never asserted; any failure is
// swallowed (a rejection is itself the finding, not a test failure). READ-ONLY here.
[Fact]
public void WriteEnabledSession_AlsoServesRead_RecordsKind()
{
if (!TryGetWriteEnv(out string host, out string sandboxTag)) return;
HistorianClientOptions options = BuildOptions(host);
using HistorianGrpcConnection connection = HistorianGrpcChannelFactory.Create(options);
HistorianGrpcHandshake.Session session = OpenWriteSession(options, connection);
(DateTime startUtc, DateTime endUtc) = LastSevenDays();
try
{
List<HistorianSample> rows = new HistorianGrpcReadOrchestrator(options)
.RunRawQueryOnSession(connection, session.ClientHandle, sandboxTag, startUtc, endUtc, 8, CancellationToken.None);
_output.WriteLine($"read-on-0x401 -> OK (rows={rows.Count}) => ONE-KIND pool (write-enabled serves reads)");
}
catch (Exception ex)
{
_output.WriteLine($"read-on-0x401 -> FAILED ({ex.GetType().Name}) => TWO-KIND pool (separate read/write)");
}
}
// --- helpers ---
private static bool TryGetWriteEnv(out string host, out string sandboxTag)
{
host = Environment.GetEnvironmentVariable("HISTORIAN_GRPC_HOST") ?? "";
sandboxTag = Environment.GetEnvironmentVariable("HISTORIAN_WRITE_SANDBOX_TAG") ?? "";
return !string.IsNullOrWhiteSpace(host)
&& !string.IsNullOrWhiteSpace(sandboxTag)
&& !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HISTORIAN_USER"));
}
private static HistorianGrpcHandshake.Session OpenWriteSession(HistorianClientOptions o, HistorianGrpcConnection c)
=> HistorianGrpcHandshake.OpenSession(c, o, CancellationToken.None,
connectionMode: HistorianWcfAuthChainHelper.NativeIntegratedWriteEnabledConnectionMode);
private static bool TryGetEnv(out string host, out string tag)
{
host = Environment.GetEnvironmentVariable("HISTORIAN_GRPC_HOST") ?? "";
tag = Environment.GetEnvironmentVariable("HISTORIAN_TEST_TAG") ?? "";
return !string.IsNullOrWhiteSpace(host)
&& !string.IsNullOrWhiteSpace(tag)
&& !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HISTORIAN_USER"));
}
private static (DateTime StartUtc, DateTime EndUtc) LastSevenDays()
{
DateTime end = DateTime.UtcNow;
return (end - TimeSpan.FromDays(7), end);
}
private static int[] ParseIdleSweep()
{
string? raw = Environment.GetEnvironmentVariable("HISTORIAN_REUSE_IDLE_SECONDS");
if (string.IsNullOrWhiteSpace(raw)) return [0, 30];
return raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(s => int.Parse(s, System.Globalization.CultureInfo.InvariantCulture)).ToArray();
}
private static HistorianClientOptions BuildOptions(string host)
{
string? user = Environment.GetEnvironmentVariable("HISTORIAN_USER");
string? password = Environment.GetEnvironmentVariable("HISTORIAN_PASSWORD");
bool explicitCreds = !string.IsNullOrEmpty(user);
int port = int.TryParse(Environment.GetEnvironmentVariable("HISTORIAN_GRPC_PORT"), out int parsed)
? parsed
: HistorianClientOptions.DefaultGrpcPort;
bool tls = string.Equals(Environment.GetEnvironmentVariable("HISTORIAN_GRPC_TLS"), "true", StringComparison.OrdinalIgnoreCase);
// Optional per-call deadline override (seconds) for slow/remote boxes — heavier aggregate
// modes over a tunnelled link can exceed the 30s default. Falls back to the SDK default.
TimeSpan timeout = int.TryParse(Environment.GetEnvironmentVariable("HISTORIAN_GRPC_TIMEOUT"), out int secs) && secs > 0
? TimeSpan.FromSeconds(secs)
: new HistorianClientOptions { Host = host }.RequestTimeout;
return new HistorianClientOptions
{
Host = host,
Port = port,
Transport = HistorianTransport.RemoteGrpc,
GrpcUseTls = tls,
AllowUntrustedServerCertificate = tls,
ServerDnsIdentity = Environment.GetEnvironmentVariable("HISTORIAN_GRPC_DNSID"),
IntegratedSecurity = !explicitCreds,
UserName = user ?? string.Empty,
Password = password ?? string.Empty,
RequestTimeout = timeout,
Compression = true // the stock client always advertises grpc gzip request encoding
};
}
}
@@ -0,0 +1,88 @@
using AVEVA.Historian.Client.Models;
using Xunit.Abstractions;
namespace AVEVA.Historian.Client.Tests;
/// <summary>
/// Live end-to-end round-trip for <see cref="HistorianSession"/>: open → write → read → status →
/// ping → dispose — ALL on ONE reused session (no re-handshake). Env-gated exactly like
/// <see cref="HandshakeReuseSpikeTests"/> (silent skip without HISTORIAN_GRPC_HOST +
/// HISTORIAN_WRITE_SANDBOX_TAG + HISTORIAN_USER). Bounded write to the sandbox tag only.
/// </summary>
public sealed class HistorianSessionRoundTripTests
{
private readonly ITestOutputHelper _output;
public HistorianSessionRoundTripTests(ITestOutputHelper output) => _output = output;
[Fact]
public async Task Session_WriteReadStatusPing_AllOnOneSession()
{
string? host = Environment.GetEnvironmentVariable("HISTORIAN_GRPC_HOST");
string? sandboxTag = Environment.GetEnvironmentVariable("HISTORIAN_WRITE_SANDBOX_TAG");
if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(sandboxTag)
|| string.IsNullOrEmpty(Environment.GetEnvironmentVariable("HISTORIAN_USER")))
{
return; // skip — env not configured
}
HistorianClientOptions options = BuildOptions(host);
await using var client = new HistorianClient(options);
await using HistorianSession session = await client.OpenSessionAsync(HistorianSessionKind.WriteEnabled, CancellationToken.None);
// 1) write on the session
bool wrote = await session.AddHistoricalValuesAsync(sandboxTag,
new[] { new HistorianHistoricalValue(DateTime.UtcNow, 42.0, OpcQuality: 192) },
CancellationToken.None);
Assert.True(wrote);
_output.WriteLine("1) write -> ok");
// 2) read on the SAME session
DateTime end = DateTime.UtcNow, start = end - TimeSpan.FromDays(7);
var rows = new List<HistorianSample>();
await foreach (HistorianSample s in session.ReadRawAsync(sandboxTag, start, end, 8, CancellationToken.None))
rows.Add(s);
_output.WriteLine($"2) session read rows={rows.Count}");
Assert.NotEmpty(rows);
// 3) status + ping on the SAME session
string? version = await session.GetSystemParameterAsync("HistorianVersion", CancellationToken.None);
Assert.False(string.IsNullOrWhiteSpace(version));
_output.WriteLine($"3) HistorianVersion={version}");
await session.PingAsync(CancellationToken.None); // must not throw
_output.WriteLine("4) ping -> ok");
_output.WriteLine("session round-trip OK (write+read+status+ping on one session)");
}
// verbatim copy of BuildOptions from HandshakeReuseSpikeTests
private static HistorianClientOptions BuildOptions(string host)
{
string? user = Environment.GetEnvironmentVariable("HISTORIAN_USER");
string? password = Environment.GetEnvironmentVariable("HISTORIAN_PASSWORD");
bool explicitCreds = !string.IsNullOrEmpty(user);
int port = int.TryParse(Environment.GetEnvironmentVariable("HISTORIAN_GRPC_PORT"), out int parsed)
? parsed
: HistorianClientOptions.DefaultGrpcPort;
bool tls = string.Equals(Environment.GetEnvironmentVariable("HISTORIAN_GRPC_TLS"), "true", StringComparison.OrdinalIgnoreCase);
TimeSpan timeout = int.TryParse(Environment.GetEnvironmentVariable("HISTORIAN_GRPC_TIMEOUT"), out int secs) && secs > 0
? TimeSpan.FromSeconds(secs)
: new HistorianClientOptions { Host = host }.RequestTimeout;
return new HistorianClientOptions
{
Host = host,
Port = port,
Transport = HistorianTransport.RemoteGrpc,
GrpcUseTls = tls,
AllowUntrustedServerCertificate = tls,
ServerDnsIdentity = Environment.GetEnvironmentVariable("HISTORIAN_GRPC_DNSID"),
IntegratedSecurity = !explicitCreds,
UserName = user ?? string.Empty,
Password = password ?? string.Empty,
RequestTimeout = timeout,
Compression = true
};
}
}