Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/Sessions.md
Original file line number Diff line number Diff line change
Expand Up @@ -1486,6 +1486,13 @@ response. To decode on arrival, use
`ManagedSessionOptions.DeferNotificationDecoding` init property. The
classic subscription engine decodes on arrival.

The decoding happens on the transport, so sessions that share one
through an `IClientChannelManager` also share this: the bodies are kept
as bytes as soon as one session on the transport wants that, including
for a classic session or one that opted out. Those still see every
notification; to decode on arrival for certain, do not share the
transport with a session that defers.

### V2 notification pooling (opt-in)

The V2 subscription engine supports activator-level pooling of
Expand Down
5 changes: 2 additions & 3 deletions src/Opc.Ua.Client/Session/ManagedSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1900,10 +1900,9 @@ await endpoint.UpdateFromServerAsync(

// The V2 engine dispatches from its own queues and drops each body
// afterwards, which is what deferred decoding needs to pay off.
if (session.SubscriptionEngine is DefaultSubscriptionEngine &&
session.MessageContext is ServiceMessageContext messageContext)
if (session.SubscriptionEngine is DefaultSubscriptionEngine)
{
messageContext.DeferNotificationBodies = m_deferNotificationDecoding;
session.DeferNotificationBodies = m_deferNotificationDecoding;
}

// Apply opt-in V2 transfer-on-recreate. The V2 engine
Expand Down
34 changes: 34 additions & 0 deletions src/Opc.Ua.Client/Session/Session.cs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ public Session(ITransportChannel channel, Session template, bool copyEventHandle
DeleteSubscriptionsOnClose = template.DeleteSubscriptionsOnClose;
TransferSubscriptionsOnReconnect = template.TransferSubscriptionsOnReconnect;
EnableTokenReuseFailover = template.EnableTokenReuseFailover;
DeferNotificationBodies = template.DeferNotificationBodies;
PublishRequestCancelDelayOnCloseSession = template.PublishRequestCancelDelayOnCloseSession;
m_sessionTimeout = template.m_sessionTimeout;
m_maxRequestMessageSize = template.m_maxRequestMessageSize;
Expand Down Expand Up @@ -904,6 +905,38 @@ public int SubscriptionCount
/// </remarks>
public bool EnableTokenReuseFailover { get; set; }

/// <summary>
/// Whether this session wants notification bodies decoded on first use.
/// </summary>
/// <remarks>
/// The decoder reads this from the message context of the transport, which
/// sessions on one channel manager can share and which a replaced transport
/// starts anew. So a session only ever turns it on, and does again before each
/// Publish. A session that does not want it cannot turn it off for others: it
/// reads deferred bodies like any other, because they decode on first read.
/// </remarks>
internal bool DeferNotificationBodies
{
get => m_deferNotificationBodies;
set
{
m_deferNotificationBodies = value;
ApplyDeferNotificationBodies();
}
}

/// <summary>
/// Applies <see cref="DeferNotificationBodies"/> to the current transport.
/// </summary>
internal void ApplyDeferNotificationBodies()
{
if (m_deferNotificationBodies &&
NullableTransportChannel?.MessageContext is ServiceMessageContext { DeferNotificationBodies: false } context)
{
context.DeferNotificationBodies = true;
}
}

/// <summary>
/// Whether the endpoint Url domain is checked in the certificate.
/// </summary>
Expand Down Expand Up @@ -7394,6 +7427,7 @@ public BackgroundWorkScope(Session owner)

/// <summary>Namespace provenance of subscriptions loaded before the session reconnects.</summary>
private ServiceMessageContext? m_restoredSubscriptionContext;
private bool m_deferNotificationBodies;
private readonly SessionSystemContext m_systemContext;
#pragma warning disable CA2213 // Disposed in DisposeAsyncCore/Dispose
private readonly NodeCache m_nodeCache;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ public ValueTask<PublishResponse> PublishAsync(
acknowledgements,
CancellationToken ct = default)
{
m_session.ApplyDeferNotificationBodies();
return m_session.PublishAsync(
requestHeader,
acknowledgements,
Expand Down
18 changes: 13 additions & 5 deletions src/Opc.Ua.Client/Subscription/NotificationMessageDispatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,29 +79,37 @@ internal static SubscriptionNotificationMessage Create(
bool republished = false)
{
var payloads = new SubscriptionNotificationPayload[message.NotificationData.Count];
for (int i = 0; i < payloads.Length; i++)
int count = 0;
for (int i = 0; i < message.NotificationData.Count; i++)
{
ExtensionObject payload = message.NotificationData[i];
if (payload.TryGetValue(out DataChangeNotification? data))
{
payloads[i] = new SubscriptionNotificationPayload(
payloads[count++] = new SubscriptionNotificationPayload(
SubscriptionNotificationKind.DataChange, new(dataChanges(data)), [], default, null);
}
else if (payload.TryGetValue(out EventNotificationList? eventList))
{
payloads[i] = new SubscriptionNotificationPayload(
payloads[count++] = new SubscriptionNotificationPayload(
SubscriptionNotificationKind.Event, [], new(events(eventList)), default, null);
}
else if (payload.TryGetValue(out StatusChangeNotification? status))
{
payloads[i] = new SubscriptionNotificationPayload(
payloads[count++] = new SubscriptionNotificationPayload(
SubscriptionNotificationKind.StatusChange, [], [], status.Status, status.DiagnosticInfo);
}
else
else if (!payload.IsDeferred)
{
throw new ServiceResultException(StatusCodes.BadDecodingError,
"A complete notification message contains an unsupported payload.");
}

// A deferred body without a value failed to decode, which was logged. It
// was a supported type, and costs only itself, not the rest of the message.
}
if (count != payloads.Length)
{
Array.Resize(ref payloads, count);
}
return new SubscriptionNotificationMessage(
handle, (DateTime)message.PublishTime, payloads, stringTable)
Expand Down
27 changes: 24 additions & 3 deletions src/Opc.Ua.Types/Encoders/BinaryDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,10 @@ private ExtensionObject ReadDeferredExtensionObject(
IEncodeableType activator,
int length)
{
// the eager path enforces the limit when it starts on the body, and a body
// without nested structures would never reach another check.
CheckNestingLevel();

// never rent a length the input cannot satisfy.
CheckRemainingBytes(length, nameof(ReadExtensionObject));
if (Context.MaxMessageSize > 0 && Context.MaxMessageSize < length)
Expand All @@ -1204,8 +1208,15 @@ private ExtensionObject ReadDeferredExtensionObject(
return new ExtensionObject(
typeId,
new DeferredExtensionObjectBody(
typeId, buffer, length, activator, Context, m_nestingLevel + 1));
typeId,
buffer,
length,
activator,
Context,
m_nestingLevel + 1,
m_deferredBodyFailureLogged ??= new StrongBox<int>()));
}

/// <summary>
/// Decodes a binary body on seekable input, retaining the original
/// namespace-zero failure and bounded recovery policy.
Expand Down Expand Up @@ -3234,6 +3245,17 @@ private static ServiceResultException CreateDecodingError(
/// </summary>
/// <exception cref="ServiceResultException"></exception>
private void CheckAndIncrementNestingLevel()
{
CheckNestingLevel();
EncodingLimits.EnsureSufficientStack();
m_nestingLevel++;
}

/// <summary>
/// Test the nesting level.
/// </summary>
/// <exception cref="ServiceResultException"></exception>
private void CheckNestingLevel()
{
if (m_nestingLevel > Context.MaxEncodingNestingLevels)
{
Expand All @@ -3242,8 +3264,6 @@ private void CheckAndIncrementNestingLevel()
"Maximum nesting level of {0} was exceeded",
Context.MaxEncodingNestingLevels);
}
EncodingLimits.EnsureSufficientStack();
m_nestingLevel++;
}

/// <summary>
Expand Down Expand Up @@ -3308,6 +3328,7 @@ protected override void Dispose(bool disposing)
// when none is. See TryReadRemainingBodyBytes.
private int m_bodyEnd = -1;
private uint m_encodeablesRecovered;
private StrongBox<int>? m_deferredBodyFailureLogged;

// The most bytes allocated up front for an array read element by
// element, see ReadArrayElements. Below the large object heap limit.
Expand Down
25 changes: 17 additions & 8 deletions src/Opc.Ua.Types/Encoders/DeferredExtensionObjectBody.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@

using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Opc.Ua
Expand All @@ -42,22 +43,26 @@ namespace Opc.Ua
internal sealed class DeferredExtensionObjectBody
{
/// <summary>
/// Create the body. It owns the rented buffer.
/// Create the body. It owns the rented buffer. The bodies of one response share
/// <paramref name="failureLogged"/>, so that a response full of malformed bodies
/// logs once, as the eager decoder does.
/// </summary>
public DeferredExtensionObjectBody(
ExpandedNodeId typeId,
byte[] buffer,
int length,
IEncodeableType activator,
IServiceMessageContext context,
uint nestingLevel)
uint nestingLevel,
StrongBox<int> failureLogged)
{
m_typeId = typeId;
m_buffer = buffer;
m_length = length;
m_activator = activator;
m_context = context;
m_nestingLevel = nestingLevel;
m_failureLogged = failureLogged;
}

/// <summary>
Expand Down Expand Up @@ -158,11 +163,14 @@ private object Decode(byte[] buffer)
errorMessage = ex.Message;
exception = ex;
}
m_context.Telemetry.CreateLogger<DeferredExtensionObjectBody>().DecodeEncodeableRecovered(
exception,
errorMessage,
m_activator.XmlName,
m_typeId);
if (Interlocked.Exchange(ref m_failureLogged.Value, 1) == 0)
{
m_context.Telemetry.CreateLogger<DeferredExtensionObjectBody>().DecodeEncodeableRecovered(
exception,
errorMessage,
m_activator.XmlName,
m_typeId);
}
return ByteString.From(buffer.AsSpan(0, m_length).ToArray());
}

Expand All @@ -174,8 +182,9 @@ private object Decode(byte[] buffer)
private readonly IEncodeableType m_activator;
private readonly IServiceMessageContext m_context;
private readonly uint m_nestingLevel;
private readonly StrongBox<int> m_failureLogged;
private byte[]? m_buffer;
private object? m_value;
private bool m_resolved;
}
}
}
53 changes: 51 additions & 2 deletions tests/Opc.Ua.Client.Tests/Session/SessionEngineContextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,51 @@ public async Task ServiceMethodsDelegateToSessionAsync()
await Task.CompletedTask.ConfigureAwait(false);
}

/// <summary>
/// A replaced transport starts with a new message context. The next Publish restores
/// deferred decoding on it.
/// </summary>
[Test]
public async Task PublishRestoresDeferredDecodingOnAReplacedTransportAsync()
{
using TestSessionScope scope = CreateSessionScope();
var initial = (ServiceMessageContext)scope.Session.MessageContext;
scope.Session.DeferNotificationBodies = true;
Assert.That(initial.DeferNotificationBodies, Is.True);

// a managed channel keeps its identity and swaps the transport behind it.
ServiceMessageContext replaced = ServiceMessageContext.Create(scope.Telemetry);
scope.Channel.SetupGet(c => c.MessageContext).Returns(replaced);
Assert.That(replaced.DeferNotificationBodies, Is.False);

try
{
await scope.Context.PublishAsync(new RequestHeader(), []).ConfigureAwait(false);
}
catch (Exception ex) when (ex is ServiceResultException or NullReferenceException)
{
// the mock channel does not answer; only the context matters here.
}

Assert.That(replaced.DeferNotificationBodies, Is.True);
}

/// <summary>
/// A session that does not defer leaves alone what another session on a shared
/// transport turned on, so the order of connecting does not change the result.
/// </summary>
[Test]
public void SessionThatDoesNotDeferLeavesASharedTransportAlone()
{
using TestSessionScope scope = CreateSessionScope();
var shared = (ServiceMessageContext)scope.Session.MessageContext;
shared.DeferNotificationBodies = true;

scope.Session.DeferNotificationBodies = false;

Assert.That(shared.DeferNotificationBodies, Is.True);
}

[Test]
public void AsyncRequestTrackingDelegatesToSession()
{
Expand Down Expand Up @@ -373,7 +418,7 @@ private static TestSessionScope CreateSessionScope()
CreateEndpoint(),
engineFactory: engineFactory);

return new TestSessionScope(session, engineFactory.Context!, telemetry);
return new TestSessionScope(session, engineFactory.Context!, telemetry, channel);
}

private static ApplicationConfiguration CreateClientConfiguration(
Expand Down Expand Up @@ -442,11 +487,13 @@ private sealed class TestSessionScope : IDisposable
public TestSessionScope(
Session session,
ISubscriptionEngineContext context,
ITelemetryContext telemetry)
ITelemetryContext telemetry,
Mock<ITransportChannel> channel)
{
Session = session;
Context = context;
Telemetry = telemetry;
Channel = channel;
}

public Session Session { get; }
Expand All @@ -455,6 +502,8 @@ public TestSessionScope(

public ITelemetryContext Telemetry { get; }

public Mock<ITransportChannel> Channel { get; }

public void Dispose()
{
Session.Dispose();
Expand Down
Loading
Loading