mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-24 02:58:36 +08:00
b25429bccc
Follows #4707 (replaces #4714, which closed when the #4707 branch was deleted). Profiling the client process under load showed per-request allocation spread over the channel write path, the response wait, per-chunk header encoders and an AES instance per message, plus a stack walk per service call. This PR removes them and extends the load harness to measure the client. ## Results Paired A/B against the #4707 head, the server work now on master (3 alternating rounds, medians, 20 sessions unless noted, workstation GC on both sides, 24-core machine). Client = the harness process, server = the reference server child. | Scenario | Throughput | p50 | p90 | Client CPU / op | Client alloc / op | Server alloc / op | |---|---|---|---|---|---|---| | Read, 1 value | **+21%** (141k → 170k req/s) | −9% | −11% | −13% | −46% (4.5 → 2.4 KB) | −20% | | Read, 1 value, ManagedSession | **+18%** | −9% | −12% | −18% | −44% | −20% | | Read, 1 value, SignAndEncrypt | **+28%** | −14% | −20% | −24% | −52% | −26% | | Read, 1 value, 200 sessions | **+29%** | −11% | −17% | −17% | −46% | −20% | | Read, 100 values | +5% | −2% | −3% | −6% | −44% (15.6 → 8.8 KB) | −2% | | Read, 100 values, SignAndEncrypt | +8% | −7% | −2% | −2% | −46% | −3% | | Write, 100 values | ±0 | ≈ | ≈ | −14% | **−63%** (10.8 → 4.0 KB) | −2% | | Browse (Server object) | **+12%** | −7% | −11% | −19% | −17% | −12% | | Data changes, classic fast callback | ±0 ¹ | ≈ | ≈ | −21% | −10% | −5% | | Data changes, classic item events | ±0 ¹ | ≈ | ≈ | ≈ ² | −7% | −5% | | Data changes, ManagedSession (V2) | ±0 ¹ | ≈ | ≈ | ±0 | −5% | −5% | | Data changes, SignAndEncrypt | ±0 ¹ | ≈ | ≈ | −22% | −14% | −7% | ¹ Throughput is bounded by the writer rate; latency is dominated by the 100 ms publishing interval. Per notification the client uses about 2 µs and 170–260 B. ² The client uses 0.2–0.4 cores in the subscription scenarios; the CPU per notification is within run-to-run noise there. Client GC pause time in the window drops 38–66% in the Read and Write scenarios (17% for Browse). About 70% of the remaining client CPU per small request is kernel time in loopback socket send/receive. ## Changes - **Activity source**: `Session`, `SessionClientBatched`, the classic `Subscription` and `ClassicSubscriptionEngine`, and the TCP/HTTPS client channels resolve their `ActivitySource` once. `TelemetryExtensions.StartActivity` called `Assembly.GetCallingAssembly()` (a stack walk) on every service call, ~8% of client CPU. - **Channel write queue** (`UaSCUaBinaryChannel`, client and server): an ordered queue drained by one thread-pool writer replaces the per-write `ContinueWith`/`Unwrap`/trailing continuation chain. The writer is queued to the issuing thread's local pool queue, like the task continuation was (queuing it globally cost ~15 µs of p50 in a first iteration). Successful writes are reported inline instead of through `Task.Run`; failed writes still go through the pool. The client channel enters its gate only for a failed write instead of on every write completion. - **`TcpByteTransport`**: no linked `CancellationTokenSource` when the caller's token cannot be cancelled (the channel always passes `None`); a single-chunk `BufferCollection` uses the `ReadOnlyMemory` send instead of the vectored `Task<int>` send; `PoolingAsyncValueTaskMethodBuilder` on .NET 6+ for the receive/send state machines; no closure per vectored send. - **`BinaryEncoder.GetNodeIdEncoding`**: `Convert.ToUInt32(uint, IFormatProvider)` bound to the `object` overload and `Convert.ToByte(enum, ...)` boxed the enum, two boxes per encoded NodeId. 44% of the client allocation of a 100-value Read; the server encodes NodeIds the same way. - **Symmetric chunk headers**: the 24 header bytes are written and read with `BinaryPrimitives` instead of a `MemoryStream` + `BinaryEncoder`/`BinaryWriter` (send) and `BinaryDecoder`/`BinaryReader` (receive) per chunk. A chunk too short for a field still gets the decoder's `BadDecodingError`. - **AES-CBC**: `ChannelToken` keeps one `Aes` per direction, used with the one-shot `EncryptCbc`/`DecryptCbc` on .NET 6+ (net48 reuses the instance and creates the transform). Previously every message created an `Aes`, imported the key (`BCryptImportKey`) and created a transform, ~15% of client CPU with SignAndEncrypt. The instance is taken out of the token while in use, so concurrent callers never share one. The public `CryptoUtils` overloads are unchanged. - **`ChannelAsyncOperation`**: `SendRequestAsync` waits on an internal task-free completion source instead of `EndAsync` (`TaskCompletionSource` + `Task` + `WaitAsync` promise + state machine); `EndAsync` registers cancellation instead of `WaitAsync(ct)`; the timeout timer uses a static callback; completing with `default(T)` shares a box. - **Session keep alive**: every good response called `Timer.Change` under the session lock, taking the timer queue lock. It now records the time; the timer callback defers itself to one interval after the last response, which is when the per-response reset made it fire. ### Behaviour notes - `TcpByteTransport.SendChunkAsync`/`ReceiveChunkAsync` return pooled `ValueTask`s on .NET 6+: like any `ValueTask` they must be awaited once. - A successful write's `HandleWriteComplete` now runs on the writer instead of a separate pool work item. Overrides outside the stack that block in it delay later writes on that channel. - The write itself no longer flows the caller's `ExecutionContext` (`Activity.Current` is not set inside the transport send). ## Harness (`perf/`) - `client-process:` and `client-per-op:` result lines; `--trace-side client` records the harness itself. - `--client managed` (ManagedSession, V2 engine) and `--callback item` (classic per-item events). - Classic fixture sessions no longer request diagnostics in every response (the server otherwise sends a `DiagnosticInfo` per notification). - `ab.sh`: `SCENARIOS`/`ROUNDS`/`OUT`, CRLF tolerant, defaults before the scenario (a `--sessions 200` scenario silently ran with 20 before); `client-scenarios.txt`; `ab-summary.ps1` reports client and server medians. - README notes two profile traps: `Monitor.Enter_Slowpath` in the sampled CPU profile without matching contention events (46 in 10 s here), and allocation ticks over-attributing small objects allocated after large arrays. ## Testing - New: `UaSCBinaryChannelWriteQueueTests` (order, one send at a time, never on the caller's stack, failures reported and later writes still sent, concurrent writers), `ChannelAsyncOperationWaitTests` (late/early completion, faults, cancellation, disposal, continuation off the completing thread, 2000-iteration completion/cancellation race, timeout), `CryptoUtilsAesCacheTests` (cached = fresh cipher text across IVs, round trips, concurrent users, token disposal), `TcpByteTransportTests` single/multi-buffer and cancellable sends, `SessionKeepAliveTests` keep-alive read exactly one interval after the last response. - After merging master: Core Stack 3571 passed, Client 2763 passed, 0 failed. - Before merging master, net10.0: Core Stack+Security 4680 passed; Client 2763; Sessions 849 (379 skipped); Server 8391; Subscriptions 643; all 0 failed. - Stress Contract+Integration: 5 failures, the same 5 on the unchanged #4707 head (`CertRotationContractTests`, `GateAndBypassTests`, `LeaseLifecycleTests`, `RetryBudgetEnforcementTests` reflection seam, `CertRotationLiveTests`), not caused by this PR. - net48 build of `UA.slnx` clean; `dotnet format whitespace` clean. ## Not changed (follow-ups) - Two `recv` calls per chunk (8-byte header, then body). Merging them needs read-ahead with carry-over, which the transport avoids so that idle peers do not hold receive buffers. - `ManagedSession` service wrappers add an async state machine and a reader lock per call (~200 B). - Generated responses allocate a discarded `ResponseHeader` (generator-wide, as noted in #4707). - Decoded `MonitoredItemNotification` objects and the V2 `DataValueChange[]` per message dominate notification allocation (`WithPoolNotifications` pools the latter). - Coalescing queued writes on one channel into one vectored send would cut syscalls under concurrent requests on a shared channel. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Marc <marcschier@hotmail.com> Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
501 lines
20 KiB
C#
501 lines
20 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Time.Testing;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Tests;
|
|
|
|
#pragma warning disable CA2000, CA2007
|
|
|
|
namespace Opc.Ua.Client.Tests
|
|
{
|
|
/// <summary>
|
|
/// Tests for the keep alive liveness bookkeeping of <see cref="Session"/>.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Regression coverage for
|
|
/// https://github.com/OPCFoundation/UA-.NETStandard/issues/4317:
|
|
/// <see cref="Session.RequestCompleted"/> defers the keep alive read on every
|
|
/// good service response, so under steady request traffic the read never
|
|
/// fires. The freshness timestamp <see cref="Session.KeepAliveStopped"/> is
|
|
/// judged against therefore has to be refreshed by those responses as well,
|
|
/// otherwise the first pause in traffic reports BadNoCommunication on a
|
|
/// perfectly healthy session.
|
|
/// </remarks>
|
|
[TestFixture]
|
|
[Parallelizable]
|
|
[Category("Client")]
|
|
[Category("Session")]
|
|
[Category("KeepAlive")]
|
|
public sealed class SessionKeepAliveTests
|
|
{
|
|
private const int kKeepAliveInterval = 5_000;
|
|
|
|
/// <summary>
|
|
/// KeepAliveInterval * m_keepAliveIntervalFactor (1) + m_keepAliveGuardBand (1000).
|
|
/// </summary>
|
|
private static readonly TimeSpan s_pastKeepAliveThreshold =
|
|
TimeSpan.FromMilliseconds(kKeepAliveInterval + 1_000 + 1);
|
|
|
|
[Test]
|
|
public void KeepAliveStoppedTripsWhenNothingIsHeardFromTheServer()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.False);
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Steady traffic keeps the session alive even though the keep alive read
|
|
/// is deferred by every response and consequently never fires.
|
|
/// </summary>
|
|
[Test]
|
|
public void GoodResponsesKeepTheSessionAliveWhileTheKeepAliveReadIsDeferred()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
long initialTimestamp = session.LastKeepAliveTimestamp;
|
|
|
|
// a request every 2 s for 20 s - each response defers the keep alive
|
|
// read by a full interval, so no keep alive read is ever sent.
|
|
for (int ii = 0; ii < 10; ii++)
|
|
{
|
|
timeProvider.Advance(TimeSpan.FromSeconds(2));
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
|
|
Assert.That(
|
|
session.KeepAliveStopped,
|
|
Is.False,
|
|
$"the server answered 2000 ms ago (iteration {ii})");
|
|
}
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(session.KeepAliveStopped, Is.False);
|
|
Assert.That(session.LastKeepAliveTimestamp, Is.GreaterThan(initialTimestamp));
|
|
});
|
|
|
|
// once the traffic stops the session must still detect the silence.
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A good response also revives a timestamp that already went stale but
|
|
/// has not been reported as an error yet - the keep alive read is still
|
|
/// in flight, the worker is skipping while reconnecting, or its tick is
|
|
/// late. Without this no traffic could rescue the session from the
|
|
/// spurious BadNoCommunication the worker is about to raise.
|
|
/// </summary>
|
|
[Test]
|
|
public void GoodResponseRevivesAStaleTimestampWhenNoErrorIsLatched()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
|
|
Assert.That(
|
|
session.KeepAliveStopped,
|
|
Is.False,
|
|
"a good response must count as proof of liveness");
|
|
}
|
|
|
|
[Test]
|
|
public void BadResponsesDoNotRefreshTheKeepAliveTimestamp()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
long initialTimestamp = session.LastKeepAliveTimestamp;
|
|
|
|
timeProvider.Advance(TimeSpan.FromMilliseconds(3_000));
|
|
session.CompleteRequest(StatusCodes.BadTimeout);
|
|
|
|
Assert.That(session.LastKeepAliveTimestamp, Is.EqualTo(initialTimestamp));
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold - TimeSpan.FromMilliseconds(3_000));
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A latched keep alive error is only cleared by an actual keep alive
|
|
/// response, never by unrelated traffic.
|
|
/// </summary>
|
|
[Test]
|
|
public void LatchedKeepAliveErrorIsNotClearedByAGoodResponse()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
session.RaiseKeepAliveError(StatusCodes.BadTimeout);
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
}
|
|
|
|
/// <summary>
|
|
/// After BadNoCommunication was reported the recovery branch of
|
|
/// OnKeepAlive must still run, i.e. good responses arriving before the
|
|
/// keep alive read completes must not silently mark the session as
|
|
/// healthy again.
|
|
/// </summary>
|
|
[Test]
|
|
public void RecoveryAfterBadNoCommunicationIsHandledByTheKeepAliveResponse()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
session.RaiseKeepAliveError(StatusCodes.BadNoCommunication);
|
|
|
|
// the keep alive read itself completes as a good response first.
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
Assert.That(
|
|
session.KeepAliveStopped,
|
|
Is.True,
|
|
"the keep alive error must survive until OnKeepAlive handled it");
|
|
|
|
session.RaiseKeepAlive();
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(
|
|
session.KeepAliveStoppedOnEnteringOnKeepAlive,
|
|
Is.True,
|
|
"OnKeepAlive must take the recovery branch");
|
|
Assert.That(session.KeepAliveStopped, Is.False);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Once the transport channel is detached the keep alive read fails with
|
|
/// BadSecureChannelClosed, which the keep alive worker reports through
|
|
/// OnKeepAliveError, and the next tick reports BadNoCommunication.
|
|
/// Neither report may dereference the missing channel: the endpoint url
|
|
/// in the log comes from the configured endpoint, not from the channel.
|
|
/// </summary>
|
|
[Test]
|
|
public void KeepAliveReadFailureIsReportedAfterTheChannelIsDetached()
|
|
{
|
|
AssertKeepAliveErrorIsReportedAfterTheChannelIsDetached(
|
|
StatusCodes.BadSecureChannelClosed);
|
|
}
|
|
|
|
/// <summary>
|
|
/// See <see cref="KeepAliveReadFailureIsReportedAfterTheChannelIsDetached"/>;
|
|
/// BadNoCommunication additionally logs KEEP ALIVE LATE with the endpoint url.
|
|
/// </summary>
|
|
[Test]
|
|
public void KeepAliveLateIsReportedAfterTheChannelIsDetached()
|
|
{
|
|
AssertKeepAliveErrorIsReportedAfterTheChannelIsDetached(
|
|
StatusCodes.BadNoCommunication);
|
|
}
|
|
|
|
private static void AssertKeepAliveErrorIsReportedAfterTheChannelIsDetached(
|
|
StatusCode statusCode)
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using KeepAliveTestSession session = CreateSession(timeProvider);
|
|
StatusCode reported = StatusCodes.Good;
|
|
session.KeepAlive += (_, e) => reported = e.Status?.StatusCode ?? StatusCodes.Good;
|
|
|
|
#pragma warning disable CS0618 // DetachChannel is obsolete
|
|
session.DetachChannel();
|
|
#pragma warning restore CS0618
|
|
|
|
timeProvider.Advance(s_pastKeepAliveThreshold);
|
|
Assert.DoesNotThrow(() => session.RaiseKeepAliveError(statusCode));
|
|
|
|
Assert.Multiple(() =>
|
|
{
|
|
Assert.That(reported, Is.EqualTo(statusCode));
|
|
Assert.That(session.KeepAliveStopped, Is.True);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// The keep alive read on a detached channel fails with a service error
|
|
/// the keep alive worker handles, not with an unexpected exception.
|
|
/// </summary>
|
|
[Test]
|
|
public void KeepAliveReadAfterTheChannelIsDetachedFailsWithBadSecureChannelClosed()
|
|
{
|
|
using KeepAliveTestSession session = CreateSession(new FakeTimeProvider());
|
|
|
|
#pragma warning disable CS0618 // DetachChannel is obsolete
|
|
session.DetachChannel();
|
|
#pragma warning restore CS0618
|
|
|
|
ServiceResultException sre = Assert.ThrowsAsync<ServiceResultException>(
|
|
async () => await session.ReadAsync(
|
|
new RequestHeader(),
|
|
0,
|
|
TimestampsToReturn.Neither,
|
|
new[]
|
|
{
|
|
new ReadValueId
|
|
{
|
|
NodeId = VariableIds.Server_ServerStatus_State,
|
|
AttributeId = Attributes.Value
|
|
}
|
|
}.ToArrayOf(),
|
|
default).ConfigureAwait(false));
|
|
|
|
Assert.That(sre.StatusCode, Is.EqualTo(StatusCodes.BadSecureChannelClosed));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Responses do not move the keep alive timer each time; the timer moves
|
|
/// itself when it fires. The keep alive read must still be sent exactly
|
|
/// one interval after the last response, and not while responses keep
|
|
/// arriving.
|
|
/// </summary>
|
|
[Test]
|
|
[CancelAfter(30000)]
|
|
public async Task TheKeepAliveReadIsSentOneIntervalAfterTheLastResponseAsync()
|
|
{
|
|
var timeProvider = new FakeTimeProvider();
|
|
using var readSent = new SemaphoreSlim(0);
|
|
using KeepAliveTestSession session = CreateSession(
|
|
timeProvider,
|
|
channel => channel
|
|
.Setup(c => c.SendRequestAsync(It.IsAny<IServiceRequest>(), It.IsAny<CancellationToken>()))
|
|
.Returns((IServiceRequest request, CancellationToken _) =>
|
|
{
|
|
readSent.Release();
|
|
return new ValueTask<IServiceResponse>(CreateKeepAliveResponse(request));
|
|
}));
|
|
session.SessionCreated(new NodeId(1u, 1), new NodeId(2u, 1));
|
|
|
|
// the first keep alive read is sent right away.
|
|
await session.StartKeepAliveTimerAsync().ConfigureAwait(false);
|
|
Assert.That(await readSent.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false), Is.True);
|
|
|
|
// a response every 2 s for 20 s: no keep alive read.
|
|
for (int ii = 0; ii < 10; ii++)
|
|
{
|
|
timeProvider.Advance(TimeSpan.FromSeconds(2));
|
|
session.CompleteRequest(StatusCodes.Good);
|
|
Assert.That(
|
|
await readSent.WaitAsync(TimeSpan.FromMilliseconds(100)).ConfigureAwait(false),
|
|
Is.False,
|
|
$"the last response was received {ii * 2000} ms after the previous one");
|
|
}
|
|
|
|
// traffic stops: nothing until a full interval after the last response.
|
|
timeProvider.Advance(TimeSpan.FromMilliseconds(kKeepAliveInterval - 10));
|
|
Assert.That(
|
|
await readSent.WaitAsync(TimeSpan.FromMilliseconds(200)).ConfigureAwait(false),
|
|
Is.False);
|
|
|
|
timeProvider.Advance(TimeSpan.FromMilliseconds(20));
|
|
Assert.That(await readSent.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false), Is.True);
|
|
}
|
|
|
|
private static ReadResponse CreateKeepAliveResponse(IServiceRequest request)
|
|
{
|
|
return new ReadResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader
|
|
{
|
|
RequestHandle = request.RequestHeader.RequestHandle,
|
|
ServiceResult = StatusCodes.Good,
|
|
Timestamp = DateTime.UtcNow
|
|
},
|
|
Results = new[] { new DataValue(new Variant((int)ServerState.Running)) }.ToArrayOf()
|
|
};
|
|
}
|
|
|
|
private static KeepAliveTestSession CreateSession(
|
|
TimeProvider timeProvider,
|
|
Action<Mock<ITransportChannel>>? setupChannel = null)
|
|
{
|
|
ITelemetryContext telemetry = NUnitTelemetryContext.Create();
|
|
ApplicationConfiguration configuration = CreateClientConfiguration(telemetry);
|
|
IServiceMessageContext messageContext = configuration.CreateMessageContext();
|
|
var channel = new Mock<ITransportChannel>();
|
|
channel.SetupGet(c => c.MessageContext).Returns(messageContext);
|
|
setupChannel?.Invoke(channel);
|
|
|
|
var session = new KeepAliveTestSession(
|
|
channel.Object,
|
|
configuration,
|
|
CreateEndpoint(),
|
|
timeProvider)
|
|
{
|
|
KeepAliveInterval = kKeepAliveInterval
|
|
};
|
|
|
|
// establish the initial liveness baseline the keep alive timer start
|
|
// would normally provide, then forget what that call observed.
|
|
session.RaiseKeepAlive();
|
|
session.ResetKeepAliveObservation();
|
|
|
|
return session;
|
|
}
|
|
|
|
private static ApplicationConfiguration CreateClientConfiguration(
|
|
ITelemetryContext telemetry)
|
|
{
|
|
return new ApplicationConfiguration(telemetry)
|
|
{
|
|
ApplicationName = "SessionKeepAliveTests",
|
|
ApplicationType = ApplicationType.Client,
|
|
ApplicationUri = "urn:localhost:SessionKeepAliveTests",
|
|
ProductUri = "urn:localhost:SessionKeepAliveTests",
|
|
ClientConfiguration = new ClientConfiguration
|
|
{
|
|
DefaultSessionTimeout = 60000,
|
|
MinSubscriptionLifetime = 10000
|
|
},
|
|
SecurityConfiguration = new SecurityConfiguration
|
|
{
|
|
ApplicationCertificate = new CertificateIdentifier()
|
|
},
|
|
TransportQuotas = new TransportQuotas { OperationTimeout = 6000 }
|
|
};
|
|
}
|
|
|
|
private static ConfiguredEndpoint CreateEndpoint()
|
|
{
|
|
var description = new EndpointDescription
|
|
{
|
|
EndpointUrl = "opc.tcp://localhost:4840",
|
|
SecurityMode = MessageSecurityMode.None,
|
|
SecurityPolicyUri = SecurityPolicies.None,
|
|
TransportProfileUri = Profiles.UaTcpTransport,
|
|
UserIdentityTokens =
|
|
[
|
|
new UserTokenPolicy
|
|
{
|
|
PolicyId = "anonymous",
|
|
TokenType = UserTokenType.Anonymous,
|
|
SecurityPolicyUri = SecurityPolicies.None
|
|
}
|
|
]
|
|
};
|
|
description.Server.ApplicationUri = description.EndpointUrl;
|
|
description.Server.ApplicationType = ApplicationType.Server;
|
|
|
|
return new ConfiguredEndpoint(
|
|
null,
|
|
description,
|
|
new EndpointConfiguration { OperationTimeout = 6000 })
|
|
{
|
|
UpdateBeforeConnect = false
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Exposes the protected keep alive hooks so the handling of service
|
|
/// responses can be driven without a server.
|
|
/// </summary>
|
|
private sealed class KeepAliveTestSession : Session
|
|
{
|
|
public KeepAliveTestSession(
|
|
ITransportChannel channel,
|
|
ApplicationConfiguration configuration,
|
|
ConfiguredEndpoint endpoint,
|
|
TimeProvider timeProvider)
|
|
: base(channel, configuration, endpoint, timeProvider: timeProvider)
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// The value of <see cref="Session.KeepAliveStopped"/> observed when
|
|
/// <see cref="OnKeepAlive"/> was entered the last time.
|
|
/// </summary>
|
|
public bool? KeepAliveStoppedOnEnteringOnKeepAlive { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Discards what <see cref="OnKeepAlive"/> observed so far.
|
|
/// </summary>
|
|
public void ResetKeepAliveObservation()
|
|
{
|
|
KeepAliveStoppedOnEnteringOnKeepAlive = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Simulates a completed service call with the given service result.
|
|
/// </summary>
|
|
public void CompleteRequest(StatusCode serviceResult)
|
|
{
|
|
RequestCompleted(
|
|
new ReadRequest { RequestHeader = new RequestHeader() },
|
|
new ReadResponse
|
|
{
|
|
ResponseHeader = new ResponseHeader { ServiceResult = serviceResult }
|
|
},
|
|
nameof(Read));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Simulates a successful keep alive read response.
|
|
/// </summary>
|
|
public void RaiseKeepAlive()
|
|
{
|
|
OnKeepAlive(ServerState.Running, DateTime.UtcNow);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Simulates a failed keep alive read.
|
|
/// </summary>
|
|
public void RaiseKeepAliveError(StatusCode statusCode)
|
|
{
|
|
OnKeepAliveError(new ServiceResult(statusCode));
|
|
}
|
|
|
|
protected override void OnKeepAlive(ServerState currentState, DateTime currentTime)
|
|
{
|
|
KeepAliveStoppedOnEnteringOnKeepAlive = KeepAliveStopped;
|
|
base.OnKeepAlive(currentState, currentTime);
|
|
}
|
|
}
|
|
}
|
|
}
|